@lincyaw/workbench 0.2.0-rc.1 → 0.2.0-rc.100

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 (100) hide show
  1. package/package.json +5 -4
  2. package/src/AgentActivityBar.tsx +25 -0
  3. package/src/MediaClipEditor.tsx +4 -3
  4. package/src/StepProductionEditor.tsx +13 -4
  5. package/src/agent-activity-messages.ts +14 -0
  6. package/src/agent-activity.ts +38 -0
  7. package/src/approvals.tsx +6 -1
  8. package/src/audio-recording.ts +27 -5
  9. package/src/authoring-client.ts +10 -10
  10. package/src/authoring-draft-fragment.ts +3 -1
  11. package/src/authoring-window.ts +100 -0
  12. package/src/body-draft-actions.ts +60 -0
  13. package/src/caption-timing-drafts.ts +18 -1
  14. package/src/component-property-drafts.ts +5 -5
  15. package/src/components.tsx +34 -36
  16. package/src/container-layout.ts +21 -0
  17. package/src/context.tsx +5 -3
  18. package/src/diagnostics.ts +1 -1
  19. package/src/document-draft-store.ts +45 -18
  20. package/src/document-drafts.ts +28 -19
  21. package/src/document-editing.ts +484 -0
  22. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  23. package/src/document-editor/CommentComposer.tsx +24 -0
  24. package/src/document-editor/ComponentMaterials.tsx +3 -9
  25. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  26. package/src/document-editor/DocumentBlockPreview.tsx +11 -4
  27. package/src/document-editor/DocumentComments.tsx +85 -14
  28. package/src/document-editor/DocumentEditor.tsx +56 -7
  29. package/src/document-editor/DocumentStepNarration.tsx +37 -26
  30. package/src/document-editor/NarrationEditor.tsx +54 -20
  31. package/src/document-editor/NewCommentDrafts.tsx +120 -37
  32. package/src/document-editor/PlaceComment.tsx +252 -0
  33. package/src/document-editor/agent-targets.ts +34 -0
  34. package/src/document-editor/blocknote-messages.ts +2 -0
  35. package/src/document-editor/comment-draft-actions.ts +40 -20
  36. package/src/document-editor/comment-draft-inspection.ts +2 -2
  37. package/src/document-editor/comment-drafts.ts +73 -25
  38. package/src/document-editor/comments.ts +30 -10
  39. package/src/document-editor/component-label.ts +11 -0
  40. package/src/document-editor/file-input.ts +2 -2
  41. package/src/document-editor/focus.ts +0 -2
  42. package/src/document-editor/insertion-place.ts +60 -0
  43. package/src/document-editor/messages.ts +3 -3
  44. package/src/document-editor/narration-schema.tsx +12 -6
  45. package/src/document-editor/narration.ts +19 -3
  46. package/src/document-editor/page-body.ts +60 -0
  47. package/src/document-editor/popover.tsx +4 -2
  48. package/src/document-editor/projection.ts +2 -2
  49. package/src/document-editor/rich-text.ts +3 -2
  50. package/src/document-editor/selection.ts +13 -0
  51. package/src/document-editor/style.css +7 -1
  52. package/src/document-editor/table-identities.ts +2 -1
  53. package/src/document-production.ts +491 -0
  54. package/src/document-session.ts +202 -56
  55. package/src/document-timing-drafts.ts +22 -2
  56. package/src/history.ts +5 -5
  57. package/src/index.ts +8 -5
  58. package/src/jobs.ts +1 -1
  59. package/src/media-drafts.ts +43 -1
  60. package/src/messages.ts +31 -14
  61. package/src/panels/DocumentNarrationPanel.tsx +2 -2
  62. package/src/panels/DocumentView.tsx +93 -61
  63. package/src/panels/DocumentVoiceDialog.tsx +25 -9
  64. package/src/panels/DocumentVoiceField.tsx +1 -1
  65. package/src/panels/ExportPanel.tsx +2 -10
  66. package/src/panels/HistoryPanel.tsx +34 -7
  67. package/src/panels/HomePanel.tsx +3 -1
  68. package/src/panels/PageDeleteDialog.tsx +4 -4
  69. package/src/panels/PageRenameDialog.tsx +1 -1
  70. package/src/panels/PreviewPanel.tsx +1 -4
  71. package/src/panels/ProductionCaptionSize.tsx +20 -0
  72. package/src/panels/ProductionCaptionTiming.tsx +12 -9
  73. package/src/panels/ProductionMediaClips.tsx +23 -7
  74. package/src/panels/ProductionPanel.tsx +16 -13
  75. package/src/panels/ProductionRecording.tsx +86 -9
  76. package/src/panels/ProductionRecordingRange.tsx +21 -19
  77. package/src/panels/ProductionTimeline.tsx +6 -1
  78. package/src/panels/ProductionTranscription.tsx +5 -4
  79. package/src/panels/SourceDocumentPanel.tsx +18 -36
  80. package/src/panels/TranscriptionAdoption.tsx +40 -34
  81. package/src/panels/VoiceCloneDialog.tsx +2 -1
  82. package/src/panels/VoiceoverDialog.tsx +1 -1
  83. package/src/places.ts +1 -36
  84. package/src/preview-playback.ts +1 -1
  85. package/src/production-draft-actions.ts +37 -0
  86. package/src/production-messages.ts +6 -0
  87. package/src/production-playback.ts +1 -1
  88. package/src/production-voice-playback.ts +3 -2
  89. package/src/sha256.ts +9 -0
  90. package/src/styles.css +43 -79
  91. package/src/transcription-drafts.ts +124 -0
  92. package/src/use-recording-adoption.ts +2 -2
  93. package/src/voice-drafts.ts +32 -8
  94. package/src/voiceover-jobs.ts +1 -1
  95. package/src/workbench-state.ts +159 -0
  96. package/src/workbench.ts +294 -951
  97. package/src/workspace-client.ts +23 -11
  98. package/src/assistant-mascot.ts +0 -62
  99. package/src/mascot-preference.ts +0 -37
  100. package/src/panels/ChangeTrail.tsx +0 -79
