dsh-spec-collab 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +28 -7
  2. package/docs/assets/demo-01-workspace.png +0 -0
  3. package/docs/assets/demo-02-ai-review.png +0 -0
  4. package/docs/assets/demo-03-patches.png +0 -0
  5. package/docs/assets/demo-04-decisions.png +0 -0
  6. package/docs/assets/demo-05-ready.png +0 -0
  7. package/docs/experience-review-checklist-2026-08-24.md +142 -0
  8. package/docs/insight-import-template.csv +3 -0
  9. package/docs/insight-import-template.md +19 -0
  10. package/docs/migration-v3.md +23 -0
  11. package/lib/client.js +11456 -1275
  12. package/lib/index.js +1335 -93
  13. package/lib/types/client/AccessibleDialog.d.ts +9 -0
  14. package/lib/types/client/AccessibleDialog.d.ts.map +1 -0
  15. package/lib/types/client/SpecWorkbench.d.ts +94 -2
  16. package/lib/types/client/SpecWorkbench.d.ts.map +1 -1
  17. package/lib/types/client/api.d.ts +26 -3
  18. package/lib/types/client/api.d.ts.map +1 -1
  19. package/lib/types/client/drafts.d.ts +8 -0
  20. package/lib/types/client/drafts.d.ts.map +1 -0
  21. package/lib/types/client/mount.d.ts.map +1 -1
  22. package/lib/types/client/review-anchors.d.ts +5 -2
  23. package/lib/types/client/review-anchors.d.ts.map +1 -1
  24. package/lib/types/engine.d.ts +37 -3
  25. package/lib/types/engine.d.ts.map +1 -1
  26. package/lib/types/git-store.d.ts +6 -0
  27. package/lib/types/git-store.d.ts.map +1 -1
  28. package/lib/types/protocol.d.ts +245 -8
  29. package/lib/types/protocol.d.ts.map +1 -1
  30. package/lib/types/review-runtime.d.ts +6 -0
  31. package/lib/types/review-runtime.d.ts.map +1 -1
  32. package/lib/types/routes.d.ts.map +1 -1
  33. package/lib/types/structured-diff.d.ts +3 -0
  34. package/lib/types/structured-diff.d.ts.map +1 -0
  35. package/package.json +5 -2
  36. package/src/client/AccessibleDialog.tsx +42 -0
  37. package/src/client/SpecWorkbench.tsx +1084 -176
  38. package/src/client/api.ts +8 -3
  39. package/src/client/drafts.ts +51 -0
  40. package/src/client/mount.tsx +40 -9
  41. package/src/client/review-anchors.ts +66 -18
  42. package/src/client/workbench.module.css +330 -73
  43. package/src/engine.ts +485 -44
  44. package/src/git-store.ts +87 -18
  45. package/src/index.ts +1 -1
  46. package/src/protocol.ts +64 -13
  47. package/src/review-runtime.ts +39 -11
  48. package/src/routes.ts +33 -4
  49. package/src/structured-diff.ts +75 -0
  50. package/src/tools.ts +1 -1
@@ -1,16 +1,18 @@
1
- import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from 'react'
1
+ import { useEffect, useMemo, useRef, useState, type CSSProperties, type FormEvent, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react'
2
2
  import MarkdownIt from 'markdown-it'
3
3
  import ToastEditor from '@toast-ui/editor'
4
4
  import '@toast-ui/editor/dist/i18n/zh-cn'
5
5
  import { InputRule, inputRules } from 'prosemirror-inputrules'
6
- import type { CollaborationAction, CommentResolution, MyActionItem, ParticipantRole, ParticipantSnapshot, RequirementStage, RequirementVersion, RequirementView, ReviewItemType, ReviewKind, ReviewWorkspaceSummary, SaveConflict } from '../protocol.ts'
6
+ import type { CollaborationAction, CommentResolution, CommentThread, MyActionItem, Notification, ParticipantRole, ParticipantSnapshot, RequirementStage, RequirementSummary, RequirementView, ReviewItemType, ReviewKind, ReviewWorkspaceSummary, SaveConflict, StructuredDiff } from '../protocol.ts'
7
7
  import type { SpecApi } from './api.ts'
8
8
  import { browserUuid } from './browser-uuid.ts'
9
- import { reviewBlockSelector, reviewSourceSnippets, reviewTargetElements } from './review-anchors.ts'
9
+ import { commentTargetElements, reviewBlockSelector, reviewSourceSnippets, reviewTargetElements } from './review-anchors.ts'
10
10
  import { friendlyActionError, workflowState, type TaskView, type WorkflowCommand, type WorkflowState } from './workflow.ts'
11
+ import { AccessibleDialog } from './AccessibleDialog.tsx'
12
+ import { deleteDraft, loadDraft, safeHttpUrl, saveDraft, truncateGraphemes } from './drafts.ts'
11
13
  import css from './workbench.module.css'
12
14
 
13
- const md = new MarkdownIt({ html: false, linkify: true })
15
+ const md = new MarkdownIt({ html: false, linkify: false })
14
16
  const inlineStyleRule = (pattern: RegExp, markName: 'strong' | 'emph' | 'code'): InputRule => new InputRule(pattern, (state, match, start, end) => {
15
17
  const text = match[1]
16
18
  const mark = state.schema.marks[markName]
@@ -22,26 +24,102 @@ const markdownShortcutsPlugin = () => ({ wysiwygPlugins: [() => inputRules({ rul
22
24
  new InputRule(/^```\s$/, (state, _match, start, end) => state.tr.delete(start, end).setBlockType(start, start, state.schema.nodes.codeBlock!)),
23
25
  inlineStyleRule(/\*\*([^*]+)\*\*$/, 'strong'), inlineStyleRule(/(?<!\*)\*([^*]+)\*$/, 'emph'), inlineStyleRule(/`([^`]+)`$/, 'code'),
24
26
  ] })] })
25
- type PrimaryMode = 'tasks' | 'discussion' | 'records'
27
+ type PrimaryMode = 'tasks' | 'discussion' | 'insights' | 'records'
26
28
  type RecordView = 'decisions' | 'versions'
27
- type CommentAnchor = { quote: string; prefix: string; suffix: string; heading?: string }
28
- type EditorSelection = CommentAnchor & { rect: { top: number; left: number } }
29
+ type DeepLinkTarget = { primaryMode: PrimaryMode; taskView?: TaskView; recordView?: RecordView; focusObjectId?: string; reviewObjectId?: string; commentObjectId?: string; error?: string }
30
+ export function resolveDeepLinkTarget(requirement: RequirementView, view: string, objectId?: string): DeepLinkTarget {
31
+ if (view === 'discussion') return objectId && !requirement.comments.some(item => item.id === objectId) ? { primaryMode: 'discussion', error: '链接指向的评论不存在或已失效' } : { primaryMode: 'discussion', ...(objectId ? { focusObjectId: objectId, commentObjectId: objectId } : {}) }
32
+ if (view === 'insights') return { primaryMode: 'insights', ...(objectId ? { focusObjectId: objectId } : {}) }
33
+ if (view === 'records') {
34
+ if (!objectId) return { primaryMode: 'records' }
35
+ if (requirement.decisions.some(item => item.id === objectId)) return { primaryMode: 'records', recordView: 'decisions', focusObjectId: objectId }
36
+ if (requirement.history.some(item => item.commit === objectId)) return { primaryMode: 'records', recordView: 'versions', focusObjectId: objectId }
37
+ return { primaryMode: 'records', error: '链接指向的决策或版本不存在' }
38
+ }
39
+ if (view !== 'tasks') return { primaryMode: 'tasks', error: '链接指向的协作视图不存在' }
40
+ if (!objectId) return { primaryMode: 'tasks' }
41
+ if (objectId === requirement.id && requirement.stage === 'ready') return { primaryMode: 'tasks', taskView: 'ready' }
42
+ const action = requirement.actionItems.find(item => item.id === objectId)
43
+ const sourceType = action?.sourceType
44
+ const sourceId = action?.sourceId ?? objectId
45
+ if (sourceType === 'comment' || requirement.comments.some(item => item.id === sourceId)) return { primaryMode: 'discussion', focusObjectId: sourceId, commentObjectId: sourceId }
46
+ if (sourceType === 'patch' || requirement.patches.some(item => item.id === sourceId)) return { primaryMode: 'tasks', taskView: 'patches', focusObjectId: sourceId }
47
+ if (sourceType === 'decision' || requirement.decisions.some(item => item.id === sourceId)) return { primaryMode: 'records', recordView: 'decisions', focusObjectId: sourceId }
48
+ if (sourceType === 'review-item' || requirement.reviewItems.some(item => item.id === sourceId)) return { primaryMode: 'tasks', taskView: 'review', focusObjectId: sourceId, reviewObjectId: sourceId }
49
+ return { primaryMode: 'tasks', error: '链接指向的待办对象不存在或已失效' }
50
+ }
51
+ export type CommentAnchor = { quote: string; prefix: string; suffix: string; heading?: string }
52
+ export type InlinePopoverPosition = { rect: { top: number; left: number }; placement: 'above' | 'below'; maxHeight?: number }
53
+ export type EditorSelection = CommentAnchor & InlinePopoverPosition
29
54
  type ReviewOpenRequest = { objectId: string; requestId: number }
55
+ type InlineReviewTarget = { itemId: string; sourceKey?: string } & Partial<InlinePopoverPosition>
56
+ type DocumentAnchorFocus = { kind: 'review'; objectId: string; sourceKey?: string } | { kind: 'comment'; objectId: string }
57
+ type PendingNavigation = { kind: 'select'; requirementId: string } | { kind: 'close' } | { kind: 'toggle-archive' } | { kind: 'deep-link'; hash: string } | { kind: 'archive'; requirementId: string; archived: boolean }
58
+ const inlineReviewPopoverSize = { width: 720, height: 760 } as const
59
+ function inlinePopoverPositionFromRect(rect: Pick<DOMRect, 'top' | 'bottom' | 'left'>, size: { width: number; height: number }): InlinePopoverPosition {
60
+ const padding = 12
61
+ const gap = 10
62
+ const viewportMaxHeight = Math.max(160, window.innerHeight - padding * 2)
63
+ const desiredHeight = Math.min(size.height, viewportMaxHeight)
64
+ const left = Math.min(Math.max(padding, rect.left), Math.max(padding, window.innerWidth - size.width - padding))
65
+ if (size.height >= 600) {
66
+ const placement: InlinePopoverPosition['placement'] = rect.top > window.innerHeight / 2 ? 'above' : 'below'
67
+ const top = Math.max(padding, (window.innerHeight - desiredHeight) / 2)
68
+ return { rect: { top, left }, placement, maxHeight: desiredHeight }
69
+ }
70
+ const spaceBelow = Math.max(0, window.innerHeight - rect.bottom - gap - padding)
71
+ const spaceAbove = Math.max(0, rect.top - gap - padding)
72
+ const usefulBelowHeight = Math.min(desiredHeight, size.height > 360 ? 280 : 180)
73
+ const placement: InlinePopoverPosition['placement'] = spaceBelow >= usefulBelowHeight || spaceBelow >= spaceAbove ? 'below' : 'above'
74
+ const available = placement === 'below' ? spaceBelow : spaceAbove
75
+ const maxHeight = Math.max(160, Math.min(desiredHeight, available || viewportMaxHeight))
76
+ const rawTop = placement === 'below' ? rect.bottom + gap : rect.top - maxHeight - gap
77
+ const top = Math.min(Math.max(padding, rawTop), Math.max(padding, window.innerHeight - maxHeight - padding))
78
+ return { rect: { top, left }, placement, maxHeight }
79
+ }
80
+ function visibleEditorContents(root: HTMLElement | null | undefined): HTMLElement | undefined {
81
+ const candidates = Array.from(root?.querySelectorAll<HTMLElement>('.toastui-editor-contents') ?? [])
82
+ const visible = candidates.filter(element => {
83
+ const rect = element.getBoundingClientRect()
84
+ const style = window.getComputedStyle(element)
85
+ return rect.width > 0 && rect.height > 0 && style.display !== 'none' && style.visibility !== 'hidden'
86
+ })
87
+ return visible.find(element => element.classList.contains('ProseMirror')) ?? visible[0] ?? candidates.find(element => element.classList.contains('ProseMirror')) ?? candidates.at(-1)
88
+ }
89
+ export function annotationScrollTargets(root: HTMLElement | null | undefined): HTMLElement[] {
90
+ if (!root) return []
91
+ const targets: HTMLElement[] = []
92
+ const add = (element: HTMLElement | null | undefined): void => {
93
+ if (element && !targets.includes(element)) targets.push(element)
94
+ }
95
+ add(visibleEditorContents(root))
96
+ root.querySelectorAll<HTMLElement>('.ProseMirror.toastui-editor-contents, .toastui-editor-ww-container, .toastui-editor-main').forEach(add)
97
+ return targets
98
+ }
30
99
  function newParticipant(): ParticipantSnapshot { return { participantId: browserUuid(), nickname: '', role: 'product', kind: 'human' } }
31
100
  function loadParticipant(): ParticipantSnapshot { try { const value = JSON.parse(localStorage.getItem('dsh-spec-collab.participant') ?? '') as ParticipantSnapshot; if (value.participantId) return { ...value, kind: 'human' } } catch {} return newParticipant() }
32
- function stageLabel(stage: RequirementStage): string { return ({ 'product-review': '产品审核', 'product-confirmation': '产品确认', 'joint-review': '产研共审', ready: 'Ready' })[stage] }
33
- function currentPendingActions(requirement: RequirementView): RequirementView['actionItems'] {
34
- const currentSourceIds = new Set([
35
- ...requirement.reviewItems.filter(item => item.commit === requirement.currentCommit).map(item => item.id),
36
- ...requirement.comments.filter(item => item.commit === requirement.currentCommit).map(item => item.id),
37
- ...requirement.patches.filter(item => item.baseCommit === requirement.currentCommit).map(item => item.id),
38
- ...requirement.decisions.filter(item => item.commit === requirement.currentCommit).map(item => item.id),
39
- ...requirement.confirmations.filter(item => item.commit === requirement.currentCommit).map(item => item.id),
40
- ])
41
- return requirement.actionItems.filter(item => item.status === 'pending' && currentSourceIds.has(item.sourceId))
101
+ function stageLabel(stage: RequirementStage): string { return ({ 'product-review': '澄清', 'product-confirmation': '产品确认', 'joint-review': '产研确认', ready: '已就绪' })[stage] }
102
+ function relativeTime(timestamp: number): string { const seconds = Math.max(0, Math.floor((Date.now() - timestamp) / 1000)); if (seconds < 60) return '刚刚'; const minutes = Math.floor(seconds / 60); if (minutes < 60) return `${minutes} 分钟前`; const hours = Math.floor(minutes / 60); if (hours < 24) return `${hours} 小时前`; return `${Math.floor(hours / 24)} 天前` }
103
+ function durationText(milliseconds: number): string { const seconds = Math.max(0, Math.round(milliseconds / 1000)); return seconds < 60 ? `${seconds} 秒` : `${Math.floor(seconds / 60)} 分 ${seconds % 60} 秒` }
104
+ function cleanDisplayText(value: string, max = 84): string { return truncateGraphemes(value.replace(/\uFFFD+/g, ''), max) }
105
+ function downloadText(name: string, text: string): void { const url = URL.createObjectURL(new Blob([text], { type: 'text/markdown;charset=utf-8' })); const anchor = document.createElement('a'); anchor.href = url; anchor.download = name; anchor.click(); URL.revokeObjectURL(url) }
106
+ function handleTabs<T extends string>(event: ReactKeyboardEvent<HTMLElement>, values: readonly T[], current: T, setCurrent: (value: T) => void): void {
107
+ if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return
108
+ event.preventDefault(); const index = Math.max(0, values.indexOf(current)); const next = event.key === 'Home' ? 0 : event.key === 'End' ? values.length - 1 : event.key === 'ArrowRight' ? (index + 1) % values.length : (index - 1 + values.length) % values.length
109
+ setCurrent(values[next]!); window.setTimeout(() => (event.currentTarget.querySelectorAll<HTMLElement>('[role="tab"]')[next])?.focus(), 0)
110
+ }
111
+ function requirementParticipantIds(requirement: RequirementSummary): Set<string> { return new Set(requirement.participantIds) }
112
+ export function mentionedParticipantIds(body: string, participants: ParticipantSnapshot[]): string[] {
113
+ return participants.filter(participant => {
114
+ const token = `@${participant.nickname}`; let index = body.indexOf(token)
115
+ while (index >= 0) { const next = body[index + token.length]; if (next === undefined || /[\s,,。!?;;、::))\]}]/u.test(next)) return true; index = body.indexOf(token, index + token.length) }
116
+ return false
117
+ }).map(item => item.participantId)
42
118
  }
43
119
  export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => void }) {
44
- const [requirements, setRequirements] = useState<RequirementView[]>([])
120
+ const workbenchRef = useRef<HTMLDivElement>(null)
121
+ const [requirements, setRequirements] = useState<RequirementSummary[]>([])
122
+ const [selectedRequirement, setSelectedRequirement] = useState<RequirementView>()
45
123
  const [reviewWorkspaces, setReviewWorkspaces] = useState<ReviewWorkspaceSummary[]>([])
46
124
  const [participantBindings, setParticipantBindings] = useState<ParticipantSnapshot[]>([])
47
125
  const [selectedId, setSelectedId] = useState<string>()
@@ -58,17 +136,25 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
58
136
  const [renameTitle, setRenameTitle] = useState('')
59
137
  const [documentsOpen, setDocumentsOpen] = useState(true)
60
138
  const [reviewOpen, setReviewOpen] = useState(true)
139
+ const [focusMode, setFocusMode] = useState(false)
140
+ const previousPaneState = useRef({ documents: true, review: true })
141
+ const [documentDrawerOpen, setDocumentDrawerOpen] = useState(false)
61
142
  const [documentsWidth, setDocumentsWidth] = useState(() => Number(localStorage.getItem('dsh-spec-collab.documents-width')) || 220)
62
143
  const [reviewWidth, setReviewWidth] = useState(() => Number(localStorage.getItem('dsh-spec-collab.review-width')) || 430)
63
144
  const [createForm, setCreateForm] = useState({ title: '', rawRequirement: '', sources: '', workspaceId: '' })
64
145
  const [primaryMode, setPrimaryMode] = useState<PrimaryMode>('tasks')
65
146
  const [taskView, setTaskView] = useState<TaskView>('review')
66
147
  const [recordView, setRecordView] = useState<RecordView>('decisions')
148
+ const [pendingWorkflow, setPendingWorkflow] = useState<Extract<WorkflowCommand, { kind: 'advance' | 'confirm' | 'generate-ready' }>>()
149
+ const [pendingNavigation, setPendingNavigation] = useState<PendingNavigation>()
67
150
  const [mobilePane, setMobilePane] = useState<'spec' | 'collab'>('spec')
68
151
  const [reviewOpenRequest, setReviewOpenRequest] = useState<ReviewOpenRequest>()
69
152
  const reviewOpenRequestId = useRef(0)
70
- const [focusedReviewId, setFocusedReviewId] = useState<string>()
71
- const [reviewSourceFocusRequest, setReviewSourceFocusRequest] = useState(0)
153
+ const [deepLinkObjectId, setDeepLinkObjectId] = useState<string>()
154
+ const resolvedDeepLinkHash = useRef('')
155
+ const approvedDeepLinkHash = useRef('')
156
+ const [documentFocus, setDocumentFocus] = useState<DocumentAnchorFocus>()
157
+ const [documentFocusRequest, setDocumentFocusRequest] = useState(0)
72
158
  const [draft, setDraft] = useState('')
73
159
  const [summary, setSummary] = useState('')
74
160
  const [notice, setNotice] = useState('')
@@ -77,29 +163,136 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
77
163
  const [mergeDraft, setMergeDraft] = useState('')
78
164
  const [myItems, setMyItems] = useState<MyActionItem[]>([])
79
165
  const [commentText, setCommentText] = useState('')
80
- const [selection, setSelection] = useState<CommentAnchor>()
81
166
  const [draftSelection, setDraftSelection] = useState<EditorSelection>()
82
- const visibleRequirements = requirements.filter(item => Boolean(item.archivedAt) === showArchived)
83
- const selected = requirements.find(item => item.id === selectedId) ?? visibleRequirements[0]
167
+ const [inlineReview, setInlineReview] = useState<InlineReviewTarget>()
168
+ const [requirementQuery, setRequirementQuery] = useState('')
169
+ const [requirementFilters, setRequirementFilters] = useState<{ stage: 'all' | RequirementStage; participantId: string; risk: boolean; unread: boolean; insights: boolean }>({ stage: 'all', participantId: '', risk: false, unread: false, insights: false })
170
+ const [pageCommentOpen, setPageCommentOpen] = useState(false)
171
+ const [pageCommentText, setPageCommentText] = useState('')
172
+ const [notifications, setNotifications] = useState<Notification[]>([])
173
+ const [notificationsOpen, setNotificationsOpen] = useState(false)
174
+ const [myWorkOpen, setMyWorkOpen] = useState(false)
175
+ const [draftSavedAt, setDraftSavedAt] = useState<number>()
176
+ const [draftContextKey, setDraftContextKey] = useState<string>()
177
+ const [undoArchiveId, setUndoArchiveId] = useState<string>()
178
+ const scrollPositions = useRef(new Map<string, number>())
179
+ const normalizedQuery = requirementQuery.trim().toLocaleLowerCase()
180
+ const unreadRequirementIds = new Set(notifications.filter(item => item.readAt === undefined).map(item => item.requirementId))
181
+ const visibleRequirements = requirements.filter(item => Boolean(item.archivedAt) === showArchived
182
+ && (!normalizedQuery || `${item.id}\n${item.title}`.toLocaleLowerCase().includes(normalizedQuery))
183
+ && (requirementFilters.stage === 'all' || item.stage === requirementFilters.stage)
184
+ && (!requirementFilters.participantId || requirementParticipantIds(item).has(requirementFilters.participantId))
185
+ && (!requirementFilters.risk || item.metrics.riskCount > 0)
186
+ && (!requirementFilters.unread || unreadRequirementIds.has(item.id))
187
+ && (!requirementFilters.insights || item.metrics.insightCount > 0))
188
+ .sort((left, right) => right.updatedAt - left.updatedAt)
189
+ const activeRequirementFilterCount = Number(requirementFilters.stage !== 'all') + Number(Boolean(requirementFilters.participantId)) + Number(requirementFilters.risk) + Number(requirementFilters.unread) + Number(requirementFilters.insights)
190
+ const selected = selectedRequirement?.id === selectedId ? selectedRequirement : undefined
84
191
  const manageTarget = requirements.find(item => item.id === manageTargetId)
85
192
  const boundRole = participantBindings.find(item => item.participantId === participant.participantId)?.role
86
193
  const currentMyItems = selected ? myItems.filter(item => item.requirementId === selected.id) : []
87
194
  const currentReviews = selected?.reviewItems.filter(item => item.commit === selected.currentCommit && !['resolved', 'invalidated', 'non-blocking-verify'].includes(item.status)) ?? []
88
195
  const documentReviews = useMemo(() => selected?.reviewItems.filter(item => item.commit === selected.currentCommit && !['resolved', 'invalidated'].includes(item.status)).slice().sort((left, right) => Number(right.status !== 'non-blocking-verify') - Number(left.status !== 'non-blocking-verify') || Number(right.severity === 'blocking') - Number(left.severity === 'blocking') || right.updatedAt - left.updatedAt) ?? [], [selected?.reviewItems, selected?.currentCommit])
196
+ const documentComments = useMemo(() => selected?.comments.filter(item => item.commit === selected.currentCommit && !['invalidated', 'orphaned'].includes(item.status)).slice().sort((left, right) => Number(right.status === 'open') - Number(left.status === 'open') || right.updatedAt - left.updatedAt) ?? [], [selected?.comments, selected?.currentCommit])
197
+ const focusedReviewId = documentFocus?.kind === 'review' ? documentFocus.objectId : undefined
198
+ const focusedCommentId = documentFocus?.kind === 'comment' ? documentFocus.objectId : undefined
199
+ const inlineReviewItem = selected?.reviewItems.find(item => item.id === inlineReview?.itemId)
200
+ const nextInlineReview = selected && inlineReviewItem ? currentReviews.find(item => item.status === 'open' && item.id !== inlineReviewItem.id) : undefined
89
201
  const pendingPatches = selected?.patches.filter(item => item.baseCommit === selected.currentCommit && item.status === 'pending') ?? []
90
- const openDiscussions = selected?.comments.filter(item => item.commit === selected.currentCommit && item.status === 'open').length ?? 0
202
+ const openDiscussions = selected?.metrics.openCommentCount ?? 0
91
203
  const failedChecks = selected?.readiness.filter(item => !item.passed).length ?? 0
204
+ const openReviewCount = selected?.metrics.openReviewCount ?? 0
205
+ const blockingReviewCount = selected?.metrics.riskCount ?? 0
206
+ const activeDecisionCount = selected?.metrics.activeDecisionCount ?? 0
207
+ const invalidatedDecisionCount = selected?.decisions.filter(item => item.status === 'invalidated').length ?? 0
208
+ const runningAiCount = selected?.aiRuns.filter(item => item.commit === selected.currentCommit && ['queued', 'running'].includes(item.status)).length ?? 0
92
209
  const workflow = selected ? workflowState(selected, participant.role) : undefined
210
+ const assertiveNotice = /失败|错误|不存在|冲突|损坏|无法|禁止|失效|未登记|阻止/.test(notice)
93
211
 
94
- const refresh = async (): Promise<void> => { try { const state = await api.state(); setRequirements(state.requirements); setParticipantBindings(state.participants); const binding = state.participants.find(item => item.participantId === participant.participantId); if (binding && binding.role !== participant.role) setParticipant(current => ({ ...current, role: binding.role })); setSelectedId(current => current && state.requirements.some(item => item.id === current) ? current : state.requirements[0]?.id) } catch (error) { setNotice(error instanceof Error ? error.message : String(error)) } }
212
+ const registered = participant.nickname.trim().length >= 2
213
+ const participantRef = useRef(participant); participantRef.current = participant
214
+ const selectedIdRef = useRef(selectedId); selectedIdRef.current = selectedId
215
+ const refresh = async (requestedId: string | undefined = selectedIdRef.current): Promise<void> => { try { const state = await api.state(requestedId); const currentParticipant = participantRef.current; const fallbackId = state.requirement?.id ?? state.requirements.find(item => item.archivedAt === undefined)?.id ?? state.requirements[0]?.id; const nextId = requestedId && state.requirements.some(item => item.id === requestedId) ? requestedId : fallbackId; setRequirements(state.requirements); setParticipantBindings(state.participants); setSelectedId(nextId); if (state.requirement?.id === nextId) setSelectedRequirement(state.requirement); else if (!nextId) setSelectedRequirement(undefined); const binding = state.participants.find(item => item.participantId === currentParticipant.participantId); if (binding && binding.role !== currentParticipant.role) setParticipant(current => ({ ...current, role: binding.role })); if (currentParticipant.nickname.trim().length >= 2) void api.notifications(currentParticipant.participantId).then(result => setNotifications(result.items), error => setNotice(error instanceof Error ? error.message : String(error))) } catch (error) { setNotice(error instanceof Error ? error.message : String(error)) } }
95
216
  useEffect(() => { void refresh(); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))); return api.events(() => { void refresh() }) }, [])
