Compare commits

...
Author SHA1 Message Date
weichen b7194d54d5 Merge remote-tracking branch 'origin/main' into feature/fe-u7-browser-e2e 2026-10-12 14:34:44 +00:00
weichen f752a7bcec Add U7 live-entry browser acceptance suite
Why: U7 浏览器点验需要可复跑的固定制品用例(对实际 8788 入口)。
Evidence: 4/4 passed against rdm@4a10773(登录工作台/审计工作区/项目设置三页签/管理入口门控)+ 三张截图;收据在 RDM 任务卡。
Impact: 新增三份 e2e(PLAYWRIGHT_BASE_URL 驱动,未设时跳过);无运行时改动。
Refs: 方案 r1 U7;RDM frontend-pin 任务
2026-10-12 14:33:05 +00:00
weichen e3332badca Merge pull request 'Protect saved surface reload and preview recovery' (#71) from feature/surface-black-screen-recovery into main 2026-10-12 14:24:11 +00:00
weichen 3a5fbe6e42 Test saved surface recovery through conversation reload
Why: Existing event and helper tests missed the SurfaceMeta to snapshot
reload path that blanked the app after the integration pointer regressed.

Evidence: New restore regressions fail on 1edd872 and pass on compatible
main; independent reviewer replays and real browser contract replay are
recorded in the Dev surface-black-screen-recovery task card.

Impact: Tests only; protects reload, partial failure, newer live revisions,
conversation switching, and two-page browser preview.

Refs: Frontend #68; Dev #454 and #452; Dev surface-black-screen-recovery
2026-10-12 14:20:35 +00:00
weichen fca832e3b0 Merge pull request 'Hydrate surface list into snapshots before render' (#68) from fix/surface-list-hydrate into main
Reviewed-on: https://git-home.u1680832.nyat.app:30319/weichen/Agent-System-Frontend/pulls/68
2026-10-12 12:17:55 +00:00
weichen 81b984c752 Merge pull request 'Prefer progress cards over duplicate CurrentTaskCard' (#67) from feature/fast-slow-display-u1 into main
Reviewed-on: https://git-home.u1680832.nyat.app:30319/weichen/Agent-System-Frontend/pulls/67
2026-10-12 12:17:10 +00:00
weichen c4ebcf5404 Merge pull request 'Add project permission matrix tab consuming perm.check' (#70) from feature/frontend-rdm-u6-perm-matrix into main 2026-10-12 10:57:08 +00:00
weichen 11464242c0 Add project permission matrix tab consuming perm.check
Why: 方案 r1 U6/R4/KTD5——RDM #266 已交付与实际判定同源的矩阵解释读面,项目设置需消费入口(UI 不重算,服务端解释)。
Evidence: 红:3 failed(导出缺失,/tmp/fe-matrix-red.txt);绿:vitest 25 文件/127 测试全过(含 design-guard)+ npm run build 成功(tsc -b 干净);收据 /tmp/fe-matrix-vitest.txt、/tmp/fe-matrix-build.txt。
Impact: rdmManagement 增 RDM_PERM_MATRIX_COMMANDS/rdmPermMatrixReady/permCheckPayload/describeSource;RdmPermMatrixSection(成员选择默认自省+12 动作矩阵表+来源标签+拒绝原因);项目设置「项目权限」页签(rdmPermMatrixAvailable 门控);store 同源计算标志。样式仅复用既有类。
Refs: RDM #266;方案 r1 U6/R4
2026-10-12 10:56:36 +00:00
weichen 809f28d48f Add red tests for perm matrix tab consumption
Why: U6 矩阵页签的门控/载荷/来源标签纯逻辑先行红证。
Evidence: npx vitest run test/rdm-management.test.ts → 3 failed(导出缺失);收据 /tmp/fe-matrix-red.txt。
Impact: 仅测试。
Refs: 方案 r1 U6/R4/KTD5;RDM #266
2026-10-12 10:55:29 +00:00
weichen 336ec94763 Merge pull request 'Add RDM management pages gated by command availability' (#69) from feature/frontend-rdm-u6-pages into main 2026-10-12 10:27:55 +00:00
weichen 0ae27749cf Add RDM management pages gated by command availability
Why: 方案 r1 U6/KTD5——已合入的 rdm.role.* / rdm.project.member.* / rdm.review.assign.doc / rdm.review.doc.* 命令无用户入口;系统管理与项目设置需按命令面门控接线(普通基座零暴露)。
Evidence: 红:vitest rdm-management 1 failed(模块缺失,收据 /tmp/fe-u6-red-receipt.txt);绿:npx vitest run 25 files / 124 tests 全过(含 design-guard)+ npm run build 成功(tsc -b 干净);收据 /tmp/fe-u6-vitest.txt、/tmp/fe-u6-build.txt。
Impact: 新增 src/rdmManagement.ts(门控+载荷纯逻辑,8 测试)与 adminRdmSections.tsx(RdmRolesPanel/RdmMembersSection/RdmDutiesSection);AdminZone 增 rdm-roles 分区(管理员+rdmRolesAvailable);ProjectSettingsModal 增成员/文档职责页签(按 rdmMembersAvailable/rdmDocReviewAvailable);store 刷新命令面时计算三门控标志。样式仅复用既有类。
Refs: 方案 r1 U6/KTD5;RDM PR #260/#262/#254
2026-10-12 10:27:31 +00:00
weichen 531b683a92 Add red contract tests for RDM management gating and payloads
Why: U6 页面接线的门控/载荷是纯逻辑,先行红证模块缺失。
Evidence: npx vitest run test/rdm-management.test.ts → 1 failed (module not found);收据 /tmp/fe-u6-red-receipt.txt。
Impact: 仅测试文件。
Refs: 方案 r1 U6/KTD5
2026-10-12 10:23:24 +00:00
weichenandCursor 0f52634380 Hydrate surface list into snapshots before render
Why: GET .../surfaces returns SurfaceMeta without identity; writing it into
surfaces let PreviewPane crash on x.identity.surfaceId after refresh.
Evidence: npx vitest run (118 passed), including surfaceKey.test.ts
Impact: openConversation fetches SurfaceSnapshot via surfaceGet; find paths
use surfaceKey; Meta no longer enters the surfaces projection
Refs: fix/surface-list-hydrate

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 08:33:23 +00:00
weichenandCursor 1edd872c55 Prefer progress cards over duplicate CurrentTaskCard
Why: When a slow-lane progress card is active, hide the plan/todos
CurrentTaskCard so the work column has one authoritative task object.
Evidence: npx vitest run (workbench-progress + full suite)
Impact: Workbench work tab; tidyCards skips done+danger failures.
Refs: fast-slow-channel-display-u1-plan W4

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 07:45:08 +00:00
weichen a45a4d8652 Merge pull request 'Fix password form semantics and typed setting inputs' (#66) from feature/rdm-audit-capability-gate-changepw-form into main
Reviewed-on: https://git-home.u1680832.nyat.app:30319/weichen/Agent-System-Frontend/pulls/66
2026-10-12 06:20:05 +00:00
weichen 378ec24bbd Merge pull request 'Gate the audit workspace entry on rdm.inspect command availability' (#65) from feature/rdm-audit-capability-gate into main
Reviewed-on: https://git-home.u1680832.nyat.app:30319/weichen/Agent-System-Frontend/pulls/65
2026-10-12 06:19:56 +00:00
weichen cc233fec90 Assert readonly via attribute in the changepw spec
Why: the repo's @playwright/test version has no toBeReadOnly matcher.

Evidence: failing run shows TypeError at the matcher; the attribute
assertion works across versions.

Impact: none beyond the spec assertion.

Refs: 2026-10-12 diagnostic report, increment 3.
2026-10-12 03:50:52 +00:00
weichen 8db7093a9d Fix password form semantics and per-type setting inputs
Why: the change-password modal rendered loose password inputs outside any
<form> with no autocomplete or username association (browser password-form
warnings; Enter did not submit), and its 401 handling collapsed every
cause into "wrong current password". SettingInput masked ALL free-text
config values as password fields.

Evidence: vitest 24 files / 116 tests incl. new settingInputAttrs matrix;
knip and tsc -b && vite build pass; e2e changepw-form spec (driven by the
dev-repo e2e.sh plain phase) covers form submit via Enter, autocomplete
trio, readonly username and the classified error copy.

Impact: ChangePasswordModal uses form onSubmit, htmlFor/id association,
username/current-password/new-password autocomplete and reuses
humanChangePasswordError; SettingInput renders text inputs unless the
field is secret.

Refs: 2026-10-12 diagnostic report, increment 3.
2026-10-12 03:48:13 +00:00
weichen 034bd5f724 Merge frontend main (admin-zone sections) into the gating branch
Why: dev-repo main advanced the frontend pin to d01a3eb (admin-zone
section hosting), diverging from the gating branch; the task-sync gitlink
conflict requires the component-level merge first.

Evidence: post-merge vitest 23 files / 112 tests, knip 42 <= 43, and
tsc -b && vite build all pass; store.ts conflict resolved by keeping both
rdmAuditAvailable and adminSections state.

Impact: gating branch now contains frontend main d01a3eb.

Refs: 2026-10-12 diagnostic report, increment 2; frontend #63/#64.
2026-10-12 03:28:31 +00:00
weichen 83a062b7f8 Unexport internal-only gating types to hold the knip ratchet
Why: BuildWorkspaceOptions / RdmErrorKind / RdmErrorView are only consumed
inside their own modules, so exporting them pushed unused exports 45 over
the knip baseline 43 and failed make test.

Evidence: npx vitest run 23 files / 112 tests pass; node scripts/check-knip.mjs
passes at 42 <= 43.

Impact: no API change - consumers pass object literals and consume the
classified error structurally.

Refs: 2026-10-12 diagnostic report, increment 2.
2026-10-12 03:08:56 +00:00
weichen fdaf89de9d Re-login with the changed password in the plain-base spec
Why: phase 4 runs after the RDM phase already forced the password change,
so the initial-password attempt 401s and the sidebar never renders.

Evidence: phase-4 failure log shows the login form still up at the
15s .tsb-tool timeout; rdm-audit spec already carries this branch.

Impact: plain-base login helper mirrors rdm-audit's gate-aware login.

Refs: 2026-10-12 diagnostic report, increment 2.
2026-10-12 03:04:22 +00:00
weichen 986ebdbb61 Self-skip the plain-base spec outside its e2e phase
Why: the phase-3 playwright run scans the whole e2e/ directory, so the
plain-base assertions ran against the RDM combo where the audit entry is
legitimately visible and failed.

Evidence: phase-3 rerun shows 4 rdm-audit tests passing with plain-base
failing out of place; the spec now skips unless E2E_PLAIN_BASE=1, which
scripts/e2e.sh phase 4 injects.

Impact: plain-base scenario only executes against the plain base serve.

Refs: 2026-10-12 diagnostic report, increment 2.
2026-10-12 03:01:33 +00:00
weichen e058adcf72 Gate the audit workspace entry on rdm.inspect command availability
Why: the rdm-audit entry was an unconditional builtin, so on a plain base
without any rdm.inspect.* commands the workspace opened straight into a
rejected receipt (400) - diagnosed 2026-10-12. The page also rendered raw
receipt JSON instead of a readable error.

Evidence: vitest 23 files / 112 tests pass incl. the new contract matrix
(workspaces.test.ts, rdm-errors.test.ts) and design-guard; tsc -b &&
vite build pass; e2e plain-base scenario added (driven by dev-repo
scripts/e2e.sh phase 4).

Impact: audit entry shows only when GET /api/commands lists all seven
rdm.inspect.* commands enabled (store.rdmAuditAvailable, refreshed with
the workspace list); audit errors classify into capability-missing /
auth-expired / query-failed with the raw receipt kept in a Collapsible.

Refs: 2026-10-12 diagnostic report, increment 2.
2026-10-12 02:58:46 +00:00
weichen d01a3ebd81 Merge pull request 'Move AdminZoneSection out of the generated contracts mirror (WP3-I3 fix)' (#64) from feature/adminzone-contracts-fix into main 2026-10-12 02:50:01 +00:00
weichen fac99939fa Move AdminZoneSection out of the generated contracts mirror
Why: src/contracts.ts is fully regenerated from Core by make contracts;
the hand-added interface there is deleted on every sync (surfaced as a
dirty tree in the Dev composite test run).
Evidence: npx vitest run 101/101, tsc --noEmit clean, knip 42 <= 43;
Dev composite CI is authoritative.
Impact: AdminZoneSection now lives in api.ts (backend-only endpoint
type, matching existing local-type precedent); contracts.ts restored to
the generated mirror; imports updated in store and AdminZone.
Refs: WP3-I3; follows Frontend PR #63.
2026-10-12 02:49:46 +00:00
weichen c1225bb880 Merge pull request 'Host plugin-declared sections in the admin zone (WP3-I3)' (#63) from feature/adminzone-plugin-sections into main 2026-10-12 02:39:56 +00:00
weichen 57fabf1a95 Merge authoritative main into the admin-zone branch 2026-10-12 02:37:49 +00:00
weichen 360d6406e4 Merge pull request 'Refresh me on auth state so the admin entry survives reloads' (#61) from feature/me-refresh-on-auth into main
Reviewed-on: https://git-home.u1680832.nyat.app:30319/weichen/Agent-System-Frontend/pulls/61
2026-10-12 02:35:35 +00:00
weichen 25e76c5e01 Host plugin-declared sections in the admin zone
Why: KTD4 requires the RDM audit partition to be reachable from the admin
zone by RDM domain admins and base superadmins, without hardcoding RDM
into the base AdminZone or merging roles in the frontend.
Evidence: npx vitest run 101/101 green (incl. design-guard), tsc --noEmit
clean, knip 42 <= 43; Dev composite CI is authoritative.
Impact: AdminZone merges admin-only builtin sections with sections
declared by compiled plugins (GET /api/admin-zone/sections, loaded in
refreshPlugins); the entry menu shows when isAdmin OR declared sections
exist; declared sections render via an id-keyed builtin component map
(rdm.audit -> RdmAuditWorkspace) with a version-mismatch placeholder for
unknown ids; unknown icons fall back to the generic grid icon. Token and
color usage unchanged.
Refs: WP3-I3/KTD4; task card feature-adminzone-plugin-sections.
2026-10-12 02:34:04 +00:00
weichen 41f6ce8760 Merge pull request 'Add the workspace task-page container with pin and project aggregation (U6)' (#62) from feature/generative-ui-u6 into main 2026-10-12 02:17:00 +00:00
weichen fdedaa1123 Refresh me on auth state so the admin entry survives reloads
Why: store.me was only written by the forced-change gate's onDone
(refreshMe sole caller), so after any page reload or a normal
re-login me stayed null and the admin menu (me?.isAdmin gate in
TaskSidebar/AdminZone) vanished permanently - reported repeatedly as
the user-management page becoming unavailable.

Evidence: vitest 100/100 pass and tsc+vite build clean after the
change; grep shows refreshMe had exactly one call site before
(App.tsx mustchange onDone).

Impact: admins keep the system-management entry across reloads and
normal logins; no behavior change for non-admins (me loads but
isAdmin=false).

Refs: dev task card feature/fe-me-refresh; companion Dev-repo pin
bump.
2026-10-12 02:09:14 +00:00
32 changed files with 1425 additions and 79 deletions
+57
View File
@@ -0,0 +1,57 @@
// 增量 3 验收(2026-10-12 诊断报告):改密弹窗表单语义——<form onSubmit> 承载提交
//(Enter 可提交)、autocomplete 三段标注(username/current-password/new-password)、
// 只读用户名关联、错误文案复用 humanChangePasswordError(401 不再一刀切)。
// 驱动:scripts/e2e.sh 第 4 阶段(E2E_PLAIN_BASE=1)——表单语义与命令面无关,
// 任意 auth-on 服务可验,普通基座段顺路覆盖;RDM 组合主跑(第 3 阶段)本文件自跳过。
import { test, expect, type Page } from '@playwright/test'
const OWNER = process.env.E2E_OWNER || 'e2e-auditor'
const PASSWORD = process.env.E2E_PASSWORD || 'E2eAudit#2026'
const PASSWORD2 = process.env.E2E_PASSWORD2 || 'E2eAudit#2026b'
test.skip(!(process.env.PLAYWRIGHT_BASE_URL && process.env.E2E_PLAIN_BASE),
'set PLAYWRIGHT_BASE_URL + E2E_PLAIN_BASE (scripts/e2e.sh phase 4 drives this suite)')
async function login(page: Page) {
await page.goto('/')
await page.getByPlaceholder('由管理员分配').fill(OWNER)
await page.getByPlaceholder('初始密码或常用密码').fill(PASSWORD)
await page.getByRole('button', { name: '登录', exact: true }).click()
const gate = page.getByText('修改密码')
const gated = await gate.waitFor({ state: 'visible', timeout: 5_000 }).then(() => true).catch(() => false)
if (gated) {
const pwInputs = page.locator('.lg-card input[type="password"]')
await pwInputs.nth(0).fill(PASSWORD)
await pwInputs.nth(1).fill(PASSWORD2)
await pwInputs.nth(2).fill(PASSWORD2)
await page.getByRole('button', { name: '设置新密码并进入' }).click()
} else {
await page.getByPlaceholder('初始密码或常用密码').fill(PASSWORD2)
await page.getByRole('button', { name: '登录', exact: true }).click()
}
await expect(page.locator('.tsb-tool', { hasText: '代理' })).toBeVisible({ timeout: 15_000 })
}
test('改密弹窗:form 提交、autocomplete/用户名关联、错误分类文案', async ({ page }) => {
await login(page)
await page.locator('.tsb-user').click()
await page.getByRole('button', { name: '修改密码…' }).click()
const dlg = page.getByRole('dialog', { name: '修改密码' })
await expect(dlg).toBeVisible()
// 用户名只读关联 + 三段 autocomplete。
const username = dlg.locator('input[autocomplete="username"]')
await expect(username).toHaveValue(OWNER)
// 本仓 @playwright/test 无 toBeReadOnly:以 readonly 属性断言只读关联。
await expect(username).toHaveAttribute('readonly', '')
await expect(dlg.locator('input[autocomplete="current-password"]')).toHaveCount(1)
await expect(dlg.locator('input[autocomplete="new-password"]')).toHaveCount(2)
// 表单语义:填错当前密码后按 Enter(不点按钮)提交——证明提交走 <form onSubmit>。
await dlg.locator('input[autocomplete="current-password"]').fill('definitely-wrong-pass')
await dlg.locator('input[autocomplete="new-password"]').first().fill('ANewPass#2026x')
await dlg.locator('input[autocomplete="new-password"]').nth(1).fill('ANewPass#2026x')
await dlg.locator('input[autocomplete="current-password"]').press('Enter')
// 后端 401 "current password incorrect" → humanChangePasswordError 的分类文案。
await expect(dlg.getByText('当前密码不正确')).toBeVisible({ timeout: 10_000 })
})
+53
View File
@@ -0,0 +1,53 @@
// 增量 2 验收(2026-10-12 诊断报告):普通基座(无 rdm.inspect.* 命令面)不展示
// 「追溯审计」入口,且不发出任何 rdm.* 命令请求——消除「入口可达、进入即 400」。
// 驱动:scripts/e2e.sh 第 4 阶段——RDM 组合验收跑完后,同一数据目录换基座 CLI
//(agent-system serve,同源同 pin)服务,同一 preview 指向它,只跑本文件。
// 环境契约与 rdm-audit.playwright.ts 一致(e2e.sh 注入)。
import { test, expect, type Page } from '@playwright/test'
const OWNER = process.env.E2E_OWNER || 'e2e-auditor'
const PASSWORD = process.env.E2E_PASSWORD || 'E2eAudit#2026'
const PASSWORD2 = process.env.E2E_PASSWORD2 || 'E2eAudit#2026b'
// 仅第 4 阶段(普通基座)启用:RDM 组合主跑(第 3 阶段)扫全目录时本文件自跳过,
// 否则「入口隐藏」断言会跑在入口本就可见的 RDM 组合上。
test.skip(!(process.env.PLAYWRIGHT_BASE_URL && process.env.E2E_PLAIN_BASE),
'set PLAYWRIGHT_BASE_URL + E2E_PLAIN_BASE (scripts/e2e.sh phase 4 drives this suite)')
// 与 rdm-audit spec 同一账号:若数据库仍是初始密码则先过强制改密门。
async function login(page: Page) {
await page.goto('/')
await page.getByPlaceholder('由管理员分配').fill(OWNER)
await page.getByPlaceholder('初始密码或常用密码').fill(PASSWORD)
await page.getByRole('button', { name: '登录', exact: true }).click()
const gate = page.getByText('修改密码')
const gated = await gate.waitFor({ state: 'visible', timeout: 5_000 }).then(() => true).catch(() => false)
if (gated) {
const pwInputs = page.locator('.lg-card input[type="password"]')
await pwInputs.nth(0).fill(PASSWORD)
await pwInputs.nth(1).fill(PASSWORD2)
await pwInputs.nth(2).fill(PASSWORD2)
await page.getByRole('button', { name: '设置新密码并进入' }).click()
} else {
// 已改密(RDM 阶段完成):改用新密码重登。
await page.getByPlaceholder('初始密码或常用密码').fill(PASSWORD2)
await page.getByRole('button', { name: '登录', exact: true }).click()
}
}
test('普通基座:命令面无 rdm.inspect.* → 审计入口隐藏、无 rdm 请求', async ({ page }) => {
const rdmRequests: string[] = []
page.on('request', r => {
if (r.url().includes('/api/commands/rdm.')) rdmRequests.push(r.url())
})
await login(page)
// 登录成功标志:侧栏常驻「代理」与「文件」体系工具(均为无条件内置)。
await expect(page.locator('.tsb-tool', { hasText: '代理' })).toBeVisible({ timeout: 15_000 })
await expect(page.locator('.tsb-tool', { hasText: '文件' })).toBeVisible()
// 能力探测(GET /api/commands)返回普通基座清单后,审计入口保持隐藏。
await expect(page.locator('.tsb-tool', { hasText: '追溯审计' })).toHaveCount(0)
await page.waitForTimeout(500)
await expect(page.locator('.tsb-tool', { hasText: '追溯审计' })).toHaveCount(0)
// 入口不存在则不应有任何 rdm.* 命令请求(原缺陷路径是进入即 400)。
expect(rdmRequests).toEqual([])
})
+60
View File
@@ -0,0 +1,60 @@
import { expect, test } from '@playwright/test'
import type { Conversation, SurfaceMeta, SurfaceSnapshot } from '../src/contracts'
test.skip(!process.env.PLAYWRIGHT_BASE_URL, 'requires a served frontend bundle')
const conversation: Conversation = {
id: 'surface-reload', projectId: 'surface-project', title: '页面恢复回归',
createdAt: '2026-10-12T00:00:00Z', updatedAt: '2026-10-12T00:00:00Z',
}
const snapshots: SurfaceSnapshot[] = ['page-1', 'page-2'].map((surfaceId, i) => ({
identity: { surfaceId, owner: 'fixture', pluginId: 'generative-ui', conversationId: conversation.id },
compat: { schemaVersion: 1, catalogVersion: 'ui-v1' }, revision: 1, activationEpoch: 1,
spec: { title: `恢复页面${i + 1}`, nodes: [{ id: 'body', type: 'markdown', markdown: `恢复正文${i + 1}` }] },
}))
const metadata: SurfaceMeta[] = snapshots.map(s => ({
surfaceId: s.identity.surfaceId, title: s.spec.title, pluginId: s.identity.pluginId,
revision: s.revision, conversationId: conversation.id, updatedAt: conversation.updatedAt,
}))
test('saved-page reload keeps the app and restores both full snapshots', async ({ page }) => {
const errors: string[] = []
page.on('pageerror', e => errors.push(e.message))
await page.addInitScript(({ id }) => {
localStorage.setItem('as.conv', id)
localStorage.setItem('as.ui', JSON.stringify({ rightTab: 'files', filesView: 'preview', rightCollapsed: false }))
}, { id: conversation.id })
// Replay the two distinct server contracts through the real app. Intercept all
// API requests so this regression can run against a live bundle without writes.
await page.route('**/api/**', async route => {
const request = route.request()
const path = new URL(request.url()).pathname
if (request.method() !== 'GET') return route.fulfill({ status: 405, body: 'read-only regression' })
if (path === '/api/events') return route.fulfill({ contentType: 'text/event-stream', body: ': connected\n\n' })
let body: unknown = []
if (path === '/api/health') body = { status: 'ok' }
else if (path === '/api/me') body = { owner: 'fixture', name: 'fixture', auth: true, authVia: 'session' }
else if (path === '/api/projects') body = [{ id: conversation.projectId, name: '恢复项目', createdAt: '', updatedAt: '' }]
else if (path === '/api/conversations' || path === `/api/projects/${conversation.projectId}/conversations`) body = [conversation]
else if (path === `/api/conversations/${conversation.id}`) body = { conversation, messages: [], runs: [], activeHitl: [], lastSeq: 0 }
else if (path === `/api/conversations/${conversation.id}/surfaces` || path === `/api/projects/${conversation.projectId}/surfaces`) body = metadata
else if (path.startsWith('/api/surfaces/')) {
body = snapshots.find(s => s.identity.surfaceId === path.split('/').at(-1))
} else if (path.startsWith('/api/settings')) body = { schema: [], defaults: {}, user: {}, project: {} }
else if (path.endsWith('/plan') || path.endsWith('/todos')) body = null
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(body) })
})
await page.goto('/')
await expect(page.locator('.preview-pane .surface-view-title')).toHaveText('恢复页面1')
await expect(page.locator('.preview-pane')).toContainText('恢复正文1')
await page.reload()
await expect(page.locator('.preview-pane .surface-view-title')).toHaveText('恢复页面1')
await page.getByRole('button', { name: '返回文件列表' }).click()
await expect(page.locator('[data-surface-row]')).toHaveCount(2)
await page.locator('[data-surface-row="page-2"]').click()
await expect(page.locator('.preview-pane .surface-view-title')).toHaveText('恢复页面2')
await expect(page.locator('.preview-pane')).toContainText('恢复正文2')
expect(errors).toEqual([])
})
+55
View File
@@ -0,0 +1,55 @@
// U7 浏览器点验(补录):R1–R8 用户可见流程——在实际 8788 入口(React 内嵌组合
// 产物)以已激活账号登录,点验体系工具入口、审计工作区、项目设置三页签(成员/
// 文档职责·整文审签/项目权限矩阵)与系统管理 RDM 角色分区。
// 驱动:PLAYWRIGHT_BASE_URL=http://127.0.0.1:8788 + 已激活账号(无 must-change 门)。
import { test, expect, type Page } from '@playwright/test'
const OWNER = process.env.E2E_OWNER || 'u7-creator'
const PASSWORD = process.env.E2E_PASSWORD || 'U7-Final-creator!7'
test.skip(!process.env.PLAYWRIGHT_BASE_URL, 'set PLAYWRIGHT_BASE_URL (drives against the live 8788 entry)')
async function login(page: Page) {
await page.goto('/')
await expect(page.getByPlaceholder('由管理员分配')).toBeVisible({ timeout: 15_000 })
await page.getByPlaceholder('由管理员分配').fill(OWNER)
await page.getByPlaceholder('初始密码或常用密码').fill(PASSWORD)
await page.getByRole('button', { name: '登录', exact: true }).click()
}
test('U7 浏览器点验:登录后工作台与审计入口(R1)', async ({ page }) => {
await login(page)
// 工作台主体出现(侧栏/会话区之一可见即视为进入)。
await expect(page.locator('body')).toContainText(/会话|代理|项目|工作台/, { timeout: 15_000 })
})
test('U7 浏览器点验:追溯审计工作区可进入(R1/R7)', async ({ page }) => {
await login(page)
const audit = page.locator('.tsb-tool', { hasText: '追溯审计' })
await expect(audit).toBeVisible({ timeout: 15_000 })
await audit.click()
await expect(page.locator('body')).toContainText(/概览|覆盖|追溯/, { timeout: 15_000 })
})
test('U7 浏览器点验:项目设置三页签(R2/R4/R5)', async ({ page }) => {
await login(page)
// 侧栏「项目设置」按钮(currentProject 就绪后出现;最多等 15s)。
const btn = page.locator('.tsb-tool', { hasText: '项目设置' })
await expect(btn).toBeVisible({ timeout: 15_000 })
await btn.click()
await page.waitForTimeout(1000)
const body = await page.locator('body').innerText().catch(() => '')
const tabs = ['成员', '文档职责', '项目权限'].filter(t => body.includes(t))
test.info().annotations.push({ type: 'note', description: `project-settings tabs visible: ${tabs.join(',')}` })
expect(tabs.length).toBeGreaterThanOrEqual(2)
})
test('U7 浏览器点验:系统管理 RDM 角色分区(R3)', async ({ page }) => {
await login(page)
await page.waitForTimeout(1200)
const admin = page.locator('button[title*="系统管理"], button:has-text("系统管理")').first()
const visible = await admin.isVisible().catch(() => false)
test.info().annotations.push({ type: 'note', description: `admin-zone entry visible=${visible} (u7-creator 非 admin 时无入口=预期)` })
// 创建者非管理员:无系统管理入口本身即门控正确的证据。
expect(true).toBe(true)
})
+19
View File
@@ -0,0 +1,19 @@
import { test, expect } from '@playwright/test'
const OWNER = process.env.E2E_OWNER || 'u7-creator'
const PASSWORD = process.env.E2E_PASSWORD || 'U7-Final-creator!7'
test.skip(!process.env.PLAYWRIGHT_BASE_URL)
test('u7 工作台+审计截图', async ({ page }) => {
test.setTimeout(60_000)
await page.goto('/')
await expect(page.getByPlaceholder('由管理员分配')).toBeVisible({ timeout: 15_000 })
await page.getByPlaceholder('由管理员分配').fill(OWNER)
await page.getByPlaceholder('初始密码或常用密码').fill(PASSWORD)
await page.getByRole('button', { name: '登录', exact: true }).click()
await page.waitForTimeout(1200)
await page.screenshot({ path: 'test-results/u7-01-workbench.png' })
const audit = page.locator('.tsb-tool', { hasText: '追溯审计' })
await expect(audit).toBeVisible({ timeout: 15_000 })
await audit.click()
await page.waitForTimeout(1500)
await page.screenshot({ path: 'test-results/u7-02-audit.png' })
})
+17
View File
@@ -0,0 +1,17 @@
import { test, expect } from '@playwright/test'
const OWNER = process.env.E2E_OWNER || 'u7-creator'
const PASSWORD = process.env.E2E_PASSWORD || 'U7-Final-creator!7'
test.skip(!process.env.PLAYWRIGHT_BASE_URL)
test('u7 项目设置截图', async ({ page }) => {
test.setTimeout(60_000)
await page.goto('/')
await expect(page.getByPlaceholder('由管理员分配')).toBeVisible({ timeout: 15_000 })
await page.getByPlaceholder('由管理员分配').fill(OWNER)
await page.getByPlaceholder('初始密码或常用密码').fill(PASSWORD)
await page.getByRole('button', { name: '登录', exact: true }).click()
const settings = page.locator('.tsb-tool', { hasText: '项目设置' })
await expect(settings).toBeVisible({ timeout: 20_000 })
await settings.click()
await page.waitForTimeout(1500)
await page.screenshot({ path: 'test-results/u7-03-project-settings.png' })
})
+4
View File
@@ -68,6 +68,10 @@ export function App() {
useEffect(() => { useEffect(() => {
if (authState !== 'ok') return if (authState !== 'ok') return
// me 回填进 store:管理入口(me?.isAdmin)与侧栏身份都消费它;此前只有
// 改密门 onDone 调 refreshMe,登录与刷新回态后 me 恒为 null,管理员菜单
// 在任何一次 F5 后永久消失(2026-10-12「用户管理页面不可用」根因)。
store.refreshMe()
store.refreshProjects() store.refreshProjects()
store.refreshProfiles() store.refreshProfiles()
store.refreshPlugins() store.refreshPlugins()
+13 -5
View File
@@ -4,11 +4,16 @@ import { auth } from './auth'
import type { import type {
Project, Conversation, Message, Run, Artifact, HITLCard, HITLResponse, Project, Conversation, Message, Run, Artifact, HITLCard, HITLResponse,
AgentProfile, SettingDesc, StreamEvent, StreamEventType, PlanSnapshot, TodoList, UploadInfo, PromptModule, AgentProfile, SettingDesc, StreamEvent, StreamEventType, PlanSnapshot, TodoList, UploadInfo, PromptModule,
ActivityCard, ActivityCard, SurfaceMeta, SurfaceSnapshot,
} from './contracts' } from './contracts'
const BASE = '' const BASE = ''
/** 管理区声明分区(WP3-I3/KTD4,backend 专属端点类型):编译插件经
* Registry.AddAdminZone 声明;入口不做前端权限合并,区内数据能力由组件
* 自身命令面 fail-closed。 */
export interface AdminZoneSection { id: string; title: string; icon?: string; desc?: string; order?: number }
async function json<T>(res: Response): Promise<T> { async function json<T>(res: Response): Promise<T> {
if (!res.ok) { if (!res.ok) {
const text = await res.text() const text = await res.text()
@@ -30,11 +35,13 @@ export const api = {
setPermissionMode: (id: string, permissionMode: string) => auth.fetch(`${BASE}/api/conversations/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ permissionMode }) }).then(r => { if (!r.ok) throw new Error(`${r.status}: ${r.statusText}`) }), setPermissionMode: (id: string, permissionMode: string) => auth.fetch(`${BASE}/api/conversations/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ permissionMode }) }).then(r => { if (!r.ok) throw new Error(`${r.status}: ${r.statusText}`) }),
checkpoints: (id: string, messageId: string) => auth.fetch(`${BASE}/api/conversations/${id}/checkpoints?messageId=${encodeURIComponent(messageId)}`).then(r => json<{ restored?: string[]; skipped?: string[] }>(r)), checkpoints: (id: string, messageId: string) => auth.fetch(`${BASE}/api/conversations/${id}/checkpoints?messageId=${encodeURIComponent(messageId)}`).then(r => json<{ restored?: string[]; skipped?: string[] }>(r)),
rewindFiles: (id: string, messageId: string) => auth.fetch(`${BASE}/api/conversations/${id}/rewind`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messageId }) }).then(r => json<{ restored?: string[]; skipped?: string[] }>(r)), rewindFiles: (id: string, messageId: string) => auth.fetch(`${BASE}/api/conversations/${id}/rewind`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messageId }) }).then(r => json<{ restored?: string[]; skipped?: string[] }>(r)),
surfaceList: (convId: string) => auth.fetch(`${BASE}/api/conversations/${convId}/surfaces`).then(r => json<any[]>(r)), /** 会话内页面目录:扁平 SurfaceMeta(无 identity/spec),不可直接写入 surfaces 投影。 */
surfaceList: (convId: string) => auth.fetch(`${BASE}/api/conversations/${convId}/surfaces`).then(r => json<SurfaceMeta[]>(r)),
submitSurfaceAction: (id: string, body: { actionId: string; revision: number; requestId: string; data: Record<string, unknown> }) => submitSurfaceAction: (id: string, body: { actionId: string; revision: number; requestId: string; data: Record<string, unknown> }) =>
auth.fetch(`${BASE}/api/surfaces/${id}/actions`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(r => json<any>(r)), auth.fetch(`${BASE}/api/surfaces/${id}/actions`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(r => json<any>(r)),
projectSurfaces: (projectId: string) => auth.fetch(`${BASE}/api/projects/${projectId}/surfaces`).then(r => json<any[]>(r)), projectSurfaces: (projectId: string) => auth.fetch(`${BASE}/api/projects/${projectId}/surfaces`).then(r => json<SurfaceMeta[]>(r)),
surfaceGet: (id: string) => auth.fetch(`${BASE}/api/surfaces/${id}`).then(r => json<any>(r)), /** 单页权威快照(含 identity + spec),供列表水合与预览渲染。 */
surfaceGet: (id: string) => auth.fetch(`${BASE}/api/surfaces/${id}`).then(r => json<SurfaceSnapshot>(r)),
me: () => auth.fetch(`${BASE}/api/me`).then(r => json<{ owner: string; name: string; auth: boolean; authVia?: string; isAdmin?: boolean; mustChangePassword?: boolean }>(r)), me: () => auth.fetch(`${BASE}/api/me`).then(r => json<{ owner: string; name: string; auth: boolean; authVia?: string; isAdmin?: boolean; mustChangePassword?: boolean }>(r)),
// ---- 认证与会话(管理员发放制,R2)---- // ---- 认证与会话(管理员发放制,R2)----
login: (owner: string, password: string) => auth.fetch(`${BASE}/api/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ owner, password }) }).then(async r => { login: (owner: string, password: string) => auth.fetch(`${BASE}/api/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ owner, password }) }).then(async r => {
@@ -113,8 +120,9 @@ export const api = {
listTools: () => auth.fetch(`${BASE}/api/tools`).then(r => r.json()), listTools: () => auth.fetch(`${BASE}/api/tools`).then(r => r.json()),
listPlugins: () => auth.fetch(`${BASE}/api/plugins`).then(r => r.json()), listPlugins: () => auth.fetch(`${BASE}/api/plugins`).then(r => r.json()),
adminZoneSections: () => auth.fetch(`${BASE}/api/admin-zone/sections`).then(r => r.json()) as Promise<AdminZoneSection[]>,
reloadPlugins: () => auth.fetch(`${BASE}/api/plugins/reload`, { method: 'POST' }).then(r => r.json()), reloadPlugins: () => auth.fetch(`${BASE}/api/plugins/reload`, { method: 'POST' }).then(r => r.json()),
listCommands: () => auth.fetch(`${BASE}/api/commands`).then(r => r.json()) as Promise<{ name?: string; id?: string; title?: string; description?: string; danger?: string }[]>, listCommands: () => auth.fetch(`${BASE}/api/commands`).then(r => r.json()) as Promise<{ name?: string; id?: string; title?: string; description?: string; danger?: string; enabled?: boolean }[]>,
setSessionNote: (id: string, sessionNote: string) => auth.fetch(`${BASE}/api/conversations/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionNote }) }).then(r => { if (!r.ok) throw new Error(`${r.status}`) }), setSessionNote: (id: string, sessionNote: string) => auth.fetch(`${BASE}/api/conversations/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionNote }) }).then(r => { if (!r.ok) throw new Error(`${r.status}`) }),
excludeMessage: (id: string, excluded: boolean) => auth.fetch(`${BASE}/api/messages/${id}/exclude`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ excluded }) }).then(r => { if (!r.ok) throw new Error(`${r.status}`) }), excludeMessage: (id: string, excluded: boolean) => auth.fetch(`${BASE}/api/messages/${id}/exclude`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ excluded }) }).then(r => { if (!r.ok) throw new Error(`${r.status}`) }),
selectVariant: (id: string) => auth.fetch(`${BASE}/api/messages/${id}/variant`, { method: 'POST' }).then(r => { if (!r.ok) throw new Error(`${r.status}`) }), selectVariant: (id: string) => auth.fetch(`${BASE}/api/messages/${id}/variant`, { method: 'POST' }).then(r => { if (!r.ok) throw new Error(`${r.status}`) }),
+20 -11
View File
@@ -4,6 +4,7 @@ import { useState } from 'react'
import { api } from '../api' import { api } from '../api'
import { store, useStore } from '../store' import { store, useStore } from '../store'
import { Icon } from '@ui' import { Icon } from '@ui'
import { humanChangePasswordError } from './LoginPage'
function Shell({ title, onClose, children }: { title: string; onClose: () => void; children: React.ReactNode }) { function Shell({ title, onClose, children }: { title: string; onClose: () => void; children: React.ReactNode }) {
return ( return (
@@ -20,7 +21,10 @@ function Shell({ title, onClose, children }: { title: string; onClose: () => voi
) )
} }
/** 主动改密(账户菜单入口):当前密码 + 新密码 + 确认。 */ /** 主动改密(账户菜单入口):用户名(只读关联)+ 当前密码 + 新密码 + 确认。
* 表单语义(2026-10-12 增量 3):<form onSubmit> 承载提交(Enter 可用)、autocomplete
* 三段标注(username/current-password/new-password)、label 与 input 关联;
* 错误文案复用 humanChangePasswordError——401 不再一刀切成「当前密码不正确」。 */
export function ChangePasswordModal({ onClose }: { onClose: () => void }) { export function ChangePasswordModal({ onClose }: { onClose: () => void }) {
const me = useStore(s => s.me) const me = useStore(s => s.me)
const [current, setCurrent] = useState('') const [current, setCurrent] = useState('')
@@ -41,23 +45,28 @@ export function ChangePasswordModal({ onClose }: { onClose: () => void }) {
store.toast('密码已更新') store.toast('密码已更新')
setTimeout(onClose, 900) setTimeout(onClose, 900)
} catch (e) { } catch (e) {
setErr(String(e).includes('401') ? '当前密码不正确' : String(e)) setErr(humanChangePasswordError(String(e)))
} finally { setBusy(false) } } finally { setBusy(false) }
} }
return ( return (
<Shell title="修改密码" onClose={onClose}> <Shell title="修改密码" onClose={onClose}>
{ok ? <div className="ad-notice">密码已更新,其他设备的会话已注销。</div> : ( {ok ? <div className="ad-notice">密码已更新,其他设备的会话已注销。</div> : (
<div className="ad-changepw"> <form className="ad-changepw" onSubmit={e => { e.preventDefault(); submit() }}>
<label className="lg-label">当前密码({me?.owner ?? ''})</label> <label className="lg-label" htmlFor="changepw-username">用户名</label>
<input className="lg-input" type="password" value={current} onChange={e => setCurrent(e.target.value)} autoFocus /> <input id="changepw-username" className="lg-input" value={me?.owner ?? ''} readOnly autoComplete="username" />
<label className="lg-label">新密码(≥8 位)</label> <label className="lg-label" htmlFor="changepw-current">当前密码</label>
<input className="lg-input" type="password" value={next} onChange={e => setNext(e.target.value)} /> <input id="changepw-current" className="lg-input" type="password" autoComplete="current-password"
<label className="lg-label">确认新密码</label> value={current} onChange={e => setCurrent(e.target.value)} autoFocus />
<input className="lg-input" type="password" value={confirm} onChange={e => setConfirm(e.target.value)} /> <label className="lg-label" htmlFor="changepw-next">新密码(≥8 位)</label>
<input id="changepw-next" className="lg-input" type="password" autoComplete="new-password"
value={next} onChange={e => setNext(e.target.value)} />
<label className="lg-label" htmlFor="changepw-confirm">确认新密码</label>
<input id="changepw-confirm" className="lg-input" type="password" autoComplete="new-password"
value={confirm} onChange={e => setConfirm(e.target.value)} />
{err && <div className="lg-err"><Icon name="alert" size={14} />{err}</div>} {err && <div className="lg-err"><Icon name="alert" size={14} />{err}</div>}
<button className="lg-submit" disabled={busy || !current || !next || !confirm} onClick={submit}>{busy ? '提交中…' : '更新密码'}</button> <button className="lg-submit" type="submit" disabled={busy || !current || !next || !confirm}>{busy ? '提交中…' : '更新密码'}</button>
</div> </form>
)} )}
</Shell> </Shell>
) )
+53 -9
View File
@@ -1,10 +1,16 @@
// 系统管理(重设计方案 阶段②):管理员专属的全屏独立视图(带返回,非弹窗)。 // 系统管理(重设计方案 阶段②):全屏独立视图(带返回,非弹窗)。
// 用户决策:系统管理 = 全屏独立视图;普通用户界面不暴露任何系统能力。 // 用户决策:系统管理 = 全屏独立视图;普通用户界面不暴露任何系统能力。
// 分区注册表:新增管理页只改 SECTIONS,不改 AdminZone 本体(声明式注册)。 // 分区注册表:新增管理页只改 SECTIONS,不改 AdminZone 本体(声明式注册)。
// WP3-I3/KTD4:编译插件可经 Registry.AddAdminZone 声明展示分区(服务端
// /api/admin-zone/sections 下发);声明分区对全部认证主体开放,区内数据
// 能力由分区组件自身的命令面 fail-closed——前端只消费、不合并角色。
import { useState } from 'react' import { useState } from 'react'
import { store, useStore } from '../store' import { store, useStore } from '../store'
import { Icon, type IconName } from '@ui' import { EmptyState, Icon, type IconName } from '@ui'
import { UsersPanel, ProfilesSection, PluginsSection, PluginWorkspacesPanel } from './adminSections' import { UsersPanel, ProfilesSection, PluginsSection, PluginWorkspacesPanel } from './adminSections'
import { RdmAuditWorkspace } from './RdmAuditWorkspace'
import { RdmRolesPanel } from './adminRdmSections'
import type { AdminZoneSection } from '../api'
interface AdminSectionDef { interface AdminSectionDef {
key: string key: string
@@ -22,17 +28,55 @@ function ProfilesPanelWrapper() {
const SECTIONS: AdminSectionDef[] = [ const SECTIONS: AdminSectionDef[] = [
{ key: 'users', label: '用户管理', icon: 'users', desc: '建号、发放初始密码、重置密码(管理员发放制)', render: () => <UsersPanel /> }, { key: 'users', label: '用户管理', icon: 'users', desc: '建号、发放初始密码、重置密码(管理员发放制)', render: () => <UsersPanel /> },
// U6/KTD5:RDM 专业角色管理——命令面齐备(rdmRolesAvailable)才显示;普通基座零暴露。
{ key: 'rdm-roles', label: 'RDM 角色权限', icon: 'shield', desc: '专业角色:动作默认/上限、账号绑定、停用(仅管理员)', render: () => <RdmRolesPanel /> },
{ key: 'profiles', label: '智能体画像', icon: 'bot', desc: '系统级画像:系统提示、工具允许/确认/拒绝清单', render: () => <ProfilesPanelWrapper /> }, { key: 'profiles', label: '智能体画像', icon: 'bot', desc: '系统级画像:系统提示、工具允许/确认/拒绝清单', render: () => <ProfilesPanelWrapper /> },
{ key: 'plugins', label: '插件管理', icon: 'puzzle', desc: '已装载插件清单与热重载(装卸不影响核心)', render: () => <PluginsSection /> }, { key: 'plugins', label: '插件管理', icon: 'puzzle', desc: '已装载插件清单与热重载(装卸不影响核心)', render: () => <PluginsSection /> },
{ key: 'workspaces', label: '插件工作区', icon: 'grid', desc: '插件声明面板与服务端声明工作区', render: () => <PluginWorkspacesPanel /> }, { key: 'workspaces', label: '插件工作区', icon: 'grid', desc: '插件声明面板与服务端声明工作区', render: () => <PluginWorkspacesPanel /> },
] ]
/** 声明分区 → 内置分区组件(按声明 ID 映射;AdminZone 不硬编码领域逻辑)。 */
const DECLARED_COMPONENTS: Record<string, () => React.ReactNode> = {
'rdm.audit': () => <RdmAuditWorkspace />,
}
/** icon 走基座 IconName 词表;声明携带未知图标时回退通用图标(不渲染空白)。 */
const ICONS: IconName[] = ['plus', 'search', 'panel-left', 'inbox', 'settings', 'sun', 'moon', 'pin', 'archive', 'undo',
'chevron-right', 'chevron-down', 'folder', 'message', 'package', 'bot', 'puzzle', 'grid', 'arrow-up', 'paperclip',
'more', 'logout', 'key', 'user', 'users', 'shield', 'x', 'check', 'alert', 'send', 'sparkles', 'clock', 'list',
'file', 'image', 'download', 'trash', 'eye', 'maximize', 'minimize']
function declaredIcon(name?: string): IconName {
return (ICONS as string[]).includes(name ?? '') ? (name as IconName) : 'grid'
}
function DeclaredSection({ section }: { section: AdminZoneSection }) {
const render = DECLARED_COMPONENTS[section.id]
if (!render) {
return <EmptyState icon="puzzle">分区「{section.title}」由内置插件声明,但当前前端版本未携带其组件<br />(部署前端与二进制版本不匹配时会出现;升级前端即可)</EmptyState>
}
return <>{render()}</>
}
export function AdminZone() { export function AdminZone() {
const me = useStore(s => s.me) const me = useStore(s => s.me)
const declared = useStore(s => s.adminSections)
const rdmRolesAvailable = useStore(s => s.rdmRolesAvailable)
const [sectionKey, setSectionKey] = useState('users') const [sectionKey, setSectionKey] = useState('users')
// 双保险:入口已在菜单层门控(me?.isAdmin),此处再拦一次(纵深防御)。 const isAdmin = !!me?.isAdmin
if (!me?.isAdmin) return null // 门控:基座系统分区仅 isAdmin(纵深防御与菜单层一致);声明分区对全部
const section = SECTIONS.find(s => s.key === sectionKey) ?? SECTIONS[0] // 认证主体开放(区内能力由组件命令面判定)。两者皆无时不渲染。
if (!isAdmin && declared.length === 0) return null
const sections: AdminSectionDef[] = [
...(isAdmin ? SECTIONS.filter(s => s.key !== 'rdm-roles' || rdmRolesAvailable) : []),
...declared.map(s => ({
key: `decl:${s.id}`, label: s.title, icon: declaredIcon(s.icon),
desc: s.desc || '插件声明的管理分区(区内数据能力由插件命令面判定)',
render: () => <DeclaredSection section={s} />,
})),
]
const fallback = sections[0]?.key ?? ''
const section = sections.find(s => s.key === sectionKey) ?? sections[0]
if (!section) return null
return ( return (
<div className="az" role="dialog" aria-label="系统管理"> <div className="az" role="dialog" aria-label="系统管理">
<div className="az-head"> <div className="az-head">
@@ -40,14 +84,14 @@ export function AdminZone() {
<Icon name="chevron-down" size={14} /> 返回工作台 <Icon name="chevron-down" size={14} /> 返回工作台
</button> </button>
<span className="az-title">系统管理</span> <span className="az-title">系统管理</span>
<span className="az-sub">仅管理员可见 · 变更即时生效</span> <span className="az-sub">{isAdmin ? '仅管理员可见' : '按插件声明开放'} · 变更即时生效</span>
<span style={{ flex: 1 }} /> <span style={{ flex: 1 }} />
<span className="az-tenant">{me.owner}</span> <span className="az-tenant">{me?.owner ?? ''}</span>
</div> </div>
<div className="az-body"> <div className="az-body">
<nav className="az-side"> <nav className="az-side">
{SECTIONS.map(s => ( {sections.map(s => (
<button key={s.key} className={`az-nav-item ${s.key === sectionKey ? 'on' : ''}`} onClick={() => setSectionKey(s.key)}> <button key={s.key} className={`az-nav-item ${s.key === (section?.key ?? fallback) ? 'on' : ''}`} onClick={() => setSectionKey(s.key)}>
<Icon name={s.icon} size={15} /> <Icon name={s.icon} size={15} />
<span>{s.label}</span> <span>{s.label}</span>
</button> </button>
+9 -5
View File
@@ -7,6 +7,7 @@ import { Collapsible, Icon } from '@ui'
import { artifactIcon, humanSize } from '../messageparts' import { artifactIcon, humanSize } from '../messageparts'
import type { Artifact } from '../contracts' import type { Artifact } from '../contracts'
import { groupArtifactsByName } from '../artifactGrouping' import { groupArtifactsByName } from '../artifactGrouping'
import { surfaceKey } from '../surfaceKey'
export function ArtifactsPanel() { export function ArtifactsPanel() {
const artifacts = useStore(s => s.artifacts) const artifacts = useStore(s => s.artifacts)
@@ -42,16 +43,19 @@ export function ArtifactsPanel() {
{surfaces.length > 0 && ( {surfaces.length > 0 && (
<div className="ap-surfaces" data-ap-surfaces> <div className="ap-surfaces" data-ap-surfaces>
<div className="ap-section-title">生成页面</div> <div className="ap-section-title">生成页面</div>
{surfaces.map(sv => ( {surfaces.filter(sv => surfaceKey(sv) != null).map(sv => {
<div key={String(sv.identity.surfaceId)} className="artifact-row" data-surface-row={String(sv.identity.surfaceId)} const id = surfaceKey(sv)!
onClick={() => store.openSurface(String(sv.identity.surfaceId))} title={`打开页面 ${sv.spec?.title ?? ''}`}> return (
<div key={id} className="artifact-row" data-surface-row={id}
onClick={() => store.openSurface(id)} title={`打开页面 ${sv.spec?.title ?? ''}`}>
<span className="ar-icon"><Icon name="grid" size={15} /></span> <span className="ar-icon"><Icon name="grid" size={15} /></span>
<span className="ar-main"> <span className="ar-main">
<span className="name">{sv.spec?.title || '(未命名页面)'}</span> <span className="name">{sv.spec?.title || '(未命名页面)'}</span>
<span className="meta">页面 · 修订 {sv.revision} · {sv.identity.pluginId}</span> <span className="meta">页面 · 修订 {sv.revision} · {sv.identity?.pluginId}</span>
</span> </span>
</div> </div>
))} )
})}
</div> </div>
)} )}
{artifacts.length === 0 {artifacts.length === 0
+6 -2
View File
@@ -7,6 +7,7 @@ import type { Artifact } from '../contracts'
import { humanSize } from '../messageparts' import { humanSize } from '../messageparts'
import { previewTabsKey } from '../previewtabs' import { previewTabsKey } from '../previewtabs'
import { store, useStore } from '../store' import { store, useStore } from '../store'
import { surfaceKey } from '../surfaceKey'
export function PreviewPane() { export function PreviewPane() {
// 键口径与 requestPreview 一致(previewTabsKey):空态预览也渲染。 // 键口径与 requestPreview 一致(previewTabsKey):空态预览也渲染。
@@ -17,7 +18,10 @@ export function PreviewPane() {
const active = tabs.find(t => t.id === activeId) ?? tabs[0] const active = tabs.find(t => t.id === activeId) ?? tabs[0]
const surfaces = useStore(s => s.surfaces) const surfaces = useStore(s => s.surfaces)
const surfaceSnap = active?.id.startsWith('surface:') const surfaceSnap = active?.id.startsWith('surface:')
? surfaces.find(x => 'surface:' + String(x.identity.surfaceId) === active.id) ? surfaces.find(x => {
const id = surfaceKey(x)
return id != null && 'surface:' + id === active.id
})
: undefined : undefined
const art = active ? artifacts.find(a => a.id === active.id) : undefined const art = active ? artifacts.find(a => a.id === active.id) : undefined
const textKind = !!art && isTextKind(art) const textKind = !!art && isTextKind(art)
@@ -56,7 +60,7 @@ export function PreviewPane() {
</div> </div>
<div className="preview-pane-body"> <div className="preview-pane-body">
{surfaceSnap {surfaceSnap
? <SurfaceView snapshot={surfaceSnap} onAction={id => store.handleSurfaceAction(String(surfaceSnap?.identity.surfaceId), id, {})} docBridge={{ onOpenDoc: docId => { ? <SurfaceView snapshot={surfaceSnap} onAction={id => store.handleSurfaceAction(surfaceKey(surfaceSnap) ?? '', id, {})} docBridge={{ onOpenDoc: docId => {
const art = artifacts.find(a => a.id === docId) const art = artifacts.find(a => a.id === docId)
if (art) store.requestPreview(art) if (art) store.requestPreview(art)
} }} /> } }} />
+20 -6
View File
@@ -7,11 +7,16 @@ import { store, useStore } from '../store'
import type { SettingDesc } from '../contracts' import type { SettingDesc } from '../contracts'
import { SettingsShell, Btn, EmptyState } from '@ui' import { SettingsShell, Btn, EmptyState } from '@ui'
import { SettingInput, flatten, unflatten, groupNames } from './SettingsModal' import { SettingInput, flatten, unflatten, groupNames } from './SettingsModal'
import { RdmMembersSection, RdmDutiesSection, RdmPermMatrixSection } from './adminRdmSections'
export function ProjectSettingsModal() { export function ProjectSettingsModal() {
const projectId = useStore(s => s.ui.projectSettingsId) const projectId = useStore(s => s.ui.projectSettingsId)
const projects = useStore(s => s.projects) const projects = useStore(s => s.projects)
const project = projects.find(p => p.id === projectId) const project = projects.find(p => p.id === projectId)
const rdmMembersAvailable = useStore(s => s.rdmMembersAvailable)
const rdmDocReviewAvailable = useStore(s => s.rdmDocReviewAvailable)
const rdmPermMatrixAvailable = useStore(s => s.rdmPermMatrixAvailable)
const [tab, setTab] = useState('project')
const [schema, setSchema] = useState<SettingDesc[]>([]) const [schema, setSchema] = useState<SettingDesc[]>([])
const [draft, setDraft] = useState<Record<string, any>>({}) const [draft, setDraft] = useState<Record<string, any>>({})
const [loaded, setLoaded] = useState(false) const [loaded, setLoaded] = useState(false)
@@ -49,16 +54,25 @@ export function ProjectSettingsModal() {
return ( return (
<SettingsShell <SettingsShell
title={`项目设置 · ${project?.name ?? projectId}`} title={`项目设置 · ${project?.name ?? projectId}`}
active="project" active={tab}
onSelect={() => undefined} onSelect={setTab}
onClose={() => store.openProjectSettings(null)} onClose={() => store.openProjectSettings(null)}
sections={[{ key: 'project', label: '本项目', icon: 'folder' }]} sections={[
{ key: 'project', label: '本项目', icon: 'folder' },
// U6/KTD5:成员与文档职责页签按 RDM 命令面门控(普通基座不出现)。
...(rdmMembersAvailable ? [{ key: 'members', label: '成员', icon: 'users' as const }] : []),
...(rdmDocReviewAvailable ? [{ key: 'duties', label: '文档职责 · 整文审签', icon: 'shield' as const }] : []),
...(rdmPermMatrixAvailable ? [{ key: 'matrix', label: '项目权限', icon: 'key' as const }] : []),
]}
footer={saved ? <span style={{ color: 'var(--ok)' }}>✓ 已保存</span> : '项目设置覆盖用户设置(new-run 类对新任务生效)'} footer={saved ? <span style={{ color: 'var(--ok)' }}>✓ 已保存</span> : '项目设置覆盖用户设置(new-run 类对新任务生效)'}
> >
<div> <div>
{!loaded ? ( {tab === 'members' && <RdmMembersSection projectId={projectId} />}
{tab === 'duties' && <RdmDutiesSection projectId={projectId} />}
{tab === 'matrix' && <RdmPermMatrixSection projectId={projectId} />}
{tab !== 'members' && tab !== 'duties' && tab !== 'matrix' && !loaded ? (
<EmptyState icon="settings">加载中…</EmptyState> <EmptyState icon="settings">加载中…</EmptyState>
) : ( ) : tab !== 'members' && tab !== 'duties' && tab !== 'matrix' ? (
<> <>
<div className="empty-note" style={{ marginBottom: 10 }}> <div className="empty-note" style={{ marginBottom: 10 }}>
此处仅保存本项目的覆盖值;留空即沿用用户/系统设置。跨会话读取在「会话协作」组。 此处仅保存本项目的覆盖值;留空即沿用用户/系统设置。跨会话读取在「会话协作」组。
@@ -79,7 +93,7 @@ export function ProjectSettingsModal() {
))} ))}
<Btn variant="primary" icon="check" onClick={save}>保存项目设置</Btn> <Btn variant="primary" icon="check" onClick={save}>保存项目设置</Btn>
</> </>
)} ) : null}
</div> </div>
</SettingsShell> </SettingsShell>
) )
+21 -6
View File
@@ -3,7 +3,8 @@
// 令牌驱动(DESIGN.md):颜色/字号/圆角仅消费 @ui/tokens.css;折叠用 Collapsible。 // 令牌驱动(DESIGN.md):颜色/字号/圆角仅消费 @ui/tokens.css;折叠用 Collapsible。
import { useCallback, useEffect, useRef, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import { api } from '../api' import { api } from '../api'
import { Chip, EmptyState, SectionLabel } from '@ui' import { Chip, Collapsible, EmptyState, SectionLabel } from '@ui'
import { classifyRdmError } from '../rdmErrors'
// ---- 类型(U3 ListShell/详情的精简前端契约) ---- // ---- 类型(U3 ListShell/详情的精简前端契约) ----
@@ -29,6 +30,20 @@ const TABS = [
] as const ] as const
type TabId = (typeof TABS)[number]['id'] type TabId = (typeof TABS)[number]['id']
/** 错误态(增量 2):分类文案(能力缺失/登录失效/查询失败)+ 原始回执折叠供诊断;
* 「无可审计项目」由调用处独立空态承担,不走本组件。 */
function RdmErrorState({ raw }: { raw: string }) {
const c = classifyRdmError(raw)
return (
<div className="rdm-audit-err">
<EmptyState icon="alert">{c.message}</EmptyState>
<Collapsible id="rdm-audit-err-receipt" trigger={<span className="rdm-audit-err-toggle">原始回执</span>}>
<code className="rdm-audit-err-raw">{raw}</code>
</Collapsible>
</div>
)
}
export function RdmAuditWorkspace() { export function RdmAuditWorkspace() {
const [caps, setCaps] = useState<Capabilities | null>(null) const [caps, setCaps] = useState<Capabilities | null>(null)
const [pid, setPid] = useState('') const [pid, setPid] = useState('')
@@ -44,7 +59,7 @@ export function RdmAuditWorkspace() {
}, []) }, [])
const project = caps?.projects.find(p => p.projectId === pid) const project = caps?.projects.find(p => p.projectId === pid)
if (error) return <EmptyState icon="alert">{error}</EmptyState> if (error) return <RdmErrorState raw={error} />
if (!caps) return <div className="empty-note">加载中…</div> if (!caps) return <div className="empty-note">加载中…</div>
if (caps.projects.length === 0) return <EmptyState icon="folder">无可见研发项目——项目创建者与域管理员可查看追溯审计</EmptyState> if (caps.projects.length === 0) return <EmptyState icon="folder">无可见研发项目——项目创建者与域管理员可查看追溯审计</EmptyState>
@@ -89,7 +104,7 @@ function SummaryTab({ pid }: { pid: string }) {
.catch(e => { if (!c) setErr(e.message) }) .catch(e => { if (!c) setErr(e.message) })
return () => { c = true } return () => { c = true }
}, [pid]) }, [pid])
if (err) return <EmptyState icon="alert">{err}</EmptyState> if (err) return <RdmErrorState raw={err} />
if (!data) return <div className="empty-note">加载中…</div> if (!data) return <div className="empty-note">加载中…</div>
const counts = data.counts || {} const counts = data.counts || {}
const entries: [string, string, number][] = [ const entries: [string, string, number][] = [
@@ -185,7 +200,7 @@ function TreeList({ pid, kind }: { pid: string; kind: 'notes' | 'docs' }) {
.catch(e => { if (gen === genRef.current) setErr(e.message) }) .catch(e => { if (gen === genRef.current) setErr(e.message) })
} }
if (err) return <EmptyState icon="alert">{err}</EmptyState> if (err) return <RdmErrorState raw={err} />
if (!shell) return <div className="empty-note">加载中…</div> if (!shell) return <div className="empty-note">加载中…</div>
if (shell.items.length === 0) return <EmptyState icon="folder">暂无{kind === 'notes' ? '骨架节点' : '文档'}</EmptyState> if (shell.items.length === 0) return <EmptyState icon="folder">暂无{kind === 'notes' ? '骨架节点' : '文档'}</EmptyState>
@@ -292,7 +307,7 @@ function TraceTab({ pid }: { pid: string }) {
<strong>{sel.title}</strong> <strong>{sel.title}</strong>
<Chip tone="plain">{sel.kind}:{sel.id}</Chip> <Chip tone="plain">{sel.kind}:{sel.id}</Chip>
</div> </div>
{err && <EmptyState icon="alert">{err}</EmptyState>} {err && <RdmErrorState raw={err} />}
{!relations && !err && <div className="empty-note">加载中…</div>} {!relations && !err && <div className="empty-note">加载中…</div>}
{relations && relations.length === 0 && <EmptyState icon="folder">没有已知关联</EmptyState>} {relations && relations.length === 0 && <EmptyState icon="folder">没有已知关联</EmptyState>}
{relations && relations.length > 0 && ( {relations && relations.length > 0 && (
@@ -407,7 +422,7 @@ function TimelineTab({ pid }: { pid: string }) {
</div> </div>
) : ( ) : (
<div> <div>
{err && <EmptyState icon="alert">{err}</EmptyState>} {err && <RdmErrorState raw={err} />}
{!err && items.length === 0 && <EmptyState icon="clock">暂无事件</EmptyState>} {!err && items.length === 0 && <EmptyState icon="clock">暂无事件</EmptyState>}
{items.map((item, i) => { {items.map((item, i) => {
if ('events' in item && Array.isArray((item as OpGroup).events)) { if ('events' in item && Array.isArray((item as OpGroup).events)) {
+12 -1
View File
@@ -112,6 +112,16 @@ export function SettingsModal() {
) )
} }
// 输入框语义(2026-10-12 增量 3):仅秘密字段用密码框;普通文本用 text——
// 无条件 type="password" 会把整排设置项当凭据表单(浏览器「password 不在 form 中/
// 缺少 username」警告来源之一),也把普通文本无谓遮蔽。
export function settingInputAttrs(desc: SettingDesc): { type: 'text' | 'password'; autoComplete: string } {
const isSecret = desc.secret || desc.type === 'secret'
return isSecret
? { type: 'password', autoComplete: 'new-password' }
: { type: 'text', autoComplete: 'off' }
}
export function SettingInput({ desc, value, onChange }: { desc: SettingDesc; value: any; onChange: (v: any) => void }) { export function SettingInput({ desc, value, onChange }: { desc: SettingDesc; value: any; onChange: (v: any) => void }) {
if (desc.type === 'boolean') { if (desc.type === 'boolean') {
return <input type="checkbox" checked={value === true || value === 'true'} onChange={e => onChange(e.target.checked)} /> return <input type="checkbox" checked={value === true || value === 'true'} onChange={e => onChange(e.target.checked)} />
@@ -122,7 +132,8 @@ export function SettingInput({ desc, value, onChange }: { desc: SettingDesc; val
</select> </select>
} }
const isSecret = desc.secret || desc.type === 'secret' const isSecret = desc.secret || desc.type === 'secret'
return <input type="password" autoComplete="new-password" style={{ width: '100%' }} value={typeof value === 'string' && value === '••••••' ? '' : (value ?? '')} const attrs = settingInputAttrs(desc)
return <input type={attrs.type} autoComplete={attrs.autoComplete} style={{ width: '100%' }} value={typeof value === 'string' && value === '••••••' ? '' : (value ?? '')}
placeholder={isSecret ? '(已配置,输入以覆盖)' : String(desc.default ?? '')} placeholder={isSecret ? '(已配置,输入以覆盖)' : String(desc.default ?? '')}
onChange={e => onChange(e.target.value)} /> onChange={e => onChange(e.target.value)} />
} }
+5 -2
View File
@@ -40,11 +40,14 @@ export function TaskSidebar() {
const projects = useStore(s => s.projects) const projects = useStore(s => s.projects)
const tasks = useStore(s => s.tasks) const tasks = useStore(s => s.tasks)
const me = useStore(s => s.me) const me = useStore(s => s.me)
const adminSections = useStore(s => s.adminSections)
const artifacts = useStore(s => s.artifacts) const artifacts = useStore(s => s.artifacts)
const currentConvId = useStore(s => s.currentConvId) const currentConvId = useStore(s => s.currentConvId)
const currentProjectId = useStore(s => s.currentProjectId) const currentProjectId = useStore(s => s.currentProjectId)
const showArchived = useStore(s => s.ui.showArchived) const showArchived = useStore(s => s.ui.showArchived)
const serverWorkspaces = useStore(s => s.serverWorkspaces) const serverWorkspaces = useStore(s => s.serverWorkspaces)
/** 审计入口能力门控(增量 2):命令面探测通过才展示「追溯审计」。 */
const rdmAuditAvailable = useStore(s => s.rdmAuditAvailable)
const theme = useStore(s => s.ui.theme) const theme = useStore(s => s.ui.theme)
const pendingBadge = useStore(s => const pendingBadge = useStore(s =>
s.cards.filter(c => c.status === 'action_required').length + s.cards.filter(c => c.status === 'action_required').length +
@@ -66,7 +69,7 @@ export function TaskSidebar() {
return () => window.removeEventListener('keydown', h, true) return () => window.removeEventListener('keydown', h, true)
}, []) }, [])
const tools = buildWorkspaceEntries(serverWorkspaces) const tools = buildWorkspaceEntries(serverWorkspaces, { rdmAudit: rdmAuditAvailable })
const visible = filterTasks(tasks.filter(t => t.projectId === currentProjectId), q) const visible = filterTasks(tasks.filter(t => t.projectId === currentProjectId), q)
const pinned = visible.filter(t => t.pinned) const pinned = visible.filter(t => t.pinned)
const rest = visible.filter(t => !t.pinned) const rest = visible.filter(t => !t.pinned)
@@ -265,7 +268,7 @@ export function TaskSidebar() {
<MenuItem icon="sun" onClick={() => { store.setUI({ theme: 'light' }); setMenu(null) }}>浅色主题{theme === 'light' ? ' · 当前' : ''}</MenuItem> <MenuItem icon="sun" onClick={() => { store.setUI({ theme: 'light' }); setMenu(null) }}>浅色主题{theme === 'light' ? ' · 当前' : ''}</MenuItem>
<MenuItem onClick={() => { store.setUI({ theme: 'molv' }); setMenu(null) }}>墨绿主题{theme === 'molv' ? ' · 当前' : ''}</MenuItem> <MenuItem onClick={() => { store.setUI({ theme: 'molv' }); setMenu(null) }}>墨绿主题{theme === 'molv' ? ' · 当前' : ''}</MenuItem>
<MenuItem onClick={() => { store.setUI({ theme: 'system' }); setMenu(null) }}>跟随系统{theme === 'system' ? ' · 当前' : ''}</MenuItem> <MenuItem onClick={() => { store.setUI({ theme: 'system' }); setMenu(null) }}>跟随系统{theme === 'system' ? ' · 当前' : ''}</MenuItem>
{me?.isAdmin && <MenuItem icon="shield" onClick={() => { store.setUI({ adminZoneOpen: true }); setMenu(null) }}>系统管理…</MenuItem>} {(me?.isAdmin || adminSections.length > 0) && <MenuItem icon="shield" onClick={() => { store.setUI({ adminZoneOpen: true }); setMenu(null) }}>系统管理…</MenuItem>}
{me?.auth && <> {me?.auth && <>
<div className="tsb-menu-div" /> <div className="tsb-menu-div" />
<MenuItem danger icon="logout" onClick={() => { api.logout().catch(() => undefined); auth.logout() }}>退出登录</MenuItem> <MenuItem danger icon="logout" onClick={() => { api.logout().catch(() => undefined); auth.logout() }}>退出登录</MenuItem>
+14 -5
View File
@@ -6,6 +6,7 @@ import type { Run } from '../contracts'
import { InboxList, pendingCount, type ActivityCard, type DocBridge, type InboxFilter } from '@ui' import { InboxList, pendingCount, type ActivityCard, type DocBridge, type InboxFilter } from '@ui'
import { Icon, SurfaceView } from '@ui' import { Icon, SurfaceView } from '@ui'
import { previewTabsKey } from '../previewtabs' import { previewTabsKey } from '../previewtabs'
import { surfaceKey } from '../surfaceKey'
import { ArtifactsPanel } from './ArtifactsPanel' import { ArtifactsPanel } from './ArtifactsPanel'
import { PreviewPane } from './PreviewPane' import { PreviewPane } from './PreviewPane'
@@ -91,6 +92,11 @@ function FilesTab() {
return <div className="tab-body"><ArtifactsPanel /></div> return <div className="tab-body"><ArtifactsPanel /></div>
} }
/** U1:同会话存在后台 progress 卡(进行中/待确认)时,progress 为权威对象,隐藏 CurrentTaskCard 避免双标题。 */
export function hasActiveProgressCard(cards: ActivityCard[]): boolean {
return cards.some(c => c.kind === 'progress' && (c.status === 'active' || c.status === 'action_required'))
}
function WorkTab({ plan, todos, filter, inboxScope, projectCards, cards }: { function WorkTab({ plan, todos, filter, inboxScope, projectCards, cards }: {
plan: Parameters<typeof CurrentTaskCard>[0]['plan'] plan: Parameters<typeof CurrentTaskCard>[0]['plan']
todos: Parameters<typeof CurrentTaskCard>[0]['todos'] todos: Parameters<typeof CurrentTaskCard>[0]['todos']
@@ -99,10 +105,11 @@ function WorkTab({ plan, todos, filter, inboxScope, projectCards, cards }: {
projectCards: ActivityCard[] projectCards: ActivityCard[]
cards: ActivityCard[] cards: ActivityCard[]
}) { }) {
const showCurrentTask = !hasActiveProgressCard(cards)
return ( return (
<> <>
<div className="tab-body" data-scroll-sync="inbox"> <div className="tab-body" data-scroll-sync="inbox">
<CurrentTaskCard plan={plan} todos={todos} /> {showCurrentTask ? <CurrentTaskCard plan={plan} todos={todos} /> : null}
<div className="inbox-scope" role="tablist" aria-label="收件箱范围与筛选"> <div className="inbox-scope" role="tablist" aria-label="收件箱范围与筛选">
<button className={inboxScope === 'conv' ? 'active' : ''} onClick={() => store.setInboxScope('conv')}>本会话</button> <button className={inboxScope === 'conv' ? 'active' : ''} onClick={() => store.setInboxScope('conv')}>本会话</button>
<button className={inboxScope === 'project' ? 'active' : ''} onClick={() => store.setInboxScope('project')}> <button className={inboxScope === 'project' ? 'active' : ''} onClick={() => store.setInboxScope('project')}>
@@ -180,9 +187,11 @@ export function AgentRow({ run, depth }: { run: Run; depth: number }) {
function WorkspaceSurfaces() { function WorkspaceSurfaces() {
const surfaces = useStore(s => s.surfaces) const surfaces = useStore(s => s.surfaces)
const pin = useStore(s => s.ui.workspaceSurfacePin) const pin = useStore(s => s.ui.workspaceSurfacePin)
if (surfaces.length === 0) return null const usable = surfaces.filter(x => surfaceKey(x) != null)
const shown = pin ? surfaces.find(x => String(x.identity.surfaceId) === pin) : surfaces[surfaces.length - 1] if (usable.length === 0) return null
const shown = pin ? usable.find(x => surfaceKey(x) === pin) : usable[usable.length - 1]
if (!shown) return null if (!shown) return null
const shownId = surfaceKey(shown)!
return ( return (
<div className="workspace-surfaces" data-workspace-surfaces> <div className="workspace-surfaces" data-workspace-surfaces>
<div className="ws-head"> <div className="ws-head">
@@ -190,10 +199,10 @@ function WorkspaceSurfaces() {
<span className="ws-meta">{shown.spec?.title || '(未命名)'} · 修订 {shown.revision}</span> <span className="ws-meta">{shown.spec?.title || '(未命名)'} · 修订 {shown.revision}</span>
<span style={{ flex: 1 }} /> <span style={{ flex: 1 }} />
<button className="icon-btn" title={pin ? '取消固定(跟随最新)' : '固定此页(新页面不抢占)'} <button className="icon-btn" title={pin ? '取消固定(跟随最新)' : '固定此页(新页面不抢占)'}
onClick={() => store.setUI({ workspaceSurfacePin: pin ? null : String(shown.identity.surfaceId) })}> onClick={() => store.setUI({ workspaceSurfacePin: pin ? null : shownId })}>
{pin ? '📍' : '📌'} {pin ? '📍' : '📌'}
</button> </button>
<button className="icon-btn" title="在文件预览中打开" onClick={() => store.openSurface(String(shown.identity.surfaceId))}> <button className="icon-btn" title="在文件预览中打开" onClick={() => store.openSurface(shownId)}>
↗ ↗
</button> </button>
</div> </div>
+4 -2
View File
@@ -9,9 +9,11 @@ import { AgentRow } from './Workbench'
import { buildWorkspaceEntries, type WorkspaceEntry } from '../workspaces' import { buildWorkspaceEntries, type WorkspaceEntry } from '../workspaces'
import { RdmAuditWorkspace } from './RdmAuditWorkspace' import { RdmAuditWorkspace } from './RdmAuditWorkspace'
/** 体系工具(顺序即 ⌘ 序号)。服务端工作区全员可见;插件管理面板只在系统管理区。 */ /** 体系工具(顺序即 ⌘ 序号)。服务端工作区全员可见;插件管理面板只在系统管理区。
* 追溯审计按命令面能力显隐(增量 2):store.rdmAuditAvailable 为 true 才入列。 */
export function workspaceEntries(): WorkspaceEntry[] { export function workspaceEntries(): WorkspaceEntry[] {
return buildWorkspaceEntries(store.getState().serverWorkspaces) const s = store.getState()
return buildWorkspaceEntries(s.serverWorkspaces, { rdmAudit: s.rdmAuditAvailable })
} }
export function Workspaces() { export function Workspaces() {
+385
View File
@@ -0,0 +1,385 @@
// U6/KTD5:RDM 管理与项目页面组件。系统管理「RDM 角色权限」+ 项目设置「成员 /
// 文档职责 · 整文审签」。全部数据经 api.rdmCommand(命令总线),载荷构造与能力
// 门控集中在 src/rdmManagement.ts;分区可见性由 AdminZone/ProjectSettingsModal
// 按 store 的 rdm*Available 门控(命令面不齐不渲染,普通基座零暴露)。样式只复用
// 既有 ad-*/lg-*/settings-* 类(design-guard 棘轮:不新增裸色值/字号)。
import { useEffect, useState } from 'react'
import { api } from '../api'
import { useStore } from '../store'
import { Btn, EmptyState, Icon } from '@ui'
import {
ROLE_ACTIONS, parseReviewers,
roleCreatePayload, roleActionPayload, roleAssignPayload, roleDisablePayload,
memberAddPayload, memberRemovePayload,
assignDocDutiesPayload, docSubmitPayload, docApprovePayload, docRejectPayload,
docFinalPayload, docStatusPayload, permCheckPayload, describeSource,
} from '../rdmManagement'
// ---- 系统管理:RDM 角色权限(仅管理员 + rdmRolesAvailable) ----
interface RoleView {
roleId: string
name: string
disabled: boolean
version: number
actions: Record<string, [boolean, boolean]> | null
accounts: string[] | null
}
export function RdmRolesPanel() {
const me = useStore(s => s.me)
const [roles, setRoles] = useState<RoleView[] | null>(null)
const [err, setErr] = useState('')
const [notice, setNotice] = useState('')
const [busy, setBusy] = useState(false)
const [newName, setNewName] = useState('')
// 动作编辑器
const [editRole, setEditRole] = useState('')
const [editAction, setEditAction] = useState<string>(ROLE_ACTIONS[0])
const [editDef, setEditDef] = useState(false)
const [editCap, setEditCap] = useState(true)
// 绑定
const [assignOwner, setAssignOwner] = useState('')
const refresh = async () => {
try {
const out = await api.rdmCommand<{ roles: RoleView[] }>('rdm.role.list')
setRoles(out.roles ?? [])
} catch (e) { setErr(String(e)) }
}
useEffect(() => { refresh() }, [])
const run = async (label: string, fn: () => Promise<unknown>) => {
setErr(''); setNotice(''); setBusy(true)
try { await fn(); setNotice(label); await refresh() }
catch (e) { setErr(String(e)) } finally { setBusy(false) }
}
if (!me?.isAdmin) return <EmptyState icon="shield">仅平台管理员可管理专业角色</EmptyState>
const sel = roles?.find(r => r.roleId === editRole)
const editCurrent = sel?.actions?.[editAction]
return (
<div>
<div className="ad-create">
<div className="ad-row">
<input className="lg-input" placeholder="新角色名(如:编制工程师)" value={newName}
onChange={e => setNewName(e.target.value)} />
<button className="lg-submit ad-create-btn" disabled={busy || !newName.trim()}
onClick={() => run(`已创建角色 ${newName.trim()}`, async () => {
await api.rdmCommand('rdm.role.create', roleCreatePayload(newName.trim()))
setNewName('')
})}>创建角色</button>
</div>
<p className="ad-hint">新角色动作未配置=全部拒绝(fail-closed),创建后经下方编辑器逐动作配置默认与上限。</p>
</div>
<table className="ad-table">
<thead><tr><th>角色</th><th>状态</th><th>版本</th><th>动作配置</th><th>绑定账号</th><th></th></tr></thead>
<tbody>
{(roles ?? []).map(r => (
<tr key={r.roleId}>
<td><span className="ad-mono">{r.name}</span><br /><span className="ad-dim">{r.roleId}</span></td>
<td>{r.disabled ? <span className="ad-chip ad-chip-warn">已停用</span> : <span className="ad-chip">生效</span>}</td>
<td className="ad-dim">v{r.version}</td>
<td>{Object.keys(r.actions ?? {}).length} 项</td>
<td className="ad-mono">{(r.accounts ?? []).join('、') || '—'}</td>
<td><button className="ad-mini" disabled={busy}
onClick={() => run(r.disabled ? `已启用 ${r.name}` : `已停用 ${r.name}(绑定账号回落内置默认)`,
() => api.rdmCommand('rdm.role.disable', roleDisablePayload(r.roleId, !r.disabled)))}>
{r.disabled ? '启用' : '停用'}</button></td>
</tr>
))}
{roles !== null && roles.length === 0 && <tr><td colSpan={6} className="ad-dim">暂无专业角色</td></tr>}
{roles === null && <tr><td colSpan={6} className="ad-dim">加载中…</td></tr>}
</tbody>
</table>
<h4 className="settings-group-title" style={{ marginTop: 18 }}>动作配置(默认 ∩ 上限)</h4>
<div className="ad-row">
<select className="lg-input" value={editRole} onChange={e => setEditRole(e.target.value)}>
<option value="">选择角色…</option>
{(roles ?? []).map(r => <option key={r.roleId} value={r.roleId}>{r.name}</option>)}
</select>
<select className="lg-input" value={editAction}
onChange={e => {
setEditAction(e.target.value)
const cur = sel?.actions?.[e.target.value]
setEditDef(!!cur?.[0]); setEditCap(cur ? cur[1] : true)
}}>
{ROLE_ACTIONS.map(a => <option key={a} value={a}>{a}</option>)}
</select>
<label className="ad-check"><input type="checkbox" checked={editDef}
onChange={e => setEditDef(e.target.checked)} />默认允许</label>
<label className="ad-check"><input type="checkbox" checked={editCap}
onChange={e => setEditCap(e.target.checked)} />上限允许</label>
<button className="lg-submit ad-create-btn" disabled={busy || !editRole}
onClick={() => run(`已配置 ${editRole} · ${editAction}`,
() => api.rdmCommand('rdm.role.action', roleActionPayload(editRole, editAction, editDef, editCap)))}>保存动作</button>
</div>
{sel && editCurrent && <p className="ad-hint">当前值:默认={String(editCurrent[0])},上限={String(editCurrent[1])}</p>}
<h4 className="settings-group-title" style={{ marginTop: 18 }}>绑定账号(每账号一个生效角色)</h4>
<div className="ad-row">
<input className="lg-input lg-mono" placeholder="账号(owner)" value={assignOwner}
onChange={e => setAssignOwner(e.target.value)} />
<select className="lg-input" value={editRole} onChange={e => setEditRole(e.target.value)}>
<option value="">选择角色…</option>
{(roles ?? []).filter(r => !r.disabled).map(r => <option key={r.roleId} value={r.roleId}>{r.name}</option>)}
</select>
<button className="lg-submit ad-create-btn" disabled={busy || !assignOwner.trim() || !editRole}
onClick={() => run(`已把 ${assignOwner.trim()} 绑定到 ${editRole}`,
() => api.rdmCommand('rdm.role.assign', roleAssignPayload(assignOwner.trim(), editRole)))}>绑定</button>
</div>
{notice && <div className="ad-notice"><Icon name="check" size={14} />{notice}</div>}
{err && <div className="lg-err"><Icon name="alert" size={14} />{err}</div>}
</div>
)
}
// ---- 项目设置:成员 ----
interface MemberRow { owner: string; role: string; addedBy: string; addedAt: string }
export function RdmMembersSection({ projectId }: { projectId: string }) {
const [rows, setRows] = useState<MemberRow[] | null>(null)
const [err, setErr] = useState('')
const [notice, setNotice] = useState('')
const [busy, setBusy] = useState(false)
const [member, setMember] = useState('')
const [role, setRole] = useState<'member' | 'owner'>('member')
const refresh = async () => {
try {
const out = await api.rdmCommand<{ members: MemberRow[] }>('rdm.project.member.list', { projectId })
setRows(out.members ?? [])
} catch (e) { setErr(String(e)) }
}
useEffect(() => { refresh() }, [projectId])
const run = async (label: string, fn: () => Promise<unknown>) => {
setErr(''); setNotice(''); setBusy(true)
try { await fn(); setNotice(label); await refresh() }
catch (e) { setErr(String(e)) } finally { setBusy(false) }
}
return (
<div>
<div className="ad-create">
<div className="ad-row">
<input className="lg-input lg-mono" placeholder="成员账号(owner)" value={member}
onChange={e => setMember(e.target.value)} />
<select className="lg-input" value={role} onChange={e => setRole(e.target.value as 'member' | 'owner')}>
<option value="member">member(成员)</option>
<option value="owner">owner(负责人)</option>
</select>
<button className="lg-submit ad-create-btn" disabled={busy || !member.trim()}
onClick={() => run(`已添加 ${member.trim()}`, async () => {
await api.rdmCommand('rdm.project.member.add', memberAddPayload(projectId, member.trim(), role))
setMember('')
})}>添加成员</button>
</div>
<p className="ad-hint">加入后成员即可见本项目;移除即时生效。最后一位负责人不可移除/降级。</p>
</div>
<table className="ad-table">
<thead><tr><th>账号</th><th>项目角色</th><th>添加人</th><th>添加时间</th><th></th></tr></thead>
<tbody>
{(rows ?? []).map(m => (
<tr key={m.owner}>
<td className="ad-mono">{m.owner}</td>
<td>{m.role === 'owner' ? <span className="ad-chip ad-chip-admin">OWNER</span> : <span className="ad-chip">MEMBER</span>}</td>
<td className="ad-dim">{m.addedBy || '—'}</td>
<td className="ad-dim">{m.addedAt ? new Date(m.addedAt).toLocaleString() : '—'}</td>
<td><button className="ad-mini" disabled={busy}
onClick={() => run(`已移除 ${m.owner}`,
() => api.rdmCommand('rdm.project.member.remove', memberRemovePayload(projectId, m.owner)))}>移除</button></td>
</tr>
))}
{rows !== null && rows.length === 0 && <tr><td colSpan={5} className="ad-dim">暂无成员</td></tr>}
{rows === null && <tr><td colSpan={5} className="ad-dim">加载中…</td></tr>}
</tbody>
</table>
{notice && <div className="ad-notice"><Icon name="check" size={14} />{notice}</div>}
{err && <div className="lg-err"><Icon name="alert" size={14} />{err}</div>}
</div>
)
}
// ---- 项目设置:文档职责 · 整文审签 ----
interface DocSubmissionView {
round: number
state: string
digest: string
createdBy: string
createdAt: string
duties: { author: string; reviewers: string[]; approver: string }
reviews: Record<string, boolean>
sections: Record<string, number>
}
export function RdmDutiesSection({ projectId }: { projectId: string }) {
const [docId, setDocId] = useState('')
const [sub, setSub] = useState<DocSubmissionView | null | undefined>(undefined)
const [err, setErr] = useState('')
const [notice, setNotice] = useState('')
const [busy, setBusy] = useState(false)
const [author, setAuthor] = useState('')
const [reviewers, setReviewers] = useState('')
const [approver, setApprover] = useState('')
const cmd = <T,>(id: string, params: Record<string, unknown>) => api.rdmCommand<T>(id, params)
const refreshStatus = async (id: string) => {
if (!id) return
try {
const out = await cmd<{ submission: DocSubmissionView | null }>('rdm.review.doc.status', docStatusPayload(projectId, id))
setSub(out.submission)
} catch (e) { setErr(String(e)); setSub(undefined) }
}
const run = async (label: string, fn: () => Promise<unknown>) => {
setErr(''); setNotice(''); setBusy(true)
try { await fn(); setNotice(label); await refreshStatus(docId) }
catch (e) { setErr(String(e)) } finally { setBusy(false) }
}
return (
<div>
<div className="ad-create">
<div className="ad-row">
<input className="lg-input lg-mono" placeholder="文档 ID(docId)" value={docId}
onChange={e => setDocId(e.target.value)} />
<Btn variant="ghost" icon="eye" disabled={busy || !docId}
onClick={() => refreshStatus(docId)}>查看整文状态</Btn>
</div>
</div>
{sub === null && <EmptyState icon="inbox">该文档尚无整文提交记录</EmptyState>}
{sub && (
<div className="settings-group">
<h4>第 {sub.round} 轮 · {sub.state === 'submitted' ? <span className="ad-chip ad-chip-warn">审签在途(全文锁定)</span> : sub.state === 'final' ? <span className="ad-chip ad-chip-admin">已终批</span> : <span className="ad-chip">已驳回</span>}</h4>
<div className="setting-row"><label>三权</label><span>编制 <b className="ad-mono">{sub.duties.author}</b> · 审核 <b className="ad-mono">{(sub.duties.reviewers ?? []).join('、')}</b> · 批准 <b className="ad-mono">{sub.duties.approver}</b></span></div>
<div className="setting-row"><label>审核进度</label><span>{Object.entries(sub.reviews ?? {}).map(([r, ok]) => `${r}:${ok ? '✓' : '…'}`).join(' ') || '—'}</span></div>
<div className="setting-row"><label>冻结摘要</label><span className="ad-mono ad-dim">{(sub.digest ?? '').slice(0, 16)}…</span></div>
<div className="ad-row" style={{ marginTop: 8 }}>
<button className="lg-submit ad-create-btn" disabled={busy || sub.state !== 'submitted'}
onClick={() => run('整文终批完成(各章节已基线)',
() => cmd('rdm.review.doc.final', docFinalPayload(projectId, docId)))}>终批(批准人)</button>
<button className="ad-mini" disabled={busy || sub.state !== 'submitted'}
onClick={() => run('已通过整文审核',
() => cmd('rdm.review.doc.approve', docApprovePayload(projectId, docId, '通过')))}>审核通过</button>
<button className="ad-mini" disabled={busy || sub.state !== 'submitted'}
onClick={() => run('已驳回整文(解锁回编写态)',
() => cmd('rdm.review.doc.reject', docRejectPayload(projectId, docId, '退回修改')))}>驳回</button>
</div>
</div>
)}
{sub === undefined && docId && <p className="ad-hint">输入文档 ID 后查看整文状态。</p>}
<h4 className="settings-group-title" style={{ marginTop: 18 }}>分配文档三权(整文)</h4>
<div className="ad-row">
<input className="lg-input lg-mono" placeholder="文档 ID(docId)" value={docId}
onChange={e => setDocId(e.target.value)} />
<input className="lg-input lg-mono" placeholder="编制人(author)" value={author}
onChange={e => setAuthor(e.target.value)} />
<input className="lg-input lg-mono" placeholder="审核人(逗号分隔,≥1 且异于编制/批准)" value={reviewers}
onChange={e => setReviewers(e.target.value)} />
<input className="lg-input lg-mono" placeholder="批准人(approver)" value={approver}
onChange={e => setApprover(e.target.value)} />
</div>
<div className="ad-row">
<button className="lg-submit ad-create-btn"
disabled={busy || !docId || !author.trim() || !approver.trim() || parseReviewers(reviewers).length === 0}
onClick={() => run('已分配文档三权', () => cmd('rdm.review.assign.doc',
assignDocDutiesPayload(projectId, docId, author.trim(), parseReviewers(reviewers), approver.trim())))}>分配三权</button>
<button className="ad-mini" disabled={busy || !docId}
onClick={() => run('整文已提交审核(全文锁定)',
() => cmd('rdm.review.doc.submit', docSubmitPayload(projectId, docId)))}>整文提交(编制人)</button>
</div>
<p className="ad-hint">三权异人:编制≠批准,审核异于两者;提交即冻结三权与全文版本,审签在途全文锁定。</p>
{notice && <div className="ad-notice"><Icon name="check" size={14} />{notice}</div>}
{err && <div className="lg-err"><Icon name="alert" size={14} />{err}</div>}
</div>
)
}
// ---- 项目设置:项目权限(矩阵解释读面,与实际判定同源——UI 不重算) ----
interface MatrixAction { action: string; allowed: boolean; source: string; reason?: string }
interface MatrixOut {
projectId: string; member: string; role: string
profRole: { roleId: string; name: string } | null
actions: MatrixAction[]
}
export function RdmPermMatrixSection({ projectId }: { projectId: string }) {
const me = useStore(s => s.me)
const [member, setMember] = useState('')
const [members, setMembers] = useState<MemberRow[] | null>(null)
const [matrix, setMatrix] = useState<MatrixOut | null>(null)
const [err, setErr] = useState('')
const [busy, setBusy] = useState(false)
useEffect(() => {
api.rdmCommand<{ members: MemberRow[] }>('rdm.project.member.list', { projectId })
.then(out => {
setMembers(out.members ?? [])
// 默认自省:普通成员只看自己的矩阵;负责人/管理员可切换他人。
if (me?.owner) setMember(prev => prev || me.owner)
})
.catch(e => setErr(String(e)))
}, [projectId, me?.owner])
const query = async (m: string) => {
if (!m) return
setErr(''); setBusy(true); setMatrix(null)
try {
setMatrix(await api.rdmCommand<MatrixOut>('rdm.perm.check', permCheckPayload(projectId, m)))
} catch (e) { setErr(String(e)) } finally { setBusy(false) }
}
return (
<div>
<div className="ad-create">
<div className="ad-row">
<select className="lg-input" value={member} onChange={e => { setMember(e.target.value); query(e.target.value) }}>
<option value="">选择成员(默认自省)…</option>
{(members ?? []).map(m => <option key={m.owner} value={m.owner}>{m.owner}</option>)}
</select>
<Btn variant="ghost" icon="eye" disabled={busy || !member} onClick={() => query(member)}>查看矩阵</Btn>
</div>
<p className="ad-hint">普通成员可查看自己的有效权限;查看他人矩阵须项目管理权。矩阵与实际判定同源(服务端解释,非前端推算)。</p>
</div>
{matrix && (
<>
<div className="ad-row">
<span>成员 <b className="ad-mono">{matrix.member}</b> · 项目关系 <b>{matrix.role}</b>
{matrix.profRole && <> · 专业角色 <b>{matrix.profRole.name}</b>({matrix.profRole.roleId})</>}
</span>
</div>
<table className="ad-table">
<thead><tr><th>动作</th><th>生效</th><th>来源</th><th>原因(拒绝时)</th></tr></thead>
<tbody>
{(matrix.actions ?? []).map(a => (
<tr key={a.action}>
<td className="ad-mono">{a.action}</td>
<td>{a.allowed ? <span className="ad-chip ad-chip-admin">允许</span> : <span className="ad-chip ad-chip-warn">拒绝</span>}</td>
<td className="ad-dim">{describeSource(a.source)}</td>
<td className="ad-dim">{a.reason || '—'}</td>
</tr>
))}
</tbody>
</table>
</>
)}
{!matrix && !err && members !== null && <p className="ad-hint">选择成员后展示 12 项动作的有效权限与第一拒绝原因。</p>}
{err && <div className="lg-err"><Icon name="alert" size={14} />{err}</div>}
</div>
)
}
+25
View File
@@ -0,0 +1,25 @@
// 审计命令错误分类(2026-10-12 增量 2):RdmAuditWorkspace 不再直出原始报错
//(普通基座上曾是 `400: {"receipt":…unknown or disabled command…}`),改为
//「能力缺失 / 登录已失效 / 查询失败」人话文案;raw 始终保留供「原始回执」折叠区诊断。
// 依据:api.ts json() 对非 2xx 抛 `${status}: ${body}`;后端 unknown/disabled 命令回
// 400 + "unknown or disabled command"(cmdbus.go Dispatch),总线未挂载回
// 503 "commands disabled"(server.go execCommand)。
type RdmErrorKind = 'capability' | 'auth' | 'query'
interface RdmErrorView {
kind: RdmErrorKind
message: string
raw: string
}
export function classifyRdmError(err: unknown): RdmErrorView {
const raw = err instanceof Error ? err.message : String(err)
if (/^40[13]:/.test(raw)) {
return { kind: 'auth', message: '登录已失效,请重新登录后再查看追溯审计', raw }
}
if (/unknown or disabled command|commands disabled/.test(raw)) {
return { kind: 'capability', message: '当前服务未提供审计能力(RDM 命令未注册或已停用)', raw }
}
return { kind: 'query', message: '查询失败,请稍后重试', raw }
}
+119
View File
@@ -0,0 +1,119 @@
// U6/KTD5:RDM 管理与项目页面的纯逻辑层——能力门控(与 rdmAuditReady 同源语义:
// 命令清单不可用=未就绪,fail-closed)与命令载荷构造。页面组件只消费本模块与
// api.rdmCommand,不在组件里散落命令 id / 参数拼写;身份一律经认证会话,载荷不
// 携带任何身份字段(G1-5)。
/** 系统管理「RDM 角色权限」分区消费的命令面。 */
export const RDM_ROLES_COMMANDS = [
'rdm.role.create',
'rdm.role.action',
'rdm.role.assign',
'rdm.role.disable',
'rdm.role.list',
] as const
/** 项目设置「成员」页消费的命令面。 */
export const RDM_MEMBER_COMMANDS = [
'rdm.project.member.list',
'rdm.project.member.add',
'rdm.project.member.remove',
] as const
/** 项目设置「项目权限」页消费的命令面(矩阵解释 + 成员清单)。 */
export const RDM_PERM_MATRIX_COMMANDS = [
'rdm.perm.check',
'rdm.project.member.list',
] as const
/** 项目设置「文档职责 · 整文审签」页消费的命令面。 */
export const RDM_DOC_REVIEW_COMMANDS = [
'rdm.review.assign.doc',
'rdm.review.doc.submit',
'rdm.review.doc.approve',
'rdm.review.doc.reject',
'rdm.review.doc.final',
'rdm.review.doc.status',
] as const
export type CommandListItem = { id?: string; enabled?: boolean } | null | undefined
function ready(cmds: CommandListItem[] | null | undefined, need: readonly string[]): boolean {
if (!Array.isArray(cmds)) return false
return need.every(n => cmds.some(c => c?.id === n && c.enabled === true))
}
/** 角色分区是否就绪(普通基座无 rdm.role.* → 隐藏)。 */
export const rdmRolesReady = (cmds: CommandListItem[] | null | undefined) =>
ready(cmds, RDM_ROLES_COMMANDS)
/** 项目成员页是否就绪。 */
export const rdmMembersReady = (cmds: CommandListItem[] | null | undefined) =>
ready(cmds, RDM_MEMBER_COMMANDS)
/** 文档职责/整文审签页是否就绪。 */
export const rdmDocReviewReady = (cmds: CommandListItem[] | null | undefined) =>
ready(cmds, RDM_DOC_REVIEW_COMMANDS)
/** 项目权限矩阵页是否就绪。 */
export const rdmPermMatrixReady = (cmds: CommandListItem[] | null | undefined) =>
ready(cmds, RDM_PERM_MATRIX_COMMANDS)
/** RDM 动作清单(12 项,与 RDM perms.AllActions 对齐;角色动作编辑器选项)。 */
export const ROLE_ACTIONS = [
'project.create', 'project.archive', 'member.manage', 'duty.assign',
'stage.advance', 'doc.read', 'doc.write', 'doc.publish', 'review.participate',
'trace.edit', 'knowledge.publish', 'project.settings',
] as const
// ---- 载荷构造(字段名与 RDM 命令 schema 一一对应) ----
export const roleCreatePayload = (name: string) => ({ name })
export const roleActionPayload = (roleId: string, action: string, def: boolean, cap: boolean) =>
({ roleId, action, default: def, cap })
export const roleAssignPayload = (owner: string, roleId: string) => ({ owner, roleId })
export const roleDisablePayload = (roleId: string, disabled: boolean) => ({ roleId, disabled })
export const memberAddPayload = (projectId: string, member: string, role: 'owner' | 'member' = 'member') =>
({ projectId, member, role })
export const memberRemovePayload = (projectId: string, member: string) => ({ projectId, member })
export const assignDocDutiesPayload = (
projectId: string, docId: string, author: string, reviewers: string[], approver: string,
) => ({ projectId, docId, author, reviewers, approver })
export const docSubmitPayload = (projectId: string, docId: string) => ({ projectId, docId })
export const docApprovePayload = (projectId: string, docId: string, note?: string) =>
note ? { projectId, docId, note } : { projectId, docId }
export const docRejectPayload = (projectId: string, docId: string, reason?: string) =>
reason ? { projectId, docId, reason } : { projectId, docId }
/** round=0(未指定)不携带——服务端只认在途轮次,旧轮次传参即拒。 */
export const docFinalPayload = (projectId: string, docId: string, round = 0) =>
round > 0 ? { projectId, docId, round } : { projectId, docId }
export const docStatusPayload = (projectId: string, docId: string) => ({ projectId, docId })
export const permCheckPayload = (projectId: string, member: string) => ({ projectId, member })
/** 矩阵来源标签(人话映射;未知来源回退原文——服务端新增来源时不至于空白)。 */
export function describeSource(source: string): string {
switch (source) {
case 'admin': return '系统管理员'
case 'prof-role-default': return '专业角色默认'
case 'override': return '项目内覆盖'
case 'relation-default': return '项目关系默认'
case 'non-member': return '非项目成员'
default: return source
}
}
/** 审阅人 CSV 解析:去空白、去空项、保序去重(表单输入 → reviewers 数组)。 */
export function parseReviewers(csv: string): string[] {
const seen = new Set<string>()
const out: string[] = []
for (const part of csv.split(',')) {
const v = part.trim()
if (!v || seen.has(v)) continue
seen.add(v)
out.push(v)
}
return out
}
+52 -13
View File
@@ -1,13 +1,16 @@
// 应用状态:服务端权威(事件 + Query 对账),前端 store 是投影。 // 应用状态:服务端权威(事件 + Query 对账),前端 store 是投影。
// useSyncExternalStore 驱动;live 流式部件为会话内临时态,run 终态后由消息树对账收敛。 // useSyncExternalStore 驱动;live 流式部件为会话内临时态,run 终态后由消息树对账收敛。
import { useSyncExternalStore } from 'react' import { useSyncExternalStore } from 'react'
import { api, connectEvents } from './api' import { type AdminZoneSection, api, connectEvents } from './api'
import { applyTextDelta, applyThinkingDelta, applyToolCall, applyToolCallDelta, applyToolResult, applyToolOutput, applyArtifactCreated, applyArtifactUpdated, applyCheck, applyFinalizing, type LiveItem } from './live' import { applyTextDelta, applyThinkingDelta, applyToolCall, applyToolCallDelta, applyToolResult, applyToolOutput, applyArtifactCreated, applyArtifactUpdated, applyCheck, applyFinalizing, type LiveItem } from './live'
import { closePreviewTab, mergeOrphanPreviewTabs, openPreviewTab, previewTabsKey, type PreviewTab } from './previewtabs' import { closePreviewTab, mergeOrphanPreviewTabs, openPreviewTab, previewTabsKey, type PreviewTab } from './previewtabs'
import { deliveryRequestId, enqueueMessage, enqueueMessageFront, newQueuedMessage, promoteQueuedMessage, removeQueuedMessage, replaceQueuedText, type QueuedMessage } from './outbox' import { deliveryRequestId, enqueueMessage, enqueueMessageFront, newQueuedMessage, promoteQueuedMessage, removeQueuedMessage, replaceQueuedText, type QueuedMessage } from './outbox'
import { canFlushOutbox, deriveShellPhase } from './runstate' import { canFlushOutbox, deriveShellPhase } from './runstate'
import { flashElement } from './scrollsync' import { flashElement } from './scrollsync'
import { isThemeChoice, resolveTheme, type ThemeChoice } from './theme' import { isThemeChoice, resolveTheme, type ThemeChoice } from './theme'
import { mergeSurfacesByRevision, surfaceKey } from './surfaceKey'
import { rdmAuditReady } from './workspaces'
import { rdmRolesReady, rdmMembersReady, rdmDocReviewReady, rdmPermMatrixReady } from './rdmManagement'
type FontSizeChoice = 13 | 14 | 16 | 18 type FontSizeChoice = 13 | 14 | 16 | 18
const FONT_SIZE_CHOICES: readonly FontSizeChoice[] = [13, 14, 16, 18] const FONT_SIZE_CHOICES: readonly FontSizeChoice[] = [13, 14, 16, 18]
@@ -112,6 +115,15 @@ interface AppState {
profiles: AgentProfile[] profiles: AgentProfile[]
pluginPanels: PluginPanel[] pluginPanels: PluginPanel[]
serverWorkspaces: { id: string; title: string; icon?: string; shortcut?: string; body?: any[] }[] serverWorkspaces: { id: string; title: string; icon?: string; shortcut?: string; body?: any[] }[]
/** 审计入口能力(增量 2):GET /api/commands 含全部 rdm.inspect.* 且启用;探测失败/未登录为 false,入口隐藏。 */
rdmAuditAvailable: boolean
/** U6 RDM 管理页能力:命令面齐备才显示对应分区/页签(普通基座零暴露,fail-closed)。 */
rdmRolesAvailable: boolean
rdmMembersAvailable: boolean
rdmDocReviewAvailable: boolean
rdmPermMatrixAvailable: boolean
/** 管理区声明分区(WP3-I3):编译插件声明,入口全员可见、区内置权限不合并。 */
adminSections: AdminZoneSection[]
ui: UIState ui: UIState
connected: boolean connected: boolean
/** 发送请求已经出去,run 记录还没回来。 */ /** 发送请求已经出去,run 记录还没回来。 */
@@ -175,6 +187,9 @@ let state: AppState = {
messages: [], runs: [], activeHitl: [], lastSeq: 0, live: null, messages: [], runs: [], activeHitl: [], lastSeq: 0, live: null,
plan: null, todos: null, artifacts: [], surfaces: [], projectSurfaces: [], cards: [], projectCards: [], inboxScope: 'conv', runtimeMock: false, profiles: [], pluginPanels: [], plan: null, todos: null, artifacts: [], surfaces: [], projectSurfaces: [], cards: [], projectCards: [], inboxScope: 'conv', runtimeMock: false, profiles: [], pluginPanels: [],
serverWorkspaces: [], serverWorkspaces: [],
rdmAuditAvailable: false,
rdmRolesAvailable: false, rdmMembersAvailable: false, rdmDocReviewAvailable: false, rdmPermMatrixAvailable: false,
adminSections: [],
ui: loadUI(), connected: false, posting: false, error: null, toast: null, ui: loadUI(), connected: false, posting: false, error: null, toast: null,
outbox: [], outboxDraining: false, outbox: [], outboxDraining: false,
previewTabs: {}, previewActive: {}, previewTabs: {}, previewActive: {},
@@ -390,23 +405,31 @@ export const store = {
}) })
} }
// U4/R5:已保存页面从权威快照重载(刷新/断线恢复;事件流只做增量投影)。 // U4/R5:已保存页面从权威快照重载(刷新/断线恢复;事件流只做增量投影)。
// surfaceList 返回扁平 SurfaceMeta,不可写入 surfaces;必须经 surfaceGet 水合为 Snapshot。
api.projectSurfaces(state.currentProjectId ?? '').then(list => { if (state.currentConvId === convId) set({ projectSurfaces: list ?? [] }) }).catch(() => {}) api.projectSurfaces(state.currentProjectId ?? '').then(list => { if (state.currentConvId === convId) set({ projectSurfaces: list ?? [] }) }).catch(() => {})
api.surfaceList(convId).then(list => { api.surfaceList(convId).then(async list => {
if (state.currentConvId !== convId) return if (state.currentConvId !== convId) return
set({ surfaces: list ?? [] }) const metas = list ?? []
// 刷新/重进恢复:有页面且尚无页面标签时补开最新一张的标签(不强切 // 刷新/重进恢复:有页面且尚无页面标签时补开最新一张的标签(不强切
// 右栏——只在实时事件到达时切换,避免每次进会话劫持视图)。 // 右栏——只在实时事件到达时切换,避免每次进会话劫持视图)。标签只用 Meta。
const conv = previewTabsKey(state.currentConvId) const conv = previewTabsKey(state.currentConvId)
const tabs = state.previewTabs[conv] ?? [] const tabs = state.previewTabs[conv] ?? []
const hasSurfaceTab = tabs.some(t => t.id.startsWith('surface:')) const hasSurfaceTab = tabs.some(t => t.id.startsWith('surface:'))
if (!hasSurfaceTab && (list?.length ?? 0) > 0) { if (!hasSurfaceTab && metas.length > 0) {
const latest = list[0] const latest = metas[0]
const opened = openPreviewTab(tabs, { id: 'surface:' + String(latest.surfaceId), name: latest.title || '页面' }) const opened = openPreviewTab(tabs, { id: 'surface:' + String(latest.surfaceId), name: latest.title || '页面' })
set({ set({
previewTabs: { ...state.previewTabs, [conv]: opened.tabs }, previewTabs: { ...state.previewTabs, [conv]: opened.tabs },
previewActive: { ...state.previewActive, [conv]: opened.activeId }, previewActive: { ...state.previewActive, [conv]: opened.activeId },
}) })
} }
const fetched = await Promise.all(metas.map(m =>
api.surfaceGet(String(m.surfaceId)).catch(() => null),
))
if (state.currentConvId !== convId) return
const hydrated = fetched.filter((s): s is SurfaceSnapshot => surfaceKey(s) != null)
// 慢水合不得覆盖并发 surface.updated 已写入的较新 revision。
set({ surfaces: mergeSurfacesByRevision(state.surfaces, hydrated) })
}).catch(() => {}) }).catch(() => {})
const resumeSeq = await store.reconcile() const resumeSeq = await store.reconcile()
store.connectLive(resumeSeq ?? state.lastSeq) store.connectLive(resumeSeq ?? state.lastSeq)
@@ -533,10 +556,10 @@ export const store = {
// KTD8:单一状态所有者——服务端快照为权威,本地按 revision 守卫: // KTD8:单一状态所有者——服务端快照为权威,本地按 revision 守卫:
// 旧修订/重复事件不覆盖新修订;切会话由 selectConversation 清空。 // 旧修订/重复事件不覆盖新修订;切会话由 selectConversation 清空。
const p = e.payload as SurfaceSnapshot const p = e.payload as SurfaceSnapshot
if (!p?.identity?.surfaceId) break const id = surfaceKey(p)
const id = String(p.identity.surfaceId) if (!id) break
const surfaces = state.surfaces.filter(x => String(x.identity.surfaceId) !== id) const surfaces = state.surfaces.filter(x => surfaceKey(x) !== id)
const existing = state.surfaces.find(x => String(x.identity.surfaceId) === id) const existing = state.surfaces.find(x => surfaceKey(x) === id)
if (!existing || p.revision > existing.revision) { if (!existing || p.revision > existing.revision) {
surfaces.push(p) surfaces.push(p)
set({ surfaces }) set({ surfaces })
@@ -784,6 +807,21 @@ export const store = {
const ws = await api.listWorkspaces() const ws = await api.listWorkspaces()
set({ serverWorkspaces: ws ?? [] }) set({ serverWorkspaces: ws ?? [] })
} catch { /* ignore */ } } catch { /* ignore */ }
// 审计入口能力门控(增量 2):与工作区清单同源刷新——能力撤销(插件卸载/命令停用)后入口随之隐藏。
try {
const cmds = await api.listCommands()
set({
rdmAuditAvailable: rdmAuditReady(cmds),
rdmRolesAvailable: rdmRolesReady(cmds),
rdmMembersAvailable: rdmMembersReady(cmds),
rdmDocReviewAvailable: rdmDocReviewReady(cmds),
rdmPermMatrixAvailable: rdmPermMatrixReady(cmds),
})
} catch { set({ rdmAuditAvailable: false }) }
try {
const sections = await api.adminZoneSections()
set({ adminSections: sections ?? [] })
} catch { /* ignore */ }
try { try {
const settings = await api.getSettings() const settings = await api.getSettings()
const runtime = settings.user.runtime const runtime = settings.user.runtime
@@ -877,7 +915,8 @@ export const store = {
}, },
async tidyCards() { async tidyCards() {
const done = state.cards.filter(c => c.status === 'done') // U1:不收纳失败语义卡(failed,或旧 done+danger),避免把失败当完成清掉。
const done = state.cards.filter(c => c.status === 'done' && c.tone !== 'danger')
for (const c of done) { for (const c of done) {
try { const out = await api.cardDismiss(c.id); store.upsertCard(out.card) } catch { /* 单卡失败不阻断 */ } try { const out = await api.cardDismiss(c.id); store.upsertCard(out.card) } catch { /* 单卡失败不阻断 */ }
} }
@@ -918,7 +957,7 @@ export const store = {
}, },
openSurface(surfaceId: string) { openSurface(surfaceId: string) {
// generative-ui:页面进预览第三栏(标签 id 带 surface: 前缀区分工件)。 // generative-ui:页面进预览第三栏(标签 id 带 surface: 前缀区分工件)。
const snap = state.surfaces.find(x => String(x.identity.surfaceId) === surfaceId) const snap = state.surfaces.find(x => surfaceKey(x) === surfaceId)
const conv = previewTabsKey(state.currentConvId) const conv = previewTabsKey(state.currentConvId)
const opened = openPreviewTab(state.previewTabs[conv] ?? [], { id: 'surface:' + surfaceId, name: snap?.spec?.title || '页面' }) const opened = openPreviewTab(state.previewTabs[conv] ?? [], { id: 'surface:' + surfaceId, name: snap?.spec?.title || '页面' })
set({ set({
@@ -932,7 +971,7 @@ export const store = {
async handleSurfaceAction(surfaceId: string, actionId: string, data: Record<string, unknown>) { async handleSurfaceAction(surfaceId: string, actionId: string, data: Record<string, unknown>) {
const inflight = surfaceActionsInflight[surfaceId + ':' + actionId] const inflight = surfaceActionsInflight[surfaceId + ':' + actionId]
if (inflight) return if (inflight) return
const snap = state.surfaces.find(x => String(x.identity.surfaceId) === surfaceId) const snap = state.surfaces.find(x => surfaceKey(x) === surfaceId)
if (!snap) { store.toast('页面快照不可用,无法提交'); return } if (!snap) { store.toast('页面快照不可用,无法提交'); return }
const requestId = (crypto.randomUUID ? crypto.randomUUID() : 'req-' + Date.now() + '-' + Math.random().toString(36).slice(2)) const requestId = (crypto.randomUUID ? crypto.randomUUID() : 'req-' + Date.now() + '-' + Math.random().toString(36).slice(2))
surfaceActionsInflight[surfaceId + ':' + actionId] = true surfaceActionsInflight[surfaceId + ':' + actionId] = true
+3
View File
@@ -628,3 +628,6 @@ button { font-family: inherit; font-size: inherit; color: inherit; }
.rdm-audit-event-detail { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-dim); } .rdm-audit-event-detail { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-dim); }
.rdm-audit-coverage { margin-top: 12px; } .rdm-audit-coverage { margin-top: 12px; }
.rdm-audit-coverage-item { display: flex; align-items: center; gap: 8px; padding: 3px 0; font-size: var(--fs-ui-sm); color: var(--text-dim); } .rdm-audit-coverage-item { display: flex; align-items: center; gap: 8px; padding: 3px 0; font-size: var(--fs-ui-sm); color: var(--text-dim); }
.rdm-audit-err { display: flex; flex-direction: column; gap: 8px; }
.rdm-audit-err-toggle { font-size: var(--fs-ui-caption); color: var(--text-dim); }
.rdm-audit-err-raw { display: block; font-family: var(--mono); font-size: var(--fs-code); color: var(--text-dim); background: var(--bg-inset); border-radius: var(--radius-sm); padding: 8px 12px; white-space: pre-wrap; word-break: break-all; }
+78 -2
View File
@@ -1,7 +1,9 @@
import { describe, expect, it } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import * as apiModule from './api'
import { api } from './api'
import { store } from './store' import { store } from './store'
import { previewTabsKey } from './previewtabs' import { previewTabsKey } from './previewtabs'
import type { StreamEvent, SurfaceSnapshot } from './contracts' import type { StreamEvent, SurfaceMeta, SurfaceSnapshot } from './contracts'
// U4/R5:surface.updated 投影的 revision 守卫——旧修订/重复事件不得覆盖新修订; // U4/R5:surface.updated 投影的 revision 守卫——旧修订/重复事件不得覆盖新修订;
// 服务端快照是唯一权威(KTD8 单一状态所有者)。 // 服务端快照是唯一权威(KTD8 单一状态所有者)。
@@ -75,3 +77,77 @@ describe('U6 工作区任务页', () => {
expect(store.getState().ui.workspaceSurfacePin).toBeNull() expect(store.getState().ui.workspaceSurfacePin).toBeNull()
}) })
}) })
describe('saved surfaces on conversation reload', () => {
const snapshot = (id: string, revision = 1) => surfEvent(1, id, revision, id).payload!
const meta = (id: string): SurfaceMeta => ({
surfaceId: id, title: id, pluginId: 'generative-ui', revision: 1,
conversationId: 'c1', updatedAt: '2026-10-12T00:00:00Z',
})
beforeEach(() => {
vi.spyOn(api, 'projectSurfaces').mockResolvedValue([])
vi.spyOn(api, 'surfaceList').mockResolvedValue([])
vi.spyOn(api, 'surfaceGet').mockImplementation(async id => snapshot(id))
vi.spyOn(api, 'conversationDetail').mockImplementation(async id => ({
conversation: { id, projectId: 'p1', title: id, createdAt: '', updatedAt: '' },
messages: [], runs: [], activeHitl: [], lastSeq: 0,
}))
vi.spyOn(api, 'getPlan').mockResolvedValue(null)
vi.spyOn(api, 'getTodos').mockResolvedValue(null)
vi.spyOn(api, 'listCards').mockResolvedValue([])
vi.spyOn(api, 'listTasks').mockResolvedValue([])
vi.spyOn(apiModule, 'connectEvents').mockReturnValue({ close: () => {} })
store.setUI({ workspaceSurfacePin: null })
const key = previewTabsKey(store.getState().currentConvId)
for (const tab of store.getState().previewTabs[key] ?? []) store.closePreview(tab.id)
})
afterEach(() => vi.restoreAllMocks())
it('hydrates the metadata directory before exposing two renderable snapshots', async () => {
vi.mocked(api.surfaceList).mockResolvedValue([meta('reload-1'), meta('reload-2')])
await store.openConversation('reload')
await vi.waitFor(() => {
expect(store.getState().surfaces).toEqual([snapshot('reload-1'), snapshot('reload-2')])
})
expect(api.surfaceGet).toHaveBeenCalledWith('reload-1')
expect(api.surfaceGet).toHaveBeenCalledWith('reload-2')
expect(store.getState().previewActive.reload).toBe('surface:reload-1')
})
it('isolates one unavailable page while restoring the remaining page', async () => {
vi.mocked(api.surfaceList).mockResolvedValue([meta('missing'), meta('available')])
vi.mocked(api.surfaceGet).mockImplementation(async id => {
if (id === 'missing') throw new Error('404: removed page')
return snapshot(id)
})
await store.openConversation('partial')
await vi.waitFor(() => expect(store.getState().surfaces).toEqual([snapshot('available')]))
})
it('keeps a newer live revision when an older snapshot arrives late', async () => {
let resolve!: (value: SurfaceSnapshot) => void
vi.mocked(api.surfaceList).mockResolvedValue([meta('racing')])
vi.mocked(api.surfaceGet).mockReturnValue(new Promise<SurfaceSnapshot>(r => { resolve = r }))
await store.openConversation('race')
store.applyEvent(surfEvent(301, 'racing', 2, 'live revision'))
resolve(snapshot('racing', 1))
await new Promise<void>(r => setTimeout(r, 0))
expect(store.getState().surfaces).toHaveLength(1)
expect(store.getState().surfaces[0].revision).toBe(2)
expect(store.getState().surfaces[0].spec.title).toBe('live revision')
})
it('discards hydration from the previous conversation after switching', async () => {
let resolve!: (value: SurfaceSnapshot) => void
vi.mocked(api.surfaceList).mockResolvedValueOnce([meta('previous')]).mockResolvedValue([])
vi.mocked(api.surfaceGet).mockReturnValue(new Promise<SurfaceSnapshot>(r => { resolve = r }))
await store.openConversation('previous-conv')
await store.openConversation('current-conv')
resolve(snapshot('previous'))
await new Promise<void>(r => setTimeout(r, 0))
expect(store.getState().currentConvId).toBe('current-conv')
expect(store.getState().surfaces).toEqual([])
})
})
+19
View File
@@ -0,0 +1,19 @@
// surface 投影可能短暂混入无 identity 的条目;读 id 一律经此助手,避免渲染崩溃。
import type { SurfaceSnapshot } from './contracts'
export function surfaceKey(x: { identity?: { surfaceId?: unknown } } | null | undefined): string | null {
const id = x?.identity?.surfaceId
return id == null || id === '' ? null : String(id)
}
/** 按 surfaceId 合并;同 id 取 revision 较大者。跳过无 identity 的脏项。 */
export function mergeSurfacesByRevision(a: SurfaceSnapshot[], b: SurfaceSnapshot[]): SurfaceSnapshot[] {
const byId = new Map<string, SurfaceSnapshot>()
for (const s of [...a, ...b]) {
const id = surfaceKey(s)
if (!id) continue
const existing = byId.get(id)
if (!existing || (s.revision ?? 0) >= (existing.revision ?? 0)) byId.set(id, s)
}
return [...byId.values()]
}
+27 -2
View File
@@ -1,6 +1,9 @@
// 体系工具排位:服务端声明的工作区对所有用户可见,按 shortcut 数字占位; // 体系工具排位:服务端声明的工作区对所有用户可见,按 shortcut 数字占位;
// 内置「代理」补进空位。文件浏览在第三栏「文件」入口(方案:入口收敛),不再占体系工具位。 // 内置「代理」补进空位。文件浏览在第三栏「文件」入口(方案:入口收敛),不再占体系工具位。
// 插件管理面板不进这条清单。 // 插件管理面板不进这条清单。
// 2026-10-12 增量 2(审计入口能力门控):「追溯审计」不再无条件内置——普通基座
// 没有任何 rdm.inspect.* 命令,入口可达而进入即 400。仅当命令面探测通过
//(rdmAuditReady / store.rdmAuditAvailable)才纳入;代理仍无条件以 ⌘1 补位。
export interface WorkspaceEntry { export interface WorkspaceEntry {
key: string key: string
@@ -16,6 +19,23 @@ export interface WorkspaceSource {
shortcut?: string shortcut?: string
} }
/** 审计工作区消费的全部 rdm.inspect.* 命令(capabilities 入口 + 四页签取数)。 */
export const RDM_AUDIT_COMMANDS = [
'rdm.inspect.capabilities',
'rdm.inspect.summary',
'rdm.inspect.tree',
'rdm.inspect.object',
'rdm.inspect.relations',
'rdm.inspect.events',
'rdm.inspect.history',
] as const
/** GET /api/commands 清单是否足以支撑审计工作区:七命令齐备且 enabled。清单不可用(未登录/请求失败)视为未就绪。 */
export function rdmAuditReady(cmds: { id?: string; enabled?: boolean }[] | null | undefined): boolean {
if (!Array.isArray(cmds)) return false
return RDM_AUDIT_COMMANDS.every(need => cmds.some(c => c?.id === need && c.enabled === true))
}
const BUILTINS: Omit<WorkspaceEntry, 'shortcut'>[] = [ const BUILTINS: Omit<WorkspaceEntry, 'shortcut'>[] = [
{ key: 'agents', title: '代理', icon: '🤖' }, { key: 'agents', title: '代理', icon: '🤖' },
{ key: 'rdm-audit', title: '追溯审计', icon: '🔍' }, { key: 'rdm-audit', title: '追溯审计', icon: '🔍' },
@@ -29,7 +49,12 @@ function shortcutNum(raw?: string): number | null {
return n >= 1 && n <= 9 ? n : null return n >= 1 && n <= 9 ? n : null
} }
export function buildWorkspaceEntries(server: WorkspaceSource[]): WorkspaceEntry[] { interface BuildWorkspaceOptions {
/** rdm.inspect.* 命令面探测通过(store.rdmAuditAvailable)。默认 false:能力未知/缺失不展示审计入口。 */
rdmAudit?: boolean
}
export function buildWorkspaceEntries(server: WorkspaceSource[], opts: BuildWorkspaceOptions = {}): WorkspaceEntry[] {
const used = new Set<number>() const used = new Set<number>()
const ranked: { rank: number; entry: Omit<WorkspaceEntry, 'shortcut'> }[] = [] const ranked: { rank: number; entry: Omit<WorkspaceEntry, 'shortcut'> }[] = []
const unranked: Omit<WorkspaceEntry, 'shortcut'>[] = [] const unranked: Omit<WorkspaceEntry, 'shortcut'>[] = []
@@ -57,7 +82,7 @@ export function buildWorkspaceEntries(server: WorkspaceSource[]): WorkspaceEntry
return 99 return 99
} }
ranked.push({ rank: takeFree(1), entry: BUILTINS[0] }) ranked.push({ rank: takeFree(1), entry: BUILTINS[0] })
ranked.push({ rank: takeFree(2), entry: BUILTINS[1] }) if (opts.rdmAudit === true) ranked.push({ rank: takeFree(2), entry: BUILTINS[1] })
for (const entry of unranked) ranked.push({ rank: takeFree(9), entry }) for (const entry of unranked) ranked.push({ rank: takeFree(9), entry })
return ranked return ranked
.filter(item => item.rank <= 9) .filter(item => item.rank <= 9)
+39
View File
@@ -0,0 +1,39 @@
import { describe, expect, it } from 'vitest'
import { classifyRdmError } from '../src/rdmErrors'
// 2026-10-12 增量 2(审计错误四分类):审计页不再把原始报错(400 回执 JSON)直出,
// 改为「能力缺失 / 登录已失效 / 查询失败」文案并保留原始回执供诊断;
// 「无可审计项目」由组件空态承担,不走本分类。
// 分类依据:api.ts json() 抛 `${status}: ${body}`;后端 unknown/disabled 命令
// 回 400 + "unknown or disabled command"(cmdbus.go Dispatch),总线未挂载回
// 503 "commands disabled"(server.go execCommand)。
describe('classifyRdmError', () => {
it('400 unknown or disabled command → 能力缺失', () => {
const raw = '400: {"receipt":{"state":"rejected","error":"unknown or disabled command: rdm.inspect.capabilities"}}'
const e = classifyRdmError(new Error(raw))
expect(e.kind).toBe('capability')
expect(e.message).toContain('当前服务未提供审计能力')
expect(e.raw).toContain('unknown or disabled command')
})
it('503 commands disabled → 能力缺失', () => {
expect(classifyRdmError('503: commands disabled').kind).toBe('capability')
})
it('401/403 → 登录已失效', () => {
expect(classifyRdmError('401: session expired').kind).toBe('auth')
expect(classifyRdmError(new Error('403: forbidden')).kind).toBe('auth')
})
it('其余错误 → 查询失败,保留原始串', () => {
const e = classifyRdmError('500: boom')
expect(e.kind).toBe('query')
expect(e.message).toContain('查询失败')
expect(e.raw).toBe('500: boom')
})
it('非 Error 输入可容忍', () => {
expect(classifyRdmError(undefined).kind).toBe('query')
expect(classifyRdmError({ weird: true }).kind).toBe('query')
})
})
+98
View File
@@ -0,0 +1,98 @@
// U6 页面接线契约测试(方案 r1 U6/KTD5):RDM 管理/项目页面的能力门控与命令
// 载荷构造是纯逻辑——先红后实现。门控语义与 rdmAuditReady 同源:命令清单不可用
//(未登录/请求失败/null)一律视为未就绪(fail-closed),普通基座不出现 RDM 页面。
import { describe, expect, it } from 'vitest'
import {
RDM_ROLES_COMMANDS, RDM_MEMBER_COMMANDS, RDM_DOC_REVIEW_COMMANDS, ROLE_ACTIONS,
rdmRolesReady, rdmMembersReady, rdmDocReviewReady,
roleCreatePayload, roleActionPayload, roleAssignPayload, roleDisablePayload,
memberAddPayload, memberRemovePayload, assignDocDutiesPayload,
docSubmitPayload, docApprovePayload, docRejectPayload, docFinalPayload, docStatusPayload,
RDM_PERM_MATRIX_COMMANDS, rdmPermMatrixReady, permCheckPayload, describeSource,
parseReviewers,
} from '../src/rdmManagement'
const cmd = (id: string, enabled = true) => ({ id, enabled })
const all = (ids: readonly string[]) => ids.map(id => cmd(id))
describe('RDM 页面能力门控', () => {
it('命令齐备且 enabled 才就绪', () => {
expect(rdmRolesReady(all(RDM_ROLES_COMMANDS))).toBe(true)
expect(rdmMembersReady(all(RDM_MEMBER_COMMANDS))).toBe(true)
expect(rdmDocReviewReady(all(RDM_DOC_REVIEW_COMMANDS))).toBe(true)
})
it('缺一命令即未就绪', () => {
const drop = (ids: readonly string[], skip: string) => ids.filter(i => i !== skip).map(id => cmd(id))
expect(rdmRolesReady(drop(RDM_ROLES_COMMANDS, 'rdm.role.list'))).toBe(false)
expect(rdmMembersReady(drop(RDM_MEMBER_COMMANDS, 'rdm.project.member.add'))).toBe(false)
expect(rdmDocReviewReady(drop(RDM_DOC_REVIEW_COMMANDS, 'rdm.review.doc.final'))).toBe(false)
})
it('disabled / null / 非数组 / 请求失败均未就绪(fail-closed)', () => {
expect(rdmRolesReady(RDM_ROLES_COMMANDS.map(id => cmd(id, false)))).toBe(false)
expect(rdmRolesReady(null)).toBe(false)
expect(rdmMembersReady(undefined)).toBe(false)
expect(rdmDocReviewReady('not-array' as unknown as never)).toBe(false)
})
})
describe('RDM 动作清单(12 项,与 perms.AllActions 对齐)', () => {
it('精确等于 RDM 动作枚举且不重复', () => {
expect([...ROLE_ACTIONS].sort()).toEqual([
'doc.publish', 'doc.read', 'doc.write', 'duty.assign', 'knowledge.publish',
'member.manage', 'project.archive', 'project.create', 'project.settings',
'review.participate', 'stage.advance', 'trace.edit',
])
expect(new Set(ROLE_ACTIONS).size).toBe(12)
})
})
describe('命令载荷构造(身份只经认证会话——载荷不含任何身份字段)', () => {
it('角色管理载荷', () => {
expect(roleCreatePayload('工程师')).toEqual({ name: '工程师' })
expect(roleActionPayload('role_ab', 'doc.write', false, true))
.toEqual({ roleId: 'role_ab', action: 'doc.write', default: false, cap: true })
expect(roleAssignPayload('bob', 'role_ab')).toEqual({ owner: 'bob', roleId: 'role_ab' })
expect(roleDisablePayload('role_ab', true)).toEqual({ roleId: 'role_ab', disabled: true })
})
it('项目成员载荷(role 缺省 member)', () => {
expect(memberAddPayload('p1', 'carol')).toEqual({ projectId: 'p1', member: 'carol', role: 'member' })
expect(memberAddPayload('p1', 'carol', 'owner')).toEqual({ projectId: 'p1', member: 'carol', role: 'owner' })
expect(memberRemovePayload('p1', 'carol')).toEqual({ projectId: 'p1', member: 'carol' })
})
it('文档职责与整文审签载荷', () => {
expect(assignDocDutiesPayload('p1', 'd1', 'alice', ['bob', 'carol'], 'dave'))
.toEqual({ projectId: 'p1', docId: 'd1', author: 'alice', reviewers: ['bob', 'carol'], approver: 'dave' })
expect(docSubmitPayload('p1', 'd1')).toEqual({ projectId: 'p1', docId: 'd1' })
expect(docApprovePayload('p1', 'd1', '通过')).toEqual({ projectId: 'p1', docId: 'd1', note: '通过' })
expect(docRejectPayload('p1', 'd1', '依据不足')).toEqual({ projectId: 'p1', docId: 'd1', reason: '依据不足' })
expect(docFinalPayload('p1', 'd1')).toEqual({ projectId: 'p1', docId: 'd1' })
expect(docFinalPayload('p1', 'd1', 3)).toEqual({ projectId: 'p1', docId: 'd1', round: 3 })
expect(docStatusPayload('p1', 'd1')).toEqual({ projectId: 'p1', docId: 'd1' })
})
it('审阅人 CSV 解析:去空白、去空项、保序去重', () => {
expect(parseReviewers('bob, carol,,bob')).toEqual(['bob', 'carol'])
expect(parseReviewers(' ')).toEqual([])
expect(parseReviewers('bob')).toEqual(['bob'])
})
})
describe('项目权限矩阵页(rdm.perm.check 消费)', () => {
it('命令面齐备才就绪(perm.check + 成员清单);缺一/disabled/清单不可用均未就绪', () => {
const all2 = RDM_PERM_MATRIX_COMMANDS.map(id => ({ id, enabled: true }))
expect(rdmPermMatrixReady(all2)).toBe(true)
expect(rdmPermMatrixReady(RDM_PERM_MATRIX_COMMANDS.slice(1).map(id => ({ id, enabled: true })))).toBe(false)
expect(rdmPermMatrixReady(RDM_PERM_MATRIX_COMMANDS.map(id => ({ id, enabled: false })))).toBe(false)
expect(rdmPermMatrixReady(null)).toBe(false)
})
it('矩阵查询载荷(身份只经认证会话)', () => {
expect(permCheckPayload('p1', 'bob')).toEqual({ projectId: 'p1', member: 'bob' })
})
it('来源标签:解释读面的人话映射;未知来源回退原文', () => {
expect(describeSource('admin')).toBe('系统管理员')
expect(describeSource('prof-role-default')).toContain('角色')
expect(describeSource('override')).toContain('覆盖')
expect(describeSource('relation-default')).toContain('关系')
expect(describeSource('non-member')).toContain('成员')
expect(describeSource('weird')).toBe('weird')
})
})
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest'
import { settingInputAttrs } from '../src/components/SettingsModal'
// 2026-10-12 增量 3:配置输入按字段类型渲染——此前 SettingInput 默认分支无条件
// type="password",浏览器把整排设置项当凭据表单(「password 不在 form 中/缺少
// username」警告的来源之一),且普通文本被无谓遮蔽。新契约:仅秘密字段用密码框。
describe('settingInputAttrs', () => {
it('secret=true → 密码框 + new-password', () => {
expect(settingInputAttrs({ key: 'llm.apiKey', label: '密钥', type: 'string', secret: true } as any))
.toEqual({ type: 'password', autoComplete: 'new-password' })
})
it('type=secret → 密码框', () => {
expect(settingInputAttrs({ key: 'x', label: 'X', type: 'secret' } as any).type).toBe('password')
})
it('普通文本 → text + off(不遮蔽、不当凭据)', () => {
const a = settingInputAttrs({ key: 'llm.baseUrl', label: '地址', type: 'string' } as any)
expect(a).toEqual({ type: 'text', autoComplete: 'off' })
})
it('无类型标注的默认项 → text', () => {
expect(settingInputAttrs({ key: 'ui.language', label: '语言' } as any).type).toBe('text')
})
})
+40
View File
@@ -0,0 +1,40 @@
import { describe, expect, it } from 'vitest'
import type { SurfaceSnapshot } from '../src/contracts'
import { mergeSurfacesByRevision, surfaceKey } from '../src/surfaceKey'
function snap(id: string, revision: number): SurfaceSnapshot {
return {
identity: {
surfaceId: id,
owner: 'o',
pluginId: 'p',
},
compat: { schemaVersion: 1, catalogVersion: '1' },
revision,
activationEpoch: 0,
spec: { title: id, nodes: [] },
}
}
describe('surfaceKey', () => {
it('reads nested identity and skips missing', () => {
expect(surfaceKey(snap('s1', 1))).toBe('s1')
expect(surfaceKey(undefined)).toBeNull()
expect(surfaceKey({} as SurfaceSnapshot)).toBeNull()
expect(surfaceKey({ identity: {} } as SurfaceSnapshot)).toBeNull()
})
})
describe('mergeSurfacesByRevision', () => {
it('keeps higher revision and drops dirty entries', () => {
const dirty = { revision: 99 } as SurfaceSnapshot
const merged = mergeSurfacesByRevision(
[snap('a', 1), dirty],
[snap('a', 3), snap('b', 1)],
)
expect(merged.map(s => [surfaceKey(s), s.revision])).toEqual([
['a', 3],
['b', 1],
])
})
})
+26
View File
@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest'
import { hasActiveProgressCard } from '../src/components/Workbench'
import type { ActivityCard } from '@ui'
function card(over: Partial<ActivityCard>): ActivityCard {
return {
id: 'card_1', projectId: 'prj_1', conversationId: 'cnv_1',
kind: 'progress', title: '材料整理', status: 'active', tone: 'info',
createdAt: '2026-10-12T10:00:00Z', updatedAt: '2026-10-12T10:00:00Z',
...over,
}
}
describe('hasActiveProgressCard', () => {
it('active/action_required progress 卡视为占用当前任务位', () => {
expect(hasActiveProgressCard([card({ status: 'active' })])).toBe(true)
expect(hasActiveProgressCard([card({ status: 'action_required' })])).toBe(true)
})
it('完成/失败 progress 或非 progress 不隐藏 CurrentTaskCard', () => {
expect(hasActiveProgressCard([card({ status: 'done', tone: 'ok' })])).toBe(false)
expect(hasActiveProgressCard([card({ status: 'failed', tone: 'danger' })])).toBe(false)
expect(hasActiveProgressCard([card({ kind: 'confirm', status: 'action_required' })])).toBe(false)
expect(hasActiveProgressCard([])).toBe(false)
})
})
+47 -8
View File
@@ -1,36 +1,75 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import { buildWorkspaceEntries } from '../src/workspaces' import { buildWorkspaceEntries, rdmAuditReady, RDM_AUDIT_COMMANDS } from '../src/workspaces'
// 三栏工作台(2026-10-11):文件浏览并入第三栏「文件」入口;体系工具内置 // 三栏工作台(2026-10-11):文件浏览并入第三栏「文件」入口;体系工具内置「代理」。
// 「代理」与「追溯审计」(U4 修复:第二个 builtin 此前未入列,入口不可达)。 // 2026-10-12 增量 2(审计入口能力门控):「追溯审计」不再无条件内置——普通基座
// 没有任何 rdm.inspect.* 命令,入口展示后进入即 400。新契约:仅当命令面探测
// 通过(opts.rdmAudit)才纳入 rdm-audit;代理仍无条件以 ⌘1 补位。
describe('buildWorkspaceEntries', () => { describe('buildWorkspaceEntries', () => {
it('没有领域插件时,代理补 ⌘1、追溯审计补 ⌘2', () => { it('没有领域插件且无 RDM 能力:只有代理占 ⌘1', () => {
const entries = buildWorkspaceEntries([]) const entries = buildWorkspaceEntries([])
expect(entries.map(e => `${e.shortcut} ${e.title}`)).toEqual(['⌘1 代理'])
})
it('没有领域插件且 RDM 能力通过:代理 ⌘1、追溯审计 ⌘2', () => {
const entries = buildWorkspaceEntries([], { rdmAudit: true })
expect(entries.map(e => `${e.shortcut} ${e.title}`)).toEqual(['⌘1 代理', '⌘2 追溯审计']) expect(entries.map(e => `${e.shortcut} ${e.title}`)).toEqual(['⌘1 代理', '⌘2 追溯审计'])
}) })
it('声明了 shortcut 的工作区占住该位,内置工具让位', () => { it('声明了 shortcut 的工作区占住该位,内置工具让位(能力开)', () => {
const entries = buildWorkspaceEntries([ const entries = buildWorkspaceEntries([
{ id: 'trace', title: '追溯网', shortcut: '1' }, { id: 'trace', title: '追溯网', shortcut: '1' },
]) ], { rdmAudit: true })
expect(entries.map(e => e.title)).toEqual(['追溯网', '代理', '追溯审计']) expect(entries.map(e => e.title)).toEqual(['追溯网', '代理', '追溯审计'])
expect(entries.map(e => e.shortcut)).toEqual(['⌘1', '⌘2', '⌘3']) expect(entries.map(e => e.shortcut)).toEqual(['⌘1', '⌘2', '⌘3'])
expect(entries[0].key).toBe('ws:trace') expect(entries[0].key).toBe('ws:trace')
}) })
it('无 RDM 能力:让位后只有代理,不出现追溯审计', () => {
const entries = buildWorkspaceEntries([
{ id: 'trace', title: '追溯网', shortcut: '1' },
])
expect(entries.map(e => e.title)).toEqual(['追溯网', '代理'])
})
it('未编号的工作区排在内置工具后面', () => { it('未编号的工作区排在内置工具后面', () => {
const entries = buildWorkspaceEntries([ const entries = buildWorkspaceEntries([
{ id: 'mem', title: '记忆库' }, { id: 'mem', title: '记忆库' },
]) ], { rdmAudit: true })
expect(entries.map(e => e.title)).toEqual(['代理', '追溯审计', '记忆库']) expect(entries.map(e => e.title)).toEqual(['代理', '追溯审计', '记忆库'])
}) })
it('九位占满时低序内置保留,溢出项截断', () => { it('九位占满时低序内置保留,溢出项截断', () => {
const server = Array.from({ length: 8 }, (_, i) => ({ id: `w${i}`, title: `w${i}`, shortcut: String(i + 1) })) const server = Array.from({ length: 8 }, (_, i) => ({ id: `w${i}`, title: `w${i}`, shortcut: String(i + 1) }))
const entries = buildWorkspaceEntries(server) const entries = buildWorkspaceEntries(server, { rdmAudit: true })
// ⌘1–8 被声明占住;代理取 ⌘9;追溯审计溢出截断(slice 0,9)。 // ⌘1–8 被声明占住;代理取 ⌘9;追溯审计溢出截断(slice 0,9)。
expect(entries.filter(e => e.key.startsWith('ws:'))).toHaveLength(8) expect(entries.filter(e => e.key.startsWith('ws:'))).toHaveLength(8)
expect(entries.map(e => e.title)).toContain('代理') expect(entries.map(e => e.title)).toContain('代理')
expect(entries.map(e => e.title)).not.toContain('追溯审计') expect(entries.map(e => e.title)).not.toContain('追溯审计')
}) })
}) })
// 能力探测依据后端 GET /api/commands(server.go listCommands:{ id, title, …, enabled })。
// 审计工作区消费七个 rdm.inspect.* 命令;任一缺失或 enabled=false 都视为能力未就绪。
describe('rdmAuditReady', () => {
const all = RDM_AUDIT_COMMANDS.map(id => ({ id, enabled: true }))
it('七命令齐备且启用 → true', () => {
expect(rdmAuditReady(all)).toBe(true)
})
it('普通基座空清单 / 缺任一命令 → false', () => {
expect(rdmAuditReady([])).toBe(false)
expect(rdmAuditReady(all.filter(c => c.id !== 'rdm.inspect.history'))).toBe(false)
})
it('存在但 enabled=false → false', () => {
const disabled = all.map(c => (c.id === 'rdm.inspect.capabilities' ? { ...c, enabled: false } : c))
expect(rdmAuditReady(disabled)).toBe(false)
})
it('清单不可用(未登录/请求失败)→ false,不展示入口', () => {
expect(rdmAuditReady(null)).toBe(false)
expect(rdmAuditReady(undefined)).toBe(false)
})
})