@@ -0,0 +1,252 @@
1
+ import { useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
2
+ import type { ContextType } from 'react'
3
+ import type { BlockNoteEditor } from '@blocknote/core'
4
+ import { CommentEditorSubmitExtension, CommentsExtension } from '@blocknote/core/comments'
5
+ import { GenericPopover, useCreateBlockNote, useDictionary, useEditorState, useExtension, useExtensionState, useThreads } from '@blocknote/react'
6
+ import { isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
7
+ import { PmButton, PmIconButton, PmNotice, PmSelect } from '../components.tsx'
8
+ import { useWorkbench, useWorkbenchState } from '../context.tsx'
9
+ import { COMMENT_EDITOR_CONTEXT, DocumentCommentThread, DraftChoices, placeReference } from './DocumentComments.tsx'
10
+ import { isNewCommentDraft, newCommentDraftSignature, sameCommentDraftTarget } from './comment-drafts.ts'
11
+ import type { CommentDraftCandidate, CommentDraftRecord, CommentDraftOperation, CommentDraftComposer, NewCommentDraftTarget } from './comment-drafts.ts'
12
+ import { discardNativeCommentDraft } from './comment-draft-actions.ts'
13
+ import { waitForDraft } from '../document-draft-store.ts'
14
+ import { isApprovalTarget } from '../approvals.tsx'
15
+ import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
16
+ import { commentEditorSchema } from './schema.tsx'
17
+ import type { DocumentEditorBlock } from './schema.tsx'
18
+ import { createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
19
+ import { CommentComposer } from './CommentComposer.tsx'
20
+ import { commentFloating } from './popover.tsx'
21
+ import { enterSubmits } from './comments.ts'
22
+ const emptyDrafts = { candidates: [], pending: false, failed: false, reading: false } as const
23
+ const subscribeEmpty = () => () => {}
24
+ type CommentContext = NonNullable<ContextType<typeof COMMENT_EDITOR_CONTEXT>>
25
+
26
+ /** The step's place anchor: the whole block when no step is chosen. */
27
+ function placeOf(blockId: string, stepId: string | undefined) {
28
+ return stepId === undefined ? { blockId } : { blockId, stepId }
29
+ }
30
+
31
+ /**
32
+ * A block preview's own comment entry. The button belongs to the preview header; the composer reuses the canonical
33
+ * comment editor and draft bank instead of inventing a second comment flow.
34
+ */
35
+ export function PlaceCommentButton(props: {
36
+ blockId: string, sectionId: string, stepId: string, stepIndex: number, onPause(): void,
37
+ }) {
38
+ const context = useContext(COMMENT_EDITOR_CONTEXT)
39
+ if (!context || context.readOnly || !context.store.auth.canCreateThread()) return null
40
+ return <PlaceCommentButtonContent {...props} context={context} />
41
+ }
42
+
43
+ function PlaceCommentButtonContent({ blockId, sectionId, stepId, stepIndex, onPause, context }: {
44
+ blockId: string, sectionId: string, stepId: string, stepIndex: number, onPause(): void, context: CommentContext,
45
+ }) {
46
+ const threads = useThreads(), workbench = useWorkbench(), comments = useExtension(CommentsExtension)
47
+ const { selectedThreadId } = useExtensionState(CommentsExtension)
48
+ const [trigger, setTrigger] = useState<HTMLSpanElement | null>(null)
49
+ const threadComposing = useRef(false)
50
+ const floating = useMemo(() => commentFloating(), [])
51
+ const t = DOCUMENT_EDITOR_MESSAGES[context.locale]
52
+ const [open, setOpen] = useState(false), [selected, setSelected] = useState<string | undefined>(stepId)
53
+ const drafts = context.store.drafts, native = useRef<CommentDraftComposer>(), composerId = useRef(randomUUID()), revision = useRef(0)
54
+ const draftState = useSyncExternalStore(drafts?.subscribe ?? subscribeEmpty, drafts?.snapshot ?? (() => emptyDrafts))
55
+ const needed = open || draftState.candidates.some(candidate => isNewCommentDraft(candidate.target) && candidate.target.anchor && isDocumentPlaceAnchor(candidate.target.anchor) && candidate.target.anchor.blockId === blockId)
56
+ const opening = useRef<{ previous?: CommentDraftRecord, ready?(owner?: CommentDraftComposer): void }>()
57
+ const alive = useRef(true)
58
+ const accept = (target: CommentDraftCandidate['target']) => isNewCommentDraft(target) && Boolean(target.anchor && isDocumentPlaceAnchor(target.anchor) && target.anchor.blockId === blockId
59
+ && (target.anchor.stepId === undefined || context.store.document.sections[sectionId]?.stepOrder.includes(target.anchor.stepId)) && context.store.draftTargetState(target) === 'current')
60
+ const ready = useMemo(() => (owner: CommentDraftComposer | undefined) => { native.current = owner; if (owner) opening.current?.ready?.(owner) }, [])
61
+ useLayoutEffect(() => {
62
+ alive.current = true
63
+ if (!drafts || !needed) return
64
+ const restore = async (candidate: CommentDraftCandidate, action: CommentDraftOperation): Promise<CommentDraftRecord | undefined> => {
65
+ if (!accept(candidate.target) || !isNewCommentDraft(candidate.target) || !candidate.target.anchor || !isDocumentPlaceAnchor(candidate.target.anchor)) return
66
+ const before = native.current, previous = before?.snapshot().record, version = context.store.version, request = ++revision.current, targetStep = candidate.target.anchor.stepId
67
+ const guard = () => {
68
+ action.signal?.throwIfAborted(); action.guard?.(); context.store.beforeAction?.()
69
+ if (!alive.current || revision.current !== request || context.store.version !== version || !accept(candidate.target)) throw new Error('client-comment-composer-changed')
70
+ }
71
+ guard()
72
+ if (previous && !await waitForDraft(drafts.confirm(previous), action.signal)) return
73
+ guard()
74
+ let resolve!: (owner?: CommentDraftComposer) => void
75
+ const mounted = new Promise<CommentDraftComposer | undefined>(yes => { resolve = yes })
76
+ const transition = { previous, ready: resolve }; opening.current = transition
77
+ try {
78
+ onPause(); setSelected(targetStep); setOpen(true)
79
+ if (targetStep !== undefined) workbench.observeDocumentStep(sectionId, targetStep)
80
+ // A mounted matching form can be reused; otherwise the keyed native form supplies readiness.
81
+ const same = before && sameCommentDraftTarget(before.target, candidate.target)
82
+ const actual = same ? before : await waitForDraft(mounted, action.signal)
83
+ guard()
84
+ if (!actual?.restore || native.current !== actual || !actual.snapshot().available || actual.snapshot().composing || !same && actual.snapshot().record) return
85
+ const value = await actual.restore(candidate, { signal: action.signal, guard })
86
+ return value
87
+ } finally { if (opening.current === transition) opening.current = undefined }
88
+ }
89
+ const stop = drafts.registerComposer({ id: composerId.current, target: { kind: 'create', intentId: composerId.current, documentId: context.store.document.id }, accepts: accept,
90
+ snapshot: () => { const current = native.current?.snapshot(); return { record: opening.current ? opening.current.previous : current?.record,
91
+ composing: current?.composing ?? false, available: alive.current && !context.readOnly && context.store.auth.canCreateThread() && (current?.available ?? true) } },
92
+ targetState: target => target && accept(target) ? 'current' : 'unavailable', restore })
93
+ return () => { alive.current = false; revision.current++; opening.current?.ready?.(); opening.current = undefined; stop() }
94
+ }, [drafts, context.store, blockId, sectionId, needed])
95
+ const anchored = [...threads.values()].filter(thread => {
96
+ const anchor = context.store.placeAnchorOf(thread.id)
97
+ return !thread.deletedAt && !thread.resolved && anchor?.blockId === blockId && (anchor.stepId === undefined || anchor.stepId === stepId)
98
+ })
99
+ const selectedAnchor = selectedThreadId ? context.store.placeAnchorOf(selectedThreadId) : undefined
100
+ const selectedThread = selectedAnchor?.blockId === blockId ? threads.get(selectedThreadId!) : undefined
101
+ useEffect(() => {
102
+ if (!selectedThread || !selectedAnchor?.stepId) return
103
+ onPause(); workbench.observeDocumentStep(sectionId, selectedAnchor.stepId)
104
+ }, [selectedThreadId, selectedAnchor?.stepId])
105
+ const change = (next: boolean) => {
106
+ revision.current++; opening.current?.ready?.()
107
+ setOpen(next)
108
+ if (next) { comments.stopPendingComment(); comments.selectThread(undefined); setSelected(stepId); onPause() }
109
+ }
110
+ const close = (next: boolean, event?: Event) => {
111
+ if (next || isApprovalTarget(event?.target ?? document.activeElement) || native.current?.snapshot().composing || threadComposing.current
112
+ || event instanceof KeyboardEvent && (event.isComposing || event.keyCode === 229)) return
113
+ change(false); comments.selectThread(undefined)
114
+ if (event instanceof KeyboardEvent && event.key === 'Escape') trigger?.querySelector('button')?.focus()
115
+ }
116
+ const shown = !context.sidebar && !open && selectedThread && !selectedThread.deletedAt && (selectedAnchor?.stepId === undefined || selectedAnchor.stepId === stepId)
117
+ return <>
118
+ <span ref={setTrigger} className="pm-document-place-comment__trigger">
119
+ <PmIconButton small icon="comment-add" label={t.stepComment(stepIndex)} onClick={() => change(!open)} />
120
+ {anchored.length > 0 && <PmButton small icon="comment" aria-label={t.stepCommentHint(stepIndex, anchored.length)} onClick={() => {
121
+ change(false); comments.stopPendingComment(); onPause(); comments.selectThread(anchored[0]!.id, false)
122
+ }}>{anchored.length}</PmButton>}
123
+ </span>
124
+ <GenericPopover reference={trigger ? { element: trigger } : undefined} focusManagerProps={{ disabled: true }}
125
+ elementProps={{ style: { zIndex: 60 }, 'aria-label': open ? t.stepComment(stepIndex) : t.stepCommentHint(stepIndex, anchored.length) }}
126
+ useFloatingOptions={{ ...floating, placement: 'bottom-start', open: Boolean(open || shown), onOpenChange: close }}>
127
+ {open && <PlaceCommentComposer key={selected ?? 'block'} context={context} blockId={blockId} sectionId={sectionId} stepId={selected}
128
+ onReady={ready} onSelect={next => { revision.current++; setSelected(next); if (next !== undefined) workbench.observeDocumentStep(sectionId, next) }} onClose={threadId => {
129
+ change(false); comments.selectThread(threadId, false)
130
+ }} />}
131
+ {shown && <div className="pm-ui-comment-threads" onCompositionStart={() => { threadComposing.current = true }} onCompositionEnd={() => { threadComposing.current = false }}>{(anchored.some(thread => thread.id === selectedThread.id) ? anchored : [selectedThread]).map(thread => <DocumentCommentThread key={thread.id} thread={thread}
132
+ selected={selectedThreadId === thread.id} referenceText={placeReference(context.store.document, context.store.placeAnchorOf(thread.id)!, t)}
133
+ onFocus={() => comments.selectThread(thread.id, false)} tabIndex={0} />)}</div>}
134
+ </GenericPopover>
135
+ </>
136
+ }
137
+
138
+ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, onClose, onReady }: {
139
+ context: CommentContext, blockId: string, sectionId: string, stepId: string | undefined, onSelect(stepId: string | undefined): void, onClose(threadId: string): void, onReady(owner?: CommentDraftComposer): void,
140
+ }) {
141
+ const fallback = context.store.document
142
+ const document = useWorkbenchState(state => state.authoring?.content) ?? fallback
143
+ const section = document?.sections[sectionId]
144
+ const t = DOCUMENT_EDITOR_MESSAGES[context.locale]
145
+ const store = context.store, drafts = store.drafts, dictionary = useDictionary()
146
+ const rich = useMemo(() => createRichProjection(), [])
147
+ const [target] = useState<NewCommentDraftTarget>(() => {
148
+ const anchor = placeOf(blockId, stepId)
149
+ return { kind: 'create', intentId: randomUUID(), documentId: document!.id, anchor, signature: newCommentDraftSignature(document!, anchor) }
150
+ })
151
+ const [busy, setBusy] = useState(false), [failure, setFailure] = useState(false)
152
+ const record = useRef<CommentDraftRecord>(), composing = useRef(false), submitting = useRef(false), composer = useRef(randomUUID())
153
+ const active = useRef(true), input = useRef(0), suppress = useRef(false)
154
+ const submitRef = useRef<() => Promise<void>>(() => Promise.resolve())
155
+ const editor: BlockNoteEditor<any, any, any> = useCreateBlockNote({
156
+ schema: commentEditorSchema, trailingBlock: false,
157
+ dictionary: { ...dictionary, placeholders: { ...dictionary.placeholders, emptyDocument: dictionary.placeholders.new_comment } },
158
+ extensions: [CommentEditorSubmitExtension({ onSubmit: async () => submitRef.current() })],
159
+ }, [blockId, stepId])
160
+ const empty = useEditorState({ editor, selector: ({ editor }) => editor.isEmpty })
161
+ const write = (composingNow: boolean) => {
162
+ const version = store.version, current = record.current
163
+ if (!drafts || !version) return
164
+ if (editor.isEmpty) {
165
+ if (current) { record.current = undefined; void drafts.clearOwn(current) }
166
+ return
167
+ }
168
+ const next = drafts.write(current?.target ?? target, current?.version ?? version, nativeRichTextToProduct(editor.document as DocumentEditorBlock[], rich), composingNow, current)
169
+ if (next) record.current = next
170
+ }
171
+ useLayoutEffect(() => {
172
+ if (!drafts) return
173
+ active.current = true
174
+ const stopEnter = enterSubmits(editor, () => submitRef.current())
175
+ const stop = editor.onChange(() => { if (!submitting.current && !suppress.current) { input.current++; write(composing.current) } })
176
+ return () => { active.current = false; input.current++; stop(); stopEnter() }
177
+ }, [drafts, editor, target, rich])
178
+ useLayoutEffect(() => {
179
+ if (!drafts) return
180
+ const owner: CommentDraftComposer = { id: composer.current, target,
181
+ snapshot: () => ({ record: record.current, composing: composing.current || editor.prosemirrorView.composing, available: active.current && !submitting.current && !editor.prosemirrorView.isDestroyed }),
182
+ targetState: () => store.draftTargetState(target), restore: recover, discard: discardActive }
183
+ const stop = drafts.registerComposer(owner); onReady(owner)
184
+ return () => { onReady(); stop() }
185
+ }, [drafts, store, target, editor])
186
+ const composition = (value: boolean) => { composing.current = value; input.current++; write(value) }
187
+ const submit = async () => {
188
+ if (!active.current || composing.current || submitting.current || busy || editor.isEmpty || editor.prosemirrorView.composing) return
189
+ if (!store.auth.canCreateThread() || store.draftTargetState(target) !== 'current') { setFailure(true); return }
190
+ setBusy(true); setFailure(false); submitting.current = true
191
+ try {
192
+ store.beforeAction?.()
193
+ const thread = await store.createPlaceThread({ blockId, stepId, body: editor.document })
194
+ const actual = store.threadSnapshot(thread.id)
195
+ if (actual) { const current = record.current; if (current) { drafts?.submitted(current, actual.comments[0]!, actual); record.current = undefined } }
196
+ onClose(thread.id)
197
+ } catch { setFailure(true) } finally { submitting.current = false; setBusy(false) }
198
+ }
199
+ submitRef.current = submit
200
+ const draftsState = useSyncExternalStore(drafts?.subscribe ?? subscribeEmpty, drafts?.snapshot ?? (() => emptyDrafts))
201
+ const candidates = draftsState.candidates.filter(candidate => isNewCommentDraft(candidate.target) && sameCommentDraftTarget(candidate.target, target) && candidate.id !== record.current?.id)
202
+ const nativeGuard = () => {
203
+ const version = store.version, before = input.current, own = record.current, native = editor.prosemirrorState, position = context.getPositionToken?.()
204
+ return () => {
205
+ store.beforeAction?.()
206
+ if (!active.current || !version || store.version !== version || input.current !== before || record.current !== own || composing.current || submitting.current
207
+ || editor.prosemirrorView.isDestroyed || editor.prosemirrorView.composing || editor.prosemirrorState.doc !== native.doc || editor.prosemirrorState.selection !== native.selection
208
+ || context.getPositionToken?.() !== position || !store.auth.canCreateThread()) throw new Error('client-comment-composer-changed')
209
+ }
210
+ }
211
+ const recover = async (candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<CommentDraftRecord | undefined> => {
212
+ const version = store.version
213
+ if (!drafts || !version) return
214
+ const current = nativeGuard(), guard = () => { operation?.signal?.throwIfAborted(); operation?.guard?.(); current(); if (store.draftTargetState(target) !== 'current') throw new Error('client-comment-target-changed') }
215
+ guard()
216
+ if (record.current && !await waitForDraft(drafts.confirm(record.current), operation?.signal)) return
217
+ guard()
218
+ const next = await drafts.recover(candidate, target, version, { signal: operation?.signal, guard })
219
+ if (!next) return
220
+ guard(); suppress.current = true
221
+ try {
222
+ editor.replaceBlocks(editor.document, productRichTextToNative(next.content, rich))
223
+ if (JSON.stringify(nativeRichTextToProduct(editor.document as DocumentEditorBlock[], rich)) !== JSON.stringify(next.content)) throw new Error('client-comment-native-unverified')
224
+ record.current = next; input.current++
225
+ } finally { suppress.current = false }
226
+ if (!operation) await drafts.discard(candidate)
227
+ return next
228
+ }
229
+ const discardActive = async (candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<boolean> => {
230
+ if (!drafts) return false
231
+ const own = record.current
232
+ if (!own || own.id !== candidate.id || own.revision !== candidate.revision) return false
233
+ return discardNativeCommentDraft(drafts, candidate, operation, nativeGuard(), () => {
234
+ suppress.current = true
235
+ try { editor.replaceBlocks(editor.document, [{ type: 'paragraph', content: [] }]); record.current = undefined; input.current++ }
236
+ finally { suppress.current = false }
237
+ })
238
+ }
239
+ const discard = async (candidate: CommentDraftCandidate) => { await drafts?.discardProposal(candidate) }
240
+ return <div onCompositionStart={() => composition(true)} onCompositionEnd={() => composition(false)}>
241
+ <CommentComposer editor={editor}>
242
+ <PmSelect label={t.stepCommentStep} value={stepId ?? ''} disabled={busy || !empty} onChange={event => onSelect(event.currentTarget.value || undefined)}>
243
+ <option value="">{t.stepCommentWhole}</option>
244
+ {section?.stepOrder.map((id, index) => <option key={id} value={id}>{t.stepCommentOption(index + 1, document?.steps[id]?.title ?? '')}</option>)}
245
+ </PmSelect>
246
+ </CommentComposer>
247
+ {failure && <PmNotice tone="warn">{t.stepCommentFailed}</PmNotice>}
248
+ {draftsState.failed && <PmNotice tone="warn">{t.commentBackupFailed}</PmNotice>}
249
+ {candidates.length > 0 && <DraftChoices candidates={candidates} preview disabled={busy} canRecover={() => store.draftTargetState(target) === 'current'}
250
+ unavailableMessage={t.commentTargetUnavailable} onRecover={async candidate => { await recover(candidate) }} onDiscard={discard} />}
251
+ </div>
252
+ }
@@ -0,0 +1,34 @@
1
+ import type { AgentActivity, TeachingDocument } from '@lincyaw/kernel'
2
+ import type { DocumentProjection } from './projection.ts'
3
+
4
+ /** Decorative attributes only: canonical IDs resolve through the editor's existing projection. */
5
+ export function markAgentTargets(root: HTMLElement, projection: DocumentProjection, document: TeachingDocument, activities: readonly AgentActivity[]): () => void {
6
+ const marked = new Set<HTMLElement>()
7
+ const mark = (element: HTMLElement | null, state: AgentActivity['state']) => {
8
+ if (!element || marked.has(element)) return
9
+ element.dataset.pmAgentTarget = state; marked.add(element)
10
+ }
11
+ for (const activity of [...activities].sort((a, b) => Number(b.state === 'running') - Number(a.state === 'running'))) {
12
+ let found = false
13
+ for (const target of activity.targets) {
14
+ let targetFound = false
15
+ if (target.block) for (const [native, owner] of projection.owners) {
16
+ if (owner !== target.block) continue
17
+ const element = root.querySelector<HTMLElement>(`[data-id="${CSS.escape(native)}"]`)
18
+ if (element) { mark(element, activity.state); targetFound = true }
19
+ }
20
+ if (target.step) {
21
+ const field = root.querySelector<HTMLElement>(`[data-step-narration="${CSS.escape(target.step)}"]`)
22
+ if (field) targetFound = true // The shared narration component owns its decorative attribute.
23
+ }
24
+ const section = target.section ?? (target.step ? document.steps[target.step]?.sectionId : undefined)
25
+ if (!targetFound && section) {
26
+ const heading = root.querySelector<HTMLElement>(`[data-document-section="${CSS.escape(section)}"]`)
27
+ if (heading) { mark(heading, activity.state); targetFound = true }
28
+ }
29
+ found ||= targetFound
30
+ }
31
+ if (!found) mark(root, activity.state)
32
+ }
33
+ return () => { for (const element of marked) delete element.dataset.pmAgentTarget }
34
+ }
@@ -35,6 +35,7 @@ export const BLOCKNOTE_MESSAGES: Record<Locale, Overrides<Dictionary>> = {
35
35
  file_panel: { upload: { file_placeholder: kinds('上传图片', '上传视频', '上传音频', '上传文件'), upload_error: '无法上传文件' }, embed: { embed_button: kinds('嵌入图片', '嵌入视频', '嵌入音频', '嵌入文件'), url_placeholder: '输入网址' } },
36
36
  link_toolbar: { delete: { tooltip: '移除链接' }, edit: { text: '编辑链接' }, open: { tooltip: '在新标签页中打开' }, form: { title_placeholder: '链接文字', url_placeholder: '链接地址' } },
37
37
  comments: {
38
+ save_button_text: '发布',
38
39
  discard_pending_comment: '要放弃这条批注吗?',
39
40
  actions: { add_reaction: '添加回应', edit_comment: '编辑批注', delete_comment: '删除批注', more_actions: '更多' },
40
41
  },
@@ -70,6 +71,7 @@ export const BLOCKNOTE_MESSAGES: Record<Locale, Overrides<Dictionary>> = {
70
71
  file_panel: { upload: { file_placeholder: kinds('Upload Picture', 'Upload Video', 'Upload Audio', 'Upload File'), upload_error: 'Couldn’t upload the file' }, embed: { embed_button: kinds('Embed Picture', 'Embed Video', 'Embed Audio', 'Embed File'), url_placeholder: 'Enter an address' } },
71
72
  link_toolbar: { delete: { tooltip: 'Remove Link' }, edit: { text: 'Edit Link' }, open: { tooltip: 'Open in New Tab' }, form: { title_placeholder: 'Link text', url_placeholder: 'Link address' } },
72
73
  comments: {
74
+ save_button_text: 'Post',
73
75
  discard_pending_comment: 'Discard this comment?',
74
76
  actions: { add_reaction: 'Add Reaction', edit_comment: 'Edit Comment', delete_comment: 'Delete Comment', more_actions: 'More' },
75
77
  },
@@ -1,58 +1,78 @@
1
1
  import type { AuthoringClientAction, AuthoringClientActionResult, ClientCommentDraftReference } from '@lincyaw/kernel'
2
2
  import { draftContentHash } from '../authoring-draft-fragment.ts'
3
3
  import { commentDraftReference } from './comment-draft-inspection.ts'
4
- import { isNewCommentDraft } from './comment-drafts.ts'
5
- import type { CommentDrafts } from './comment-drafts.ts'
4
+ import type { CommentDrafts, CommentDraftCandidate, CommentDraftOperation } from './comment-drafts.ts'
5
+
6
+ /** Native views call this same guarded retirement before clearing their visible form state. */
7
+ export async function discardNativeCommentDraft(drafts: CommentDrafts, candidate: CommentDraftCandidate, operation: CommentDraftOperation | undefined, guard: () => void, clear: () => void): Promise<boolean> {
8
+ const current = () => { operation?.signal?.throwIfAborted(); operation?.guard?.(); guard() }
9
+ current()
10
+ if (!await drafts.discard(candidate, { signal: operation?.signal, guard: current })) return false
11
+ current(); clear(); return true
12
+ }
6
13
 
7
14
  const sameReference = (a: ClientCommentDraftReference | null, b: ClientCommentDraftReference | null): boolean => a === null || b === null ? a === b
8
15
  : a.id === b.id && a.revision === b.revision && a.token === b.token
9
16
 
10
17
  /** The native composer, rather than its backup, acknowledges actual editor adoption. */
11
18
  export async function mutateCommentDrafts(drafts: CommentDrafts, action: Extract<AuthoringClientAction, { type: 'comment-drafts.restore' | 'comment-drafts.discard' }>, signal: AbortSignal, owned: () => void, fits: (result: AuthoringClientActionResult) => boolean): Promise<AuthoringClientActionResult> {
12
- const read = await drafts.readForAgent(signal, action.draft), candidate = read.candidates[0]!
19
+ const input = drafts.inputGuard()
20
+ const readBeforeMutation = async (reference: ClientCommentDraftReference) => {
21
+ for (let attempt = 0; ; attempt++) {
22
+ signal.throwIfAborted(); owned(); input()
23
+ try { const value = await drafts.readForAgent(signal, reference); signal.throwIfAborted(); owned(); input(); return value }
24
+ catch (error) {
25
+ signal.throwIfAborted(); owned(); input()
26
+ if (attempt >= 3 || !(error instanceof Error) || error.message !== 'client-comment-drafts-changed') throw error
27
+ }
28
+ }
29
+ }
30
+ const read = await readBeforeMutation(action.draft), candidate = read.candidates[0]!
13
31
  owned()
14
32
  if (action.type === 'comment-drafts.discard') {
15
- const guard = () => { signal.throwIfAborted(); owned(); if (drafts.targetActive(candidate.target) || candidate.composing || candidate.pending) throw new Error('client-comment-draft-needs-human') }
33
+ const guard = () => { signal.throwIfAborted(); owned(); if (!drafts.canDiscard(candidate)) throw new Error('client-comment-draft-needs-human') }
16
34
  const result: AuthoringClientActionResult = { type: action.type, family: 'comment', draft: action.draft, discarded: true }
17
35
  guard()
18
36
  if (!fits(result)) throw new Error('client-comment-result-too-large')
19
- if (!await drafts.discard(action.draft, { signal, guard })) throw new Error('client-comment-drafts-changed')
20
- guard()
37
+ if (!await drafts.discardProposal(candidate, { signal, guard })) throw new Error('client-comment-drafts-changed')
38
+ signal.throwIfAborted(); owned()
21
39
  return result
22
40
  }
23
- if (isNewCommentDraft(candidate.target) || candidate.composing || candidate.pending || candidate.storage !== 'durable') throw new Error('client-comment-draft-needs-human')
24
- const composer = drafts.composer(action.composerId), choice = await drafts.restoreChoice(candidate, signal)
25
- owned()
26
- if (!composer?.restore || choice?.composerId !== action.composerId || !sameReference(choice.expectedCurrent, action.expectedCurrent)) throw new Error('client-comment-composer-unavailable')
41
+ if (candidate.composing || candidate.pending || candidate.storage !== 'durable') throw new Error('client-comment-draft-needs-human')
42
+ const choice = await drafts.restoreChoice(candidate, signal)
43
+ owned(); input()
44
+ if (!choice || action.composerId !== undefined && (choice.composerId !== action.composerId || !sameReference(choice.expectedCurrent, action.expectedCurrent ?? null))) throw new Error('client-comment-composer-unavailable')
45
+ const { composerId, expectedCurrent } = choice, composer = drafts.composer(composerId)
46
+ if (!composer?.restore) throw new Error('client-comment-composer-unavailable')
27
47
  const previous = composer.snapshot().record
28
48
  if (previous) {
29
- if (!action.expectedCurrent) throw new Error('client-comment-drafts-changed')
30
- const current = await drafts.readForAgent(signal, action.expectedCurrent)
49
+ if (!expectedCurrent) throw new Error('client-comment-drafts-changed')
50
+ const current = await readBeforeMutation(expectedCurrent)
31
51
  owned()
32
52
  if (current.candidates[0]?.storage !== 'durable') throw new Error('client-comment-draft-needs-human')
33
- } else if (action.expectedCurrent !== null) throw new Error('client-comment-drafts-changed')
53
+ } else if (expectedCurrent !== null) throw new Error('client-comment-drafts-changed')
34
54
  const guard = () => {
35
55
  signal.throwIfAborted(); owned()
36
56
  const state = composer.snapshot()
37
- if (!drafts.ownersKnown || drafts.composer(action.composerId) !== composer || state.record !== previous || !state.available || state.composing || composer.targetState() === 'unavailable') throw new Error('client-comment-composer-changed')
57
+ if (!drafts.ownersKnown || drafts.composer(composerId) !== composer || state.record !== previous || !state.available || state.composing || composer.targetState(candidate.target) === 'unavailable') throw new Error('client-comment-composer-changed')
38
58
  }
39
59
  guard()
40
- const targetState = composer.targetState()
60
+ const targetState = composer.targetState(candidate.target)
41
61
  if (targetState === 'unavailable') throw new Error('client-comment-composer-unavailable')
42
- if (!fits({ type: action.type, family: 'comment', draft: action.draft, composerId: action.composerId,
43
- restored: { id: '0'.repeat(36), revision: 1, token: '0'.repeat(64) }, preservedCurrent: action.expectedCurrent, targetState })) throw new Error('client-comment-result-too-large')
62
+ if (!fits({ type: action.type, family: 'comment', draft: action.draft, composerId,
63
+ restored: { id: '0'.repeat(36), revision: 1, token: '0'.repeat(64) }, preservedCurrent: expectedCurrent, targetState })) throw new Error('client-comment-result-too-large')
44
64
  const record = await composer.restore(candidate, { signal, guard })
45
65
  if (!record) throw new Error('client-comment-native-unverified')
46
66
  const adopted = () => {
47
67
  signal.throwIfAborted(); owned()
48
68
  const state = composer.snapshot()
49
- if (!drafts.ownersKnown || drafts.composer(action.composerId) !== composer || state.record !== record || !state.available || state.composing || !drafts.owns(record)) throw new Error('client-comment-composer-changed')
69
+ if (!drafts.ownersKnown || drafts.composer(composerId) !== composer || state.record !== record || !state.available || state.composing || !drafts.owns(record)) throw new Error('client-comment-composer-changed')
50
70
  }
51
71
  adopted()
52
72
  const token = await draftContentHash(JSON.stringify(record))
53
73
  adopted()
54
- const result: AuthoringClientActionResult = { type: action.type, family: 'comment', draft: action.draft, composerId: action.composerId,
55
- restored: commentDraftReference({ ...record, token, storage: 'durable' }), preservedCurrent: action.expectedCurrent, targetState }
74
+ const result: AuthoringClientActionResult = { type: action.type, family: 'comment', draft: action.draft, composerId,
75
+ restored: commentDraftReference({ ...record, token, storage: 'durable' }), preservedCurrent: expectedCurrent, targetState }
56
76
  if (!fits(result)) throw new Error('client-comment-result-too-large')
57
77
  return result
58
78
  }
@@ -9,7 +9,7 @@ export const commentDraftReference = (value: CommentDraftCandidate) => ({ id: va
9
9
  export function commentDraftMetadata(value: CommentDraftCandidate, drafts: CommentDrafts): ClientCommentDraftMetadata {
10
10
  const target = value.target
11
11
  return { draft: commentDraftReference(value), kind: isNewCommentDraft(target) ? 'create' : target.commentId ? 'edit' : 'reply', storage: value.storage,
12
- updatedAt: value.updatedAt, baseVersion: value.version, composing: value.composing, pendingSubmission: Boolean(value.pending), ownersKnown: drafts.ownersKnown, active: drafts.activeRecord(value), discardable: !value.composing && !value.pending && !drafts.targetActive(value.target),
12
+ updatedAt: value.updatedAt, baseVersion: value.version, composing: value.composing, pendingSubmission: Boolean(value.pending), ownersKnown: drafts.ownersKnown, active: drafts.activeRecord(value), discardable: drafts.canDiscard(value),
13
13
  ...isNewCommentDraft(target) ? {} : { threadId: target.threadId, ...target.commentId ? { commentId: target.commentId } : {} } }
14
14
  }
15
15
 
@@ -17,7 +17,7 @@ export async function inspectCommentDrafts(drafts: CommentDrafts, action: Extrac
17
17
  const read = await drafts.readForAgent(signal, action.type === 'comment-drafts.read' ? action.draft : undefined)
18
18
  const current = () => { signal.throwIfAborted(); if (drafts.revision !== read.revision) throw new Error('client-comment-drafts-changed') }
19
19
  if (action.type === 'comment-drafts.inspect') {
20
- const values = await Promise.all(read.candidates.map(async value => { const restore = await drafts.restoreChoice(value, signal); return { ...commentDraftMetadata(value, drafts), ...restore ? { restore } : {} } })), token = await hash(JSON.stringify({ values, coverage: read.coverage, skippedInvalid: read.skippedInvalid }))
20
+ const values = await Promise.all(read.candidates.map(async value => { const restore = await drafts.restoreChoice(value, signal); return { ...commentDraftMetadata(value, drafts), ...restore ? { restorable: true as const, ...action.details ? { restore } : {} } : {} } })), token = await hash(JSON.stringify({ values, coverage: read.coverage, skippedInvalid: read.skippedInvalid }))
21
21
  current()
22
22
  if (action.cursor && action.cursor.token !== token) throw new Error('client-comment-drafts-changed')
23
23
  const start = action.cursor ? values.findIndex(value => value.draft.id === action.cursor!.after) + 1 : 0