96
- useEffect(() => { if (selected) setDraft(selected.version.markdown) }, [selected?.id, selected?.currentCommit])
97
- useEffect(() => { setFocusedReviewId(undefined); setDraftSelection(undefined) }, [selected?.id, selected?.currentCommit])
217
+ useEffect(() => { if (!selectedId || selectedRequirement?.id === selectedId) return; void refresh(selectedId) }, [selectedId, selectedRequirement?.id])
218
+ useEffect(() => {
219
+ let cancelled = false
220
+ setDraftContextKey(undefined)
221
+ if (!selected) { setDraft(''); setSummary(''); return }
222
+ const contextKey = `${selected.id}:${participant.participantId}:${selected.currentCommit}`
223
+ void loadDraft(selected.id, participant.participantId).then(saved => {
224
+ if (cancelled) return
225
+ if (saved && saved.markdown !== selected.version.markdown) { setDraft(saved.markdown); setSummary(saved.summary); setDraftSavedAt(saved.updatedAt); setNotice(saved.baseCommit === selected.currentCommit ? '已恢复本地草稿' : '已恢复旧基线草稿,保存时会进入冲突合并') }
226
+ else { setDraft(selected.version.markdown); setSummary(''); setDraftSavedAt(undefined) }
227
+ setDraftContextKey(contextKey)
228
+ })
229
+ return () => { cancelled = true }
230
+ }, [selected?.id, selected?.currentCommit, participant.participantId])
231
+ useEffect(() => { setDocumentFocus(undefined); setDraftSelection(undefined); setCommentText(''); setInlineReview(undefined) }, [selected?.id, selected?.currentCommit])
98
232
  useEffect(() => { localStorage.setItem('dsh-spec-collab.participant', JSON.stringify(participant)) }, [participant])
99
233
  useEffect(() => { localStorage.setItem('dsh-spec-collab.documents-width', String(documentsWidth)) }, [documentsWidth])
100
234
  useEffect(() => { localStorage.setItem('dsh-spec-collab.review-width', String(reviewWidth)) }, [reviewWidth])
101
235
  useEffect(() => { if (!registered) { setMyItems([]); return }; void api.myItems(participant).then(setMyItems, error => setNotice(error instanceof Error ? error.message : String(error))) }, [participant.participantId, participant.role, requirements])
102
- const registered = participant.nickname.trim().length >= 2
236
+ useEffect(() => {
237
+ if (!selected || draftContextKey !== `${selected.id}:${participant.participantId}:${selected.currentCommit}` || draft === selected.version.markdown) return
238
+ const timer = window.setTimeout(() => { const updatedAt = Date.now(); void saveDraft({ requirementId: selected.id, participantId: participant.participantId, baseCommit: selected.currentCommit, markdown: draft, summary, updatedAt }).then(() => setDraftSavedAt(updatedAt)) }, 500)
239
+ return () => window.clearTimeout(timer)
240
+ }, [selected?.id, selected?.currentCommit, selected?.version.markdown, participant.participantId, draft, summary, draftContextKey])
241
+ useEffect(() => {
242
+ const beforeUnload = (event: BeforeUnloadEvent): void => { if (selected && draft !== selected.version.markdown) { event.preventDefault(); event.returnValue = '' } }
243
+ window.addEventListener('beforeunload', beforeUnload); return () => window.removeEventListener('beforeunload', beforeUnload)
244
+ }, [selected?.id, selected?.version.markdown, draft])
245
+ useEffect(() => {
246
+ if (!selected) return
247
+ const timer = window.setTimeout(() => { const scroller = workbenchRef.current?.querySelector<HTMLElement>('.toastui-editor-ww-container'); if (scroller) scroller.scrollTop = scrollPositions.current.get(selected.id) ?? 0 }, 80)
248
+ return () => { window.clearTimeout(timer); const scroller = workbenchRef.current?.querySelector<HTMLElement>('.toastui-editor-ww-container'); if (scroller) scrollPositions.current.set(selected.id, scroller.scrollTop) }
249
+ }, [selected?.id])
250
+ useEffect(() => {
251
+ const shortcut = (event: KeyboardEvent): void => {
252
+ if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLocaleLowerCase() === 'f') { event.preventDefault(); toggleFocusMode() }
253
+ else if ((event.metaKey || event.ctrlKey) && event.key.toLocaleLowerCase() === 's') { event.preventDefault(); if (selected && draft !== selected.version.markdown && summary.trim()) void save() }
254
+ }
255
+ window.addEventListener('keydown', shortcut); return () => window.removeEventListener('keydown', shortcut)
256
+ }, [focusMode, documentsOpen, reviewOpen, selected?.id, selected?.version.markdown, draft, summary])
257
+ useEffect(() => {
258
+ const resolve = (): void => {
259
+ if (location.hash === resolvedDeepLinkHash.current) return
260
+ const match = /^#spec-collab\/([^/]+)\/([^/]+)(?:\/([^?]+))?/.exec(location.hash)
261
+ if (!match) return
262
+ const requirementId = decodeURIComponent(match[1]!); const view = match[2]!; const objectId = match[3] ? decodeURIComponent(match[3]) : undefined
263
+ const requirement = requirements.find(item => item.id === requirementId)
264
+ if (!requirement) { if (requirements.length > 0) { resolvedDeepLinkHash.current = location.hash; setNotice('链接指向的需求不存在或已被删除') } return }
265
+ if (selected && selected.id !== requirementId && draft !== selected.version.markdown && approvedDeepLinkHash.current !== location.hash) { setPendingNavigation({ kind: 'deep-link', hash: location.hash }); return }
266
+ if (selected?.id !== requirementId) { setSelectedId(requirementId); return }
267
+ const target = resolveDeepLinkTarget(selected, view, objectId)
268
+ approvedDeepLinkHash.current = ''
269
+ resolvedDeepLinkHash.current = location.hash
270
+ setDocumentDrawerOpen(false); setReviewOpen(true)
271
+ setPrimaryMode(target.primaryMode); setMobilePane('collab')
272
+ if (target.taskView) setTaskView(target.taskView)
273
+ if (target.recordView) setRecordView(target.recordView)
274
+ if (target.commentObjectId) setDocumentFocus({ kind: 'comment', objectId: target.commentObjectId })
275
+ if (target.reviewObjectId) setReviewOpenRequest({ objectId: target.reviewObjectId, requestId: ++reviewOpenRequestId.current })
276
+ setDeepLinkObjectId(target.focusObjectId)
277
+ if (target.error) setNotice(target.error)
278
+ }
279
+ resolve(); window.addEventListener('hashchange', resolve); return () => window.removeEventListener('hashchange', resolve)
280
+ }, [requirements, selected?.id, selected?.version.markdown, draft])
281
+ useEffect(() => {
282
+ if (!deepLinkObjectId) return
283
+ let located = false
284
+ let cleanupTimer = 0
285
+ const timers = [80, 180, 360, 720].map(delay => window.setTimeout(() => {
286
+ if (located) return
287
+ const element = document.getElementById(`spec-object-${deepLinkObjectId}`)
288
+ if (!element) return
289
+ located = true
290
+ element.scrollIntoView({ block: 'center' })
291
+ element.setAttribute('data-dsh-deep-link-focus', '')
292
+ cleanupTimer = window.setTimeout(() => { element.removeAttribute('data-dsh-deep-link-focus'); setDeepLinkObjectId(undefined) }, 2400)
293
+ }, delay))
294
+ return () => { timers.forEach(window.clearTimeout); window.clearTimeout(cleanupTimer) }
295
+ }, [deepLinkObjectId, selected?.id, primaryMode, taskView, recordView])
103
296
 
104
297
  const act = async (factory: (actor: ParticipantSnapshot) => CollaborationAction): Promise<boolean> => {
105
298
  if (!registered) { setIdentityOpen(true); setNotice('首次写操作前请登记花名'); return false }
@@ -110,48 +303,118 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
110
303
  if (result.conflict) { setSaveConflict(result.conflict); setMergeDraft(result.conflict.draftMarkdown); setNotice('检测到并发修改。请在三方对比中合并后再提交。'); return false }
111
304
  setNotice(friendlyActionError(result.error)); return false
112
305
  }
113
- setSaveConflict(undefined); await refresh(); if (!result.deletedRequirementId) setSelectedId(result.requirement.id); return true
306
+ setSaveConflict(undefined)
307
+ if (result.deletedRequirementId) { selectedIdRef.current = undefined; setSelectedId(undefined); setSelectedRequirement(undefined); await refresh() }
308
+ else { selectedIdRef.current = result.requirement.id; setSelectedId(result.requirement.id); setSelectedRequirement(result.requirement); await refresh(result.requirement.id) }
309
+ return true
114
310
  }
311
+ catch (error) { setNotice(`操作失败:${error instanceof Error ? error.message : String(error)}`); return false }
115
312
  finally { setBusy(false) }
116
313
  }
117
314
 
315
+ const performNavigation = (navigation: PendingNavigation): void => {
316
+ if (navigation.kind === 'select') { setSelectedId(navigation.requirementId); setPrimaryMode('tasks'); setDocumentDrawerOpen(false); return }
317
+ if (navigation.kind === 'toggle-archive') { setShowArchived(value => !value); setSelectedId(undefined); setManageMenuId(undefined); return }
318
+ if (navigation.kind === 'deep-link') { approvedDeepLinkHash.current = navigation.hash; window.dispatchEvent(new HashChangeEvent('hashchange')); return }
319
+ if (navigation.kind === 'archive') { void archiveRequirementById(navigation.requirementId, navigation.archived); return }
320
+ if (location.hash.startsWith('#spec-collab/')) { history.replaceState(history.state, '', `${location.pathname}${location.search}`); resolvedDeepLinkHash.current = '' }
321
+ onClose()
322
+ }
323
+ const requestNavigation = (navigation: PendingNavigation): void => {
324
+ if (selected && draft !== selected.version.markdown) { setPendingNavigation(navigation); return }
325
+ performNavigation(navigation)
326
+ }
327
+ const leaveWithDraft = async (discard: boolean): Promise<void> => {
328
+ if (!pendingNavigation) return
329
+ const navigation = pendingNavigation; setPendingNavigation(undefined)
330
+ if (discard && selected) { void deleteDraft(selected.id, participant.participantId); setDraft(selected.version.markdown); setSummary(''); setDraftSavedAt(undefined) }
331
+ else if (selected && draft !== selected.version.markdown) { const updatedAt = Date.now(); await saveDraft({ requirementId: selected.id, participantId: participant.participantId, baseCommit: selected.currentCommit, markdown: draft, summary, updatedAt }); setDraftSavedAt(updatedAt) }
332
+ performNavigation(navigation)
333
+ }
334
+ const selectRequirement = (id: string): void => requestNavigation({ kind: 'select', requirementId: id })
335
+ const closeWorkbench = (): void => requestNavigation({ kind: 'close' })
336
+ useEffect(() => { const requestClose = (event: Event): void => { event.preventDefault(); closeWorkbench() }; document.addEventListener('dsh-spec-collab-request-close', requestClose); return () => document.removeEventListener('dsh-spec-collab-request-close', requestClose) }, [selected?.id, selected?.version.markdown, draft])
337
+ const toggleFocusMode = (): void => {
338
+ if (!focusMode) { previousPaneState.current = { documents: documentsOpen, review: reviewOpen }; setDocumentsOpen(false); setReviewOpen(false); setMobilePane('spec'); setFocusMode(true) }
339
+ else { setDocumentsOpen(previousPaneState.current.documents); setReviewOpen(previousPaneState.current.review); setFocusMode(false) }
340
+ }
341
+
118
342
  const create = async (): Promise<void> => {
119
343
  const links = createForm.sources.split('\n').map(value => value.trim()).filter(Boolean)
120
344
  const ok = await act(actor => ({ kind: 'requirement.create', participant: actor, title: createForm.title, rawRequirement: createForm.rawRequirement, workspaceId: createForm.workspaceId, sources: links.map((label, index) => ({ id: `source-${index + 1}`, sourceType: /^https?:/.test(label) ? 'link' : 'text', label, ...(/^https?:/.test(label) ? { stableId: label } : {}), accessStatus: /^https?:/.test(label) ? 'unverified' : 'available' })) }))
121
345
  if (ok) { setCreateOpen(false); setCreateForm({ title: '', rawRequirement: '', sources: '', workspaceId: '' }); setPrimaryMode('tasks'); setTaskView('review') }
122
346
  }
123
347
  const bindWorkspace = async (): Promise<void> => { if (!selected || !bindWorkspaceId) return; if (await act(actor => ({ kind: 'requirement.bind-workspace', participant: actor, requirementId: selected.id, workspaceId: bindWorkspaceId }))) { setBindWorkspaceOpen(false); setBindWorkspaceId('') } }
124
- const save = async (): Promise<void> => { if (!selected) return; const ok = await act(actor => ({ kind: 'version.save', participant: actor, requirementId: selected.id, baseCommit: selected.currentCommit, markdown: draft, summary })); if (ok) { setSummary(''); setNotice('已创建新的 Git commit,等待变更审核') } }
348
+ const save = async (): Promise<void> => { if (!selected) return; const ok = await act(actor => ({ kind: 'version.save', participant: actor, requirementId: selected.id, baseCommit: selected.currentCommit, markdown: draft, summary })); if (ok) { await deleteDraft(selected.id, participant.participantId); setDraftSavedAt(undefined); setSummary(''); setNotice('已保存到版本库,并创建新的 Git commit') } }
125
349
  const requestReview = async (reviewKind: ReviewKind): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'review.request', participant: actor, requirementId: selected.id, reviewKind })) }
126
350
  const confirm = async (role: ParticipantRole): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'confirmation.create', participant: actor, requirementId: selected.id, role, scope: 'version' })) }
127
351
  const advance = async (): Promise<void> => { if (!selected) return; await act(actor => ({ kind: 'stage.advance', participant: actor, requirementId: selected.id })) }
128
- const focusReviewItem = (objectId: string): void => {
129
- setFocusedReviewId(objectId)
130
- setReviewSourceFocusRequest(value => value + 1)
352
+ const scrollToCollabObject = (objectId: string): void => {
353
+ window.setTimeout(() => document.getElementById(`spec-object-${objectId}`)?.scrollIntoView({ block: 'center' }), 100)
354
+ }
355
+ const focusDocumentAnchor = (focus: DocumentAnchorFocus): void => {
356
+ setDocumentFocus(focus)
357
+ setDocumentFocusRequest(value => value + 1)
358
+ }
359
+ const focusReviewItem = (objectId: string, sourceKey?: string): void => {
360
+ focusDocumentAnchor({ kind: 'review', objectId, ...(sourceKey ? { sourceKey } : {}) })
361
+ }
362
+ const focusCommentItem = (objectId: string): void => {
363
+ focusDocumentAnchor({ kind: 'comment', objectId })
131
364
  }
132
- const openReviewItem = (objectId: string, pane: 'spec' | 'collab' = 'collab'): void => {
365
+ const openReviewItem = (objectId: string, position?: InlinePopoverPosition, sourceKey?: string, pane: 'spec' | 'collab' = 'spec'): void => {
133
366
  setPrimaryMode('tasks')
134
367
  setTaskView('review')
368
+ if (pane === 'collab') setReviewOpen(true)
369
+ setMobilePane('spec')
370
+ setDraftSelection(undefined)
371
+ setCommentText('')
372
+ focusReviewItem(objectId, sourceKey)
373
+ setInlineReview({ itemId: objectId, ...(sourceKey ? { sourceKey } : {}), ...(position ? { rect: position.rect, placement: position.placement, ...(position.maxHeight ? { maxHeight: position.maxHeight } : {}) } : {}) })
374
+ if (!position) {
375
+ window.setTimeout(() => {
376
+ const fallbackPosition = inlinePopoverPositionFromRect({ top: 144, bottom: 154, left: Math.max(12, window.innerWidth / 2 - inlineReviewPopoverSize.width / 2) }, inlineReviewPopoverSize)
377
+ setInlineReview(current => current?.itemId === objectId && !current.rect ? { ...current, rect: fallbackPosition.rect, placement: fallbackPosition.placement, ...(fallbackPosition.maxHeight ? { maxHeight: fallbackPosition.maxHeight } : {}) } : current)
378
+ }, 420)
379
+ }
380
+ }
381
+ const updateInlineReviewPosition = (objectId: string, position: InlinePopoverPosition, sourceKey?: string): void => {
382
+ setInlineReview(current => current?.itemId === objectId ? { itemId: objectId, ...(sourceKey ? { sourceKey } : current.sourceKey ? { sourceKey: current.sourceKey } : {}), rect: position.rect, placement: position.placement, ...(position.maxHeight ? { maxHeight: position.maxHeight } : {}) } : current)
383
+ }
384
+ const openCommentItem = (objectId: string, pane: 'spec' | 'collab' = 'collab'): void => {
385
+ setPrimaryMode('discussion')
135
386
  setReviewOpen(true)
136
387
  setMobilePane(pane)
137
- focusReviewItem(objectId)
138
- setReviewOpenRequest({ objectId, requestId: ++reviewOpenRequestId.current })
388
+ focusCommentItem(objectId)
389
+ scrollToCollabObject(objectId)
390
+ }
391
+ const locateReviewItem = (objectId: string, sourceKey?: string): void => {
392
+ openReviewItem(objectId, undefined, sourceKey)
139
393
  }
140
- const locateReviewItem = (objectId: string): void => {
141
- focusReviewItem(objectId)
394
+ const locateCommentItem = (objectId: string): void => {
395
+ focusCommentItem(objectId)
142
396
  setMobilePane('spec')
143
397
  }
398
+ const revealReadyPackage = (): void => {
399
+ window.setTimeout(() => workbenchRef.current?.querySelector<HTMLElement>('[data-ready-package]')?.scrollIntoView({ block: 'start' }), 80)
400
+ }
144
401
  const executeWorkflow = async (command: WorkflowCommand): Promise<void> => {
145
402
  if (!selected || command.kind === 'none') return
146
403
  if (command.kind === 'open') {
147
404
  setPrimaryMode('tasks')
148
405
  setTaskView(command.view)
149
406
  setMobilePane('collab')
407
+ if (command.view === 'ready') revealReadyPackage()
150
408
  if (command.view === 'review' && command.objectId) openReviewItem(command.objectId)
151
409
  return
152
410
  }
153
411
  if (command.kind === 'bind-workspace') { setBindWorkspaceOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))); return }
154
412
  if (command.kind === 'request-review') { setTaskView('review'); await requestReview(command.reviewKind); return }
413
+ if (command.kind === 'advance' || command.kind === 'confirm' || command.kind === 'generate-ready') { setPendingWorkflow(command); return }
414
+ }
415
+ const confirmWorkflow = async (): Promise<void> => {
416
+ if (!pendingWorkflow || !selected) return
417
+ const command = pendingWorkflow; setPendingWorkflow(undefined)
155
418
  if (command.kind === 'advance') { await advance(); return }
156
419
  if (command.kind === 'confirm') { await confirm(command.role); return }
157
420
  setTaskView('ready')
@@ -159,11 +422,28 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
159
422
  }
160
423
  const openMyItem = (item: MyActionItem): void => {
161
424
  if (item.target.tab === 'review') { openReviewItem(item.target.objectId); return }
162
- if (item.target.tab === 'discussion') setPrimaryMode('discussion')
425
+ if (item.target.tab === 'discussion') { openCommentItem(item.target.objectId); return }
163
426
  else if (item.target.tab === 'decisions') { setPrimaryMode('records'); setRecordView('decisions') }
164
427
  else { setPrimaryMode('tasks'); setTaskView(item.target.tab === 'patches' ? 'patches' : item.target.tab === 'ready' ? 'ready' : 'review') }
165
428
  setMobilePane('collab')
166
- window.setTimeout(() => document.getElementById(`spec-object-${item.target.objectId}`)?.scrollIntoView({ block: 'center' }), 100)
429
+ scrollToCollabObject(item.target.objectId)
430
+ }
431
+ const openTaskView = (view: TaskView): void => {
432
+ setPrimaryMode('tasks')
433
+ setTaskView(view)
434
+ setReviewOpen(true)
435
+ setMobilePane('collab')
436
+ }
437
+ const openDiscussionView = (): void => {
438
+ setPrimaryMode('discussion')
439
+ setReviewOpen(true)
440
+ setMobilePane('collab')
441
+ }
442
+ const openRecordView = (view: RecordView): void => {
443
+ setPrimaryMode('records')
444
+ setRecordView(view)
445
+ setReviewOpen(true)
446
+ setMobilePane('collab')
167
447
  }
168
448
  const resizePane = (side: 'documents' | 'review', event: ReactPointerEvent<HTMLDivElement>): void => {
169
449
  event.preventDefault()
@@ -176,21 +456,48 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
176
456
  const stop = (): void => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', stop); document.body.style.cursor = '' }
177
457
  document.body.style.cursor = 'col-resize'; window.addEventListener('pointermove', move); window.addEventListener('pointerup', stop)
178
458
  }
459
+ const resizePaneWithKeyboard = (side: 'documents' | 'review', event: ReactKeyboardEvent<HTMLDivElement>): void => {
460
+ const current = side === 'documents' ? documentsWidth : reviewWidth; const min = side === 'documents' ? 160 : 320; const max = side === 'documents' ? 360 : 600
461
+ let next: number | undefined
462
+ if (event.key === 'Home') next = min
463
+ else if (event.key === 'End') next = max
464
+ else if (event.key === 'ArrowLeft') next = current + (side === 'documents' ? -1 : 1) * (event.shiftKey ? 64 : 16)
465
+ else if (event.key === 'ArrowRight') next = current + (side === 'documents' ? 1 : -1) * (event.shiftKey ? 64 : 16)
466
+ if (next === undefined) return
467
+ event.preventDefault(); const value = Math.max(min, Math.min(max, next)); if (side === 'documents') setDocumentsWidth(value); else setReviewWidth(value)
468
+ }
179
469
  const renameRequirement = async (): Promise<void> => { if (!manageTarget) return; if (await act(actor => ({ kind: 'requirement.rename', participant: actor, requirementId: manageTarget.id, title: renameTitle }))) { setRenameOpen(false); setManageTargetId(undefined) } }
180
- const archiveRequirement = async (target: RequirementView): Promise<void> => { const archived = !target.archivedAt; if (await act(actor => ({ kind: 'requirement.archive', participant: actor, requirementId: target.id, archived }))) { setManageMenuId(undefined); setSelectedId(visibleRequirements.find(item => item.id !== target.id)?.id) } }
470
+ const archiveRequirementById = async (requirementId: string, archived: boolean): Promise<void> => { if (await act(actor => ({ kind: 'requirement.archive', participant: actor, requirementId, archived }))) { setManageMenuId(undefined); setSelectedId(visibleRequirements.find(item => item.id !== requirementId)?.id); if (archived) { setUndoArchiveId(requirementId); setNotice('需求已归档,Git 历史仍然保留'); window.setTimeout(() => setUndoArchiveId(current => current === requirementId ? undefined : current), 8_000) } } }
471
+ const archiveRequirement = async (target: RequirementSummary): Promise<void> => { const navigation: PendingNavigation = { kind: 'archive', requirementId: target.id, archived: !target.archivedAt }; if (selected?.id === target.id && draft !== selected.version.markdown) { setPendingNavigation(navigation); return }; await archiveRequirementById(navigation.requirementId, navigation.archived) }
472
+ const undoArchive = async (): Promise<void> => { if (!undoArchiveId) return; const id = undoArchiveId; if (await act(actor => ({ kind: 'requirement.unarchive', participant: actor, requirementId: id }))) { setUndoArchiveId(undefined); setShowArchived(false); setSelectedId(id); setNotice('已撤销归档') } }
181
473
  const deleteRequirement = async (): Promise<void> => { if (!manageTarget) return; if (await act(actor => ({ kind: 'requirement.delete', participant: actor, requirementId: manageTarget.id }))) { setDeleteOpen(false); setManageMenuId(undefined); setManageTargetId(undefined) } }
182
474
 
183
- const captureSelection = (): void => {
184
- if (!draftSelection) return
185
- setSelection(draftSelection)
186
- setDraftSelection(undefined)
187
- setPrimaryMode('discussion')
188
- setReviewOpen(true)
189
- setMobilePane('collab')
475
+ const updateDraftSelection = (value?: EditorSelection): void => {
476
+ if (!value) {
477
+ setDraftSelection(current => commentText.trim() ? current : undefined)
478
+ return
479
+ }
480
+ const sameAnchor = draftSelection?.quote === value.quote && draftSelection.prefix === value.prefix && draftSelection.suffix === value.suffix && draftSelection.heading === value.heading
481
+ if (!sameAnchor) setCommentText('')
482
+ setDraftSelection(value)
483
+ setInlineReview(undefined)
484
+ setDocumentFocus(undefined)
485
+ }
486
+ const cancelCommentDraft = (): void => { setDraftSelection(undefined); setCommentText('') }
487
+ const addComment = async (): Promise<void> => {
488
+ if (!selected || !draftSelection || !commentText.trim()) return
489
+ const anchor: CommentAnchor = { quote: draftSelection.quote, prefix: draftSelection.prefix, suffix: draftSelection.suffix, ...(draftSelection.heading ? { heading: draftSelection.heading } : {}) }
490
+ const mentions = mentionedParticipantIds(commentText, participantBindings)
491
+ const ok = await act(actor => ({ kind: 'comment.create', participant: actor, requirementId: selected.id, commit: selected.currentCommit, anchor, body: commentText.trim(), mentions }))
492
+ if (ok) { setDraftSelection(undefined); setCommentText(''); setNotice('讨论已提交,AI 正在结合正文和工作区上下文分析') }
493
+ }
494
+ const addPageComment = async (): Promise<void> => {
495
+ if (!selected || !pageCommentText.trim()) return
496
+ const mentions = mentionedParticipantIds(pageCommentText, participantBindings)
497
+ if (await act(actor => ({ kind: 'comment.create', participant: actor, requirementId: selected.id, commit: selected.currentCommit, scope: 'page', body: pageCommentText.trim(), mentions }))) { setPageCommentOpen(false); setPageCommentText(''); setPrimaryMode('discussion'); setReviewOpen(true); setMobilePane('collab'); setNotice('页面总评已提交') }
190
498
  }
191
- const addComment = async (): Promise<void> => { if (!selected || !selection) return; const ok = await act(actor => ({ kind: 'comment.create', participant: actor, requirementId: selected.id, commit: selected.currentCommit, anchor: selection, body: commentText })); if (ok) { setSelection(undefined); setCommentText(''); setNotice('讨论已提交,AI 正在结合正文和工作区上下文分析') } }
192
499
 
193
- return <div className={css.workbench}>
500
+ return <div ref={workbenchRef} className={`${css.workbench} ${focusMode ? css.focusMode : ''}`}>
194
501
  <header className={css.header}>
195
502
  <div className={css.titleBlock}>
196
503
  <span className={css.productName}>需求共创</span>
@@ -199,40 +506,51 @@ export function SpecWorkbench({ api, onClose }: { api: SpecApi; onClose: () => v
199
506
  </div>
200
507
  {selected && <StageRail stage={selected.stage}/>}
201
508
  <div className={css.headerActions}>
202
- <button className={css.quietButton} aria-label="返回聊天" onClick={onClose}><span aria-hidden="true">←</span><span className={css.backLabel}>返回聊天</span></button>
509
+ <button className={css.quietButton} aria-label="返回聊天" onClick={closeWorkbench}><span aria-hidden="true">←</span><span className={css.backLabel}>返回聊天</span></button>
510
+ <button className={css.quietButton} aria-pressed={focusMode} title="聚焦正文(⌘⇧F)" onClick={toggleFocusMode}>{focusMode ? '退出聚焦' : '聚焦正文'}</button>
511
+ {registered && <button className={css.myWorkButton} onClick={() => setMyWorkOpen(true)}>我的工作{myItems.length + notifications.filter(item => item.readAt === undefined).length > 0 && <b>{myItems.length + notifications.filter(item => item.readAt === undefined).length}</b>}</button>}
512
+ {registered && <button className={css.notificationButton} aria-label={`通知,${notifications.filter(item => item.readAt === undefined).length} 条未读`} onClick={() => setNotificationsOpen(true)}>通知{notifications.some(item => item.readAt === undefined) && <b>{notifications.filter(item => item.readAt === undefined).length}</b>}</button>}
203
513
  <button className={css.identity} onClick={() => setIdentityOpen(true)}>{registered ? `${participant.nickname} · ${participant.role === 'product' ? '产品' : '研发'}` : '登记身份'}</button>
204
514
  </div>
205
515
  </header>
206
- <div className={notice ? css.notice : css.noticeHidden}>{notice}<button aria-label="关闭" onClick={() => setNotice('')}>×</button></div>
207
- <div className={css.mobileViewSwitch}><button className={mobilePane === 'spec' ? css.activeMode : ''} onClick={() => setMobilePane('spec')}>需求正文</button><button className={mobilePane === 'collab' ? css.activeMode : ''} onClick={() => setMobilePane('collab')}>下一步{currentMyItems.length > 0 ? ` · ${currentMyItems.length}` : ''}</button></div>
516
+ <div className={notice ? css.notice : css.noticeHidden} role={assertiveNotice ? 'alert' : 'status'} aria-live={assertiveNotice ? 'assertive' : 'polite'} aria-atomic="true"><span>{notice}</span>{undoArchiveId && <button onClick={() => void undoArchive()}>撤销归档</button>}<button aria-label="关闭" onClick={() => setNotice('')}>×</button></div>
517
+ <div className={css.mobileViewSwitch}><button className={css.mobileDocumentsTrigger} onClick={() => setDocumentDrawerOpen(true)}>需求列表</button><button className={mobilePane === 'spec' ? css.activeMode : ''} onClick={() => setMobilePane('spec')}>需求正文</button><button className={mobilePane === 'collab' ? css.activeMode : ''} onClick={() => setMobilePane('collab')}>协作{currentMyItems.length > 0 ? ` · ${currentMyItems.length}` : ''}</button></div>
208
518
  <div className={`${css.grid} ${mobilePane === 'spec' ? css.mobileSpec : css.mobileCollab}`} style={{ '--documents-width': documentsOpen ? `${documentsWidth}px` : '0px', '--documents-handle': documentsOpen ? '6px' : '0px', '--review-width': reviewOpen ? `${reviewWidth}px` : '0px', '--review-handle': reviewOpen ? '6px' : '0px' } as CSSProperties}>
209
- <aside className={`${css.documents} ${documentsOpen ? '' : css.paneClosed}`} aria-label="需求列表">
210
- <div className={css.paneHead}><strong>{showArchived ? '已归档' : '需求'}</strong><div className={css.paneActions}><button onClick={() => { setShowArchived(value => !value); setSelectedId(undefined); setManageMenuId(undefined) }}>{showArchived ? '返回进行中' : '查看归档'}</button>{!showArchived && <button className={css.createButton} aria-label="新建需求" title="新建需求" onClick={() => { setCreateOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))) }}>+</button>}<button className={css.iconButton} aria-label="收起需求栏" title="收起需求栏" onClick={() => setDocumentsOpen(false)}>‹</button></div></div>
211
- <nav>{visibleRequirements.map(item => <div className={css.requirementRow} key={item.id}><button className={`${css.documentButton} ${item.id === selected?.id ? css.selectedDoc : ''}`} onClick={() => { setSelectedId(item.id); setPrimaryMode('tasks') }}><span>{item.title}</span><small><i className={`${css.statusDot} ${css[`stage_${item.stage}`]}`}/>{item.archivedAt ? `归档于 ${new Date(item.archivedAt).toLocaleDateString()}` : `${stageLabel(item.stage)}${item.stage !== 'ready' && currentPendingActions(item).filter(task => task.blocking).length > 0 ? ` · ${currentPendingActions(item).filter(task => task.blocking).length} 项待处理` : ''}`}</small></button><button className={css.rowMenuButton} aria-label={`${item.title} 更多操作`} title="更多操作" onClick={() => { setSelectedId(item.id); setManageMenuId(current => current === item.id ? undefined : item.id) }}>…</button>{manageMenuId === item.id && <div className={css.requirementMenu}><button onClick={() => { setManageTargetId(item.id); setRenameTitle(item.title); setRenameOpen(true); setManageMenuId(undefined) }}>重命名</button><button onClick={() => void archiveRequirement(item)}>{item.archivedAt ? '取消归档' : '归档需求'}</button><button className={css.dangerText} onClick={() => { setManageTargetId(item.id); setDeleteOpen(true); setManageMenuId(undefined) }}>删除需求</button></div>}</div>)}</nav>
519
+ <aside className={`${css.documents} ${documentsOpen ? '' : css.paneClosed} ${documentDrawerOpen ? css.mobileDocumentsOpen : ''}`} aria-label="需求列表">
520
+ <div className={css.paneHead}><strong>{showArchived ? '已归档' : '需求'}</strong><div className={css.paneActions}><button onClick={() => requestNavigation({ kind: 'toggle-archive' })}>{showArchived ? '返回进行中' : '查看归档'}</button>{!showArchived && <button className={css.createButton} aria-label="新建需求" title="新建需求" onClick={() => { setCreateOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))) }}>+</button>}<button className={css.mobileDrawerClose} aria-label="关闭需求列表" onClick={() => setDocumentDrawerOpen(false)}>×</button><button className={css.iconButton} aria-label="收起需求栏" title="收起需求栏" onClick={() => setDocumentsOpen(false)}>‹</button></div></div>
521
+ <div className={css.requirementFilters}>
522
+ <label className={css.requirementSearch}>搜索需求<input type="search" value={requirementQuery} onChange={event => setRequirementQuery(event.target.value)} placeholder="标题或编号"/></label>
523
+ <div><label>阶段<select value={requirementFilters.stage} onChange={event => setRequirementFilters(current => ({ ...current, stage: event.target.value as typeof current.stage }))}><option value="all">全部阶段</option>{stageSteps.map(item => <option key={item.stage} value={item.stage}>{item.label}</option>)}</select></label><label>参与者<select value={requirementFilters.participantId} onChange={event => setRequirementFilters(current => ({ ...current, participantId: event.target.value }))}><option value="">全部参与者</option>{participantBindings.map(person => <option key={person.participantId} value={person.participantId}>{person.nickname}</option>)}</select></label></div>
524
+ <div className={css.filterChecks}><label><input type="checkbox" checked={requirementFilters.risk} onChange={event => setRequirementFilters(current => ({ ...current, risk: event.target.checked }))}/>有风险</label><label><input type="checkbox" checked={requirementFilters.unread} onChange={event => setRequirementFilters(current => ({ ...current, unread: event.target.checked }))}/>有未读</label><label><input type="checkbox" checked={requirementFilters.insights} onChange={event => setRequirementFilters(current => ({ ...current, insights: event.target.checked }))}/>有洞察</label></div>
525
+ {(activeRequirementFilterCount > 0 || normalizedQuery) && <div className={css.activeFilters}><span>{activeRequirementFilterCount + Number(Boolean(normalizedQuery))} 个筛选条件生效</span><button onClick={() => { setRequirementQuery(''); setRequirementFilters({ stage: 'all', participantId: '', risk: false, unread: false, insights: false }) }}>清除全部</button></div>}
526
+ </div>
527
+ <nav>{visibleRequirements.map(item => <div className={css.requirementRow} key={item.id}><button className={`${css.documentButton} ${item.id === selected?.id ? css.selectedDoc : ''}`} onClick={() => selectRequirement(item.id)}><span>{item.title}</span><small><i className={`${css.statusDot} ${css[`stage_${item.stage}`]}`}/>{item.archivedAt ? `归档于 ${new Date(item.archivedAt).toLocaleDateString()}` : `${stageLabel(item.stage)}${item.metrics.pendingActionCount > 0 ? ` · ${item.metrics.pendingActionCount} 项待处理` : ''}`}</small></button><button className={css.rowMenuButton} aria-label={`${item.title} 更多操作`} title="更多操作" onClick={() => { selectRequirement(item.id); setManageMenuId(current => current === item.id ? undefined : item.id) }}>…</button>{manageMenuId === item.id && <div className={css.requirementMenu}><button onClick={() => { setManageTargetId(item.id); setRenameTitle(item.title); setRenameOpen(true); setManageMenuId(undefined) }}>重命名</button><button onClick={() => void archiveRequirement(item)}>{item.archivedAt ? '取消归档' : '归档需求'}</button><button className={css.dangerText} onClick={() => { setManageTargetId(item.id); setDeleteOpen(true); setManageMenuId(undefined) }}>删除需求</button></div>}</div>)}</nav>
212
528
  {visibleRequirements.length === 0 && <div className={css.emptyList}><strong>{showArchived ? '还没有归档需求' : '从一个真实问题开始'}</strong><p>{showArchived ? '归档后的需求会出现在这里。' : '输入原始需求,AI 会先帮你找出缺口。'}</p>{!showArchived && <button onClick={() => { setCreateOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))) }}>新建需求</button>}</div>}
213
529
  </aside>
214
- <div className={`${css.resizer} ${documentsOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整需求栏宽度" aria-orientation="vertical" onPointerDown={event => resizePane('documents', event)}/>
530
+ <div className={`${css.resizer} ${documentsOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整需求栏宽度" aria-orientation="vertical" aria-valuemin={160} aria-valuemax={360} aria-valuenow={documentsWidth} tabIndex={documentsOpen ? 0 : -1} onKeyDown={event => resizePaneWithKeyboard('documents', event)} onPointerDown={event => resizePane('documents', event)}/>
215
531
  <main className={css.editorPane}>
216
- <div className={css.toolbar}><div className={css.editorTitle}>{!documentsOpen && <button className={css.iconButton} aria-label="展开需求栏" title="展开需求栏" onClick={() => setDocumentsOpen(true)}>›</button>}<div><span>正式需求</span><strong>需求正文</strong></div></div><div><span className={draft !== selected?.version.markdown ? css.unsaved : css.editorMeta}>{draft !== selected?.version.markdown ? '有未保存改动' : '所有改动已保存'}</span><input className={css.summaryInput} required aria-label="说明本次改动" value={summary} onChange={event => setSummary(event.target.value)} placeholder="简要说明本次改动"/><button className={css.saveButton} disabled={busy || !selected || draft === selected.version.markdown || !summary.trim()} onClick={() => void save()}>保存版本</button>{!reviewOpen && <button className={css.iconButton} aria-label="展开下一步面板" title="展开下一步面板" onClick={() => setReviewOpen(true)}>‹</button>}</div></div>
217
- {draftSelection && <div className={css.selectionPrompt} role="toolbar" aria-label="选中文字操作" style={{ top: draftSelection.rect.top, left: draftSelection.rect.left }}><span>“{draftSelection.quote.replace(/\s+/g, ' ').slice(0, 42)}{draftSelection.quote.length > 42 ? '…' : ''}”</span><button className={css.commentAction} onClick={captureSelection}>就这段提问</button><button aria-label="取消文字选择" title="取消" onClick={() => setDraftSelection(undefined)}>×</button></div>}
218
- {!selected ? <div className={css.emptyMain}><div><span>从问题到共识</span><h2>创建第一份需求</h2><p>写下用户问题和期望结果,AI 会协助补齐范围、规则与验收标准。</p><button className={css.execute} onClick={() => { setCreateOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))) }}>新建需求</button></div></div> : <div className={css.editorBody}><RichMarkdownEditor key={`${selected.id}:${selected.currentCommit}`} markdown={draft} reviewItems={documentReviews} selectedReviewId={focusedReviewId} focusRequest={reviewSourceFocusRequest} onChange={setDraft} onSelection={value => { setDraftSelection(value); if (value) setFocusedReviewId(undefined) }} onOpenReview={openReviewItem}/></div>}
532
+ <div className={css.toolbar}><div className={css.editorTitle}><button className={css.mobileDocumentsTrigger} aria-label="打开需求列表" onClick={() => setDocumentDrawerOpen(true)}>☰</button>{!documentsOpen && <button className={css.iconButton} aria-label="展开需求栏" title="展开需求栏" onClick={() => setDocumentsOpen(true)}>›</button>}<div><span>正式需求</span><strong>需求正文 · 可编辑</strong></div></div><div><span className={draft !== selected?.version.markdown ? css.unsaved : css.editorMeta}>{draft !== selected?.version.markdown ? `本地草稿${draftSavedAt ? ` · ${relativeTime(draftSavedAt)}` : ''}` : '已保存到版本库'}</span><label className={css.summaryField}>本次改动<input className={css.summaryInput} required value={summary} onChange={event => setSummary(event.target.value)} placeholder="例如:补充退款边界"/></label><button title={!selected ? '请先选择需求' : draft === selected.version.markdown ? '正文没有变化' : !summary.trim() ? '请填写本次改动说明' : '保存到版本库(⌘S)'} className={css.saveButton} disabled={busy || !selected || draft === selected.version.markdown || !summary.trim()} onClick={() => void save()}>保存到版本库</button><button onClick={() => setPageCommentOpen(true)} disabled={!selected}>评论整篇</button>{!reviewOpen && <button className={css.iconButton} aria-label="展开协作面板" title="展开协作面板" onClick={() => setReviewOpen(true)}>‹</button>}</div></div>
533
+ {draftSelection && <InlineCommentComposer selection={draftSelection} text={commentText} setText={setCommentText} busy={busy} cancel={cancelCommentDraft} submit={addComment}/>}
534
+ {inlineReviewItem && inlineReview?.rect && inlineReview.placement && <InlineReviewComposer item={inlineReviewItem} sourceMarkdown={selected?.version.markdown ?? ''} requirementId={selected?.id ?? ''} position={{ rect: inlineReview.rect, placement: inlineReview.placement, ...(inlineReview.maxHeight ? { maxHeight: inlineReview.maxHeight } : {}) }} nextItemId={nextInlineReview?.id} busy={busy} act={act} close={() => setInlineReview(undefined)} locateSource={sourceKey => locateReviewItem(inlineReviewItem.id, sourceKey)} complete={continueToNext => { if (continueToNext && nextInlineReview) openReviewItem(nextInlineReview.id); else setInlineReview(undefined) }}/>}
535
+ {!selected ? <div className={css.emptyMain}><div><span>从问题到共识</span><h2>创建第一份需求</h2><p>写下用户问题和期望结果,AI 会协助补齐范围、规则与验收标准。</p><button className={css.execute} onClick={() => { setCreateOpen(true); void api.reviewWorkspaces().then(setReviewWorkspaces, error => setNotice(error instanceof Error ? error.message : String(error))) }}>新建需求</button></div></div> : <><DocumentCollabBar activeMode={primaryMode} activeTaskView={taskView} activeRecordView={recordView} stats={{ openReviews: openReviewCount, blockingReviews: blockingReviewCount, openDiscussions, pendingPatches: pendingPatches.length, activeDecisions: activeDecisionCount, invalidatedDecisions: invalidatedDecisionCount, runningAi: runningAiCount, dirty: draft !== selected.version.markdown }} onOpenReviews={() => openTaskView('review')} onOpenDiscussion={openDiscussionView} onOpenPatches={() => openTaskView('patches')} onOpenDecisions={() => openRecordView('decisions')}/><div className={css.editorBody}><RichMarkdownEditor key={`${selected.id}:${selected.currentCommit}`} markdown={draft} reviewItems={documentReviews} comments={documentComments} documentFocus={documentFocus} focusRequest={documentFocusRequest} onChange={setDraft} onSelection={updateDraftSelection} onOpenReview={openReviewItem} onReviewLocated={updateInlineReviewPosition} onOpenComment={openCommentItem}/></div></>}
219
536
  </main>
220
- <div className={`${css.resizer} ${reviewOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整协作栏宽度" aria-orientation="vertical" onPointerDown={event => resizePane('review', event)}/>
537
+ <div className={`${css.resizer} ${reviewOpen ? '' : css.resizerHidden}`} role="separator" aria-label="调整协作栏宽度" aria-orientation="vertical" aria-valuemin={320} aria-valuemax={600} aria-valuenow={reviewWidth} tabIndex={reviewOpen ? 0 : -1} onKeyDown={event => resizePaneWithKeyboard('review', event)} onPointerDown={event => resizePane('review', event)}/>
221
538
  <aside className={`${css.review} ${reviewOpen ? '' : css.paneClosed}`} aria-label="需求协作">
222
- <div className={css.primaryNav}><div role="tablist" aria-label="协作视图"><button role="tab" aria-selected={primaryMode === 'tasks'} className={primaryMode === 'tasks' ? css.activeMode : ''} onClick={() => setPrimaryMode('tasks')}>下一步{currentMyItems.length > 0 && <span className={css.tabBadge}>{currentMyItems.length}</span>}</button><button role="tab" aria-selected={primaryMode === 'discussion'} className={primaryMode === 'discussion' ? css.activeMode : ''} onClick={() => setPrimaryMode('discussion')}>讨论{openDiscussions > 0 && <span className={css.tabBadge}>{openDiscussions}</span>}</button><button role="tab" aria-selected={primaryMode === 'records'} className={primaryMode === 'records' ? css.activeMode : ''} onClick={() => setPrimaryMode('records')}>记录</button></div><button className={`${css.iconButton} ${css.collapseRight}`} aria-label="收起下一步面板" title="收起下一步面板" onClick={() => setReviewOpen(false)}>›</button></div>
223
- {selected && primaryMode === 'tasks' && <>
539
+ <div className={css.primaryNav}><div role="tablist" aria-label="协作视图" onKeyDown={event => handleTabs(event, ['tasks', 'discussion', 'insights', 'records'], primaryMode, setPrimaryMode)}><button id="collab-tab-tasks" aria-controls="collab-panel-tasks" role="tab" tabIndex={primaryMode === 'tasks' ? 0 : -1} aria-selected={primaryMode === 'tasks'} className={primaryMode === 'tasks' ? css.activeMode : ''} onClick={() => setPrimaryMode('tasks')}>下一步{currentMyItems.length > 0 && <span className={css.tabBadge}>{currentMyItems.length}</span>}</button><button id="collab-tab-discussion" aria-controls="collab-panel-discussion" role="tab" tabIndex={primaryMode === 'discussion' ? 0 : -1} aria-selected={primaryMode === 'discussion'} className={primaryMode === 'discussion' ? css.activeMode : ''} onClick={() => setPrimaryMode('discussion')}>讨论{openDiscussions > 0 && <span className={css.tabBadge}>{openDiscussions}</span>}</button><button id="collab-tab-insights" aria-controls="collab-panel-insights" role="tab" tabIndex={primaryMode === 'insights' ? 0 : -1} aria-selected={primaryMode === 'insights'} className={primaryMode === 'insights' ? css.activeMode : ''} onClick={() => setPrimaryMode('insights')}>洞察{selected && selected.metrics.insightCount > 0 && <span className={css.tabBadge}>{selected.metrics.insightCount}</span>}</button><button id="collab-tab-records" aria-controls="collab-panel-records" role="tab" tabIndex={primaryMode === 'records' ? 0 : -1} aria-selected={primaryMode === 'records'} className={primaryMode === 'records' ? css.activeMode : ''} onClick={() => setPrimaryMode('records')}>记录</button></div><button className={`${css.iconButton} ${css.collapseRight}`} aria-label="收起协作面板" title="收起协作面板" onClick={() => setReviewOpen(false)}>›</button></div>
540
+ {selected && primaryMode === 'tasks' && <div className={css.tabPanel} id="collab-panel-tasks" role="tabpanel" aria-labelledby="collab-tab-tasks">
224
541
  {workflow && <WorkflowFocus state={workflow} pendingForMe={currentMyItems.length} onExecute={() => void executeWorkflow(workflow.command)}/>}
225
- {currentMyItems.length > 0 && <TaskQueue items={currentMyItems} open={openMyItem}/>}
226
- <div className={css.contextNav} role="tablist" aria-label="待处理内容"><button role="tab" aria-selected={taskView === 'review'} className={taskView === 'review' ? css.activeContext : ''} onClick={() => setTaskView('review')}>问题{currentReviews.length > 0 && <span>{currentReviews.length}</span>}</button><button role="tab" aria-selected={taskView === 'patches'} className={taskView === 'patches' ? css.activeContext : ''} onClick={() => setTaskView('patches')}>AI 建议{pendingPatches.length > 0 && <span>{pendingPatches.length}</span>}</button><button role="tab" aria-selected={taskView === 'ready'} className={taskView === 'ready' ? css.activeContext : ''} onClick={() => setTaskView('ready')}>完成条件{failedChecks > 0 && <span>{failedChecks}</span>}</button></div>
227
- <div className={css.threadList}>{taskView === 'review' && <ReviewPanel requirement={selected} act={act} api={api} focusedItemId={focusedReviewId} openRequest={reviewOpenRequest} onSelectReview={focusReviewItem} onLocateSource={locateReviewItem} onOpenRequestHandled={requestId => setReviewOpenRequest(current => current?.requestId === requestId ? undefined : current)}/>} {taskView === 'patches' && <PatchPanel requirement={selected} act={act}/>} {taskView === 'ready' && <ReadyPanel requirement={selected} act={act}/>}</div>
228
- </>}
229
- {selected && primaryMode === 'discussion' && <div className={css.threadList}><DiscussionPanel requirement={selected} selection={selection} text={commentText} setText={setCommentText} cancel={() => setSelection(undefined)} submit={addComment} participant={participant} act={act} api={api}/></div>}
230
- {selected && primaryMode === 'records' && <><div className={css.contextNav} role="tablist" aria-label="需求记录"><button role="tab" aria-selected={recordView === 'decisions'} className={recordView === 'decisions' ? css.activeContext : ''} onClick={() => setRecordView('decisions')}>关键决策</button><button role="tab" aria-selected={recordView === 'versions'} className={recordView === 'versions' ? css.activeContext : ''} onClick={() => setRecordView('versions')}>版本历史</button></div><div className={css.threadList}>{recordView === 'decisions' && <DecisionPanel requirement={selected} act={act}/>} {recordView === 'versions' && <VersionPanel requirement={selected} api={api}/>}</div></>}
542
+ {currentMyItems.length > 0 && <TaskQueue items={currentMyItems} open={openMyItem} participants={participantBindings} act={act}/>}
543
+ <div className={css.contextNav} role="tablist" aria-label="待处理内容" onKeyDown={event => handleTabs(event, ['review', 'patches', 'ready'], taskView, setTaskView)}><button id="tasks-tab-review" aria-controls="tasks-panel-review" role="tab" tabIndex={taskView === 'review' ? 0 : -1} aria-selected={taskView === 'review'} className={taskView === 'review' ? css.activeContext : ''} onClick={() => setTaskView('review')}>问题{currentReviews.length > 0 && <span>{currentReviews.length}</span>}</button><button id="tasks-tab-patches" aria-controls="tasks-panel-patches" role="tab" tabIndex={taskView === 'patches' ? 0 : -1} aria-selected={taskView === 'patches'} className={taskView === 'patches' ? css.activeContext : ''} onClick={() => setTaskView('patches')}>AI 建议{pendingPatches.length > 0 && <span>{pendingPatches.length}</span>}</button><button id="tasks-tab-ready" aria-controls="tasks-panel-ready" role="tab" tabIndex={taskView === 'ready' ? 0 : -1} aria-selected={taskView === 'ready'} className={taskView === 'ready' ? css.activeContext : ''} onClick={() => setTaskView('ready')}>完成条件{failedChecks > 0 && <span>{failedChecks}</span>}</button></div>
544
+ <div id={`tasks-panel-${taskView}`} role="tabpanel" aria-labelledby={`tasks-tab-${taskView}`} className={css.threadList}>{taskView === 'review' && <ReviewPanel key={selected.id} requirement={selected} act={act} api={api} focusedItemId={focusedReviewId} openRequest={reviewOpenRequest} onSelectReview={focusReviewItem} onLocateSource={locateReviewItem} onOpenRequestHandled={requestId => setReviewOpenRequest(current => current?.requestId === requestId ? undefined : current)}/>} {taskView === 'patches' && <PatchPanel key={selected.id} requirement={selected} act={act} api={api}/>} {taskView === 'ready' && <ReadyPanel key={selected.id} requirement={selected} act={act}/>}</div>
545
+ </div>}
546
+ {selected && primaryMode === 'discussion' && <div id="collab-panel-discussion" role="tabpanel" aria-labelledby="collab-tab-discussion" className={css.threadList}><DiscussionPanel requirement={selected} notifications={notifications} focusedCommentId={focusedCommentId} onSelectComment={focusCommentItem} onLocateComment={locateCommentItem} act={act} api={api}/></div>}
547
+ {selected && primaryMode === 'insights' && <div id="collab-panel-insights" role="tabpanel" aria-labelledby="collab-tab-insights" className={css.threadList}><InsightPanel key={selected.id} requirement={selected} api={api} act={act}/></div>}
548
+ {selected && primaryMode === 'records' && <div id="collab-panel-records" role="tabpanel" aria-labelledby="collab-tab-records" className={css.tabPanel}><div className={css.contextNav} role="tablist" aria-label="需求记录" onKeyDown={event => handleTabs(event, ['decisions', 'versions'], recordView, setRecordView)}><button id="records-tab-decisions" aria-controls="records-panel-decisions" role="tab" tabIndex={recordView === 'decisions' ? 0 : -1} aria-selected={recordView === 'decisions'} className={recordView === 'decisions' ? css.activeContext : ''} onClick={() => setRecordView('decisions')}>关键决策</button><button id="records-tab-versions" aria-controls="records-panel-versions" role="tab" tabIndex={recordView === 'versions' ? 0 : -1} aria-selected={recordView === 'versions'} className={recordView === 'versions' ? css.activeContext : ''} onClick={() => setRecordView('versions')}>版本历史</button></div><div id={`records-panel-${recordView}`} role="tabpanel" aria-labelledby={`records-tab-${recordView}`} className={css.threadList}>{recordView === 'decisions' && <DecisionPanel key={selected.id} requirement={selected} act={act}/>} {recordView === 'versions' && <VersionPanel key={selected.id} requirement={selected} api={api} act={act}/>}</div></div>}
231
549
  {!selected && <div className={css.emptyAside}><strong>等待创建需求</strong><p>创建后,下一步操作会显示在这里。</p></div>}
232
550
  </aside>
233
551
  </div>
234
552
  <footer className={css.footer}><span>AI 可以检查和建议,最终版本始终由人确认</span><span>{selected ? `${stageLabel(selected.stage)} · ${selected.currentCommit.slice(0, 8)} · ${selected.aiRuns.at(-1)?.status === 'running' ? 'AI 分析中' : '版本已记录'}` : '从原始需求开始'}</span></footer>
235
- {identityOpen && <IdentityDialog value={participant} {...(boundRole === undefined ? {} : { boundRole })} onChange={setParticipant} close={() => setIdentityOpen(false)}/>} {createOpen && <CreateDialog value={createForm} setValue={setCreateForm} workspaces={reviewWorkspaces} close={() => setCreateOpen(false)} submit={() => void create()} busy={busy}/>} {bindWorkspaceOpen && selected && <WorkspaceDialog value={bindWorkspaceId} setValue={setBindWorkspaceId} workspaces={reviewWorkspaces} close={() => { setBindWorkspaceOpen(false); setBindWorkspaceId('') }} submit={() => void bindWorkspace()} busy={busy}/>} {renameOpen && <RenameDialog title={renameTitle} setTitle={setRenameTitle} close={() => { setRenameOpen(false); setManageTargetId(undefined) }} submit={() => void renameRequirement()} busy={busy}/>} {deleteOpen && manageTarget && <DeleteDialog title={manageTarget.title} close={() => { setDeleteOpen(false); setManageTargetId(undefined) }} submit={() => void deleteRequirement()} busy={busy}/>} {saveConflict && <ConflictDialog conflict={saveConflict} value={mergeDraft} setValue={setMergeDraft} close={() => setSaveConflict(undefined)} busy={busy} submit={() => void act(actor => ({ kind: 'version.save', participant: actor, requirementId: saveConflict.requirementId, baseCommit: saveConflict.currentCommit, markdown: mergeDraft, summary })).then(ok => { if (ok) { setDraft(mergeDraft); setSummary(''); setSaveConflict(undefined); setNotice('冲突已合并并创建新的 Git commit') } })}/>}
553
+ {identityOpen && <IdentityDialog value={participant} {...(boundRole === undefined ? {} : { boundRole })} onChange={setParticipant} close={() => setIdentityOpen(false)} save={() => { localStorage.setItem('dsh-spec-collab.participant', JSON.stringify(participant)); setIdentityOpen(false); if (selected) void api.action({ kind: 'participant.register', participant, requirementId: selected.id }).then(result => { if (!result.ok) throw new Error(result.error); return refresh() }).catch(error => setNotice(`登记失败:${error instanceof Error ? error.message : String(error)}`)) }}/>} {createOpen && <CreateDialog value={createForm} setValue={setCreateForm} workspaces={reviewWorkspaces} close={() => setCreateOpen(false)} submit={() => void create()} busy={busy}/>} {bindWorkspaceOpen && selected && <WorkspaceDialog value={bindWorkspaceId} setValue={setBindWorkspaceId} workspaces={reviewWorkspaces} close={() => { setBindWorkspaceOpen(false); setBindWorkspaceId('') }} submit={() => void bindWorkspace()} busy={busy}/>} {renameOpen && <RenameDialog title={renameTitle} setTitle={setRenameTitle} close={() => { setRenameOpen(false); setManageTargetId(undefined) }} submit={() => void renameRequirement()} busy={busy}/>} {deleteOpen && manageTarget && <DeleteDialog title={manageTarget.title} close={() => { setDeleteOpen(false); setManageTargetId(undefined) }} submit={() => void deleteRequirement()} busy={busy}/>} {saveConflict && <ConflictDialog conflict={saveConflict} value={mergeDraft} setValue={setMergeDraft} close={() => setSaveConflict(undefined)} busy={busy} submit={() => void act(actor => ({ kind: 'version.save', participant: actor, requirementId: saveConflict.requirementId, baseCommit: saveConflict.currentCommit, markdown: mergeDraft, summary })).then(ok => { if (ok) { setDraft(mergeDraft); setSummary(''); setSaveConflict(undefined); setNotice('冲突已合并并创建新的 Git commit') } })}/>} {pageCommentOpen && selected && <PageCommentDialog value={pageCommentText} setValue={setPageCommentText} close={() => setPageCommentOpen(false)} submit={() => void addPageComment()} busy={busy}/>} {notificationsOpen && <NotificationDialog notifications={notifications} close={() => setNotificationsOpen(false)} open={item => { setNotificationsOpen(false); location.hash = item.deepLink }} markRead={item => void act(actor => ({ kind: 'notification.mark-read', participant: actor, requirementId: item.requirementId, notificationIds: [item.id] }))}/>} {myWorkOpen && <MyWorkDialog items={myItems} notifications={notifications} close={() => setMyWorkOpen(false)} openItem={item => { setMyWorkOpen(false); const tab = item.target.tab; const view = tab === 'discussion' ? 'discussion' : tab === 'decisions' ? 'records' : 'tasks'; location.hash = `#spec-collab/${encodeURIComponent(item.requirementId)}/${view}/${encodeURIComponent(item.target.objectId)}` }} openNotification={item => { setMyWorkOpen(false); location.hash = item.deepLink }}/>} {pendingNavigation && selected && <AccessibleDialog title="处理未保存草稿" close={() => setPendingNavigation(undefined)} className={css.dialogSurface} dismissOnBackdrop={false}><div className={css.dialogForm}><div className={css.dialogHead}><div><span>本地草稿保护</span><h2>离开前如何处理当前草稿?</h2></div><button aria-label="继续编辑" onClick={() => setPendingNavigation(undefined)}>×</button></div><p>草稿已自动保存在此浏览器,尚未写入 Git。保留后可在下次打开此需求时继续;丢弃后无法恢复。</p><div className={css.stickyActions}><button onClick={() => setPendingNavigation(undefined)}>继续编辑</button><button onClick={() => void leaveWithDraft(true)} className={css.dangerText}>丢弃并离开</button><button className={css.execute} onClick={() => void leaveWithDraft(false)}>保留草稿并离开</button></div></div></AccessibleDialog>} {pendingWorkflow && selected && <AccessibleDialog title="确认流程操作" close={() => setPendingWorkflow(undefined)} className={css.dialogSurface}><div className={css.dialogForm}><div className={css.dialogHead}><div><span>流程确认</span><h2>{pendingWorkflow.kind === 'advance' ? `进入${selected.stage === 'product-review' ? '产品确认' : '产研确认'}?` : pendingWorkflow.kind === 'confirm' ? `确认当前版本 ${selected.currentCommit.slice(0, 8)}?` : '生成就绪需求?'}</h2></div><button aria-label="关闭" onClick={() => setPendingWorkflow(undefined)}>×</button></div><p>{pendingWorkflow.kind === 'advance' ? '阶段变化会通知协作者,当前版本和所有历史记录保持可追溯。' : pendingWorkflow.kind === 'confirm' ? '确认只绑定当前 commit;正文再次变化后需要重新确认。' : '将以产品和研发共同确认的当前 commit 生成可下载交付包。'}</p><div className={css.stickyActions}><button onClick={() => setPendingWorkflow(undefined)}>取消</button><button className={css.execute} onClick={() => void confirmWorkflow()}>确认执行</button></div></div></AccessibleDialog>}
236
554
  </div>
237
555
  }
238
556
 
@@ -256,13 +574,61 @@ function WorkflowFocus({ state, pendingForMe, onExecute }: { state: WorkflowStat
256
574
  </section>
257
575
  }
258
576
  const taskTypeLabel: Record<MyActionItem['type'], string> = { reply: '需要回复', confirm: '需要确认', review: '需要审核', reconfirm: '需要重新确认' }
259
- function TaskQueue({ items, open }: { items: MyActionItem[]; open: (item: MyActionItem) => void }) {
577
+ function TaskQueue({ items, open, participants, act }: { items: MyActionItem[]; open: (item: MyActionItem) => void; participants: ParticipantSnapshot[]; act: Act }) {
260
578
  const sorted = items.slice().sort((left, right) => Number(right.blocking) - Number(left.blocking) || right.updatedAt - left.updatedAt)
261
- return <details className={css.taskQueue}><summary><span>与你相关的事项</span><b>{items.length}</b></summary><div>{sorted.map(item => <button key={item.id} onClick={() => open(item)}><span>{item.blocking ? '优先' : '普通'}</span><div><strong>{taskTypeLabel[item.type]}</strong><small>{new Date(item.updatedAt).toLocaleString()}</small></div><i aria-hidden="true">›</i></button>)}</div></details>
579
+ return <details className={css.taskQueue}><summary><span>与你相关的事项</span><b>{items.length}</b></summary><div>{sorted.map(item => <div className={css.taskRow} key={item.id}><button onClick={() => open(item)}><span>{item.blocking ? '优先' : '普通'}</span><div><strong>{item.objectTitle}</strong><small title={new Date(item.updatedAt).toLocaleString()}>{taskTypeLabel[item.type]} · {stageLabel(item.dueStage)}前 · {relativeTime(item.updatedAt)}</small></div><i aria-hidden="true">›</i></button><div className={css.taskAssignment}><label>指派<select aria-label="指派待办" value={item.assigneeParticipantId ?? `role:${item.assigneeRole}`} onChange={event => { const assignee = participants.find(person => person.participantId === event.target.value); const role = event.target.value === 'role:engineering' ? 'engineering' : assignee?.role ?? 'product'; void act(actor => ({ kind: 'action.assign', participant: actor, requirementId: item.requirementId, actionItemId: item.id, assigneeRole: role, ...(assignee ? { assigneeParticipantId: assignee.participantId } : {}), dueStage: item.dueStage })) }}><option value="role:product">产品角色</option><option value="role:engineering">研发角色</option>{participants.map(person => <option key={person.participantId} value={person.participantId}>{person.nickname}</option>)}</select></label><label>截止阶段<select aria-label="待办截止阶段" value={item.dueStage} onChange={event => void act(actor => ({ kind: 'action.assign', participant: actor, requirementId: item.requirementId, actionItemId: item.id, assigneeRole: item.assigneeRole, ...(item.assigneeParticipantId ? { assigneeParticipantId: item.assigneeParticipantId } : {}), dueStage: event.target.value as RequirementStage }))}>{stageSteps.map(stage => <option key={stage.stage} value={stage.stage}>{stage.label}</option>)}</select></label></div></div>)}</div></details>
262
580
  }
263
581
 
264
- type ReviewDocumentMarker = { itemId: string; title: string; top: number; left: number; blocking: boolean }
265
- function RichMarkdownEditor({ markdown, reviewItems, selectedReviewId, focusRequest, onChange, onSelection, onOpenReview }: { markdown: string; reviewItems: ReviewItemView[]; selectedReviewId?: string | undefined; focusRequest: number; onChange: (markdown: string) => void; onSelection: (selection?: EditorSelection) => void; onOpenReview: (itemId: string) => void }) {
582
+ type DocumentCollabStats = { openReviews: number; blockingReviews: number; openDiscussions: number; pendingPatches: number; activeDecisions: number; invalidatedDecisions: number; runningAi: number; dirty: boolean }
583
+ function DocumentCollabBar({ activeMode, activeTaskView, activeRecordView, stats, onOpenReviews, onOpenDiscussion, onOpenPatches, onOpenDecisions }: { activeMode: PrimaryMode; activeTaskView: TaskView; activeRecordView: RecordView; stats: DocumentCollabStats; onOpenReviews: () => void; onOpenDiscussion: () => void; onOpenPatches: () => void; onOpenDecisions: () => void }) {
584
+ const reviewActive = activeMode === 'tasks' && activeTaskView === 'review'
585
+ const patchActive = activeMode === 'tasks' && activeTaskView === 'patches'
586
+ const discussionActive = activeMode === 'discussion'
587
+ const decisionsActive = activeMode === 'records' && activeRecordView === 'decisions'
588
+ return <section className={css.editorCollabBar} aria-label="正文协作状态">
589
+ <div className={css.collabBarState}>
590
+ <span className={stats.dirty ? css.collabStateDirty : css.collabStateSaved}>{stats.dirty ? '草稿未保存' : '当前正文'}</span>
591
+ {stats.runningAi > 0 && <span className={css.collabStateRunning}><i className={css.runningDot}/>AI 分析中 · {stats.runningAi}</span>}
592
+ </div>
593
+ <div className={css.collabBarActions}>
594
+ <button type="button" className={`${css.collabMetric} ${reviewActive ? css.collabMetricActive : ''} ${stats.blockingReviews > 0 ? css.collabMetricWarn : ''}`} aria-pressed={reviewActive} onClick={onOpenReviews}><b>{stats.openReviews}</b><span>待回答问题</span>{stats.blockingReviews > 0 && <small>{stats.blockingReviews} 阻塞</small>}</button>
595
+ <button type="button" className={`${css.collabMetric} ${discussionActive ? css.collabMetricActive : ''}`} aria-pressed={discussionActive} onClick={onOpenDiscussion}><b>{stats.openDiscussions}</b><span>打开讨论</span></button>
596
+ <button type="button" className={`${css.collabMetric} ${patchActive ? css.collabMetricActive : ''}`} aria-pressed={patchActive} onClick={onOpenPatches}><b>{stats.pendingPatches}</b><span>AI 建议</span></button>
597
+ <button type="button" className={`${css.collabMetric} ${decisionsActive ? css.collabMetricActive : ''} ${stats.invalidatedDecisions > 0 ? css.collabMetricWarn : ''}`} aria-pressed={decisionsActive} onClick={onOpenDecisions}><b>{stats.activeDecisions}</b><span>生效决策</span>{stats.invalidatedDecisions > 0 && <small>{stats.invalidatedDecisions} 作废</small>}</button>
598
+ </div>
599
+ </section>
600
+ }
601
+
602
+ export function InlineCommentComposer({ selection, text, setText, busy, cancel, submit }: { selection: EditorSelection; text: string; setText: (value: string) => void; busy: boolean; cancel: () => void; submit: () => Promise<void> }) {
603
+ const quote = selection.quote.replace(/\s+/g, ' ').trim()
604
+ const excerpt = quote.length > 72 ? `${quote.slice(0, 72)}…` : quote
605
+ const canSubmit = !busy && Boolean(text.trim())
606
+ return <form className={`${css.selectionPrompt} ${selection.placement === 'above' ? css.selectionPromptAbove : css.selectionPromptBelow}`} role="dialog" aria-label="围绕选中正文发起讨论" style={{ top: selection.rect.top, left: selection.rect.left }} onSubmit={event => { event.preventDefault(); if (canSubmit) void submit() }} onKeyDown={event => {
607
+ if (event.key === 'Escape') { event.preventDefault(); cancel() }
608
+ if ((event.metaKey || event.ctrlKey) && event.key === 'Enter' && canSubmit) { event.preventDefault(); void submit() }
609
+ }}>
610
+ <div className={css.selectionPromptHead}>
611
+ <div><b>{selection.heading?.trim() || '正文片段'}</b><small>{excerpt}</small></div>
612
+ <button type="button" className={css.selectionPromptClose} aria-label="取消文字选择" title="取消" onClick={cancel}>×</button>
613
+ </div>
614
+ <textarea required autoFocus aria-label="讨论内容" value={text} onChange={event => setText(event.target.value)} placeholder="直接写下问题或补充意见"/>
615
+ <div className={css.selectionPromptActions}>
616
+ <small>提交后 AI 会结合正文和工作区上下文分析。</small>
617
+ <div className={css.selectionPromptButtons}>
618
+ <button type="button" className={css.selectionPromptCancel} onClick={cancel}>取消</button>
619
+ <button type="submit" className={css.selectionPromptSubmit} disabled={!canSubmit}>{busy ? '提交中' : '提交'}</button>
620
+ </div>
621
+ </div>
622
+ </form>
623
+ }
624
+
625
+ type DocumentMarker = { kind: 'review' | 'comment'; objectId: string; label: string; title: string; top: number; left: number; highlightTop: number; highlightLeft: number; highlightWidth: number; highlightHeight: number; blocking: boolean; selected: boolean }
626
+ function DocumentMarkerIcon({ kind, blocking }: { kind: DocumentMarker['kind']; blocking: boolean }) {
627
+ if (kind === 'comment') return <svg viewBox="0 0 20 20" aria-hidden="true" focusable="false"><path d="M4.2 4.5h11.6a1.7 1.7 0 0 1 1.7 1.7v6.1a1.7 1.7 0 0 1-1.7 1.7H9l-4.2 2.8V14h-.6a1.7 1.7 0 0 1-1.7-1.7V6.2a1.7 1.7 0 0 1 1.7-1.7Z" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></svg>
628
+ if (blocking) return <svg viewBox="0 0 20 20" aria-hidden="true" focusable="false"><path d="M10 2.6 18 16.5H2L10 2.6Z" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/><path d="M10 7.2v4.6M10 14.4v.1" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"/></svg>
629
+ return <svg viewBox="0 0 20 20" aria-hidden="true" focusable="false"><circle cx="10" cy="10" r="7.4" fill="none" stroke="currentColor" strokeWidth="1.6"/><path d="M7.9 7.6a2.3 2.3 0 1 1 3.1 2.2c-.8.4-1 .9-1 1.6M10 14.3v.1" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
630
+ }
631
+ function RichMarkdownEditor({ markdown, reviewItems, comments, documentFocus, focusRequest, onChange, onSelection, onOpenReview, onReviewLocated, onOpenComment }: { markdown: string; reviewItems: ReviewItemView[]; comments: CommentThread[]; documentFocus?: DocumentAnchorFocus | undefined; focusRequest: number; onChange: (markdown: string) => void; onSelection: (selection?: EditorSelection) => void; onOpenReview: (itemId: string, position?: InlinePopoverPosition, sourceKey?: string) => void; onReviewLocated: (itemId: string, position: InlinePopoverPosition, sourceKey?: string) => void; onOpenComment: (commentId: string) => void }) {
266
632
  const shell = useRef<HTMLDivElement>(null)
267
633
  const host = useRef<HTMLDivElement>(null)
268
634
  const instance = useRef<ToastEditor>()
@@ -271,39 +637,74 @@ function RichMarkdownEditor({ markdown, reviewItems, selectedReviewId, focusRequ
271
637
  const onChangeRef = useRef(onChange)
272
638
  const onSelectionRef = useRef(onSelection)
273
639
  const onOpenReviewRef = useRef(onOpenReview)
640
+ const onReviewLocatedRef = useRef(onReviewLocated)
641
+ const onOpenCommentRef = useRef(onOpenComment)
274
642
  const reviewItemsRef = useRef(reviewItems)
275
- const selectedReviewIdRef = useRef(selectedReviewId)
643
+ const commentsRef = useRef(comments)
644
+ const documentFocusRef = useRef(documentFocus)
276
645
  const syncAnnotationsRef = useRef<() => void>(() => {})
277
- const [markers, setMarkers] = useState<ReviewDocumentMarker[]>([])
646
+ const [markers, setMarkers] = useState<DocumentMarker[]>([])
278
647
  onChangeRef.current = onChange
279
648
  onSelectionRef.current = onSelection
280
649
  onOpenReviewRef.current = onOpenReview
650
+ onReviewLocatedRef.current = onReviewLocated
651
+ onOpenCommentRef.current = onOpenComment
281
652
  reviewItemsRef.current = reviewItems
282
- selectedReviewIdRef.current = selectedReviewId
653
+ commentsRef.current = comments
654
+ documentFocusRef.current = documentFocus
283
655
  useEffect(() => {
284
656
  if (!host.current || !shell.current) return
285
657
  const editor = new ToastEditor({ el: host.current, initialValue: markdown, initialEditType: 'wysiwyg', hideModeSwitch: true, toolbarItems: [], plugins: [markdownShortcutsPlugin], height: '100%', language: 'zh-CN', usageStatistics: false, autofocus: false })
286
658
  const markInteraction = (): void => { interacted.current = true }
287
659
  let frame = 0
288
660
  const syncAnnotations = (): void => {
289
- const editorRoot = host.current?.querySelector<HTMLElement>('.toastui-editor-contents')
661
+ const editorRoot = visibleEditorContents(host.current)
290
662
  const shellElement = shell.current
291
663
  if (!editorRoot || !shellElement) return
292
- const selectedSourceClass = css.reviewSourceSelected!
293
- editorRoot.querySelectorAll<HTMLElement>(`.${selectedSourceClass}`).forEach(element => element.classList.remove(selectedSourceClass))
664
+ const reviewSourceClass = css.reviewSourceSelected!
665
+ const commentSourceClass = css.commentSourceSelected!
666
+ editorRoot.querySelectorAll<HTMLElement>('[data-annotation-kind]').forEach(element => { element.removeAttribute('data-annotation-kind'); element.removeAttribute('data-annotation-selected') })
667
+ editorRoot.querySelectorAll<HTMLElement>(`.${reviewSourceClass}, .${commentSourceClass}`).forEach(element => element.classList.remove(reviewSourceClass, commentSourceClass))
294
668
  const shellRect = shellElement.getBoundingClientRect()
295
669
  const slots = new Map<HTMLElement, number>()
296
- const nextMarkers: ReviewDocumentMarker[] = []
297
- reviewItemsRef.current.forEach(item => {
298
- const targets = reviewTargetElements(editorRoot, item)
299
- if (item.id === selectedReviewIdRef.current) targets.forEach(target => target.classList.add(selectedSourceClass))
300
- const target = targets[0]
301
- if (!target) return
670
+ const nextMarkers: DocumentMarker[] = []
671
+ const focus = documentFocusRef.current
672
+ const addMarker = (target: HTMLElement, marker: Omit<DocumentMarker, 'top' | 'left' | 'highlightTop' | 'highlightLeft' | 'highlightWidth' | 'highlightHeight'>): void => {
302
673
  const rect = target.getBoundingClientRect()
303
674
  if (rect.bottom < shellRect.top || rect.top > shellRect.bottom) return
304
675
  const slot = slots.get(target) ?? 0
305
676
  slots.set(target, slot + 1)
306
- nextMarkers.push({ itemId: item.id, title: item.question.trim() || item.statement.trim(), top: rect.top - shellRect.top + Math.min(8, rect.height / 2) + slot * 25, left: Math.max(4, rect.left - shellRect.left - 30), blocking: item.severity === 'blocking' })
677
+ const highlightLeft = Math.max(0, rect.left - shellRect.left - 5)
678
+ const highlightTop = rect.top - shellRect.top - 3
679
+ nextMarkers.push({
680
+ ...marker,
681
+ top: rect.top - shellRect.top + Math.min(8, rect.height / 2) + slot * 25,
682
+ left: Math.max(4, rect.left - shellRect.left - 30),
683
+ highlightTop,
684
+ highlightLeft,
685
+ highlightWidth: Math.max(28, Math.min(shellRect.width - highlightLeft - 8, rect.width + 10)),
686
+ highlightHeight: Math.max(26, Math.min(shellRect.height - Math.max(0, highlightTop) - 4, rect.height + 6)),
687
+ })
688
+ }
689
+ reviewItemsRef.current.forEach(item => {
690
+ const selected = focus?.kind === 'review' && focus.objectId === item.id
691
+ const targets = reviewTargetElements(editorRoot, item, selected ? focus.sourceKey : undefined)
692
+ const target = targets[0]
693
+ if (!target) return
694
+ target.dataset.annotationKind = target.dataset.annotationKind === 'comment' ? 'mixed' : 'review'
695
+ if (selected) target.classList.add(reviewSourceClass)
696
+ if (selected) target.dataset.annotationSelected = 'review'
697
+ addMarker(target, { kind: 'review', objectId: item.id, label: item.severity === 'blocking' ? '!' : '?', title: item.question.trim() || item.statement.trim(), blocking: item.severity === 'blocking', selected })
698
+ })
699
+ commentsRef.current.forEach(comment => {
700
+ const selected = focus?.kind === 'comment' && focus.objectId === comment.id
701
+ const targets = commentTargetElements(editorRoot, comment.anchor)
702
+ const target = targets[0]
703
+ if (!target) return
704
+ target.dataset.annotationKind = target.dataset.annotationKind === 'review' ? 'mixed' : 'comment'
705
+ if (selected) target.classList.add(commentSourceClass)
706
+ if (selected) target.dataset.annotationSelected = 'comment'
707
+ addMarker(target, { kind: 'comment', objectId: comment.id, label: '评', title: comment.body.trim() || comment.anchor?.quote.trim() || '整篇需求评论', blocking: false, selected })
307
708
  })
308
709
  setMarkers(nextMarkers)
309
710
  }
@@ -319,14 +720,12 @@ function RichMarkdownEditor({ markdown, reviewItems, selectedReviewId, focusRequ
319
720
  const block = start?.closest<HTMLElement>(reviewBlockSelector)
320
721
  const blockText = block?.textContent ?? quote
321
722
  const quoteIndex = blockText.indexOf(quote)
322
- const headings = Array.from(host.current?.querySelectorAll<HTMLElement>('.toastui-editor-contents h1, .toastui-editor-contents h2, .toastui-editor-contents h3, .toastui-editor-contents h4') ?? [])
723
+ const headings = Array.from(visibleEditorContents(host.current)?.querySelectorAll<HTMLElement>('h1, h2, h3, h4') ?? [])
323
724
  const anchorNode = block ?? start
324
725
  const heading = anchorNode ? headings.filter(candidate => Boolean(candidate.compareDocumentPosition(anchorNode) & Node.DOCUMENT_POSITION_FOLLOWING)).at(-1)?.textContent?.trim() : undefined
325
726
  const rect = range.getBoundingClientRect()
326
- const left = Math.min(Math.max(12, rect.left), Math.max(12, window.innerWidth - 390))
327
- const below = rect.bottom + 9
328
- const top = below + 48 < window.innerHeight ? below : Math.max(8, rect.top - 46)
329
- onSelectionRef.current({ quote, prefix: quoteIndex < 0 ? '' : blockText.slice(Math.max(0, quoteIndex - 80), quoteIndex), suffix: quoteIndex < 0 ? '' : blockText.slice(quoteIndex + quote.length, quoteIndex + quote.length + 80), ...(heading ? { heading } : {}), rect: { top, left } })
727
+ const position = inlinePopoverPositionFromRect(rect, { width: 360, height: 230 })
728
+ onSelectionRef.current({ quote, prefix: quoteIndex < 0 ? '' : blockText.slice(Math.max(0, quoteIndex - 80), quoteIndex), suffix: quoteIndex < 0 ? '' : blockText.slice(quoteIndex + quote.length, quoteIndex + quote.length + 80), ...(heading ? { heading } : {}), ...position })
330
729
  }
331
730
  editor.on('change', change)
332
731
  host.current.addEventListener('beforeinput', markInteraction)
@@ -335,17 +734,23 @@ function RichMarkdownEditor({ markdown, reviewItems, selectedReviewId, focusRequ
335
734
  host.current.addEventListener('pointerdown', markInteraction)
336
735
  host.current.addEventListener('mouseup', selection)
337
736
  host.current.addEventListener('keyup', selection)
338
- const scrollContainer = host.current.querySelector<HTMLElement>('.toastui-editor-ww-container')
339
737
  const scroll = (): void => { onSelectionRef.current(undefined); scheduleAnnotations() }
340
- scrollContainer?.addEventListener('scroll', scroll, { passive: true })
738
+ const scrollTargets = new Set<HTMLElement>()
739
+ const bindScrollTarget = (element: HTMLElement): void => {
740
+ if (scrollTargets.has(element)) return
741
+ scrollTargets.add(element)
742
+ element.addEventListener('scroll', scroll, { passive: true })
743
+ }
744
+ const bindAnnotationScrollTargets = (): void => annotationScrollTargets(host.current).forEach(bindScrollTarget)
745
+ bindAnnotationScrollTargets()
341
746
  window.addEventListener('resize', scheduleAnnotations)
342
747
  const resizeObserver = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(scheduleAnnotations)
343
748
  resizeObserver?.observe(shell.current)
344
- const mutationObserver = new MutationObserver(scheduleAnnotations)
749
+ const mutationObserver = new MutationObserver(() => { bindAnnotationScrollTargets(); scheduleAnnotations() })
345
750
  mutationObserver.observe(host.current, { childList: true, subtree: true })
346
751
  instance.current = editor
347
752
  scheduleAnnotations()
348
- return () => { cancelAnimationFrame(frame); mutationObserver.disconnect(); resizeObserver?.disconnect(); window.removeEventListener('resize', scheduleAnnotations); scrollContainer?.removeEventListener('scroll', scroll); host.current?.removeEventListener('beforeinput', markInteraction); host.current?.removeEventListener('paste', markInteraction); host.current?.removeEventListener('drop', markInteraction); host.current?.removeEventListener('pointerdown', markInteraction); host.current?.removeEventListener('mouseup', selection); host.current?.removeEventListener('keyup', selection); editor.destroy() }
753
+ return () => { cancelAnimationFrame(frame); mutationObserver.disconnect(); resizeObserver?.disconnect(); window.removeEventListener('resize', scheduleAnnotations); scrollTargets.forEach(element => element.removeEventListener('scroll', scroll)); host.current?.removeEventListener('beforeinput', markInteraction); host.current?.removeEventListener('paste', markInteraction); host.current?.removeEventListener('drop', markInteraction); host.current?.removeEventListener('pointerdown', markInteraction); host.current?.removeEventListener('mouseup', selection); host.current?.removeEventListener('keyup', selection); editor.destroy() }
349
754
  }, [])
350
755
  useEffect(() => {
351
756
  const editor = instance.current
@@ -357,14 +762,31 @@ function RichMarkdownEditor({ markdown, reviewItems, selectedReviewId, focusRequ
357
762
  }, [markdown])
358
763
  useEffect(() => {
359
764
  syncAnnotationsRef.current()
360
- if (!selectedReviewId || focusRequest === 0) return
361
- const editorRoot = host.current?.querySelector<HTMLElement>('.toastui-editor-contents')
362
- const item = reviewItems.find(candidate => candidate.id === selectedReviewId)
363
- const target = editorRoot && item ? reviewTargetElements(editorRoot, item)[0] : undefined
364
- target?.scrollIntoView({ behavior: 'smooth', block: 'center' })
365
- window.setTimeout(() => syncAnnotationsRef.current(), 220)
366
- }, [reviewItems, selectedReviewId, focusRequest])
367
- return <div className={css.richEditorShell} ref={shell}><div className={css.richEditor} ref={host}/><div className={css.reviewAnchorLayer} aria-label="正文问题锚点">{markers.map(marker => <button key={marker.itemId} type="button" className={`${css.documentReviewAnchor} ${marker.blocking ? css.documentReviewAnchorBlocking : ''} ${marker.itemId === selectedReviewId ? css.documentReviewAnchorSelected : ''}`} style={{ top: marker.top, left: marker.left }} title={marker.title} aria-label={`打开问题:${marker.title}`} onMouseDown={event => event.preventDefault()} onClick={() => onOpenReviewRef.current(marker.itemId)}>?</button>)}</div></div>
765
+ if (!documentFocus || focusRequest === 0) return
766
+ const findTarget = (): HTMLElement | undefined => {
767
+ const editorRoot = visibleEditorContents(host.current)
768
+ if (!editorRoot) return undefined
769
+ if (documentFocus.kind === 'review') {
770
+ const item = reviewItems.find(candidate => candidate.id === documentFocus.objectId)
771
+ return item ? reviewTargetElements(editorRoot, item, documentFocus.sourceKey)[0] : undefined
772
+ }
773
+ const comment = comments.find(candidate => candidate.id === documentFocus.objectId)
774
+ return comment ? commentTargetElements(editorRoot, comment.anchor)[0] : undefined
775
+ }
776
+ const findReviewMarker = (): HTMLElement | undefined => Array.from(shell.current?.querySelectorAll<HTMLElement>('[data-review-object-id]') ?? []).find(element => element.dataset.reviewObjectId === documentFocus.objectId)
777
+ const target = findTarget()
778
+ target?.scrollIntoView(documentFocus.kind === 'review' ? { block: 'center' } : { behavior: 'smooth', block: 'center' })
779
+ const updateLocatedReview = (): void => {
780
+ syncAnnotationsRef.current()
781
+ if (documentFocus.kind !== 'review') return
782
+ const anchor = findReviewMarker() ?? findTarget()
783
+ if (anchor) onReviewLocatedRef.current(documentFocus.objectId, inlinePopoverPositionFromRect(anchor.getBoundingClientRect(), inlineReviewPopoverSize), documentFocus.sourceKey)
784
+ }
785
+ if (documentFocus.kind === 'review') window.requestAnimationFrame(() => window.requestAnimationFrame(updateLocatedReview))
786
+ else window.setTimeout(updateLocatedReview, 220)
787
+ }, [reviewItems, comments, documentFocus, focusRequest])
788
+ return <div className={css.richEditorShell} ref={shell}><div className={css.richEditor} ref={host}/><div className={css.reviewAnchorLayer} aria-label="正文协作锚点">{markers.map(marker => <span key={`highlight-${marker.kind}-${marker.objectId}`} className={`${css.documentAnchorHighlight} ${marker.kind === 'comment' ? css.documentCommentHighlight : css.documentReviewHighlight} ${marker.blocking ? css.documentReviewHighlightBlocking : ''} ${marker.selected ? css.documentAnchorHighlightSelected : ''}`} style={{ top: marker.highlightTop, left: marker.highlightLeft, width: marker.highlightWidth, height: marker.highlightHeight }} aria-hidden="true"/>)}
789
+ {markers.map(marker => <button key={`${marker.kind}-${marker.objectId}`} type="button" className={`${marker.kind === 'comment' ? css.documentCommentAnchor : css.documentReviewAnchor} ${marker.blocking ? css.documentReviewAnchorBlocking : ''} ${marker.selected ? css.documentAnchorSelected : ''}`} style={{ top: marker.top, left: marker.left }} title={marker.title} aria-label={marker.kind === 'comment' ? `打开评论:${marker.title}` : `打开问题:${marker.title}`} data-review-object-id={marker.kind === 'review' ? marker.objectId : undefined} data-comment-object-id={marker.kind === 'comment' ? marker.objectId : undefined} onMouseDown={event => event.preventDefault()} onClick={event => marker.kind === 'comment' ? onOpenCommentRef.current(marker.objectId) : onOpenReviewRef.current(marker.objectId, inlinePopoverPositionFromRect(event.currentTarget.getBoundingClientRect(), inlineReviewPopoverSize))}><DocumentMarkerIcon kind={marker.kind} blocking={marker.blocking}/></button>)}</div></div>
368
790
  }
369
791
 
370
792
  type Act = (factory: (actor: ParticipantSnapshot) => CollaborationAction) => Promise<boolean>
@@ -372,11 +794,11 @@ const reviewKindLabel: Record<ReviewKind, string> = { 'product-first': '需求
372
794
  const reviewTypeLabel: Record<ReviewItemType, string> = { goal: '目标', evidence: '依据', 'history-conflict': '历史冲突', 'current-implementation': '当前实现', scope: '范围', semantics: '规则语义', completeness: '完整性', acceptance: '验收', risk: '风险' }
373
795
  const statusLabel: Record<string, string> = { queued: '排队中', running: '分析中', completed: '已完成', failed: '失败', open: '待处理', answered: '已回答待整理', 'joint-review': '待产研共议', 'non-blocking-verify': '保留待核对', resolved: '已解决', invalidated: '已失效', pending: '待确认', accepted: '已接受', rejected: '未采用', stale: '已过期', blocking: '阻塞', major: '重要', minor: '一般' }
374
796
  const evidenceStatusLabel: Record<string, string> = { FACT: '已有依据', INFERENCE: '根据现有信息推断', ASSUMPTION: '暂定规则', TO_VERIFY: '待核对' }
797
+ const commentResolutionLabel: Record<CommentResolution, string> = { 'written-back': '已回写正文', decision: '形成决策', rejected: '不采纳', 'open-question': '转开放问题' }
375
798
  function MarkdownBody({ text, className = '' }: { text: string; className?: string | undefined }) { return <div className={`${css.markdownBody} ${className}`} dangerouslySetInnerHTML={{ __html: md.render(text) }}/> }
376
799
  type ReviewItemView = RequirementView['reviewItems'][number]
377
- export function ReviewPanel({ requirement, act, api, focusedItemId, openRequest, onSelectReview, onLocateSource, onOpenRequestHandled }: { requirement: RequirementView; act: Act; api: SpecApi; focusedItemId?: string | undefined; openRequest?: ReviewOpenRequest | undefined; onSelectReview?: (itemId: string) => void; onLocateSource?: (itemId: string) => void; onOpenRequestHandled?: (requestId: number) => void }) {
800
+ export function ReviewPanel({ requirement, act, api, focusedItemId, openRequest, onSelectReview, onLocateSource, onOpenRequestHandled }: { requirement: RequirementView; act: Act; api: SpecApi; focusedItemId?: string | undefined; openRequest?: ReviewOpenRequest | undefined; onSelectReview?: (itemId: string) => void; onLocateSource?: (itemId: string, sourceKey?: string) => void; onOpenRequestHandled?: (requestId: number) => void }) {
378
801
  const [selectedItemId, setSelectedItemId] = useState<string>()
379
- const closeSelectedItem = useCallback(() => setSelectedItemId(undefined), [])
380
802
  const current = requirement.reviewItems.filter(item => item.commit === requirement.currentCommit).slice().sort((left, right) => Number(right.severity === 'blocking') - Number(left.severity === 'blocking') || right.updatedAt - left.updatedAt)
381
803
  const historical = requirement.reviewItems.filter(item => item.commit !== requirement.currentCommit)
382
804
  const active = current.filter(item => !['resolved', 'invalidated', 'non-blocking-verify'].includes(item.status))
@@ -384,10 +806,14 @@ export function ReviewPanel({ requirement, act, api, focusedItemId, openRequest,
384
806
  const unansweredCount = active.filter(item => item.status === 'open').length
385
807
  const answeredCount = active.filter(item => item.status === 'answered').length
386
808
  const processedCount = current.filter(item => item.status !== 'open').length
387
- const selectedItem = [...current, ...historical].find(item => item.id === selectedItemId)
388
- const nextAnswerable = active.find(item => item.status === 'open' && item.id !== selectedItemId)
389
809
  const currentRuns = requirement.aiRuns.filter(run => run.commit === requirement.currentCommit)
390
- const openItem = (itemId: string): void => { setSelectedItemId(itemId); onSelectReview?.(itemId) }
810
+ const currentStageSessionId = requirement.aiConversations?.find(item => item.stage === requirement.stage && item.stageCycle === requirement.stageCycle)?.sessionId
811
+ const openItem = (itemId: string): void => {
812
+ setSelectedItemId(itemId)
813
+ const sourceKey = [...current, ...historical].find(item => item.id === itemId)?.sourceAnchors?.[0] ? `quote-0` : undefined
814
+ onSelectReview?.(itemId)
815
+ onLocateSource?.(itemId, sourceKey)
816
+ }
391
817
  useEffect(() => {
392
818
  if (!openRequest) return
393
819
  if ([...current, ...historical].some(item => item.id === openRequest.objectId)) openItem(openRequest.objectId)
@@ -395,12 +821,11 @@ export function ReviewPanel({ requirement, act, api, focusedItemId, openRequest,
395
821
  }, [openRequest?.requestId])
396
822
  return <>
397
823
  <div className={css.panelSummary}><div><strong>问题检查清单</strong><span>{unansweredCount > 0 ? `${unansweredCount} 项待回答 · ${active.filter(item => item.severity === 'blocking' && item.status === 'open').length} 项阻塞下一阶段` : answeredCount > 0 ? '回答已齐,下一步让 AI 回读' : active.length > 0 ? `${active.length} 项等待后续处理` : '当前版本已全部处理'}</span></div>{current.length > 0 && <div className={css.checklistMeter}><small>{processedCount}/{current.length}</small><progress aria-label={`已回答或处理 ${processedCount} 项,共 ${current.length} 项`} value={processedCount} max={current.length}/></div>}</div>
398
- {currentRuns.length > 0 && <details className={css.runHistory}><summary>查看本轮 AI 检查记录({currentRuns.length})</summary>{currentRuns.slice().reverse().map(run => <div className={css.run} key={run.id}><div><strong>{reviewKindLabel[run.kind]}</strong><span>{statusLabel[run.status] ?? run.status}</span></div>{run.maturitySummary && <MarkdownBody text={run.maturitySummary}/>} {run.error && <p className={css.chatError}>{friendlyActionError(run.error)}</p>}{run.sessionId && <AiConversation api={api} requirementId={requirement.id} sessionId={run.sessionId}/>}</div>)}</details>}
824
+ {currentRuns.length > 0 && <details className={css.runHistory}><summary>AI 运行中心({currentRuns.length}){currentStageSessionId ? ' · 当前阶段复用 1 个会话' : ''}</summary>{currentRuns.slice().reverse().map(run => { const endedAt = ['completed', 'failed'].includes(run.status) ? run.updatedAt : Date.now(); const sharedSession = Boolean(run.sessionId && run.sessionId === currentStageSessionId); const step = run.status === 'queued' ? '等待可用执行槽' : run.status === 'running' ? sharedSession ? '复用当前阶段上下文并分析增量' : '读取工作区并核对当前正文' : run.status === 'completed' ? '检查结果已写入问题清单' : '运行中断,输入和历史结果已保留'; return <div className={css.run} key={run.id}><div><strong>{reviewKindLabel[run.kind]}</strong><span>{statusLabel[run.status] ?? run.status}</span></div><dl><div><dt>当前步骤</dt><dd>{step}</dd></div><div><dt>开始</dt><dd title={new Date(run.createdAt).toLocaleString()}>{relativeTime(run.createdAt)}</dd></div><div><dt>耗时</dt><dd>{durationText(endedAt - run.createdAt)}</dd></div></dl>{run.maturitySummary && <MarkdownBody text={run.maturitySummary}/>} {run.error && <><p className={css.chatError}>{friendlyActionError(run.error)}</p><button className={css.panelAction} onClick={() => void act(actor => ({ kind: 'review.request', participant: actor, requirementId: requirement.id, reviewKind: run.kind }))}>重试本次检查</button></>}{run.sessionId && <AiConversation api={api} requirementId={requirement.id} sessionId={run.sessionId}/>}</div>})}</details>}
399
825
  {current.length === 0 && <div className={css.emptyPanel}><strong>等待 AI 完成检查</strong><p>检查结果会按优先级出现在这里。</p></div>}
400
826
  {active.length > 0 && <ReviewChecklist items={active} selectedItemId={focusedItemId ?? selectedItemId} open={openItem}/>}
401
827
  {deferred.length > 0 && <details className={css.historyGroup}><summary>保留待核对 · {deferred.length}</summary><ReviewChecklist items={deferred} selectedItemId={focusedItemId ?? selectedItemId} open={openItem}/></details>}
402
828
  {historical.length > 0 && <details className={css.historyGroup}><summary>历史问题 · {historical.length}</summary><ReviewChecklist items={historical.slice().reverse()} selectedItemId={focusedItemId ?? selectedItemId} open={openItem}/></details>}
403
- {selectedItem && <ReviewDecisionDialog key={selectedItem.id} item={selectedItem} sourceMarkdown={requirement.version?.markdown ?? ''} requirementId={requirement.id} nextItemId={nextAnswerable?.id} act={act} close={closeSelectedItem} locateSource={() => { closeSelectedItem(); onLocateSource?.(selectedItem.id) }} complete={continueToNext => { if (continueToNext && nextAnswerable) openItem(nextAnswerable.id); else closeSelectedItem() }}/>}
404
829
  </>
405
830
  }
406
831
  function ReviewChecklist({ items, selectedItemId, open }: { items: ReviewItemView[]; selectedItemId?: string | undefined; open: (itemId: string) => void }) {
@@ -426,70 +851,94 @@ const dispositionGuidance: Record<keyof typeof dispositionLabel, string> = {
426
851
  'to-verify': '这项不会继续阻塞当前阶段,但会保留在待核对清单。',
427
852
  'joint-review': '把问题留到产研共审,由产品和研发共同决定。',
428
853
  }
429
- function ReviewDecisionDialog({ item, sourceMarkdown, requirementId, nextItemId, act, close, locateSource, complete }: { item: ReviewItemView; sourceMarkdown: string; requirementId: string; nextItemId?: string | undefined; act: Act; close: () => void; locateSource: () => void; complete: (continueToNext: boolean) => void }) {
854
+ export function InlineReviewComposer({ item, sourceMarkdown, requirementId, position, nextItemId, busy, act, close, locateSource, complete }: { item: ReviewItemView; sourceMarkdown: string; requirementId: string; position: InlinePopoverPosition; nextItemId?: string | undefined; busy: boolean; act: Act; close: () => void; locateSource: (sourceKey?: string) => void; complete: (continueToNext: boolean) => void }) {
430
855
  const [disposition, setDisposition] = useState<keyof typeof dispositionLabel>('context')
431
856
  const [body, setBody] = useState('')
432
- const dialogRef = useRef<HTMLElement>(null)
433
- const returnFocusRef = useRef<HTMLElement | null>(typeof document !== 'undefined' && document.activeElement instanceof HTMLElement ? document.activeElement : null)
857
+ const formRef = useRef<HTMLFormElement>(null)
434
858
  const recommendations = item.recommendedOptions?.map(option => option.trim()).filter(Boolean).slice(0, 5) ?? []
435
859
  const sourceSnippets = reviewSourceSnippets(sourceMarkdown, item)
860
+ const primarySource = sourceSnippets[0]
436
861
  const canRespond = !item.response && item.status === 'open'
437
862
  useEffect(() => {
438
- const dialog = dialogRef.current
439
- const focusableSelector = 'button:not(:disabled), select:not(:disabled), textarea:not(:disabled), input:not(:disabled), [href], [tabindex]:not([tabindex="-1"])'
440
- const focusable = (): HTMLElement[] => dialog ? Array.from(dialog.querySelectorAll<HTMLElement>(focusableSelector)) : []
441
- if (dialog && !dialog.contains(document.activeElement)) (dialog.querySelector<HTMLElement>('textarea') ?? focusable()[0])?.focus()
442
863
  const keydown = (event: KeyboardEvent): void => {
443
864
  if (event.key === 'Escape') { event.preventDefault(); close(); return }
444
- if (event.key !== 'Tab') return
445
- const controls = focusable()
446
- if (controls.length === 0) { event.preventDefault(); return }
447
- const first = controls[0]!
448
- const last = controls[controls.length - 1]!
449
- if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus() }
450
- else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus() }
451
865
  }
452
866
  window.addEventListener('keydown', keydown)
453
- return () => { window.removeEventListener('keydown', keydown); returnFocusRef.current?.focus() }
867
+ window.setTimeout(() => formRef.current?.querySelector<HTMLElement>('textarea')?.focus(), 0)
868
+ return () => window.removeEventListener('keydown', keydown)
454
869
  }, [close])
455
870
  const choose = (option: string): void => { setBody(option); setDisposition('accept-modified') }
456
871
  const submit = async (continueToNext: boolean): Promise<void> => { const answer = body.trim() || (disposition === 'joint-review' ? '转产研共同决策' : ''); if (answer && await act(actor => ({ kind: 'review.respond', participant: actor, requirementId, reviewItemId: item.id, disposition, body: answer }))) complete(continueToNext) }
457
- const canSubmit = Boolean(body.trim()) || disposition === 'joint-review'
458
- return <div className={`${css.modal} ${css.reviewDecisionModal}`} onMouseDown={event => { if (event.currentTarget === event.target) close() }}>
459
- <section ref={dialogRef} className={css.reviewDecisionDialog} role="dialog" aria-modal="true" aria-labelledby={`review-dialog-${item.id}`}>
460
- <header className={css.reviewDecisionHeader}><div><div className={css.decisionTags}><b>{statusLabel[item.severity] ?? item.severity}</b><span>{reviewTypeLabel[item.type]}</span><span>{evidenceStatusLabel[item.epistemicStatus] ?? item.epistemicStatus}</span></div><h2 id={`review-dialog-${item.id}`}>{item.statement}</h2></div><button aria-label="关闭问题窗口" title="关闭" onClick={close}>×</button></header>
461
- <div className={css.reviewDecisionBody}>
462
- <main className={css.reviewDecisionContext}>
463
- <section className={css.decisionQuestion}><span>待澄清问题</span><MarkdownBody text={item.question}/></section>
464
- {sourceSnippets.length > 0 && <section className={css.decisionSection}><div className={css.decisionSectionHead}><h3>关联正文</h3><button onClick={locateSource}>在正文中查看</button></div><div className={css.decisionSourceList}>{sourceSnippets.map(snippet => <div className={css.decisionSource} key={snippet.key}><span>{snippet.label}{snippet.line ? ` · 第 ${snippet.line} 行` : ''}</span><MarkdownBody text={snippet.markdown}/></div>)}</div></section>}
465
- <section className={css.decisionSection}><h3>为什么需要明确</h3><MarkdownBody text={item.impact}/></section>
466
- <section className={css.decisionSection}><div className={css.decisionSectionHead}><h3>依据与来源</h3><span>{item.evidence.length} 条</span></div>{item.evidence.length === 0 ? <p className={css.decisionEmpty}>当前没有可核对的资料,可以按业务判断回答,或选择保留待核对。</p> : <div className={css.decisionEvidenceList}>{item.evidence.map((evidence, index) => <div className={css.decisionEvidence} key={`${evidence.source}-${index}`}><code>{evidence.source}{evidence.version ? `@${evidence.version}` : ''}</code><MarkdownBody text={evidence.statement}/></div>)}</div>}</section>
467
- {(item.affectedSections.length > 0 || item.affectedAcceptanceIds.length > 0) && <section className={css.decisionSection}><h3>可能影响</h3><p>{[...item.affectedSections, ...item.affectedAcceptanceIds].join(' · ')}</p></section>}
468
- </main>
469
- <aside className={css.reviewDecisionAside} aria-label="处理这个问题">
470
- {item.response ? <div className={css.decisionResponse}><span>已回复</span><strong>{item.response.participant.nickname}</strong><small>{dispositionLabel[item.response.disposition]}</small><MarkdownBody text={item.response.body}/></div> : canRespond ? <>
471
- <div className={css.decisionAsideHead}><span>你的回答</span><strong>先选处理结果,再写下最终结论</strong></div>
472
- {recommendations.length > 0 && <fieldset className={css.decisionOptions}><legend>可直接采用的回答</legend>{recommendations.map((option, index) => <button key={option} className={body === option ? css.selectedDecisionOption : ''} aria-pressed={body === option} onClick={() => choose(option)}><span>{option}</span><b>{body === option ? '已选择' : String(index + 1).padStart(2, '0')}</b></button>)}</fieldset>}
473
- <div className={css.decisionForm}><label>保存后如何处理<select required value={disposition} onChange={event => setDisposition(event.target.value as keyof typeof dispositionLabel)}>{Object.entries(dispositionLabel).map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></label><p className={css.decisionModeHint}>{dispositionGuidance[disposition]}</p><label>最终结论<textarea required autoFocus value={body} onChange={event => setBody(event.target.value)} placeholder={disposition === 'evidence' ? '粘贴数据、案例或来源链接,并说明它支持什么结论' : disposition === 'joint-review' ? '可选:补充希望产品和研发重点讨论的边界' : '写清最终判断、适用范围、例外情况和取舍理由'}/></label></div>
474
- <div className={css.decisionActions}><button onClick={close}>取消</button><div>{nextItemId && <button disabled={!canSubmit} onClick={() => void submit(false)}>保存并返回清单</button>}<button className={css.execute} disabled={!canSubmit} onClick={() => void submit(Boolean(nextItemId))}>{nextItemId ? '保存并回答下一题' : '保存最后一项回答'}</button></div></div>
475
- </> : <div className={css.decisionResponse}><span>{statusLabel[item.status] ?? item.status}</span><strong>这条记录当前不可回复</strong><p>你仍可以查看完整问题、影响和来源。</p></div>}
476
- </aside>
477
- </div>
872
+ const canSubmit = !busy && (Boolean(body.trim()) || disposition === 'joint-review')
873
+ return <form ref={formRef} className={`${css.inlineReviewPrompt} ${position.placement === 'above' ? css.selectionPromptAbove : css.selectionPromptBelow}`} role="dialog" aria-label="回答待处理问题" style={{ top: position.rect.top, left: position.rect.left, maxHeight: position.maxHeight }} onSubmit={event => { event.preventDefault(); if (canSubmit) void submit(Boolean(nextItemId)) }} onKeyDown={event => {
874
+ if ((event.metaKey || event.ctrlKey) && event.key === 'Enter' && canSubmit) { event.preventDefault(); void submit(Boolean(nextItemId)) }
875
+ }}>
876
+ <header className={css.inlineReviewHead}>
877
+ <div><div className={css.decisionTags}><b>{statusLabel[item.severity] ?? item.severity}</b><span>{reviewTypeLabel[item.type]}</span><span>{evidenceStatusLabel[item.epistemicStatus] ?? item.epistemicStatus}</span></div><strong>{item.statement}</strong></div>
878
+ <span className={css.inlineReviewHeadActions}><button type="button" onClick={() => void navigator.clipboard.writeText(`${location.origin}${location.pathname}#spec-collab/${requirementId}/tasks/${item.id}`)}>复制链接</button><button type="button" aria-label="关闭问题窗口" title="关闭" onClick={close}>×</button></span>
879
+ </header>
880
+ <div className={css.inlineReviewBody} data-dialog-scroll-region>
881
+ <section className={css.inlineReviewQuestion}><span>待回答</span><MarkdownBody text={item.question}/></section>
882
+ {primarySource && <button type="button" className={css.inlineReviewSource} onClick={() => locateSource(primarySource.targetKey)}><span>{primarySource.label}{primarySource.line ? ` · 第 ${primarySource.line} 行` : ''}</span><q>{primarySource.markdown.replace(/\s+/g, ' ').slice(0, 96)}{primarySource.markdown.length > 96 ? '…' : ''}</q></button>}
883
+ {item.response ? <div className={css.decisionResponse}><span>已回复</span><strong>{item.response.participant.nickname}</strong><small>{dispositionLabel[item.response.disposition]}</small><MarkdownBody text={item.response.body}/></div> : canRespond ? <>
884
+ {recommendations.length > 0 && <fieldset className={`${css.decisionOptions} ${css.inlineDecisionOptions}`}><legend>可采用的回答</legend>{recommendations.map((option, index) => <button type="button" key={option} className={body === option ? css.selectedDecisionOption : ''} aria-pressed={body === option} onClick={() => choose(option)}><span>{option}</span><b>{body === option ? '已选择' : String(index + 1).padStart(2, '0')}</b></button>)}</fieldset>}
885
+ <div className={`${css.decisionForm} ${css.inlineDecisionForm}`}><label>保存后如何处理<select required value={disposition} onChange={event => setDisposition(event.target.value as keyof typeof dispositionLabel)}>{Object.entries(dispositionLabel).map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></label><p className={css.decisionModeHint}>{dispositionGuidance[disposition]}</p><label>最终结论<textarea required value={body} onChange={event => setBody(event.target.value)} placeholder={disposition === 'evidence' ? '粘贴数据、案例或来源链接,并说明它支持什么结论' : disposition === 'joint-review' ? '可选:补充希望产品和研发重点讨论的边界' : '写清最终判断、适用范围、例外情况和取舍理由'}/></label></div>
886
+ <details className={css.inlineReviewDetails}><summary>影响与依据</summary><section><h3>为什么需要明确</h3><MarkdownBody text={item.impact}/></section><section><h3>依据与来源 · {item.evidence.length}</h3>{item.evidence.length === 0 ? <p className={css.decisionEmpty}>当前没有可核对的资料,可以按业务判断回答,或选择保留待核对。</p> : <div className={css.decisionEvidenceList}>{item.evidence.map((evidence, index) => <div className={css.decisionEvidence} key={`${evidence.source}-${index}`}><code>{evidence.source}{evidence.version ? `@${evidence.version}` : ''}</code><MarkdownBody text={evidence.statement}/></div>)}</div>}</section>{(item.affectedSections.length > 0 || item.affectedAcceptanceIds.length > 0) && <section><h3>可能影响</h3><p>{[...item.affectedSections, ...item.affectedAcceptanceIds].join(' · ')}</p></section>}</details>
887
+ </> : <div className={css.decisionResponse}><span>{statusLabel[item.status] ?? item.status}</span><strong>这条记录当前不可回复</strong><p>你仍可以查看完整问题、影响和来源。</p></div>}
888
+ </div>
889
+ {canRespond && <div className={css.inlineReviewActions}><button type="button" onClick={close}>取消</button><div>{nextItemId && <button type="button" disabled={!canSubmit} onClick={() => void submit(false)}>保存并留在此处</button>}<button type="submit" className={css.execute} disabled={!canSubmit}>{busy ? '保存中' : nextItemId ? '保存并下一题' : '保存回答'}</button></div></div>}
890
+ </form>
891
+ }
892
+ export function DiscussionPanel({ requirement, notifications, focusedCommentId, onSelectComment, onLocateComment, act, api }: { requirement: RequirementView; notifications?: Notification[] | undefined; selection?: { quote: string } | undefined; text?: string; setText?: (value: string) => void; cancel?: () => void; submit?: () => Promise<void>; focusedCommentId?: string | undefined; onSelectComment?: (commentId: string) => void; onLocateComment?: (commentId: string) => void; act: Act; api: SpecApi }) {
893
+ const [filter, setFilter] = useState<'open' | 'resolved' | 'unread' | 'all'>('open'); const [sort, setSort] = useState<'document' | 'recent'>('document'); const [replyDrafts, setReplyDrafts] = useState<Record<string, string>>({}); const [directory, setDirectory] = useState<ParticipantSnapshot[]>([])
894
+ useEffect(() => { const request = (api as Partial<SpecApi>).directory?.(); if (request) void request.then(setDirectory, () => undefined) }, [requirement.id])
895
+ useEffect(() => { const focused = requirement.comments.find(item => item.id === focusedCommentId); if (focused) setFilter(focused.commit !== requirement.currentCommit ? 'all' : focused.status === 'open' ? 'open' : 'resolved') }, [focusedCommentId, requirement.id, requirement.currentCommit])
896
+ const locateComment = (commentId: string): void => {
897
+ onSelectComment?.(commentId)
898
+ onLocateComment?.(commentId)
899
+ }
900
+ const comments = requirement.comments.slice().sort((left, right) => sort === 'recent' ? right.updatedAt - left.updatedAt : Number(right.status === 'open') - Number(left.status === 'open') || left.createdAt - right.createdAt)
901
+ const currentComments = comments.filter(comment => comment.commit === requirement.currentCommit)
902
+ const unreadCommentNotifications = (notifications ?? []).filter(item => item.requirementId === requirement.id && item.objectType === 'comment' && item.readAt === undefined)
903
+ const unreadCommentIds = new Set(unreadCommentNotifications.map(item => item.objectId))
904
+ const unreadComments = currentComments.filter(comment => unreadCommentIds.has(comment.id))
905
+ const openComments = currentComments.filter(comment => comment.status === 'open')
906
+ const closedComments = currentComments.filter(comment => comment.status !== 'open')
907
+ const historicalComments = comments.filter(comment => comment.commit !== requirement.currentCommit)
908
+ const renderThread = (comment: CommentThread) => {
909
+ const selected = focusedCommentId === comment.id
910
+ const currentVersion = comment.commit === requirement.currentCommit
911
+ const resolvedText = comment.resolution ? commentResolutionLabel[comment.resolution] : undefined
912
+ return <section id={`spec-object-${comment.id}`} className={`${css.commentThread} ${selected ? css.commentThreadSelected : ''} ${comment.status !== 'open' ? css.commentThreadClosed : ''}`} key={comment.id} aria-current={selected ? 'true' : undefined}>
913
+ <header className={css.commentThreadHead}>
914
+ <div className={css.commentGlyph} aria-hidden="true">评</div>
915
+ <div className={css.commentThreadMeta}>
916
+ <strong>{comment.author.nickname}</strong>
917
+ <div className={css.threadPills}><span>{currentVersion ? '当前正文' : '历史正文'}</span><span>{statusLabel[comment.status] ?? comment.status}</span><span>AI {statusLabel[comment.aiStatus] ?? comment.aiStatus}</span>{resolvedText && <span>{resolvedText}</span>}</div>
918
+ </div>
919
+ <div className={css.threadHeaderActions}>{unreadCommentIds.has(comment.id) && <button type="button" onClick={() => void act(actor => ({ kind: 'notification.mark-read', participant: actor, requirementId: requirement.id, notificationIds: unreadCommentNotifications.filter(item => item.objectId === comment.id).map(item => item.id) }))}>标为已读</button>}{comment.anchor && <button type="button" className={css.locateSourceButton} onClick={() => locateComment(comment.id)}>定位正文</button>}<button type="button" onClick={() => void navigator.clipboard.writeText(`${location.origin}${location.pathname}#spec-collab/${requirement.id}/discussion/${comment.id}`)}>复制链接</button></div>
920
+ </header>
921
+ {comment.anchor && <button type="button" className={css.commentSourceButton} onClick={() => locateComment(comment.id)}><span>{comment.anchor.heading?.trim() || '原文片段'}</span><q>{comment.anchor.quote}</q></button>}
922
+ {!comment.anchor && <div className={css.commentSourceButton}><span>整篇需求</span><q>页面级总评</q></div>}
923
+ <MarkdownBody text={comment.body} className={css.commentBody}/>
924
+ {comment.aiSessionId && <AiConversation api={api} requirementId={requirement.id} sessionId={comment.aiSessionId}/>}
925
+ {comment.replies.length > 0 && <div className={css.replyStack}>{comment.replies.map(reply => <div className={css.reply} key={reply.id}><strong>{reply.author.nickname}{reply.author.kind === 'ai' ? ' · 智能助手' : ''}</strong><MarkdownBody text={reply.body}/></div>)}</div>}
926
+ {comment.status === 'open' && <div className={css.replyComposer}><label>回复评论<textarea value={replyDrafts[comment.id] ?? ''} onChange={event => setReplyDrafts(current => ({ ...current, [comment.id]: event.target.value }))} placeholder={directory.length > 0 ? `输入回复,可使用 ${directory.slice(0, 2).map(item => `@${item.nickname}`).join('、')}` : '输入回复'}/></label><button disabled={!(replyDrafts[comment.id] ?? '').trim()} onClick={() => { const body = (replyDrafts[comment.id] ?? '').trim(); const mentions = mentionedParticipantIds(body, directory); void act(actor => ({ kind: 'comment.reply', participant: actor, requirementId: requirement.id, commentId: comment.id, body, mentions })).then(ok => { if (ok) setReplyDrafts(current => ({ ...current, [comment.id]: '' })) }) }}>回复</button></div>}
927
+ {comment.status === 'open' && <div className={css.commentActions}>{(['written-back', 'decision', 'rejected', 'open-question'] as CommentResolution[]).map(resolution => <button key={resolution} onClick={() => void act(actor => ({ kind: 'comment.resolve', participant: actor, requirementId: requirement.id, commentId: comment.id, resolution }))}>{commentResolutionLabel[resolution]}</button>)}</div>}
928
+ {comment.status === 'resolved' && <div className={css.commentActions}><button onClick={() => void act(actor => ({ kind: 'comment.reopen', participant: actor, requirementId: requirement.id, commentId: comment.id }))}>重新打开</button></div>}
478
929
  </section>
930
+ }
931
+ return <div className={css.discussionPanel}>
932
+ <div className={css.discussionSummary}><div><strong>统一评论</strong><span>{openComments.length > 0 ? `${openComments.length} 个当前正文问题待收口` : '当前正文没有待处理讨论'}</span></div><b>{comments.length}</b></div>
933
+ <div className={css.discussionFilters}><label>状态<select value={filter} onChange={event => setFilter(event.target.value as typeof filter)}><option value="open">未解决</option><option value="unread">未读</option><option value="resolved">已解决</option><option value="all">全部</option></select></label><label>排序<select value={sort} onChange={event => setSort(event.target.value as typeof sort)}><option value="document">正文顺序</option><option value="recent">最近更新</option></select></label></div>
934
+ {filter === 'open' && openComments.length === 0 && <div className={css.emptyPanel}><strong>没有打开的评论</strong><p>选中正文可发起行内评论,也可以使用“评论整篇”给出页面总评。</p></div>}
935
+ {filter === 'unread' && unreadComments.length === 0 && <div className={css.emptyPanel}><strong>没有未读评论</strong><p>新的提及、回复和重新打开会进入插件内通知。</p></div>}
936
+ {(filter === 'open' || filter === 'all') && openComments.map(renderThread)}
937
+ {filter === 'unread' && unreadComments.map(renderThread)}
938
+ {(filter === 'resolved' || filter === 'all') && closedComments.map(renderThread)}
939
+ {filter === 'all' && historicalComments.length > 0 && <details className={css.historyGroup} open={historicalComments.some(item => item.id === focusedCommentId)}><summary>历史正文讨论 · {historicalComments.length}</summary><div className={css.threadStack}>{historicalComments.map(renderThread)}</div></details>}
479
940
  </div>
480
941
  }
481
- function DiscussionPanel({ requirement, selection, text, setText, cancel, submit, act, api }: { requirement: RequirementView; selection: { quote: string } | undefined; text: string; setText: (value: string) => void; cancel: () => void; submit: () => Promise<void>; participant: ParticipantSnapshot; act: Act; api: SpecApi }) {
482
- return <>
483
- {selection && <section className={css.newThread}>
484
- <header><span>正文讨论</span><strong>围绕选中内容提问</strong></header>
485
- <blockquote>{selection.quote}</blockquote>
486
- <label>你想确认什么?<textarea required autoFocus value={text} onChange={event => setText(event.target.value)} placeholder="例如:这里的适用范围是否包含移动端?"/></label>
487
- <small>提交后,AI 会结合当前正文和已关联的工作区上下文给出分析。</small>
488
- <div><button onClick={cancel}>取消</button><button className={css.execute} disabled={!text.trim()} onClick={() => void submit()}>提交并让 AI 分析</button></div>
489
- </section>}
490
- {requirement.comments.slice().reverse().map(comment => <section id={`spec-object-${comment.id}`} key={comment.id}><blockquote>{comment.anchor.quote}</blockquote><strong>{comment.author.nickname}</strong><MarkdownBody text={comment.body}/><small>智能分析:{comment.aiStatus}{comment.aiSessionId ? ` · ${comment.aiSessionId.slice(0, 8)}` : ''}</small>{comment.aiSessionId && <AiConversation api={api} requirementId={requirement.id} sessionId={comment.aiSessionId}/>} {comment.replies.map(reply => <div className={css.reply} key={reply.id}><strong>{reply.author.nickname}{reply.author.kind === 'ai' ? ' · 智能助手' : ''}</strong><MarkdownBody text={reply.body}/></div>)}{comment.status === 'open' && <div>{(['written-back', 'decision', 'rejected', 'open-question'] as CommentResolution[]).map(resolution => <button key={resolution} onClick={() => void act(actor => ({ kind: 'comment.resolve', participant: actor, requirementId: requirement.id, commentId: comment.id, resolution }))}>{({ 'written-back': '已回写正文', decision: '形成决策', rejected: '不采纳', 'open-question': '转为开放问题' })[resolution]}</button>)}</div>}</section>)}
491
- </>
492
- }
493
942
  function AiConversation({ api, requirementId, sessionId }: { api: SpecApi; requirementId: string; sessionId: string }) {
494
943
  const [open, setOpen] = useState(false)
495
944
  const [messages, setMessages] = useState<Array<{ role: 'user' | 'assistant'; text: string }>>([])
@@ -501,9 +950,81 @@ function AiConversation({ api, requirementId, sessionId }: { api: SpecApi; requi
501
950
  const send = async (): Promise<void> => { if (!draft.trim()) return; setSending(true); try { await api.followUp(requirementId, sessionId, draft); setMessages(current => [...current, { role: 'user', text: draft }]); setDraft(''); window.setTimeout(() => { void load() }, 1000) } catch (reason) { setError(reason instanceof Error ? reason.message : String(reason)) } finally { setSending(false) } }
502
951
  return <div className={css.aiConversation}><button className={`${css.chatToggle} ${open ? css.collapseChat : ''}`} aria-label={open ? '收起智能对话' : '展开智能对话'} title={open ? '收起智能对话' : '展开智能对话'} onClick={() => setOpen(value => !value)}>{open ? '⌃' : '展开智能对话'}</button>{open && <><div className={css.chatMessages}>{messages.map((message, index) => <div key={`${message.role}-${index}`} className={message.role === 'assistant' ? css.aiMessage : css.userMessage}><strong>{message.role === 'assistant' ? '智能助手' : '你'}</strong><div dangerouslySetInnerHTML={{ __html: md.render(message.text) }}/></div>)}{messages.length === 0 && !error && <small>正在读取审核会话…</small>}</div>{error && <p className={css.chatError}>{error}</p>}<div className={css.chatComposer}><textarea required aria-label="追问内容(必填)" value={draft} onChange={event => setDraft(event.target.value)} placeholder="追问内容(必填)"/><button disabled={sending || !draft.trim()} onClick={() => void send()}>发送</button></div></>}</div>
503
952
  }
504
- function PatchPanel({ requirement, act }: { requirement: RequirementView; act: Act }) {
953
+
954
+ type InsightData = Awaited<ReturnType<SpecApi['insights']>>
955
+ function InsightPanel({ requirement, api, act }: { requirement: RequirementView; api: SpecApi; act: Act }) {
956
+ const [data, setData] = useState<InsightData>({ items: [], total: 0, links: [], customers: [], companies: [], sources: [] })
957
+ const [catalog, setCatalog] = useState<InsightData>({ items: [], total: 0, links: [], customers: [], companies: [], sources: [] })
958
+ const [filters, setFilters] = useState<{ customerId: string; companyId: string; sourceId: string; importance: '' | keyof typeof importanceLabel }>({ customerId: '', companyId: '', sourceId: '', importance: '' })
959
+ const [form, setForm] = useState({ title: '', body: '', customer: '', customerRef: '', company: '', companyRef: '', source: '', url: '', importance: 'unknown' as 'unknown' | 'want' | 'important' | 'critical', targets: '' })
960
+ const [open, setOpen] = useState(false); const [error, setError] = useState(''); const [importPreview, setImportPreview] = useState<ReturnType<typeof parseInsightFile>>()
961
+ const importSummary = useMemo(() => {
962
+ if (!importPreview) return { added: 0, updated: 0, duplicates: 0 }
963
+ const sourceId = stableLocalId('source', `${importPreview.kind}:${importPreview.name}`)
964
+ const existing = new Set(catalog.items.filter(item => item.sourceId === sourceId).map(item => normalizeInsightBody(item.body)))
965
+ const seen = new Set<string>(); let duplicates = 0
966
+ for (const row of importPreview.rows) { const body = normalizeInsightBody(row.body); if (existing.has(body) || seen.has(body)) duplicates += 1; else seen.add(body) }
967
+ return { added: importPreview.rows.length - duplicates, updated: 0, duplicates }
968
+ }, [catalog.items, importPreview])
969
+ const load = (): void => { void Promise.all([api.insights({ requirementId: requirement.id }), api.insights({ requirementId: requirement.id, ...(filters.customerId ? { customerId: filters.customerId } : {}), ...(filters.companyId ? { companyId: filters.companyId } : {}), ...(filters.sourceId ? { sourceId: filters.sourceId } : {}), ...(filters.importance ? { importance: filters.importance } : {}) })]).then(([all, filtered]) => { setCatalog(all); setData(filtered) }, reason => setError(reason instanceof Error ? reason.message : String(reason))) }
970
+ useEffect(load, [requirement.id, requirement.metrics.insightCount, filters.customerId, filters.companyId, filters.sourceId, filters.importance])
971
+ const submit = async (): Promise<void> => {
972
+ if (!form.body.trim() || !form.source.trim()) return
973
+ const companyId = form.company.trim() ? stableLocalId('company', form.companyRef || form.company) : undefined
974
+ const customerId = form.customer.trim() ? stableLocalId('customer', form.customerRef || `${form.company}:${form.customer}`) : undefined
975
+ const sourceId = stableLocalId('source', form.url || form.source); const insightId = `insight-${browserUuid()}`
976
+ if (companyId && !await act(actor => ({ kind: 'company.upsert', participant: actor, requirementId: requirement.id, company: { id: companyId, name: form.company.trim(), ...(form.companyRef.trim() ? { externalRef: form.companyRef.trim() } : {}) } }))) return
977
+ if (customerId && !await act(actor => ({ kind: 'customer.upsert', participant: actor, requirementId: requirement.id, customer: { id: customerId, displayName: form.customer.trim(), ...(companyId ? { companyId } : {}), ...(form.customerRef.trim() ? { externalRef: form.customerRef.trim() } : {}) } }))) return
978
+ const sourceUrl = safeHttpUrl(form.url.trim())
979
+ if (!await act(actor => ({ kind: 'source.upsert', participant: actor, requirementId: requirement.id, source: { id: sourceId, kind: form.url.trim() ? 'url' : 'text', label: form.source.trim(), ...(sourceUrl ? { url: sourceUrl } : {}), accessStatus: form.url.trim() && !sourceUrl ? 'unverified' : 'available' } }))) return
980
+ const links = parseInsightTargets(form.targets, requirement.id)
981
+ if (await act(actor => ({ kind: 'insight.create', participant: actor, requirementId: requirement.id, insight: { id: insightId, sourceId, ...(customerId ? { customerId } : {}), ...(companyId && !customerId ? { companyId } : {}), title: form.title.trim() || truncateGraphemes(form.body.trim(), 28), body: form.body.trim(), importance: form.importance, capturedAt: Date.now() }, links }))) { setOpen(false); setForm({ title: '', body: '', customer: '', customerRef: '', company: '', companyRef: '', source: '', url: '', importance: 'unknown', targets: '' }); load() }
982
+ }
983
+ const importRows = async (): Promise<void> => {
984
+ if (!importPreview || importPreview.errors.length > 0) return
985
+ const defaultSourceId = stableLocalId('source', `${importPreview.kind}:${importPreview.name}`); const sources = new Map<string, { id: string; kind: 'url' | 'csv' | 'markdown'; label: string; url?: string; accessStatus: 'available' | 'unverified' }>(); const companies = new Map<string, { id: string; name: string; externalRef?: string }>(); const customers = new Map<string, { id: string; displayName: string; companyId?: string; externalRef?: string }>()
986
+ sources.set(defaultSourceId, { id: defaultSourceId, kind: importPreview.kind, label: importPreview.name, accessStatus: 'available' })
987
+ const links: Array<{ insightId: string; requirementId: string; targetType: 'requirement' | 'section' | 'acceptance-criterion'; targetId?: string }> = []
988
+ const rows = importPreview.rows.map((row, index) => {
989
+ const companyId = row.company ? stableLocalId('company', row.companyRef || row.company) : undefined; const customerId = row.customer ? stableLocalId('customer', row.customerRef || `${row.company}:${row.customer}`) : undefined
990
+ if (companyId) companies.set(companyId, { id: companyId, name: row.company!, ...(row.companyRef ? { externalRef: row.companyRef } : {}) }); if (customerId) customers.set(customerId, { id: customerId, displayName: row.customer!, ...(companyId ? { companyId } : {}), ...(row.customerRef ? { externalRef: row.customerRef } : {}) })
991
+ const sourceUrl = safeHttpUrl(row.sourceUrl ?? ''); const sourceLabel = row.source?.trim() || row.sourceUrl?.trim(); const sourceId = sourceLabel ? stableLocalId('source', sourceUrl || sourceLabel) : defaultSourceId
992
+ if (sourceLabel) sources.set(sourceId, { id: sourceId, kind: sourceUrl ? 'url' : importPreview.kind, label: row.source?.trim() || sourceUrl || sourceLabel, ...(sourceUrl ? { url: sourceUrl } : {}), accessStatus: sourceUrl || !row.sourceUrl ? 'available' : 'unverified' })
993
+ const id = `insight-${browserUuid()}-${index}`; links.push(...parseInsightTargets(row.targets?.join(',') ?? '', requirement.id).map(link => ({ insightId: id, ...link })))
994
+ return { id, sourceId, ...(customerId ? { customerId } : {}), ...(companyId && !customerId ? { companyId } : {}), title: row.title || truncateGraphemes(row.body, 28), body: row.body, importance: row.importance, capturedAt: row.capturedAt ?? Date.now() }
995
+ })
996
+ if (await act(actor => ({ kind: 'insight.import', participant: actor, requirementId: requirement.id, sources: [...sources.values()], companies: [...companies.values()], customers: [...customers.values()], rows, links }))) { setImportPreview(undefined); load() }
997
+ }
998
+ return <div className={css.insightPanel}><div className={css.insightScore}><div><span>客户重要度分</span><b>{requirement.metrics.customerImportanceScore}</b></div><dl><div><dt>洞察</dt><dd>{requirement.metrics.insightCount}</dd></div><div><dt>客户</dt><dd>{requirement.metrics.customerCount}</dd></div><div><dt>公司</dt><dd>{requirement.metrics.companyCount}</dd></div><div><dt>匿名</dt><dd>{requirement.metrics.anonymousInsightCount}</dd></div></dl></div><div className={css.insightFilters}><label>客户<select value={filters.customerId} onChange={event => setFilters(current => ({ ...current, customerId: event.target.value }))}><option value="">全部</option>{catalog.customers.map(item => <option key={item.id} value={item.id}>{item.displayName}</option>)}</select></label><label>公司<select value={filters.companyId} onChange={event => setFilters(current => ({ ...current, companyId: event.target.value }))}><option value="">全部</option>{catalog.companies.map(item => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label><label>来源<select value={filters.sourceId} onChange={event => setFilters(current => ({ ...current, sourceId: event.target.value }))}><option value="">全部</option>{catalog.sources.map(item => <option key={item.id} value={item.id}>{item.label}</option>)}</select></label><label>重要度<select value={filters.importance} onChange={event => setFilters(current => ({ ...current, importance: event.target.value as typeof current.importance }))}><option value="">全部</option>{Object.entries(importanceLabel).map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></label></div><div className={css.insightActions}><button className={css.execute} onClick={() => setOpen(true)}>记录客户洞察</button><label className={css.fileButton}>导入 CSV / Markdown<input type="file" accept=".csv,.md,.markdown,text/csv,text/markdown" onChange={event => { const file = event.target.files?.[0]; if (!file) return; if (file.size > 5 * 1024 * 1024) { setError('文件超过 5 MB'); return } void file.text().then(text => setImportPreview(parseInsightFile(file.name, text))) }}/></label></div>{error && <p className={css.chatError}>{error}</p>}{importPreview && <section className={css.importPreview}><header><div><strong>{importPreview.name}</strong><span>新增 {importSummary.added} · 更新 {importSummary.updated} · 重复 {importSummary.duplicates} · 错误 {importPreview.errors.length}</span></div><button onClick={() => setImportPreview(undefined)}>取消</button></header>{importPreview.errors.map(errorText => <p key={errorText}>{errorText}</p>)}<div>{importPreview.rows.slice(0, 5).map((row, index) => <article key={index}><b>{row.title || truncateGraphemes(row.body, 24)}</b><span>{row.customer || '匿名'} · {importanceLabel[row.importance]}{row.targets?.length ? ` · ${row.targets.length} 个关联` : ''}</span></article>)}</div><button className={css.execute} disabled={importPreview.errors.length > 0 || importPreview.rows.length === 0} onClick={() => void importRows()}>确认原子导入</button></section>}{data.items.length === 0 && <div className={css.emptyPanel}><strong>没有符合条件的客户证据</strong><p>清除筛选,或记录客户原声并把它连接到需求、规则和验收标准。</p></div>}{data.items.map(insight => { const source = data.sources.find(item => item.id === insight.sourceId) ?? catalog.sources.find(item => item.id === insight.sourceId); const customer = data.customers.find(item => item.id === insight.customerId) ?? catalog.customers.find(item => item.id === insight.customerId); const company = data.companies.find(item => item.id === (insight.companyId ?? customer?.companyId)) ?? catalog.companies.find(item => item.id === (insight.companyId ?? customer?.companyId)); return <article id={`spec-object-${insight.id}`} className={css.insightCard} key={insight.id}><header><span>{importanceLabel[insight.importance]}</span><time title={new Date(insight.capturedAt).toLocaleString()}>{relativeTime(insight.capturedAt)}</time></header><h3>{insight.title}</h3><blockquote>{insight.body}</blockquote><footer><span>{customer?.displayName ?? '匿名客户'}{company ? ` · ${company.name}` : ''}</span>{source?.url && safeHttpUrl(source.url) ? <a href={source.url} target="_blank" rel="noreferrer">{source.label}</a> : <code>{source?.label ?? insight.sourceId}</code>}</footer><div className={css.insightLinks}>{data.links.filter(link => link.insightId === insight.id).map(link => <span key={link.id}>{link.targetType === 'requirement' ? '需求' : link.targetId}<button aria-label={`取消关联 ${link.targetId ?? '需求'}`} onClick={() => void act(actor => ({ kind: 'insight.unlink', participant: actor, requirementId: requirement.id, linkId: link.id })).then(ok => { if (ok) load() })}>×</button></span>)}<button onClick={() => { void navigator.clipboard.writeText(`${location.origin}${location.pathname}#spec-collab/${requirement.id}/insights/${insight.id}`) }}>复制链接</button></div></article>})}{open && <AccessibleDialog title="记录客户洞察" close={() => setOpen(false)} className={css.insightDialog}><form onSubmit={event => { event.preventDefault(); void submit() }}><div className={css.dialogHead}><div><span>客户证据</span><h2>记录客户洞察</h2></div><button type="button" aria-label="关闭" onClick={() => setOpen(false)}>×</button></div><label>洞察正文(必填)<textarea autoFocus required value={form.body} onChange={event => setForm({ ...form, body: event.target.value })} placeholder="保留客户原话或可核对的观察"/></label><div className={css.formGrid}><label>标题<input value={form.title} onChange={event => setForm({ ...form, title: event.target.value })}/></label><label>重要度<select value={form.importance} onChange={event => setForm({ ...form, importance: event.target.value as typeof form.importance })}>{Object.entries(importanceLabel).map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></label></div><div className={css.formGrid}><label>客户显示名<input value={form.customer} onChange={event => setForm({ ...form, customer: event.target.value })}/></label><label>客户外部编号<input value={form.customerRef} onChange={event => setForm({ ...form, customerRef: event.target.value })}/></label><label>公司<input value={form.company} onChange={event => setForm({ ...form, company: event.target.value })}/></label><label>公司外部编号<input value={form.companyRef} onChange={event => setForm({ ...form, companyRef: event.target.value })}/></label></div><div className={css.formGrid}><label>来源名称(必填)<input required value={form.source} onChange={event => setForm({ ...form, source: event.target.value })}/></label><label>来源 URL(选填,仅 http/https)<input type="url" value={form.url} onChange={event => setForm({ ...form, url: event.target.value })}/></label></div><label>关联目标(逗号分隔)<input value={form.targets} onChange={event => setForm({ ...form, targets: event.target.value })} placeholder="section:业务规则, ac:AC-2, requirement:需求编号"/><small>当前需求会自动关联;可追加多个需求、章节或验收标准。</small></label><div className={css.stickyActions}><button type="button" onClick={() => setOpen(false)}>取消</button><button className={css.execute} disabled={!form.body.trim() || !form.source.trim()}>保存洞察</button></div></form></AccessibleDialog>}</div>
999
+ }
1000
+
1001
+ const importanceLabel = { unknown: '未标注', want: '想要', important: '重要', critical: '关键' } as const
1002
+ type ImportedInsight = { title?: string; body: string; customer?: string; customerRef?: string; company?: string; companyRef?: string; source?: string; sourceUrl?: string; importance: keyof typeof importanceLabel; capturedAt?: number; targets?: string[] }
1003
+ function normalizeInsightBody(value: string): string { return value.normalize('NFKC').trim().replace(/\s+/g, ' ').toLocaleLowerCase() }
1004
+ function stableLocalId(prefix: string, value: string): string { let hash = 2166136261; for (const character of value.normalize('NFKC').toLocaleLowerCase()) { hash ^= character.codePointAt(0) ?? 0; hash = Math.imul(hash, 16777619) } return `${prefix}-${(hash >>> 0).toString(16)}` }
1005
+ function parseInsightTargets(value: string, currentRequirementId: string): Array<{ requirementId: string; targetType: 'requirement' | 'section' | 'acceptance-criterion'; targetId?: string }> { return value.split(/[,,;;\n]/).map(item => item.trim()).filter(Boolean).map(item => { const [rawType = '', ...rest] = item.split(':'); const targetId = rest.join(':').trim(); const type = rawType.trim().toLocaleLowerCase(); if ((type === 'requirement' || type === '需求') && targetId) return { requirementId: targetId, targetType: 'requirement' as const }; if ((type === 'ac' || type === '验收') && targetId) return { requirementId: currentRequirementId, targetType: 'acceptance-criterion' as const, targetId }; if ((type === 'section' || type === '章节') && targetId) return { requirementId: currentRequirementId, targetType: 'section' as const, targetId }; return { requirementId: currentRequirementId, targetType: 'section' as const, targetId: item } }) }
1006
+ export function parseInsightFile(name: string, text = ''): { name: string; kind: 'csv' | 'markdown'; rows: ImportedInsight[]; errors: string[] } {
1007
+ const kind = name.toLocaleLowerCase().endsWith('.csv') ? 'csv' : 'markdown'; const rows: ImportedInsight[] = []; const errors: string[] = []
1008
+ if (kind === 'markdown') {
1009
+ const sections = text.split(/^##\s+/m).slice(1)
1010
+ for (const [index, section] of sections.entries()) { const [heading = '', ...bodyLines] = section.split('\n'); const metadataLine = /^[-*]\s*(客户|客户编号|公司|公司编号|重要度|来源|来源 URL|关联目标)\s*[::]/; const metadata = new Map(bodyLines.filter(line => metadataLine.test(line)).map(line => { const match = /^[-*]\s*([^::]+)\s*[::]\s*(.*)$/.exec(line)!; return [match[1]!.trim(), match[2]!.trim()] })); const body = bodyLines.filter(line => !metadataLine.test(line)).join('\n').trim(); if (!body) { errors.push(`第 ${index + 1} 个 Markdown 小节缺少正文`); continue } const customer = metadata.get('客户'); const customerRef = metadata.get('客户编号'); const company = metadata.get('公司'); const companyRef = metadata.get('公司编号'); const source = metadata.get('来源'); const sourceUrl = metadata.get('来源 URL'); const targets = metadata.get('关联目标')?.split(/[,,;;]/).map(value => value.trim()).filter(Boolean); rows.push({ title: heading.trim(), body, ...(customer ? { customer } : {}), ...(customerRef ? { customerRef } : {}), ...(company ? { company } : {}), ...(companyRef ? { companyRef } : {}), ...(source ? { source } : {}), ...(sourceUrl ? { sourceUrl } : {}), importance: parseImportance(metadata.get('重要度')), ...(targets?.length ? { targets } : {}) }) }
1011
+ } else {
1012
+ const records = parseCsvRecords(text.replace(/^\uFEFF/, '')); const headers = (records.shift() ?? []).map(value => value.trim().toLocaleLowerCase()); const bodyIndex = headers.indexOf('body')
1013
+ if (bodyIndex < 0) errors.push('CSV 缺少必填列 body')
1014
+ for (const [index, values] of records.entries()) { const value = (key: string): string => values[headers.indexOf(key)]?.trim() ?? ''; const body = values[bodyIndex]?.trim() ?? ''; if (!body) { errors.push(`CSV 第 ${index + 2} 条记录缺少 body`); continue } const targets = (value('targets') || value('target')).split(/[;;]/).map(item => item.trim()).filter(Boolean); const customerRef = value('customer_external_ref') || value('customer_ref'); const companyRef = value('company_external_ref') || value('company_ref'); const source = value('source'); const sourceUrl = value('source_url') || value('url'); rows.push({ ...(value('title') ? { title: value('title') } : {}), body, ...(value('customer') ? { customer: value('customer') } : {}), ...(customerRef ? { customerRef } : {}), ...(value('company') ? { company: value('company') } : {}), ...(companyRef ? { companyRef } : {}), ...(source ? { source } : {}), ...(sourceUrl ? { sourceUrl } : {}), importance: parseImportance(value('importance')), ...(Number.isFinite(Date.parse(value('captured_at'))) ? { capturedAt: Date.parse(value('captured_at')) } : {}), ...(targets.length ? { targets } : {}) }) }
1015
+ }
1016
+ if (rows.length > 2_000) errors.push('最多导入 2,000 条洞察')
1017
+ return { name, kind, rows: rows.slice(0, 2_000), errors }
1018
+ }
1019
+ function parseCsvLine(line: string): string[] { const values: string[] = []; let value = ''; let quoted = false; for (let index = 0; index < line.length; index += 1) { const char = line[index]!; if (char === '"' && quoted && line[index + 1] === '"') { value += '"'; index += 1 } else if (char === '"') quoted = !quoted; else if (char === ',' && !quoted) { values.push(value); value = '' } else value += char } values.push(value); return values }
1020
+ function parseCsvRecords(text: string): string[][] { const records: string[][] = []; let record = ''; let quoted = false; for (let index = 0; index < text.length; index += 1) { const char = text[index]!; if (char === '"') { record += char; if (quoted && text[index + 1] === '"') { record += text[index + 1]; index += 1 } else quoted = !quoted } else if ((char === '\n' || char === '\r') && !quoted) { if (char === '\r' && text[index + 1] === '\n') index += 1; if (record.trim()) records.push(parseCsvLine(record)); record = '' } else record += char } if (record.trim()) records.push(parseCsvLine(record)); return records }
1021
+ function parseImportance(value: string | undefined): keyof typeof importanceLabel { const normalized = value?.trim().toLocaleLowerCase(); return normalized === 'critical' || normalized === '关键' ? 'critical' : normalized === 'important' || normalized === '重要' ? 'important' : normalized === 'want' || normalized === '想要' ? 'want' : 'unknown' }
1022
+
1023
+ function PatchPanel({ requirement, act, api }: { requirement: RequirementView; act: Act; api: SpecApi }) {
505
1024
  const [summaries, setSummaries] = useState<Record<string, string>>({})
506
1025
  const [submitting, setSubmitting] = useState<string>()
1026
+ const [reviewing, setReviewing] = useState<{ patchId: string; diff: StructuredDiff }>()
1027
+ const [diffError, setDiffError] = useState('')
507
1028
  const current = requirement.patches.filter(patch => patch.baseCommit === requirement.currentCommit && patch.status === 'pending').slice().reverse()
508
1029
  const historical = requirement.patches.filter(patch => !current.some(item => item.id === patch.id)).slice().reverse()
509
1030
  const renderPatch = (patch: RequirementView['patches'][number]) => {
@@ -512,25 +1033,47 @@ function PatchPanel({ requirement, act }: { requirement: RequirementView; act: A
512
1033
  return <article id={`spec-object-${patch.id}`} className={css.reviewCard} key={patch.id}>
513
1034
  <div className={css.badges}><b>{statusLabel[patch.status] ?? patch.status}</b><span>{reviewKindLabel[patch.reviewKind]}</span></div>
514
1035
  <MarkdownBody text={patch.summary} className={css.reviewTitle}/>
1036
+ <dl className={css.patchImpact}><div><dt>影响章节</dt><dd>{patch.affectedSections.length > 0 ? patch.affectedSections.join('、') : '未标注'}</dd></div><div><dt>验收项</dt><dd>{patch.affectedAcceptanceIds.length > 0 ? patch.affectedAcceptanceIds.join('、') : '无'}</dd></div><div><dt>修改规模</dt><dd>{Math.abs(patch.proposedMarkdown.length - requirement.version.markdown.length)} 字符净变化</dd></div><div><dt>冲突风险</dt><dd>{patch.baseCommit === requirement.currentCommit ? '基线一致,可原子接受' : '基线已变化,禁止接受'}</dd></div></dl>
515
1037
  {!chinese && <div className={css.legacyWarning}><strong>旧建议无法使用</strong><p>这份建议生成于中文约束启用前,请重新运行 AI 检查。</p></div>}
516
- <details className={css.patchDetails}><summary>查看修改后的完整正文</summary><MarkdownBody text={patch.proposedMarkdown}/></details>
1038
+ <button className={css.panelAction} onClick={async () => { setDiffError(''); try { setReviewing({ patchId: patch.id, diff: await api.previewDiff(requirement.version.markdown, patch.proposedMarkdown, `基线 ${patch.baseCommit.slice(0, 8)}`, 'AI 建议') }) } catch (error) { setDiffError(error instanceof Error ? error.message : String(error)) } }}>审核全部改动</button>
517
1039
  {patch.status === 'pending' && (chinese ? <div className={css.patchAccept}><label>版本说明<input required value={commitSummary} onChange={event => setSummaries(currentValues => ({ ...currentValues, [patch.id]: event.target.value }))}/></label><div className={css.cardActions}><button className={css.execute} disabled={submitting === patch.id || !commitSummary.trim()} onClick={async () => { setSubmitting(patch.id); try { await act(actor => ({ kind: 'patch.accept', participant: actor, requirementId: requirement.id, patchId: patch.id, summary: commitSummary })) } finally { setSubmitting(undefined) } }}>{submitting === patch.id ? '正在写入…' : '接受并写入正文'}</button><button disabled={submitting === patch.id} onClick={() => void act(actor => ({ kind: 'patch.reject', participant: actor, requirementId: requirement.id, patchId: patch.id }))}>不采用</button></div></div> : <div className={css.cardActions}><button onClick={() => void act(actor => ({ kind: 'review.request', participant: actor, requirementId: requirement.id, reviewKind: patch.reviewKind }))}>重新生成建议</button><button onClick={() => void act(actor => ({ kind: 'patch.reject', participant: actor, requirementId: requirement.id, patchId: patch.id }))}>废弃旧建议</button></div>)}
518
1040
  </article>
519
1041
  }
520
- return <>{current.length === 0 && <div className={css.emptyPanel}><strong>当前没有需要审核的 AI 建议</strong><p>AI 根据你的回答整理正文后,建议会出现在这里。</p></div>}{current.map(renderPatch)}{historical.length > 0 && <details className={css.historyGroup}><summary>历史建议 · {historical.length}</summary><div>{historical.map(renderPatch)}</div></details>}</>
1042
+ return <>{diffError && <p className={css.chatError}>{diffError}</p>}{current.length === 0 && <div className={css.emptyPanel}><strong>当前没有需要审核的 AI 建议</strong><p>AI 根据你的回答整理正文后,建议会出现在这里。</p></div>}{current.map(renderPatch)}{historical.length > 0 && <details className={css.historyGroup}><summary>历史建议 · {historical.length}</summary><div>{historical.map(renderPatch)}</div></details>}{reviewing && <AccessibleDialog title="审核 AI 建议差异" close={() => setReviewing(undefined)} className={css.diffDialog}><div className={css.diffHeader}><div><span>整包原子接受</span><h2>审核 AI 建议的全部改动</h2></div><button aria-label="关闭差异" onClick={() => setReviewing(undefined)}>×</button></div><StructuredDiffView diff={reviewing.diff}/><div className={css.diffActions}><button onClick={() => setReviewing(undefined)}>继续检查</button><button className={css.execute} onClick={() => { const patch = current.find(item => item.id === reviewing.patchId); if (!patch) return; const summary = summaries[patch.id] ?? `合入 AI 建议:${patch.summary}`; void act(actor => ({ kind: 'patch.accept', participant: actor, requirementId: requirement.id, patchId: patch.id, summary })).then(ok => { if (ok) setReviewing(undefined) }) }}>整包接受并保存</button></div></AccessibleDialog>}</>
521
1043
  }
522
1044
  function DecisionPanel({ requirement, act }: { requirement: RequirementView; act: Act }) {
523
1045
  const [open, setOpen] = useState(false)
524
- const [form, setForm] = useState({ question: '', decision: '', rationale: '' })
525
- const submit = async (): Promise<void> => { if (await act(actor => ({ kind: 'decision.create', participant: actor, requirementId: requirement.id, question: form.question, options: [], decision: form.decision, rationale: form.rationale, affectedSections: [], affectedAcceptanceIds: [] }))) { setOpen(false); setForm({ question: '', decision: '', rationale: '' }) } }
526
- return <>{requirement.decisions.map(item => <section id={`spec-object-${item.id}`} key={item.id}><MarkdownBody text={item.question} className={css.reviewTitle}/><MarkdownBody text={item.decision}/><small>{item.rationale} · {item.confirmer.nickname}</small></section>)}{open ? <div className={css.decisionForm}><label>待决策问题(必填)<textarea required autoFocus value={form.question} onChange={event => setForm({ ...form, question: event.target.value })}/></label><label>确认结论(必填)<textarea required value={form.decision} onChange={event => setForm({ ...form, decision: event.target.value })}/></label><label>决策理由(选填)<textarea value={form.rationale} onChange={event => setForm({ ...form, rationale: event.target.value })}/></label><div className={css.cardActions}><button onClick={() => setOpen(false)}>取消</button><button className={css.execute} disabled={!form.question.trim() || !form.decision.trim()} onClick={() => void submit()}>保存决策</button></div></div> : <button className={css.panelAction} onClick={() => setOpen(true)}>记录新决策</button>}</>
1046
+ const formRef = useRef<HTMLDivElement>(null)
1047
+ const [form, setForm] = useState({ question: '', decision: '', rationale: '', sections: '', acceptanceIds: '' })
1048
+ const affectedSections = form.sections.split(',').map(value => value.trim()).filter(Boolean)
1049
+ const affectedAcceptanceIds = form.acceptanceIds.split(',').map(value => value.trim()).filter(Boolean)
1050
+ useEffect(() => {
1051
+ if (!open) return
1052
+ const behavior = window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth'
1053
+ const frame = window.requestAnimationFrame(() => formRef.current?.scrollIntoView({ block: 'start', behavior }))
1054
+ return () => window.cancelAnimationFrame(frame)
1055
+ }, [open])
1056
+ const submit = async (): Promise<void> => { if (await act(actor => ({ kind: 'decision.create', participant: actor, requirementId: requirement.id, question: form.question, options: [], decision: form.decision, rationale: form.rationale, affectedSections, affectedAcceptanceIds }))) { setOpen(false); setForm({ question: '', decision: '', rationale: '', sections: '', acceptanceIds: '' }) } }
1057
+ return <>{requirement.decisions.length === 0 && !open && <div className={css.emptyPanel}><strong>还没有需要长期保留的决策</strong><p>当评论形成明确取舍、例外或边界时,把它记录为决策,避免版本变化后丢失上下文。</p><button className={css.execute} onClick={() => setOpen(true)}>记录第一个决策</button></div>}{requirement.decisions.map(item => <section id={`spec-object-${item.id}`} key={item.id}><MarkdownBody text={item.question} className={css.reviewTitle}/><MarkdownBody text={item.decision}/><small title={new Date(item.createdAt).toLocaleString()}>{item.rationale} · {item.confirmer.nickname} · {relativeTime(item.createdAt)} · {item.status === 'active' ? '生效中' : '已作废'}</small><button className={css.recordLinkButton} onClick={() => void navigator.clipboard.writeText(`${location.origin}${location.pathname}#spec-collab/${requirement.id}/records/${item.id}?commit=${item.commit}`)}>复制链接</button></section>)}{open ? <div ref={formRef} className={css.decisionForm}><label>待决策问题(必填)<textarea rows={2} required autoFocus value={form.question} onChange={event => setForm({ ...form, question: event.target.value })}/></label><label>确认结论(必填)<textarea rows={3} required value={form.decision} onChange={event => setForm({ ...form, decision: event.target.value })}/></label><label>决策理由(选填)<textarea rows={2} value={form.rationale} onChange={event => setForm({ ...form, rationale: event.target.value })}/></label><label>受影响章节(与 AC 至少填写一项)<input list="decision-sections" value={form.sections} onChange={event => setForm({ ...form, sections: event.target.value })} placeholder="业务术语与规则"/><datalist id="decision-sections">{[...requirement.version.markdown.matchAll(/^##\s+(.+)$/gm)].map(match => <option key={match[1]} value={match[1]}/>)}</datalist></label><label>受影响 AC IDs(与章节至少填写一项)<input value={form.acceptanceIds} onChange={event => setForm({ ...form, acceptanceIds: event.target.value })} placeholder="AC-RETRY-001"/></label><div className={css.stickyActions}><button onClick={() => setOpen(false)}>取消</button><button className={css.execute} disabled={!form.question.trim() || !form.decision.trim() || (affectedSections.length === 0 && affectedAcceptanceIds.length === 0)} onClick={() => void submit()}>保存决策</button></div></div> : requirement.decisions.length > 0 && <button className={css.panelAction} onClick={() => setOpen(true)}>记录新决策</button>}</>
527
1058
  }
528
- function VersionPanel({ requirement, api }: { requirement: RequirementView; api: SpecApi }) {
529
- const [historical, setHistorical] = useState<RequirementVersion>()
1059
+ function VersionPanel({ requirement, api, act }: { requirement: RequirementView; api: SpecApi; act: Act }) {
1060
+ const previous = requirement.history.find(version => version.commit !== requirement.currentCommit)?.commit ?? requirement.currentCommit
1061
+ const [baseCommit, setBaseCommit] = useState(previous)
1062
+ const [headCommit, setHeadCommit] = useState(requirement.currentCommit)
1063
+ const [comparison, setComparison] = useState<StructuredDiff>()
530
1064
  const [loading, setLoading] = useState(false)
531
1065
  const [error, setError] = useState('')
532
- const open = async (commit: string): Promise<void> => { setLoading(true); setError(''); try { setHistorical(await api.version(requirement.id, commit)) } catch (reason) { setError(reason instanceof Error ? reason.message : String(reason)) } finally { setLoading(false) } }
533
- return <>{historical && <div className={css.versionCompare}><div className={css.compareHead}><strong>版本内容比对</strong><button aria-label="关闭版本比对" title="关闭版本比对" onClick={() => setHistorical(undefined)}>×</button></div><div className={css.compareColumns}><section><b>历史版本 · {historical.commit.slice(0, 8)}</b><MarkdownBody text={historical.markdown}/></section><section><b>当前版本 · {requirement.currentCommit.slice(0, 8)}</b><MarkdownBody text={requirement.version.markdown}/></section></div></div>}{error && <p className={css.chatError}>{error}</p>}{requirement.history.map(version => <button className={css.versionRow} key={version.commit} disabled={loading} onClick={() => void open(version.commit)}><code>{version.commit.slice(0, 10)}</code><span>{version.summary}</span><small>{version.author.nickname} · {new Date(version.createdAt).toLocaleString()}</small></button>)}</>
1066
+ const [restoreCommit, setRestoreCommit] = useState<string>()
1067
+ const compare = async (): Promise<void> => { if (baseCommit === headCommit) return; setLoading(true); setError(''); try { setComparison(await api.diff(requirement.id, baseCommit, headCommit)) } catch (reason) { setError(reason instanceof Error ? reason.message : String(reason)) } finally { setLoading(false) } }
1068
+ const restore = async (): Promise<void> => { if (!restoreCommit) return; if (await act(actor => ({ kind: 'version.restore', participant: actor, requirementId: requirement.id, commit: restoreCommit, summary: `恢复版本 ${restoreCommit.slice(0, 8)}` }))) setRestoreCommit(undefined) }
1069
+ return <><div className={css.versionPicker}><label>基准版本<select value={baseCommit} onChange={event => setBaseCommit(event.target.value)}>{requirement.history.map(version => <option key={version.commit} value={version.commit}>{version.commit === requirement.currentCommit ? '当前 · ' : ''}{version.commit.slice(0, 8)} · {cleanDisplayText(version.summary)}</option>)}</select></label><label>对比版本<select value={headCommit} onChange={event => setHeadCommit(event.target.value)}>{requirement.history.map(version => <option key={version.commit} value={version.commit}>{version.commit === requirement.currentCommit ? '当前 · ' : ''}{version.commit.slice(0, 8)} · {cleanDisplayText(version.summary)}</option>)}</select></label><button className={css.execute} disabled={loading || baseCommit === headCommit} onClick={() => void compare()}>{loading ? '生成中…' : '比较差异'}</button></div>{error && <p className={css.chatError}>{error}</p>}{requirement.history.map(version => <div id={`spec-object-${version.commit}`} className={css.versionRow} key={version.commit} aria-current={version.commit === requirement.currentCommit ? 'true' : undefined}><div className={css.versionCopy}><code>{version.commit.slice(0, 10)}</code><span>{cleanDisplayText(version.summary)}</span><small title={new Date(version.createdAt).toLocaleString()}>{version.author.nickname} · {relativeTime(version.createdAt)}</small></div><div className={css.versionActions}><button onClick={() => void navigator.clipboard.writeText(`${location.origin}${location.pathname}#spec-collab/${requirement.id}/records/${version.commit}?commit=${version.commit}`)}>复制链接</button><button disabled={version.commit === requirement.currentCommit} onClick={() => setRestoreCommit(version.commit)}>{version.commit === requirement.currentCommit ? '当前版本' : '恢复为新版本'}</button></div></div>)}{comparison && <AccessibleDialog title="版本差异" close={() => setComparison(undefined)} className={css.diffDialog}><div className={css.diffHeader}><div><span>版本历史</span><h2>比较两个版本</h2></div><button aria-label="关闭版本差异" onClick={() => setComparison(undefined)}>×</button></div><StructuredDiffView diff={comparison}/><div className={css.diffActions}><button onClick={() => setComparison(undefined)}>关闭</button></div></AccessibleDialog>}{restoreCommit && <AccessibleDialog title="恢复历史版本" close={() => setRestoreCommit(undefined)} className={css.dialogSurface}><div className={css.dialogForm}><div className={css.dialogHead}><div><span>可追溯恢复</span><h2>恢复 {restoreCommit.slice(0, 8)} 为新版本?</h2></div><button aria-label="关闭" onClick={() => setRestoreCommit(undefined)}>×</button></div><p>系统会创建新的 Git commit,不移动或重写历史。受正文变化影响的确认、决策与 AI 建议将按现有规则失效。</p><div className={css.stickyActions}><button onClick={() => setRestoreCommit(undefined)}>取消</button><button className={css.dangerButton} onClick={() => void restore()}>确认恢复并创建版本</button></div></div></AccessibleDialog>}</>
1070
+ }
1071
+
1072
+ function StructuredDiffView({ diff }: { diff: StructuredDiff }) {
1073
+ const [expanded, setExpanded] = useState<Set<string>>(() => new Set())
1074
+ const toggle = (key: string): void => setExpanded(current => { const next = new Set(current); if (next.has(key)) next.delete(key); else next.add(key); return next })
1075
+ const lines = (items: StructuredDiff['hunks'][number]['lines'], key: string) => items.map((line, index) => <div key={`${key}-${index}`} className={line.type === 'added' ? css.diffAdded : line.type === 'removed' ? css.diffRemoved : css.diffContext}><span>{line.oldLine ?? ''}</span><span>{line.newLine ?? ''}</span><b aria-hidden="true">{line.type === 'added' ? '+' : line.type === 'removed' ? '−' : ' '}</b><code>{line.text || ' '}</code></div>)
1076
+ return <div className={css.structuredDiff}><header><code>{diff.baseLabel}</code><span>→</span><code>{diff.headLabel}</code><b>+{diff.added} / −{diff.removed}</b></header>{diff.hunks.length === 0 ? <div className={css.emptyPanel}>两个版本没有正文差异。</div> : diff.hunks.map(hunk => { const beforeKey = `${hunk.id}:before`; const afterKey = `${hunk.id}:after`; return <section key={hunk.id}>{hunk.collapsedBefore > 0 && (expanded.has(beforeKey) ? <><button className={css.diffCollapsed} onClick={() => toggle(beforeKey)}>收起 {hunk.collapsedBefore} 行上下文</button>{lines(hunk.collapsedBeforeLines, beforeKey)}</> : <button className={css.diffCollapsed} onClick={() => toggle(beforeKey)}>展开前方 {hunk.collapsedBefore} 行未变内容</button>)}{lines(hunk.lines, hunk.id)}{hunk.collapsedAfter > 0 && (expanded.has(afterKey) ? <>{lines(hunk.collapsedAfterLines, afterKey)}<button className={css.diffCollapsed} onClick={() => toggle(afterKey)}>收起 {hunk.collapsedAfter} 行上下文</button></> : <button className={css.diffCollapsed} onClick={() => toggle(afterKey)}>展开后方 {hunk.collapsedAfter} 行未变内容</button>)}</section> })}</div>
534
1077
  }
535
1078
  const readinessLabel: Record<string, string> = { goal: '目标与用户结果', acceptance: '验收标准', scope: '范围与非范围', semantics: '业务语义', evidence: '证据来源', 'test-constraints': '测试约束' }
536
1079
  function ReadyPanel({ requirement, act }: { requirement: RequirementView; act: Act }) {
@@ -541,13 +1084,378 @@ function ReadyPanel({ requirement, act }: { requirement: RequirementView; act: A
541
1084
  if (ok) { setReturnOpen(false); setForm({ summary: '', sections: '', acceptanceIds: '', source: '', version: '', evidence: '' }) }
542
1085
  }
543
1086
  const passed = requirement.readiness.filter(check => check.passed).length
544
- return <><div className={css.readyHead}><h3>交付条件</h3><span>{passed} / {requirement.readiness.length} 已满足</span></div><div className={css.checklist}>{requirement.readiness.map(check => <section className={`${css.checkItem} ${check.passed ? css.checkPassed : css.checkBlocked}`} key={check.key}><span className={css.checkIcon} aria-hidden="true">{check.passed ? '✓' : '!'}</span><div><strong>{readinessLabel[check.key] ?? check.key}</strong><small>{check.passed ? '已满足' : '需要补充'}</small>{check.reasons.map(reason => <MarkdownBody key={reason} text={reason}/>)}</div></section>)}</div>{requirement.readyPackage && <section><strong>交付需求 · {requirement.readyPackage.packageHash.slice(0, 12)}</strong><MarkdownBody text={requirement.readyPackage.markdown}/></section>}{requirement.stage === 'ready' && <section className={css.downstreamReturn}><button onClick={() => setReturnOpen(value => !value)}>{returnOpen ? '取消返回问题' : '反馈研发阶段发现的问题'}</button>{returnOpen && <div><label>问题摘要(必填)<textarea required value={form.summary} onChange={event => setForm({ ...form, summary: event.target.value })} placeholder="描述研发阶段发现的产品语义或验收问题"/></label><label>受影响章节(与 AC 至少填写一项)<input value={form.sections} onChange={event => setForm({ ...form, sections: event.target.value })} placeholder="业务术语与规则"/></label><label>受影响 AC IDs(与章节至少填写一项)<input value={form.acceptanceIds} onChange={event => setForm({ ...form, acceptanceIds: event.target.value })} placeholder="AC-RETRY-001"/></label><label>依据来源(选填)<input value={form.source} onChange={event => setForm({ ...form, source: event.target.value })} placeholder="测试报告、Issue 或代码位置"/></label><label>依据版本(选填)<input value={form.version} onChange={event => setForm({ ...form, version: event.target.value })} placeholder="commit SHA 或版本号"/></label><label>依据说明(选填)<textarea value={form.evidence} onChange={event => setForm({ ...form, evidence: event.target.value })}/></label><button className={css.execute} disabled={!form.summary.trim() || (!form.sections.trim() && !form.acceptanceIds.trim())} onClick={() => void submitReturn()}>重新打开受影响内容</button></div>}</section>}</>
1087
+ return <><div className={css.readyHead}><h3>交付条件</h3><span>{passed} / {requirement.readiness.length} 已满足</span></div><div className={css.checklist}>{requirement.readiness.map(check => <section className={`${css.checkItem} ${check.passed ? css.checkPassed : css.checkBlocked}`} key={check.key}><span className={css.checkIcon} aria-hidden="true">{check.passed ? '✓' : '!'}</span><div><strong>{readinessLabel[check.key] ?? check.key}</strong><small>{check.passed ? '已满足' : '需要补充'}</small>{check.reasons.map(reason => <MarkdownBody key={reason} text={reason}/>)}</div></section>)}</div>{requirement.readyPackage && <section className={css.readyPackage} data-ready-package><div className={css.readyPackageHead}><div><span>就绪需求</span><strong>{requirement.readyPackage.packageHash.slice(0, 12)}</strong></div><div><button onClick={() => void navigator.clipboard.writeText(requirement.readyPackage!.markdown)}>复制 Markdown</button><button onClick={() => downloadText(`${requirement.id}.md`, requirement.readyPackage!.markdown)}>下载 .md</button><button onClick={() => void navigator.clipboard.writeText(requirement.readyPackage!.commit)}>复制 commit</button>{requirement.commitUrl && <a href={requirement.commitUrl} target="_blank" rel="noreferrer">打开 commit</a>}<button onClick={() => void navigator.clipboard.writeText(`${location.origin}${location.pathname}#spec-collab/${requirement.id}/tasks/${requirement.id}?commit=${requirement.readyPackage!.commit}`)}>复制分享链接</button></div></div><MarkdownBody text={requirement.readyPackage.markdown}/></section>}{requirement.stage === 'ready' && <section className={css.downstreamReturn}><button onClick={() => setReturnOpen(value => !value)}>{returnOpen ? '取消返回问题' : '反馈研发阶段发现的问题'}</button>{returnOpen && <div><label>问题摘要(必填)<textarea required value={form.summary} onChange={event => setForm({ ...form, summary: event.target.value })} placeholder="描述研发阶段发现的产品语义或验收问题"/></label><label>受影响章节(与 AC 至少填写一项)<input value={form.sections} onChange={event => setForm({ ...form, sections: event.target.value })} placeholder="业务术语与规则"/></label><label>受影响 AC IDs(与章节至少填写一项)<input value={form.acceptanceIds} onChange={event => setForm({ ...form, acceptanceIds: event.target.value })} placeholder="AC-RETRY-001"/></label><label>依据来源(选填)<input value={form.source} onChange={event => setForm({ ...form, source: event.target.value })} placeholder="测试报告、Issue 或代码位置"/></label><label>依据版本(选填)<input value={form.version} onChange={event => setForm({ ...form, version: event.target.value })} placeholder="commit SHA 或版本号"/></label><label>依据说明(选填)<textarea value={form.evidence} onChange={event => setForm({ ...form, evidence: event.target.value })}/></label><button className={css.execute} disabled={!form.summary.trim() || (!form.sections.trim() && !form.acceptanceIds.trim())} onClick={() => void submitReturn()}>重新打开受影响内容</button></div>}</section>}</>
545
1088
  }
546
1089
  function ConflictDialog({ conflict, value, setValue, close, submit, busy }: { conflict: SaveConflict; value: string; setValue: (value: string) => void; close: () => void; submit: () => void; busy: boolean }) {
547
- return <div className={`${css.modal} ${css.conflictModal}`}><div className={css.conflictDialog}><div className={css.conflictHeader}><div><h2>解决保存冲突</h2><p>基线 {conflict.baseCommit.slice(0, 8)} 已被更新为 {conflict.currentCommit.slice(0, 8)}。Git 尚未写入你的草稿。</p></div><button aria-label="关闭冲突窗口" onClick={close}>×</button></div><div className={css.conflictColumns}><label>打开时的基线(只读)<textarea readOnly value={conflict.baseMarkdown}/></label><label>远端最新版本(只读)<textarea readOnly value={conflict.currentMarkdown}/></label><label>合并稿(必填)<textarea required value={value} onChange={event => setValue(event.target.value)}/></label></div><div className={css.conflictDiffs}><details><summary>基线 → 远端 Diff</summary><pre>{conflict.baseToCurrentDiff}</pre></details><details><summary>基线 → 本地草稿 Diff</summary><pre>{conflict.baseToDraftDiff}</pre></details></div><div className={css.conflictActions}><button onClick={close}>稍后处理</button><button className={css.execute} disabled={busy || !value.trim()} onClick={submit}>{busy ? '正在提交…' : '基于最新版本提交合并稿'}</button></div></div></div>
1090
+ return <AccessibleDialog title="解决保存冲突" close={close} className={css.conflictDialog} dismissOnBackdrop={false}><div className={css.conflictHeader}><div><h2>解决保存冲突</h2><p>基线 {conflict.baseCommit.slice(0, 8)} 已更新为 {conflict.currentCommit.slice(0, 8)},Git 尚未写入你的本地草稿。</p></div><button aria-label="关闭冲突窗口" onClick={close}>×</button></div><div className={css.conflictColumns}><label>打开时的基线(只读)<textarea readOnly value={conflict.baseMarkdown}/></label><label>版本库最新版本(只读)<textarea readOnly value={conflict.currentMarkdown}/></label><label>合并稿(必填)<textarea required value={value} onChange={event => setValue(event.target.value)}/></label></div><div className={css.conflictDiffs}><details><summary>基线 → 版本库 Diff</summary><pre>{conflict.baseToCurrentDiff}</pre></details><details><summary>基线 → 本地草稿 Diff</summary><pre>{conflict.baseToDraftDiff}</pre></details></div><div className={css.conflictActions}><button onClick={close}>稍后处理</button><button className={css.execute} disabled={busy || !value.trim()} onClick={submit}>{busy ? '正在提交…' : '基于最新版本保存合并稿'}</button></div></AccessibleDialog>
1091
+ }
1092
+ function DialogForm({ title, close, children, submit, noValidate = false }: { title: string; close: () => void; children: ReactNode; submit: (event: FormEvent) => void; noValidate?: boolean }) { return <AccessibleDialog title={title} close={close} className={css.dialogSurface}><form className={css.dialogForm} noValidate={noValidate} onSubmit={submit}>{children}</form></AccessibleDialog> }
1093
+ function IdentityDialog({
1094
+ value,
1095
+ boundRole,
1096
+ onChange,
1097
+ close,
1098
+ save,
1099
+ }: {
1100
+ value: ParticipantSnapshot;
1101
+ boundRole?: ParticipantRole;
1102
+ onChange: (value: ParticipantSnapshot) => void;
1103
+ close: () => void;
1104
+ save: () => void;
1105
+ }) {
1106
+ return (
1107
+ <DialogForm
1108
+ title="设置协作身份"
1109
+ close={close}
1110
+ submit={(event) => {
1111
+ event.preventDefault();
1112
+ if (value.nickname.trim().length >= 2) save();
1113
+ }}
1114
+ >
1115
+ <div className={css.dialogHead}>
1116
+ <div>
1117
+ <span>协作身份</span>
1118
+ <h2>设置花名和角色</h2>
1119
+ </div>
1120
+ <button type="button" aria-label="关闭" onClick={close}>
1121
+ ×
1122
+ </button>
1123
+ </div>
1124
+ <p>用于标记回答、决策和版本确认。同一浏览器首次参与后,角色保持不变。</p>
1125
+ <label>
1126
+ 花名(必填)
1127
+ <input
1128
+ required
1129
+ autoFocus
1130
+ value={value.nickname}
1131
+ onChange={(event) =>
1132
+ onChange({ ...value, nickname: event.target.value })
1133
+ }
1134
+ />
1135
+ </label>
1136
+ <label>
1137
+ 参与角色(必填)
1138
+ <select
1139
+ required
1140
+ disabled={boundRole !== undefined}
1141
+ value={boundRole ?? value.role}
1142
+ onChange={(event) =>
1143
+ onChange({ ...value, role: event.target.value as ParticipantRole })
1144
+ }
1145
+ >
1146
+ <option value="product">产品</option>
1147
+ <option value="engineering">研发</option>
1148
+ </select>
1149
+ </label>
1150
+ {boundRole && (
1151
+ <small>
1152
+ 当前身份已固定为{boundRole === "product" ? "产品" : "研发"}角色。
1153
+ </small>
1154
+ )}
1155
+ <div className={css.stickyActions}>
1156
+ <button type="button" onClick={close}>
1157
+ 取消
1158
+ </button>
1159
+ <button
1160
+ className={css.execute}
1161
+ disabled={value.nickname.trim().length < 2}
1162
+ >
1163
+ 保存身份
1164
+ </button>
1165
+ </div>
1166
+ </DialogForm>
1167
+ );
1168
+ }
1169
+ function RenameDialog({
1170
+ title,
1171
+ setTitle,
1172
+ close,
1173
+ submit,
1174
+ busy,
1175
+ }: {
1176
+ title: string;
1177
+ setTitle: (title: string) => void;
1178
+ close: () => void;
1179
+ submit: () => void;
1180
+ busy: boolean;
1181
+ }) {
1182
+ return (
1183
+ <DialogForm
1184
+ title="重命名需求"
1185
+ close={close}
1186
+ submit={(event) => {
1187
+ event.preventDefault();
1188
+ submit();
1189
+ }}
1190
+ >
1191
+ <div className={css.dialogHead}>
1192
+ <h2>重命名需求</h2>
1193
+ <button type="button" aria-label="关闭" onClick={close}>
1194
+ ×
1195
+ </button>
1196
+ </div>
1197
+ <label>
1198
+ 需求名称(必填)
1199
+ <input
1200
+ required
1201
+ autoFocus
1202
+ value={title}
1203
+ onChange={(event) => setTitle(event.target.value)}
1204
+ />
1205
+ </label>
1206
+ <div className={css.stickyActions}>
1207
+ <button type="button" onClick={close}>
1208
+ 取消
1209
+ </button>
1210
+ <button className={css.execute} disabled={busy || !title.trim()}>
1211
+ 保存名称
1212
+ </button>
1213
+ </div>
1214
+ </DialogForm>
1215
+ );
1216
+ }
1217
+ function DeleteDialog({
1218
+ title,
1219
+ close,
1220
+ submit,
1221
+ busy,
1222
+ }: {
1223
+ title: string;
1224
+ close: () => void;
1225
+ submit: () => void;
1226
+ busy: boolean;
1227
+ }) {
1228
+ return (
1229
+ <DialogForm
1230
+ title="删除需求"
1231
+ close={close}
1232
+ submit={(event) => {
1233
+ event.preventDefault();
1234
+ submit();
1235
+ }}
1236
+ >
1237
+ <div className={css.dialogHead}>
1238
+ <h2>删除需求</h2>
1239
+ <button type="button" aria-label="关闭" onClick={close}>
1240
+ ×
1241
+ </button>
1242
+ </div>
1243
+ <p>
1244
+ 将删除“{title}”及其协作记录,并创建 Git 删除提交。历史版本仍可从 Git
1245
+ 恢复。
1246
+ </p>
1247
+ <div className={css.stickyActions}>
1248
+ <button type="button" onClick={close}>
1249
+ 取消
1250
+ </button>
1251
+ <button className={css.dangerButton} disabled={busy}>
1252
+ {busy ? "正在删除…" : "确认删除"}
1253
+ </button>
1254
+ </div>
1255
+ </DialogForm>
1256
+ );
1257
+ }
1258
+ function WorkspaceDialog({
1259
+ value,
1260
+ setValue,
1261
+ workspaces,
1262
+ close,
1263
+ submit,
1264
+ busy,
1265
+ }: {
1266
+ value: string;
1267
+ setValue: (value: string) => void;
1268
+ workspaces: ReviewWorkspaceSummary[];
1269
+ close: () => void;
1270
+ submit: () => void;
1271
+ busy: boolean;
1272
+ }) {
1273
+ return (
1274
+ <DialogForm
1275
+ title="关联项目"
1276
+ close={close}
1277
+ submit={(event) => {
1278
+ event.preventDefault();
1279
+ submit();
1280
+ }}
1281
+ >
1282
+ <div className={css.dialogHead}>
1283
+ <h2>关联项目</h2>
1284
+ <button type="button" aria-label="关闭" onClick={close}>
1285
+ ×
1286
+ </button>
1287
+ </div>
1288
+ <p>AI 会从所选项目读取代码、规范和团队知识。关联后不能中途切换。</p>
1289
+ <label>
1290
+ 需求所在项目(必填)
1291
+ <select
1292
+ required
1293
+ autoFocus
1294
+ value={value}
1295
+ onChange={(event) => setValue(event.target.value)}
1296
+ >
1297
+ <option value="" disabled>
1298
+ {workspaces.length > 0 ? "选择一个项目" : "当前没有可用项目"}
1299
+ </option>
1300
+ {workspaces.map((workspace) => (
1301
+ <option key={workspace.workspaceId} value={workspace.workspaceId}>
1302
+ {workspace.title} · {workspace.path}
1303
+ </option>
1304
+ ))}
1305
+ </select>
1306
+ </label>
1307
+ <div className={css.stickyActions}>
1308
+ <button type="button" onClick={close}>
1309
+ 取消
1310
+ </button>
1311
+ <button className={css.execute} disabled={busy || !value}>
1312
+ 确认关联
1313
+ </button>
1314
+ </div>
1315
+ </DialogForm>
1316
+ );
1317
+ }
1318
+ function CreateDialog({
1319
+ value,
1320
+ setValue,
1321
+ workspaces,
1322
+ close,
1323
+ submit,
1324
+ busy,
1325
+ }: {
1326
+ value: {
1327
+ title: string;
1328
+ rawRequirement: string;
1329
+ sources: string;
1330
+ workspaceId: string;
1331
+ };
1332
+ setValue: (value: {
1333
+ title: string;
1334
+ rawRequirement: string;
1335
+ sources: string;
1336
+ workspaceId: string;
1337
+ }) => void;
1338
+ workspaces: ReviewWorkspaceSummary[];
1339
+ close: () => void;
1340
+ submit: () => void;
1341
+ busy: boolean;
1342
+ }) {
1343
+ const [attempted, setAttempted] = useState(false);
1344
+ const errors = [
1345
+ ...(!value.title.trim() ? ["请填写需求标题"] : []),
1346
+ ...(!value.workspaceId ? ["请选择需求所在项目"] : []),
1347
+ ...(!value.rawRequirement.trim() ? ["请填写原始需求"] : []),
1348
+ ];
1349
+ return (
1350
+ <DialogForm
1351
+ title="新建需求"
1352
+ close={close}
1353
+ noValidate
1354
+ submit={(event) => {
1355
+ event.preventDefault();
1356
+ setAttempted(true);
1357
+ if (errors.length === 0) submit();
1358
+ else window.requestAnimationFrame(() => document.getElementById(!value.title.trim() ? 'create-requirement-title' : !value.workspaceId ? 'create-requirement-workspace' : 'create-requirement-raw')?.focus());
1359
+ }}
1360
+ >
1361
+ <div className={css.dialogHead}>
1362
+ <div>
1363
+ <span>新需求</span>
1364
+ <h2>从真实问题开始</h2>
1365
+ </div>
1366
+ <button type="button" aria-label="关闭" onClick={close}>
1367
+ ×
1368
+ </button>
1369
+ </div>
1370
+ <p>
1371
+ 先写清用户问题和期望结果。创建后 AI
1372
+ 会读取所选项目的已配置资料并在后台检查,你可以离开页面。
1373
+ </p>
1374
+ {attempted && errors.length > 0 && (
1375
+ <div className={css.formErrors} role="alert">
1376
+ <strong>还需要补充</strong>
1377
+ {errors.map((error) => (
1378
+ <span key={error}>{error}</span>
1379
+ ))}
1380
+ </div>
1381
+ )}
1382
+ <label>
1383
+ 需求标题(必填)
1384
+ <input
1385
+ id="create-requirement-title"
1386
+ autoFocus
1387
+ required
1388
+ value={value.title}
1389
+ aria-invalid={attempted && !value.title.trim()}
1390
+ onChange={(event) =>
1391
+ setValue({ ...value, title: event.target.value })
1392
+ }
1393
+ />
1394
+ </label>
1395
+ <label>
1396
+ 需求所在项目(必填)
1397
+ <select
1398
+ id="create-requirement-workspace"
1399
+ required
1400
+ value={value.workspaceId}
1401
+ aria-invalid={attempted && !value.workspaceId}
1402
+ onChange={(event) =>
1403
+ setValue({ ...value, workspaceId: event.target.value })
1404
+ }
1405
+ >
1406
+ <option value="" disabled>
1407
+ {workspaces.length > 0 ? "选择一个项目" : "当前没有可用项目"}
1408
+ </option>
1409
+ {workspaces.map((workspace) => (
1410
+ <option key={workspace.workspaceId} value={workspace.workspaceId}>
1411
+ {workspace.title} · {workspace.path}
1412
+ </option>
1413
+ ))}
1414
+ </select>
1415
+ </label>
1416
+ <label>
1417
+ 原始需求(必填)
1418
+ <textarea
1419
+ id="create-requirement-raw"
1420
+ required
1421
+ value={value.rawRequirement}
1422
+ aria-invalid={attempted && !value.rawRequirement.trim()}
1423
+ onChange={(event) =>
1424
+ setValue({ ...value, rawRequirement: event.target.value })
1425
+ }
1426
+ placeholder="描述用户遇到的问题、期望结果、已有方案和已知限制"
1427
+ />
1428
+ </label>
1429
+ <label>
1430
+ 补充资料(选填,每行一项)
1431
+ <textarea
1432
+ value={value.sources}
1433
+ onChange={(event) =>
1434
+ setValue({ ...value, sources: event.target.value })
1435
+ }
1436
+ placeholder="相关文档链接&#10;历史决策&#10;代码目录或组件"
1437
+ />
1438
+ </label>
1439
+ <div className={css.createSummary}>
1440
+ <strong>提交后</strong>
1441
+ <span>创建 Git 初始版本</span>
1442
+ <span>开始产品 AI 初审</span>
1443
+ <span>输入和运行状态会保留</span>
1444
+ </div>
1445
+ <div className={css.stickyActions}>
1446
+ <button type="button" onClick={close}>
1447
+ 取消
1448
+ </button>
1449
+ <button className={css.execute} disabled={busy}>
1450
+ {busy ? "正在创建…" : "创建并开始 AI 检查"}
1451
+ </button>
1452
+ </div>
1453
+ </DialogForm>
1454
+ );
1455
+ }
1456
+ function PageCommentDialog({ value, setValue, close, submit, busy }: { value: string; setValue: (value: string) => void; close: () => void; submit: () => void; busy: boolean }) { return <DialogForm title="评论整篇需求" close={close} submit={event => { event.preventDefault(); submit() }}><div className={css.dialogHead}><div><span>页面总评</span><h2>评论整篇需求</h2></div><button type="button" aria-label="关闭" onClick={close}>×</button></div><p>用于整体方向、完整性或跨章节问题。针对具体文字时,请在正文中选中片段评论。</p><label>评论内容(必填)<textarea autoFocus required value={value} onChange={event => setValue(event.target.value)}/></label><div className={css.stickyActions}><button type="button" onClick={close}>取消</button><button className={css.execute} disabled={busy || !value.trim()}>提交总评</button></div></DialogForm> }
1457
+ function NotificationDialog({ notifications, close, open, markRead }: { notifications: Notification[]; close: () => void; open: (item: Notification) => void; markRead: (item: Notification) => void }) { return <AccessibleDialog title="通知中心" close={close} className={css.notificationDialog}><div className={css.dialogHead}><div><span>插件内协作</span><h2>通知中心</h2></div><button aria-label="关闭" onClick={close}>×</button></div>{notifications.length === 0 ? <div className={css.emptyPanel}><strong>没有新通知</strong><p>提及、回复、指派和状态变化会出现在这里。</p></div> : <div className={css.notificationList}>{notifications.map(item => <article className={item.readAt ? '' : css.unreadNotification} key={item.id}><button onClick={() => { markRead(item); open(item) }}><strong>{item.message}</strong><span title={new Date(item.createdAt).toLocaleString()}>{relativeTime(item.createdAt)}</span></button>{!item.readAt && <button onClick={() => markRead(item)}>标为已读</button>}</article>)}</div>}</AccessibleDialog> }
1458
+ function MyWorkDialog({ items, notifications, close, openItem, openNotification }: { items: MyActionItem[]; notifications: Notification[]; close: () => void; openItem: (item: MyActionItem) => void; openNotification: (item: Notification) => void }) {
1459
+ const unread = notifications.filter(item => item.readAt === undefined)
1460
+ return <AccessibleDialog title="我的工作" close={close} className={css.notificationDialog}><div className={css.dialogHead}><div><span>跨需求个人工作台</span><h2>我的工作</h2></div><button aria-label="关闭" onClick={close}>×</button></div><div className={css.myWorkSummary}><span><b>{items.length}</b> 个待办</span><span><b>{unread.length}</b> 条未读</span></div>{items.length === 0 && unread.length === 0 ? <div className={css.emptyPanel}><strong>当前没有需要你处理的事项</strong><p>指派、提及、回复和待确认项会跨需求汇总到这里。</p></div> : <div className={css.myWorkList}>{items.map(item => <button key={`${item.category}-${item.id}`} onClick={() => openItem(item)}><span>{item.blocking ? '优先处理' : '普通'}</span><strong>{item.objectTitle}</strong><small title={new Date(item.updatedAt).toLocaleString()}>{item.requirementTitle} · {taskTypeLabel[item.type]} · {stageLabel(item.dueStage)}前 · {relativeTime(item.updatedAt)}</small></button>)}{unread.map(item => <button key={item.id} onClick={() => openNotification(item)}><span>{item.kind === 'mention' ? '@ 提及' : item.kind === 'assignment' ? '指派' : '未读通知'}</span><strong>{item.message}</strong><small title={new Date(item.createdAt).toLocaleString()}>{relativeTime(item.createdAt)}</small></button>)}</div>}</AccessibleDialog>
548
1461
  }
549
- function IdentityDialog({ value, boundRole, onChange, close }: { value: ParticipantSnapshot; boundRole?: ParticipantRole; onChange: (value: ParticipantSnapshot) => void; close: () => void }) { return <div className={css.modal}><form onSubmit={event => { event.preventDefault(); if (value.nickname.trim().length >= 2) close() }}><h2>设置协作身份</h2><p>用于标记回答、决策和版本确认。同一浏览器首次参与后,角色会保持不变。</p><label>花名(必填)<input required autoFocus value={value.nickname} onChange={event => onChange({ ...value, nickname: event.target.value })}/></label><label>参与角色(必填)<select required disabled={boundRole !== undefined} value={boundRole ?? value.role} onChange={event => onChange({ ...value, role: event.target.value as ParticipantRole })}><option value="product">产品</option><option value="engineering">研发</option></select></label>{boundRole && <small>当前身份已固定为{boundRole === 'product' ? '产品' : '研发'}角色。</small>}<button type="submit" disabled={value.nickname.trim().length < 2}>保存身份</button></form></div> }
550
- function RenameDialog({ title, setTitle, close, submit, busy }: { title: string; setTitle: (title: string) => void; close: () => void; submit: () => void; busy: boolean }) { return <div className={css.modal}><form onSubmit={event => { event.preventDefault(); submit() }}><h2>重命名需求</h2><label>需求名称(必填)<input required autoFocus value={title} onChange={event => setTitle(event.target.value)}/></label><div><button type="button" onClick={close}>取消</button><button type="submit" disabled={busy || !title.trim()}>保存名称</button></div></form></div> }
551
- function DeleteDialog({ title, close, submit, busy }: { title: string; close: () => void; submit: () => void; busy: boolean }) { return <div className={css.modal}><form onSubmit={event => { event.preventDefault(); submit() }}><h2>删除需求</h2><p>将删除“{title}”及其协作记录,并创建 Git 删除提交。历史版本仍可从 Git 恢复。</p><div><button type="button" onClick={close}>取消</button><button type="submit" className={css.dangerButton} disabled={busy}>{busy ? '正在删除…' : '确认删除'}</button></div></form></div> }
552
- function WorkspaceDialog({ value, setValue, workspaces, close, submit, busy }: { value: string; setValue: (value: string) => void; workspaces: ReviewWorkspaceSummary[]; close: () => void; submit: () => void; busy: boolean }) { return <div className={css.modal}><form onSubmit={event => { event.preventDefault(); submit() }}><h2>关联项目</h2><p>AI 会从所选项目读取代码、规范和团队知识。关联后不能中途切换。</p><label>需求所在项目(必填)<select required autoFocus value={value} onChange={event => setValue(event.target.value)}><option value="" disabled>{workspaces.length > 0 ? '选择一个项目' : '当前没有可用项目'}</option>{workspaces.map(workspace => <option key={workspace.workspaceId} value={workspace.workspaceId}>{workspace.title} · {workspace.path}</option>)}</select></label><div><button type="button" onClick={close}>取消</button><button type="submit" disabled={busy || !value}>确认关联</button></div></form></div> }
553
- function CreateDialog({ value, setValue, workspaces, close, submit, busy }: { value: { title: string; rawRequirement: string; sources: string; workspaceId: string }; setValue: (value: { title: string; rawRequirement: string; sources: string; workspaceId: string }) => void; workspaces: ReviewWorkspaceSummary[]; close: () => void; submit: () => void; busy: boolean }) { return <div className={css.modal}><form onSubmit={event => { event.preventDefault(); submit() }}><h2>新建需求</h2><p>先写清用户问题和期望结果,其余缺口交给 AI 检查。</p><label>需求标题(必填)<input required value={value.title} onChange={event => setValue({ ...value, title: event.target.value })}/></label><label>需求所在项目(必填)<select required value={value.workspaceId} onChange={event => setValue({ ...value, workspaceId: event.target.value })}><option value="" disabled>{workspaces.length > 0 ? '选择一个项目' : '当前没有可用项目'}</option>{workspaces.map(workspace => <option key={workspace.workspaceId} value={workspace.workspaceId}>{workspace.title} · {workspace.path}</option>)}</select></label><label>原始需求(必填)<textarea required value={value.rawRequirement} onChange={event => setValue({ ...value, rawRequirement: event.target.value })} placeholder="描述用户遇到的问题、期望结果、已有方案和已知限制"/></label><label>补充资料(选填,每行一项)<textarea value={value.sources} onChange={event => setValue({ ...value, sources: event.target.value })} placeholder="相关文档链接&#10;历史决策&#10;代码目录或组件"/></label><div><button type="button" onClick={close}>取消</button><button type="submit" disabled={busy || !value.title.trim() || !value.rawRequirement.trim() || !value.workspaceId}>创建并开始 AI 检查</button></div></form></div> }