@lincyaw/workbench 0.2.0-rc.53 → 0.2.0-rc.54

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workbench",
3
- "version": "0.2.0-rc.53",
3
+ "version": "0.2.0-rc.54",
4
4
  "description": "Presmium's workbench panels in React (the documents, a document edited on its rendered page with comments and version history) with the workspace service's client and the preview protocol's workbench side; @lincyaw/dsh places them in presmium studio (experimental)",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -55,8 +55,8 @@
55
55
  "@tiptap/pm": "3.32.0",
56
56
  "katex": "0.18.10",
57
57
  "react-resizable-panels": "4.14.5",
58
- "@lincyaw/design": "1.0.0-rc.53",
59
- "@lincyaw/kernel": "1.0.0-rc.53"
58
+ "@lincyaw/design": "1.0.0-rc.54",
59
+ "@lincyaw/kernel": "1.0.0-rc.54"
60
60
  },
61
61
  "peerDependencies": {
62
62
  "react": "^18.3.1",
@@ -67,6 +67,6 @@
67
67
  "@types/react-dom": "18.3.7",
68
68
  "react": "^18.3.1",
69
69
  "react-dom": "^18.3.1",
70
- "@lincyaw/compiler": "1.0.0-rc.53"
70
+ "@lincyaw/compiler": "1.0.0-rc.54"
71
71
  }
72
72
  }
package/src/approvals.tsx CHANGED
@@ -6,6 +6,11 @@ import { WorkspaceServerError } from './workspace-client.ts'
6
6
 
7
7
  interface Pending { id: string, request: ApprovalRequest }
8
8
 
9
+ /** Approval controls belong to the operation's editing context, including their portaled panel. */
10
+ export function isApprovalTarget(target: EventTarget | null | undefined): boolean {
11
+ return target instanceof Element && Boolean(target.closest('[data-approval-trigger], .pmw-approvals'))
12
+ }
13
+
9
14
  /**
10
15
  * The host's operations waiting for the author, such as an external MCP client's import: shown only while one is
11
16
  * pending, answered here as in the viewer's "Approvals". The host times them out; a late answer is reported, not retried.
@@ -38,7 +43,7 @@ export function WorkbenchApprovals({ density = 'compact' }: { density?: 'compact
38
43
  }
39
44
  return (
40
45
  <PmPopover open={open} onOpenChange={setOpen} label={t.approvalsTitle} name="pmw-approvals" trigger={
41
- <PmButton variant="accent" density={density}>{t.approvals(pending.length)}</PmButton>
46
+ <PmButton data-approval-trigger="" variant="accent" density={density}>{t.approvals(pending.length)}</PmButton>
42
47
  }>
43
48
  <h2 className="pmw-approvals__heading">{t.approvalsTitle}</h2>
44
49
  <ul className="pmw-approvals__list">
@@ -333,12 +333,12 @@ export function PmDialog({ open, label, closeLabel, name, actions, description,
333
333
  }
334
334
 
335
335
  /** A non-modal floating panel on its trigger, with the shared `pm-ui-popover` surface (host's PmPopover for React pages). */
336
- export function PmPopover({ open, label, name, placement = 'below-end', trigger, onOpenChange, children }: { open: boolean, label: string, name?: string, placement?: PopoverPlacement, trigger: ReactNode, onOpenChange(open: boolean): void, children?: ReactNode }) {
336
+ export function PmPopover({ open, label, name, placement = 'below-end', trigger, onOpenChange, onInteractOutside, children }: { open: boolean, label: string, name?: string, placement?: PopoverPlacement, trigger: ReactNode, onOpenChange(open: boolean): void, onInteractOutside?: ComponentProps<typeof Popover.Content>['onInteractOutside'], children?: ReactNode }) {
337
337
  return (
338
338
  <Popover.Root open={open} onOpenChange={onOpenChange}>
339
339
  <Popover.Trigger asChild>{trigger}</Popover.Trigger>
340
340
  <Popover.Portal>
341
- <Popover.Content className={cls('pm-ui-popover', 'pm-ui-floating', 'pm-ui', name)} aria-label={label} {...placementOf(placement)} sideOffset={6} collisionPadding={16} onEscapeKeyDown={event => event.stopPropagation()}>
341
+ <Popover.Content className={cls('pm-ui-popover', 'pm-ui-floating', 'pm-ui', name)} aria-label={label} {...placementOf(placement)} sideOffset={6} collisionPadding={16} onInteractOutside={onInteractOutside} onEscapeKeyDown={event => event.stopPropagation()}>
342
342
  {children}
343
343
  </Popover.Content>
344
344
  </Popover.Portal>
@@ -8,11 +8,14 @@ import { FloatingThreadController, getReferenceText, Thread, useBlockNoteEditor,
8
8
  import type { ComponentProps, ThreadProps } from '@blocknote/react'
9
9
  import type { Locale } from '../messages.ts'
10
10
  import { PmButton, PmEmpty, PmNotice, PmSelect } from '../components.tsx'
11
+ import { isApprovalTarget } from '../approvals.tsx'
11
12
  import { useWorkbenchState } from '../context.tsx'
12
13
  import { enterSubmits } from './comments.ts'
13
14
  import type { DocumentCommentEditorHandle, DocumentThreadStore } from './comments.ts'
14
15
  import type { CommentDrafts, CommentDraftCandidate, CommentDraftRecord, CommentDraftReference, CommentDraftOperation } from './comment-drafts.ts'
15
- import { isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
16
+ import { commentDraftBaseline, isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
17
+ import { discardNativeCommentDraft } from './comment-draft-actions.ts'
18
+ import { waitForDraft } from '../document-draft-store.ts'
16
19
  import { createRichProjection, fallbackText, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
17
20
  import { commentEditorSchema } from './schema.tsx'
18
21
  import type { DocumentEditorBlock } from './schema.tsx'
@@ -164,7 +167,7 @@ export function DocumentThreadsSidebar({ children }: { children?: ReactNode }) {
164
167
  const focus = (id: string, event: FocusEvent) => { if (!(event.target as HTMLElement).closest('.bn-action-toolbar')) comments.selectThread(id) }
165
168
  const blur = (event: FocusEvent) => {
166
169
  const next = event.relatedTarget
167
- if (!next || next.closest('.bn-action-toolbar')) return
170
+ if (!next || isApprovalTarget(next) || next.closest('.bn-action-toolbar')) return
168
171
  const parent = next.closest('.bn-thread')
169
172
  if (!parent || !(event.target instanceof Node) || !parent.contains(event.target)) comments.selectThread(undefined)
170
173
  }
@@ -291,7 +294,7 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
291
294
  || props.editor.prosemirrorState.selection !== native.selection || context.getPositionToken?.() !== position || record.current !== own
292
295
  || context.store.draftTargetState(target) === 'unavailable') throw new Error('client-comment-composer-changed')
293
296
  }
294
- if (own && !await drafts.confirm(own)) return
297
+ if (own && !await waitForDraft(drafts.confirm(own), operation?.signal)) return
295
298
  owns()
296
299
  const value = await drafts.recover(candidate, target, version, { signal: operation?.signal, guard: owns })
297
300
  if (!value) return
@@ -307,11 +310,30 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
307
310
  if (!operation) await drafts.discard(candidate)
308
311
  return value
309
312
  }
313
+ const discardActive = async (candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<boolean> => {
314
+ const own = record.current, version = context?.store.version, before = input.current, native = props.editor.prosemirrorState, position = context?.getPositionToken?.()
315
+ if (!drafts || !context || !target || !version || !own || own.id !== candidate.id || own.revision !== candidate.revision) return false
316
+ const guard = () => {
317
+ context.store.beforeAction?.()
318
+ if (!active.current || !current.current.editable || context.store.version !== version || composing.current || submitting.current || input.current !== before || record.current !== own
319
+ || props.editor.prosemirrorView.isDestroyed || props.editor.prosemirrorView.composing || props.editor.prosemirrorState.doc !== native.doc
320
+ || props.editor.prosemirrorState.selection !== native.selection || context.getPositionToken?.() !== position) throw new Error('client-comment-composer-changed')
321
+ }
322
+ const saved = target.commentId ? context.store.threadSnapshot(target.threadId)?.comments.find(value => value.id === target.commentId && !value.deletedAt) : undefined
323
+ if (target.commentId && !saved?.content) return false
324
+ return discardNativeCommentDraft(drafts, candidate, operation, guard, () => {
325
+ suppress.current = true
326
+ try {
327
+ props.editor.replaceBlocks(props.editor.document, saved?.content ? productRichTextToNative(saved.content, rich.current) : [{ type: 'paragraph', content: [] }])
328
+ record.current = undefined; input.current++; handle?.restoreBaseline(saved ? commentDraftBaseline(saved) : undefined); setRevision(value => value + 1)
329
+ } finally { suppress.current = false }
330
+ })
331
+ }
310
332
  useLayoutEffect(() => {
311
333
  if (!drafts || !target || !props.editable) return
312
334
  return drafts.registerComposer({ id: composerId.current, target,
313
335
  snapshot: () => { const available = active.current && current.current.editable && !submitting.current && !props.editor.prosemirrorView.isDestroyed; return { record: record.current, composing: composing.current || available && props.editor.prosemirrorView.composing, available } },
314
- targetState: () => context?.store.draftTargetState(target) ?? 'unavailable', restore: recover })
336
+ targetState: () => context?.store.draftTargetState(target) ?? 'unavailable', restore: recover, discard: discardActive })
315
337
  }, [drafts, handle, props.editor, props.editable])
316
338
  const composition = (value: boolean) => {
317
339
  composing.current = value
@@ -325,7 +347,7 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
325
347
  <MantineCommentEditor {...props} />
326
348
  {recoveryFailure && <PmNotice tone="warn">{t.commentRecoveryChanged}</PmNotice>}
327
349
  {failure && <PmNotice tone="danger">{failure === 'changed' ? t.commentChanged : t.commentUnavailable}</PmNotice>}
328
- {drafts && props.editable && <DraftChoices candidates={candidates} disabled={composing.current || submitting.current} onRecover={async candidate => { const captured = handle, owner = recoveryOwner.current; setRecoveryFailure(false); try { await recover(candidate) } catch { if (active.current && current.current.editable && currentHandle.current === captured && recoveryOwner.current === owner) setRecoveryFailure(true) } }} onDiscard={async candidate => { await drafts.discard(candidate) }} />}
350
+ {drafts && props.editable && <DraftChoices candidates={candidates} disabled={composing.current || submitting.current} onRecover={async candidate => { const captured = handle, owner = recoveryOwner.current; setRecoveryFailure(false); try { await recover(candidate) } catch { if (active.current && current.current.editable && currentHandle.current === captured && recoveryOwner.current === owner) setRecoveryFailure(true) } }} onDiscard={async candidate => { await drafts.discardProposal(candidate) }} />}
329
351
  {drafts && props.editable && state.failed && !context?.sidebar && <PmNotice tone="warn">{t.commentBackupFailed}</PmNotice>}
330
352
  </div>
331
353
  }
@@ -9,8 +9,11 @@ import { isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
9
9
  import { TextSelection } from '@tiptap/pm/state'
10
10
  import { COMMENT_EDITOR_CONTEXT, DraftChoices } from './DocumentComments.tsx'
11
11
  import { isNewCommentDraft, sameCommentDraftTarget } 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'
12
15
  import { enterSubmits } from './comments.ts'
13
- import type { CommentDraftCandidate, CommentDraftRecord, CommentDraftReference, NewCommentDraftTarget } from './comment-drafts.ts'
16
+ import type { CommentDraftCandidate, CommentDraftRecord, CommentDraftReference, CommentDraftOperation, NewCommentDraftTarget } from './comment-drafts.ts'
14
17
  import { createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
15
18
  import type { DocumentEditorBlock, NativeDocumentEditor } from './schema.tsx'
16
19
  import { PmNotice } from '../components.tsx'
@@ -26,13 +29,18 @@ interface ComposerBinding {
26
29
  input: number
27
30
  composing: boolean
28
31
  active: boolean
32
+ submitting: boolean
33
+ adopting?: boolean
34
+ previous?: ComposerBinding
35
+ adoption?: { guard(): void, finish(record?: CommentDraftRecord): void }
29
36
  }
30
- interface PreparedDraft { record: CommentDraftRecord, origin: CommentDraftReference, doc: NativeDocumentEditor['prosemirrorState']['doc'], selection: NativeDocumentEditor['prosemirrorState']['selection'], version: string }
37
+ interface PreparedDraft { record: CommentDraftRecord, origin?: CommentDraftReference, previous?: ComposerBinding, doc: NativeDocumentEditor['prosemirrorState']['doc'], selection: NativeDocumentEditor['prosemirrorState']['selection'], version: string, adoption?: ComposerBinding['adoption'], canUse(editor: CommentEditor): boolean }
31
38
  interface NewDraftOwner {
32
39
  editor: NativeDocumentEditor
33
40
  latest: { current: ComposerBinding | undefined }
34
41
  prepared: { current: PreparedDraft | undefined }
35
- restore(candidate: CommentDraftCandidate, current?: () => boolean): Promise<void>
42
+ generation: number
43
+ restore(candidate: CommentDraftCandidate, current?: () => boolean, operation?: CommentDraftOperation): Promise<CommentDraftRecord | undefined>
36
44
  failure?: boolean
37
45
  }
38
46
  const NEW_DRAFT_OWNER = createContext<NewDraftOwner | undefined>(undefined)
@@ -43,27 +51,33 @@ const emptyState = { candidates: [], pending: false, failed: false, reading: fal
43
51
  export function NewCommentDraftProvider({ children }: { children?: ReactNode }) {
44
52
  const context = useContext(COMMENT_EDITOR_CONTEXT), editor = useBlockNoteEditor() as NativeDocumentEditor, comments = useExtension(CommentsExtension)
45
53
  const latest = useRef<ComposerBinding>(), prepared = useRef<PreparedDraft>(), active = useRef(true), operation = useRef(0)
46
- const [failure, setFailure] = useState(false)
47
- useEffect(() => { active.current = true; return () => { active.current = false; ++operation.current; prepared.current = undefined; latest.current = undefined } }, [editor])
48
- const restore = async (candidate: CommentDraftCandidate, current = () => true) => {
54
+ const composerId = useRef(randomUUID()), handoff = useRef<() => void>()
55
+ const [failure, setFailure] = useState(false), [generation, setGeneration] = useState(0)
56
+ useEffect(() => { active.current = true; return () => { active.current = false; ++operation.current; handoff.current?.(); prepared.current = undefined; latest.current = undefined } }, [editor])
57
+ const restore = async (candidate: CommentDraftCandidate, current = () => true, action?: CommentDraftOperation): Promise<CommentDraftRecord | undefined> => {
49
58
  const store = context?.store, drafts = store?.drafts, target = candidate.target
50
59
  if (!store || !drafts || !isNewCommentDraft(target) || candidate.storage !== 'durable' || editor.prosemirrorView.isDestroyed || editor.prosemirrorView.composing) return
51
- const binding = latest.current
60
+ const binding = latest.current?.active ? latest.current : undefined
52
61
  if (binding?.record && !drafts.owns(binding.record)) binding.record = undefined
62
+ handoff.current?.()
53
63
  const request = ++operation.current, input = binding?.input, record = binding?.record
54
64
  try {
55
65
  store.beforeAction?.()
56
66
  if (!store.auth.canCreateThread() || store.draftTargetState(target) !== 'current' || !store.newDraftPositions(target, editor)) { setFailure(true); return }
57
- const version = store.version, native = editor.prosemirrorState, extensionState = comments.store.state, position = context.getPositionToken?.()
58
- if (!version || binding?.composing || binding?.editor.prosemirrorView.composing) return
67
+ const version = store.version, native = editor.prosemirrorState, extensionState = comments.store.state, position = context.getPositionToken?.(), form = binding?.editor.prosemirrorState
68
+ if (!version || binding?.composing || binding?.submitting || binding?.editor.prosemirrorView.composing) return
59
69
  const owns = () => active.current && current() && request === operation.current && !editor.prosemirrorView.isDestroyed && !editor.prosemirrorView.composing && store.version === version
60
70
  && context.getPositionToken?.() === position
61
71
  && editor.prosemirrorState.doc === native.doc && editor.prosemirrorState.selection === native.selection && comments.store.state === extensionState
62
72
  && (!binding || latest.current === binding && binding.input === input && binding.record === record && !binding.composing)
63
- if (record && !await drafts.confirm(record) || !owns()) return
64
- const nextTarget = { ...target, intentId: randomUUID() }, next = await drafts.recover(candidate, nextTarget, version)
73
+ const guard = () => { action?.signal?.throwIfAborted(); action?.guard?.(); if (!owns()) throw new Error('client-comment-composer-changed') }
74
+ guard()
75
+ if (record && !await waitForDraft(drafts.confirm(record), action?.signal)) return
76
+ guard()
77
+ const nextTarget = { ...target, intentId: randomUUID() }, next = await drafts.recover(candidate, nextTarget, version, { signal: action?.signal, guard })
65
78
  store.beforeAction?.()
66
- if (!next || !owns()) return
79
+ if (!next) return
80
+ guard()
67
81
  const positions = store.newDraftPositions(nextTarget, editor)
68
82
  if (!positions) { setFailure(true); return }
69
83
  comments.stopPendingComment()
@@ -71,14 +85,46 @@ export function NewCommentDraftProvider({ children }: { children?: ReactNode })
71
85
  editor.focus()
72
86
  editor.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, positions.from, positions.to)).scrollIntoView())
73
87
  // The public controller creates the actual editor; this is only its strictly committed handoff.
74
- prepared.current = { record: next, origin: candidate, doc: editor.prosemirrorState.doc, selection: editor.prosemirrorState.selection, version }
88
+ let finish!: (record?: CommentDraftRecord) => void
89
+ const adopted = new Promise<CommentDraftRecord | undefined>(resolve => { finish = resolve })
90
+ const pending: PreparedDraft = { record: next, previous: binding, ...!action ? { origin: candidate } : {}, doc: editor.prosemirrorState.doc, selection: editor.prosemirrorState.selection, version,
91
+ canUse: actual => (!binding || binding.input === input && binding.record === record && !binding.composing && !binding.submitting)
92
+ && (actual === binding?.editor ? !actual.prosemirrorView.isDestroyed && actual.prosemirrorState.doc === form?.doc && actual.prosemirrorState.selection === form?.selection : actual.isEmpty) }
93
+ if (action) {
94
+ let settled = false
95
+ const complete = (value?: CommentDraftRecord) => { if (settled) return; settled = true; if (handoff.current === cancel) handoff.current = undefined; finish(value) }
96
+ const cancel = () => complete()
97
+ handoff.current = cancel
98
+ pending.adoption = { finish: complete, guard: () => {
99
+ action.signal?.throwIfAborted(); store.beforeAction?.()
100
+ const actual = latest.current
101
+ if (!active.current || !current() || request !== operation.current || store.version !== version || editor.prosemirrorView.isDestroyed || editor.prosemirrorView.composing
102
+ || editor.prosemirrorState.doc !== pending.doc || editor.prosemirrorState.selection !== pending.selection || !actual?.active || actual.record !== next || actual.input !== 0
103
+ || actual.composing || actual.submitting || !store.newDraftPositions(nextTarget, editor)) throw new Error('client-comment-composer-changed')
104
+ } }
105
+ }
106
+ prepared.current = pending
75
107
  comments.startPendingComment()
76
- prepared.current.selection = editor.prosemirrorState.selection
108
+ pending.selection = editor.prosemirrorState.selection
109
+ setGeneration(value => value + 1)
77
110
  setFailure(false)
78
111
  context.onDraftRestore?.()
79
- } catch { if (active.current && request === operation.current) setFailure(true) }
112
+ if (action) return await waitForDraft(adopted, action.signal)
113
+ } catch (error) { if (active.current && request === operation.current) setFailure(true); if (action) throw error }
114
+ finally { if (request === operation.current) handoff.current?.() }
80
115
  }
81
- return <NEW_DRAFT_OWNER.Provider value={{ editor, latest, prepared, restore, failure }}>{children}</NEW_DRAFT_OWNER.Provider>
116
+ useLayoutEffect(() => {
117
+ const store = context?.store, drafts = store?.drafts
118
+ if (!store || !drafts) return
119
+ return drafts.registerComposer({ id: composerId.current, target: { kind: 'create', intentId: composerId.current, documentId: store.document.id },
120
+ accepts: target => isNewCommentDraft(target) && Boolean(store.newDraftPositions(target, editor)),
121
+ snapshot: () => { const binding = latest.current?.active ? latest.current : undefined; return { record: binding?.record,
122
+ composing: editor.prosemirrorView.composing || Boolean(binding?.composing || binding?.editor.prosemirrorView.composing),
123
+ available: active.current && !context.readOnly && !editor.prosemirrorView.isDestroyed && !binding?.submitting && store.auth.canCreateThread() } },
124
+ targetState: target => target && isNewCommentDraft(target) && store.newDraftPositions(target, editor) ? 'current' : 'unavailable',
125
+ restore: (candidate, action) => restore(candidate, () => active.current, action) })
126
+ }, [context?.store, context?.readOnly, editor])
127
+ return <NEW_DRAFT_OWNER.Provider value={{ editor, latest, prepared, generation, restore, failure }}>{children}</NEW_DRAFT_OWNER.Provider>
82
128
  }
83
129
 
84
130
  /**
@@ -107,7 +153,8 @@ export function DocumentNewCommentController() {
107
153
  const position = useEditorState({ editor, selector: ({ editor }) => pendingComment ? { from: editor.prosemirrorState.selection.from, to: editor.prosemirrorState.selection.to } : undefined })
108
154
  const floating = useMemo(() => commentFloating(), [])
109
155
  return <PositionPopover position={position} focusManagerProps={{ disabled: true }} elementProps={{ style: { zIndex: COMPOSER_LAYER } }}
110
- useFloatingOptions={{ placement: 'bottom', ...floating, open: pendingComment, onOpenChange(open) {
156
+ useFloatingOptions={{ placement: 'bottom', ...floating, open: pendingComment, onOpenChange(open, event?: Event) {
157
+ if (!open && isApprovalTarget(event?.target ?? document.activeElement)) return
111
158
  if (open || !owner || owner.latest.current?.composing || owner.latest.current?.editor.prosemirrorView.composing) return
112
159
  try { context?.store.beforeAction?.() } catch { return }
113
160
  comments.stopPendingComment()
@@ -127,15 +174,20 @@ function DocumentNewCommentComposer({ newCommentEditor }: { newCommentEditor: Co
127
174
  try {
128
175
  context.store.beforeAction?.()
129
176
  const restored = owner.prepared.current, prepared = restored && restored.version === context.store.version
130
- && restored.doc === owner.editor.prosemirrorState.doc && restored.selection === owner.editor.prosemirrorState.selection && newCommentEditor.isEmpty
177
+ && restored.doc === owner.editor.prosemirrorState.doc && restored.selection === owner.editor.prosemirrorState.selection && restored.canUse(newCommentEditor)
131
178
  && isNewCommentDraft(restored.record.target) && context.store.newDraftPositions(restored.record.target, owner.editor) ? restored : undefined
179
+ if (restored && !prepared && owner.latest.current?.editor === newCommentEditor) {
180
+ const retained = owner.latest.current
181
+ retained.active = true; owner.prepared.current = undefined; restored.adoption?.finish(); setBinding(retained)
182
+ return () => { retained.active = false }
183
+ }
132
184
  const target = prepared && isNewCommentDraft(prepared.record.target) ? prepared.record.target : context.store.newDraftTarget(owner.editor)
133
- const value: ComposerBinding = { target, editor: newCommentEditor, record: prepared?.record, origin: prepared?.origin, input: 0, composing: false, active: true }
134
- if (prepared) owner.prepared.current = undefined
185
+ const value: ComposerBinding = { target, editor: newCommentEditor, record: prepared?.record, origin: prepared?.origin, adoption: prepared?.adoption, previous: prepared?.previous, adopting: Boolean(prepared), input: 0, composing: false, active: true, submitting: false }
186
+ if (restored) { if (!prepared) restored.adoption?.finish(); owner.prepared.current = undefined }
135
187
  owner.latest.current = value; setBinding(value)
136
188
  return () => { value.active = false }
137
189
  } catch { /* The unchanged native form remains available when no authoritative target can be confirmed. */ }
138
- }, [newCommentEditor, context?.store, owner?.editor])
190
+ }, [newCommentEditor, context?.store, owner?.editor, owner?.generation])
139
191
  const value = useMemo(() => ({ ...nativeComponents, Comments: { ...nativeComponents.Comments, Editor: NewCommentEditor } }), [nativeComponents])
140
192
  return <NEW_COMPOSER_BINDING.Provider value={{ binding, ready: () => render(value => value + 1) }}><ComponentsContext.Provider value={value}>
141
193
  <FloatingComposer newCommentEditor={newCommentEditor} />
@@ -150,9 +202,24 @@ function NewCommentEditor(props: ComponentProps['Comments']['Editor']) {
150
202
  const drafts = context?.store.drafts, state = useSyncExternalStore(drafts?.subscribe ?? emptySubscribe, drafts?.snapshot ?? (() => emptyState))
151
203
  useLayoutEffect(() => {
152
204
  if (!binding || !drafts || !context || !owner) return
153
- if (binding.record && props.editor.isEmpty) {
154
- props.editor.replaceBlocks(props.editor.document, productRichTextToNative(binding.record.content, rich))
155
- if (binding.origin) { void drafts.discard(binding.origin); binding.origin = undefined }
205
+ if (binding.record && (props.editor.isEmpty || binding.adopting)) {
206
+ let replaced = false
207
+ try {
208
+ binding.adoption?.guard()
209
+ props.editor.replaceBlocks(props.editor.document, productRichTextToNative(binding.record.content, rich))
210
+ replaced = true
211
+ if (JSON.stringify(nativeRichTextToProduct(props.editor.document as DocumentEditorBlock[], rich)) !== JSON.stringify(binding.record.content)) throw new Error('client-comment-native-unverified')
212
+ binding.adoption?.finish(binding.record); binding.adoption = undefined; binding.adopting = false
213
+ if (binding.origin) { void drafts.discard(binding.origin); binding.origin = undefined }
214
+ } catch {
215
+ binding.adoption?.finish(); binding.adoption = undefined; binding.adopting = false
216
+ const previous = binding.previous
217
+ if (!replaced && previous?.editor === props.editor) {
218
+ binding.target = previous.target; binding.record = previous.record; binding.origin = previous.origin; binding.input = previous.input
219
+ } else binding.record = undefined
220
+ setFailure(true)
221
+ }
222
+ binding.previous = undefined
156
223
  }
157
224
  const original = props.editor.getExtension(CommentEditorSubmitExtension)
158
225
  let guarded: typeof original, stopEnter = () => {}
@@ -164,13 +231,13 @@ function NewCommentEditor(props: ComponentProps['Comments']['Editor']) {
164
231
  const positions = context.store.newDraftPositions(binding.target, owner.editor), selection = owner.editor.prosemirrorState.selection
165
232
  if (!context.store.auth.canCreateThread() || !positions || selection.from !== positions.from || selection.to !== positions.to) { setFailure(true); return }
166
233
  const before = new Set(context.store.getThreads().keys()), record = binding.record
167
- submitting.current = true
234
+ submitting.current = true; binding.submitting = true
168
235
  try {
169
236
  const result = original.submit(), thread = [...context.store.getThreads().values()].find(thread => !before.has(thread.id))
170
237
  const actual = thread && context.store.threadSnapshot(thread.id)
171
238
  if (actual) { drafts.submitted(record, actual.comments[0], actual); binding.record = undefined }
172
239
  await result
173
- } finally { submitting.current = false }
240
+ } finally { submitting.current = false; binding.submitting = false }
174
241
  } catch { setFailure(true) }
175
242
  } }))
176
243
  guarded = props.editor.getExtension(CommentEditorSubmitExtension); composer.ready()
@@ -187,11 +254,26 @@ function NewCommentEditor(props: ComponentProps['Comments']['Editor']) {
187
254
  return () => { stop(); stopEnter(); if (original && guarded && !props.editor.prosemirrorView.isDestroyed && props.editor.getExtension(CommentEditorSubmitExtension) === guarded) props.editor.replaceExtension(guarded, original) }
188
255
  }, [binding, drafts, props.editor])
189
256
  const composerId = useRef(randomUUID())
257
+ const discardActive = async (candidate: CommentDraftCandidate, action?: CommentDraftOperation): Promise<boolean> => {
258
+ if (!binding || !drafts || !context || !owner || !binding.record || binding.record.id !== candidate.id || binding.record.revision !== candidate.revision) return false
259
+ const record = binding.record, input = binding.input, native = props.editor.prosemirrorState, version = context.store.version, position = context.getPositionToken?.()
260
+ const guard = () => {
261
+ context.store.beforeAction?.()
262
+ if (!binding.active || owner.latest.current !== binding || binding.record !== record || binding.input !== input || context.store.version !== version
263
+ || context.getPositionToken?.() !== position || binding.composing || submitting.current || props.editor.prosemirrorView.isDestroyed
264
+ || props.editor.prosemirrorView.composing || props.editor.prosemirrorState.doc !== native.doc || props.editor.prosemirrorState.selection !== native.selection) throw new Error('client-comment-composer-changed')
265
+ }
266
+ return discardNativeCommentDraft(drafts, candidate, action, guard, () => {
267
+ suppress.current = true
268
+ try { props.editor.replaceBlocks(props.editor.document, [{ type: 'paragraph', content: [] }]); binding.record = undefined; binding.origin = undefined; binding.input++ }
269
+ finally { suppress.current = false }
270
+ })
271
+ }
190
272
  useLayoutEffect(() => {
191
273
  if (!binding || !drafts || !context) return
192
274
  return drafts.registerComposer({ id: composerId.current, target: binding.target,
193
275
  snapshot: () => { const available = binding.active && !submitting.current && !props.editor.prosemirrorView.isDestroyed; return { record: binding.record, composing: binding.composing || available && props.editor.prosemirrorView.composing, available } },
194
- targetState: () => context.store.draftTargetState(binding.target) })
276
+ targetState: () => context.store.draftTargetState(binding.target), discard: discardActive })
195
277
  }, [binding, drafts, props.editor])
196
278
  const t = DOCUMENT_EDITOR_MESSAGES[context?.locale ?? 'en']
197
279
  const composition = (value: boolean) => {
@@ -216,10 +298,10 @@ export function DocumentNewCommentRecovery() {
216
298
  if (!drafts || !owner) return null
217
299
  return <>{owner.failure && <PmNotice tone="warn">{t.commentTargetUnavailable}</PmNotice>}<DraftChoices candidates={candidates} preview
218
300
  canRecover={candidate => isNewCommentDraft(candidate.target) && Boolean(context?.store.newDraftPositions(candidate.target, owner.editor))}
219
- unavailableMessage={t.commentTargetUnavailable} onRecover={candidate => owner.restore(candidate, () => active.current)} onDiscard={async candidate => {
301
+ unavailableMessage={t.commentTargetUnavailable} onRecover={async candidate => { await owner.restore(candidate, () => active.current) }} onDiscard={async candidate => {
220
302
  const binding = owner.latest.current, record = binding?.record, input = binding?.input
221
303
  const { token, storage, ...value } = candidate
222
- if (await drafts.discard(candidate) && binding && owner.latest.current === binding && binding.input === input && binding.record === record
304
+ if (await drafts.discardProposal(candidate) && binding && owner.latest.current === binding && binding.input === input && binding.record === record
223
305
  && record && JSON.stringify(record) === JSON.stringify(value)) binding.record = undefined
224
306
  }} /></>
225
307
  }
@@ -4,12 +4,15 @@ import type { BlockNoteEditor } from '@blocknote/core'
4
4
  import { CommentEditorSubmitExtension } from '@blocknote/core/comments'
5
5
  import { components } from '@blocknote/mantine'
6
6
  import { useCreateBlockNote, useDictionary, useEditorState, useThreads } from '@blocknote/react'
7
- import { randomUUID } from '@lincyaw/kernel'
7
+ import { isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
8
8
  import { PmButton, PmIconButton, PmNotice, PmPopover, PmSelect } from '../components.tsx'
9
9
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
10
10
  import { COMMENT_EDITOR_CONTEXT, DraftChoices } from './DocumentComments.tsx'
11
11
  import { isNewCommentDraft, newCommentDraftSignature, sameCommentDraftTarget } from './comment-drafts.ts'
12
- import type { CommentDraftCandidate, CommentDraftRecord, NewCommentDraftTarget } from './comment-drafts.ts'
12
+ import type { CommentDraftCandidate, CommentDraftRecord, CommentDraftOperation, CommentDraftComposer, NewCommentDraftTarget } from './comment-drafts.ts'
13
+ import { discardNativeCommentDraft } from './comment-draft-actions.ts'
14
+ import { waitForDraft } from '../document-draft-store.ts'
15
+ import { isApprovalTarget } from '../approvals.tsx'
13
16
  import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
14
17
  import { commentEditorSchema } from './schema.tsx'
15
18
  import type { DocumentEditorBlock } from './schema.tsx'
@@ -43,24 +46,68 @@ function PlaceCommentButtonContent({ blockId, sectionId, stepId, stepIndex, onPa
43
46
  const threads = useThreads(), workbench = useWorkbench()
44
47
  const t = DOCUMENT_EDITOR_MESSAGES[context.locale]
45
48
  const [open, setOpen] = useState(false), [selected, setSelected] = useState<string | undefined>(stepId)
49
+ const drafts = context.store.drafts, native = useRef<CommentDraftComposer>(), composerId = useRef(randomUUID()), revision = useRef(0)
50
+ const draftState = useSyncExternalStore(drafts?.subscribe ?? subscribeEmpty, drafts?.snapshot ?? (() => emptyDrafts))
51
+ const needed = open || draftState.candidates.some(candidate => isNewCommentDraft(candidate.target) && candidate.target.anchor && isDocumentPlaceAnchor(candidate.target.anchor) && candidate.target.anchor.blockId === blockId)
52
+ const opening = useRef<{ previous?: CommentDraftRecord, ready?(owner?: CommentDraftComposer): void }>()
53
+ const alive = useRef(true)
54
+ const accept = (target: CommentDraftCandidate['target']) => isNewCommentDraft(target) && Boolean(target.anchor && isDocumentPlaceAnchor(target.anchor) && target.anchor.blockId === blockId
55
+ && (target.anchor.stepId === undefined || context.store.document.sections[sectionId]?.stepOrder.includes(target.anchor.stepId)) && context.store.draftTargetState(target) === 'current')
56
+ const ready = useMemo(() => (owner: CommentDraftComposer | undefined) => { native.current = owner; if (owner) opening.current?.ready?.(owner) }, [])
57
+ useLayoutEffect(() => {
58
+ alive.current = true
59
+ if (!drafts || !needed) return
60
+ const restore = async (candidate: CommentDraftCandidate, action: CommentDraftOperation): Promise<CommentDraftRecord | undefined> => {
61
+ if (!accept(candidate.target) || !isNewCommentDraft(candidate.target) || !candidate.target.anchor || !isDocumentPlaceAnchor(candidate.target.anchor)) return
62
+ const before = native.current, previous = before?.snapshot().record, version = context.store.version, request = ++revision.current, targetStep = candidate.target.anchor.stepId
63
+ const guard = () => {
64
+ action.signal?.throwIfAborted(); action.guard?.(); context.store.beforeAction?.()
65
+ if (!alive.current || revision.current !== request || context.store.version !== version || !accept(candidate.target)) throw new Error('client-comment-composer-changed')
66
+ }
67
+ guard()
68
+ if (previous && !await waitForDraft(drafts.confirm(previous), action.signal)) return
69
+ guard()
70
+ let resolve!: (owner?: CommentDraftComposer) => void
71
+ const mounted = new Promise<CommentDraftComposer | undefined>(yes => { resolve = yes })
72
+ const transition = { previous, ready: resolve }; opening.current = transition
73
+ try {
74
+ onPause(); setSelected(targetStep); setOpen(true)
75
+ if (targetStep !== undefined) workbench.observeDocumentStep(sectionId, targetStep)
76
+ // A mounted matching form can be reused; otherwise the keyed native form supplies readiness.
77
+ const same = before && sameCommentDraftTarget(before.target, candidate.target)
78
+ const actual = same ? before : await waitForDraft(mounted, action.signal)
79
+ guard()
80
+ if (!actual?.restore || native.current !== actual || !actual.snapshot().available || actual.snapshot().composing || !same && actual.snapshot().record) return
81
+ const value = await actual.restore(candidate, { signal: action.signal, guard })
82
+ return value
83
+ } finally { if (opening.current === transition) opening.current = undefined }
84
+ }
85
+ const stop = drafts.registerComposer({ id: composerId.current, target: { kind: 'create', intentId: composerId.current, documentId: context.store.document.id }, accepts: accept,
86
+ snapshot: () => { const current = native.current?.snapshot(); return { record: opening.current ? opening.current.previous : current?.record,
87
+ composing: current?.composing ?? false, available: alive.current && !context.readOnly && context.store.auth.canCreateThread() && (current?.available ?? true) } },
88
+ targetState: target => target && accept(target) ? 'current' : 'unavailable', restore })
89
+ return () => { alive.current = false; revision.current++; opening.current?.ready?.(); opening.current = undefined; stop() }
90
+ }, [drafts, context.store, blockId, sectionId, needed])
46
91
  const count = useMemo(() => [...threads.values()].filter(thread => {
47
92
  if (thread.deletedAt || thread.resolved) return false
48
93
  const anchor = context.store.placeAnchorOf(thread.id)
49
94
  return anchor?.blockId === blockId && anchor.stepId === stepId
50
95
  }).length, [threads, context, blockId, stepId])
51
96
  const change = (next: boolean) => {
97
+ revision.current++; opening.current?.ready?.()
52
98
  setOpen(next)
53
99
  if (next) setSelected(stepId)
54
100
  }
55
101
  return <PmPopover open={open} label={t.stepComment(stepIndex)} name="pm-document-place-comment" placement="below-end" onOpenChange={change}
102
+ onInteractOutside={event => { if (isApprovalTarget(event.detail.originalEvent.target)) event.preventDefault() }}
56
103
  trigger={<PmIconButton tooltip={false} small icon="comment-add" label={t.stepCommentHint(stepIndex, count)} onClick={onPause} />}>
57
104
  {open && <PlaceCommentComposer key={selected ?? 'block'} context={context} blockId={blockId} sectionId={sectionId} stepId={selected}
58
- onSelect={next => { setSelected(next); if (next !== undefined) workbench.observeDocumentStep(sectionId, next) }} onClose={() => setOpen(false)} />}
105
+ onReady={ready} onSelect={next => { revision.current++; setSelected(next); if (next !== undefined) workbench.observeDocumentStep(sectionId, next) }} onClose={() => change(false)} />}
59
106
  </PmPopover>
60
107
  }
61
108
 
62
- function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, onClose }: {
63
- context: CommentContext, blockId: string, sectionId: string, stepId: string | undefined, onSelect(stepId: string | undefined): void, onClose(): void,
109
+ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, onClose, onReady }: {
110
+ context: CommentContext, blockId: string, sectionId: string, stepId: string | undefined, onSelect(stepId: string | undefined): void, onClose(): void, onReady(owner?: CommentDraftComposer): void,
64
111
  }) {
65
112
  const workbench = useWorkbench()
66
113
  const fallback = context.store.document
@@ -75,6 +122,7 @@ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, o
75
122
  })
76
123
  const [busy, setBusy] = useState(false), [failure, setFailure] = useState(false)
77
124
  const record = useRef<CommentDraftRecord>(), composing = useRef(false), submitting = useRef(false), composer = useRef(randomUUID())
125
+ const active = useRef(true), input = useRef(0), suppress = useRef(false)
78
126
  const submitRef = useRef<() => Promise<void>>(() => Promise.resolve())
79
127
  const editor: BlockNoteEditor<any, any, any> = useCreateBlockNote({
80
128
  schema: commentEditorSchema, trailingBlock: false,
@@ -94,16 +142,19 @@ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, o
94
142
  }
95
143
  useLayoutEffect(() => {
96
144
  if (!drafts) return
97
- const stop = editor.onChange(() => { if (!submitting.current) write(composing.current) })
98
- return stop
145
+ active.current = true
146
+ const stop = editor.onChange(() => { if (!submitting.current && !suppress.current) { input.current++; write(composing.current) } })
147
+ return () => { active.current = false; input.current++; stop() }
99
148
  }, [drafts, editor, target, rich])
100
149
  useLayoutEffect(() => {
101
150
  if (!drafts) return
102
- return drafts.registerComposer({ id: composer.current, target,
103
- snapshot: () => ({ record: record.current, composing: composing.current || editor.prosemirrorView.composing, available: !editor.prosemirrorView.isDestroyed }),
104
- targetState: () => store.draftTargetState(target) })
151
+ const owner: CommentDraftComposer = { id: composer.current, target,
152
+ snapshot: () => ({ record: record.current, composing: composing.current || editor.prosemirrorView.composing, available: active.current && !submitting.current && !editor.prosemirrorView.isDestroyed }),
153
+ targetState: () => store.draftTargetState(target), restore: recover, discard: discardActive }
154
+ const stop = drafts.registerComposer(owner); onReady(owner)
155
+ return () => { onReady(); stop() }
105
156
  }, [drafts, store, target, editor])
106
- const composition = (value: boolean) => { composing.current = value; write(value) }
157
+ const composition = (value: boolean) => { composing.current = value; input.current++; write(value) }
107
158
  const submit = async () => {
108
159
  if (submitting.current || busy || editor.isEmpty || editor.prosemirrorView.composing) return
109
160
  if (!store.auth.canCreateThread() || store.draftTargetState(target) !== 'current') { setFailure(true); return }
@@ -120,17 +171,44 @@ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, o
120
171
  submitRef.current = submit
121
172
  const draftsState = useSyncExternalStore(drafts?.subscribe ?? subscribeEmpty, drafts?.snapshot ?? (() => emptyDrafts))
122
173
  const candidates = draftsState.candidates.filter(candidate => isNewCommentDraft(candidate.target) && sameCommentDraftTarget(candidate.target, target))
123
- const recover = async (candidate: CommentDraftCandidate) => {
174
+ const nativeGuard = () => {
175
+ const version = store.version, before = input.current, own = record.current, native = editor.prosemirrorState, position = context.getPositionToken?.()
176
+ return () => {
177
+ store.beforeAction?.()
178
+ if (!active.current || !version || store.version !== version || input.current !== before || record.current !== own || composing.current || submitting.current
179
+ || editor.prosemirrorView.isDestroyed || editor.prosemirrorView.composing || editor.prosemirrorState.doc !== native.doc || editor.prosemirrorState.selection !== native.selection
180
+ || context.getPositionToken?.() !== position || !store.auth.canCreateThread()) throw new Error('client-comment-composer-changed')
181
+ }
182
+ }
183
+ const recover = async (candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<CommentDraftRecord | undefined> => {
124
184
  const version = store.version
125
185
  if (!drafts || !version) return
126
- const next = await drafts.recover(candidate, target, version)
186
+ const current = nativeGuard(), guard = () => { operation?.signal?.throwIfAborted(); operation?.guard?.(); current(); if (store.draftTargetState(target) !== 'current') throw new Error('client-comment-target-changed') }
187
+ guard()
188
+ if (record.current && !await waitForDraft(drafts.confirm(record.current), operation?.signal)) return
189
+ guard()
190
+ const next = await drafts.recover(candidate, target, version, { signal: operation?.signal, guard })
127
191
  if (!next) return
128
- // Keep the recovered record current before the editor publishes its content, then retire the old copy.
129
- record.current = next
130
- void drafts.discard(candidate)
131
- editor.replaceBlocks(editor.document, productRichTextToNative(next.content, rich))
192
+ guard(); suppress.current = true
193
+ try {
194
+ editor.replaceBlocks(editor.document, productRichTextToNative(next.content, rich))
195
+ if (JSON.stringify(nativeRichTextToProduct(editor.document as DocumentEditorBlock[], rich)) !== JSON.stringify(next.content)) throw new Error('client-comment-native-unverified')
196
+ record.current = next; input.current++
197
+ } finally { suppress.current = false }
198
+ if (!operation) await drafts.discard(candidate)
199
+ return next
200
+ }
201
+ const discardActive = async (candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<boolean> => {
202
+ if (!drafts) return false
203
+ const own = record.current
204
+ if (!own || own.id !== candidate.id || own.revision !== candidate.revision) return false
205
+ return discardNativeCommentDraft(drafts, candidate, operation, nativeGuard(), () => {
206
+ suppress.current = true
207
+ try { editor.replaceBlocks(editor.document, [{ type: 'paragraph', content: [] }]); record.current = undefined; input.current++ }
208
+ finally { suppress.current = false }
209
+ })
132
210
  }
133
- const discard = async (candidate: CommentDraftCandidate) => { await drafts?.discard(candidate) }
211
+ const discard = async (candidate: CommentDraftCandidate) => { await drafts?.discardProposal(candidate) }
134
212
  return <div className="pm-document-place-comment__body pm-ui-block-editor">
135
213
  <PmSelect label={t.stepCommentStep} value={stepId ?? ''} disabled={busy || !empty} onChange={event => onSelect(event.currentTarget.value || undefined)}>
136
214
  <option value="">{t.stepCommentWhole}</option>
@@ -141,7 +219,7 @@ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, o
141
219
  </div>
142
220
  {failure && <PmNotice tone="warn">{t.stepCommentFailed}</PmNotice>}
143
221
  {candidates.length > 0 && <DraftChoices candidates={candidates} preview disabled={busy} canRecover={() => store.draftTargetState(target) === 'current'}
144
- unavailableMessage={t.commentTargetUnavailable} onRecover={recover} onDiscard={discard} />}
222
+ unavailableMessage={t.commentTargetUnavailable} onRecover={async candidate => { await recover(candidate) }} onDiscard={discard} />}
145
223
  <div className="pm-document-place-comment__actions">
146
224
  <PmButton small disabled={busy} onClick={onClose}>{t.stepCommentCancel}</PmButton>
147
225
  <PmButton small variant="primary" loading={busy} disabled={busy || empty} onClick={() => void submit()}>{t.stepCommentSave}</PmButton>
@@ -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
@@ -1,6 +1,6 @@
1
1
  import { documentAnchorKey, documentCommentTargets, isDocumentPlaceAnchor, isRecord, randomUUID, validateDocument, validateDocumentCommentAnchor } from '@lincyaw/kernel'
2
2
  import type { DocumentComment, DocumentThread, DocumentThreadAnchor, RichTextNode, TeachingDocument } from '@lincyaw/kernel'
3
- import { DocumentDraftStore } from '../document-draft-store.ts'
3
+ import { DocumentDraftStore, waitForDraft } from '../document-draft-store.ts'
4
4
  import { sha256 as tokenOf } from '../sha256.ts'
5
5
  import type { DraftStoreResult } from '../document-draft-store.ts'
6
6
 
@@ -39,8 +39,10 @@ export interface CommentDraftComposer {
39
39
  id: string
40
40
  target: CommentComposerTarget
41
41
  snapshot(): { record?: CommentDraftRecord, composing: boolean, available: boolean }
42
- targetState(): 'current' | 'changed' | 'unavailable'
42
+ targetState(target?: CommentComposerTarget): 'current' | 'changed' | 'unavailable'
43
+ accepts?(target: CommentComposerTarget): boolean
43
44
  restore?(candidate: CommentDraftCandidate, operation: CommentDraftOperation): Promise<CommentDraftRecord | undefined>
45
+ discard?(candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<boolean>
44
46
  }
45
47
  interface Writing { record: CommentDraftRecord, raw: string, store: DocumentDraftStore, generation: number, pending: boolean, failed: boolean, done: Promise<DraftStoreResult>, clearing?: boolean }
46
48
  const PREFIX = 'presmium.comment-draft.v1:'
@@ -117,14 +119,56 @@ export class CommentDrafts {
117
119
  targetActive(target: CommentComposerTarget): boolean { return !this.ownersKnown || [...this.#composers.values()].some(value => sameCommentDraftTarget(value.target, target) && value.snapshot().available) }
118
120
  activeRecord(record: CommentDraftRecord): boolean { return [...this.#composers.values()].some(value => value.snapshot().record?.id === record.id && value.snapshot().record?.revision === record.revision && value.snapshot().available) }
119
121
  owns(record: CommentDraftRecord): boolean { return !this.#closed && this.#writing.get(record.id)?.record === record }
122
+ /** Durability acknowledgements can settle without changing author input or native ownership. */
123
+ inputGuard(): () => void {
124
+ const records = new Map([...this.#writing].map(([id, value]) => [id, value.record])), unknown = this.#unregisteredComposers
125
+ const owners = [...this.#composers].map(([id, value]) => ({ id, value, ...value.snapshot() }))
126
+ return () => {
127
+ if (this.#closed || unknown !== this.#unregisteredComposers || records.size !== this.#writing.size || [...records].some(([id, record]) => this.#writing.get(id)?.record !== record)
128
+ || owners.length !== this.#composers.size || owners.some(owner => {
129
+ const state = owner.value.snapshot()
130
+ return this.#composers.get(owner.id) !== owner.value || state.record !== owner.record || state.composing !== owner.composing || state.available !== owner.available
131
+ })) throw new Error('client-comment-drafts-changed')
132
+ }
133
+ }
134
+ #activeComposers(candidate: CommentDraftRecord): CommentDraftComposer[] {
135
+ return [...this.#composers.values()].filter(composer => {
136
+ if (composer.accepts) return false // A recovery controller is not a second owner of the visible editor.
137
+ const record = composer.snapshot().record
138
+ return record?.id === candidate.id && record.revision === candidate.revision
139
+ })
140
+ }
141
+ canDiscard(candidate: CommentDraftCandidate): boolean {
142
+ if (!this.ownersKnown || candidate.composing || candidate.pending) return false
143
+ const owners = this.#activeComposers(candidate)
144
+ return !owners.length || owners.length === 1 && Boolean(owners[0]!.discard && owners[0]!.snapshot().available && !owners[0]!.snapshot().composing)
145
+ }
146
+ /** Both the UI and MCP retire the exact branch before changing the actual mounted editor. */
147
+ async discardProposal(candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<boolean> {
148
+ operation?.signal?.throwIfAborted(); operation?.guard?.()
149
+ if (!this.canDiscard(candidate)) throw new Error('client-comment-draft-needs-human')
150
+ const owners = this.#activeComposers(candidate)
151
+ const guard = () => {
152
+ operation?.signal?.throwIfAborted(); operation?.guard?.()
153
+ const current = this.#activeComposers(candidate)
154
+ if (!this.canDiscard(candidate) || current.length !== owners.length || current.some((owner, index) => owner !== owners[index])) throw new Error('client-comment-composer-changed')
155
+ }
156
+ guard()
157
+ return owners[0] ? owners[0].discard!(candidate, { signal: operation?.signal, guard }) : this.discard(candidate, { signal: operation?.signal, guard })
158
+ }
120
159
  async restoreChoice(candidate: CommentDraftCandidate, signal: AbortSignal): Promise<{ composerId: string, expectedCurrent: CommentDraftReference | null } | undefined> {
121
- if (!this.ownersKnown || isNewCommentDraft(candidate.target) || candidate.storage !== 'durable' || candidate.composing || candidate.pending) return
122
- const matching = [...this.#composers.values()].filter(value => value.restore && sameCommentDraftTarget(value.target, candidate.target) && value.snapshot().available && !value.snapshot().composing && value.targetState() !== 'unavailable')
160
+ if (!this.ownersKnown || candidate.storage !== 'durable' || candidate.composing || candidate.pending) return
161
+ const available = [...this.#composers.values()].filter(value => value.restore && value.snapshot().available && !value.snapshot().composing && value.targetState(candidate.target) !== 'unavailable')
162
+ const direct = available.filter(value => !value.accepts && sameCommentDraftTarget(value.target, candidate.target))
163
+ const matching = direct.length ? direct : available.filter(value => value.accepts?.(candidate.target))
123
164
  if (matching.length !== 1) return
124
165
  const composer = matching[0]!, current = composer.snapshot().record
125
166
  if (!current) return { composerId: composer.id, expectedCurrent: null }
126
167
  const writing = this.#writing.get(current.id)
127
- if (current.id === candidate.id || current.composing || current.pending || !writing || writing.record !== current || writing.pending || writing.failed || !writing.store.owns(keyOf(this.#scope, current.id), writing.raw)) return
168
+ if (current.id === candidate.id || current.composing || current.pending || !writing || writing.record !== current) return
169
+ if (writing.pending && await waitForDraft(writing.done, signal) !== 'committed') return
170
+ signal.throwIfAborted()
171
+ if (writing.failed || this.#writing.get(current.id) !== writing || !writing.store.owns(keyOf(this.#scope, current.id), writing.raw)) return
128
172
  const token = await tokenOf(writing.raw); signal.throwIfAborted()
129
173
  if (this.#composers.get(composer.id) !== composer || composer.snapshot().record !== current || !composer.snapshot().available || composer.snapshot().composing) throw new Error('client-comment-drafts-changed')
130
174
  return { composerId: composer.id, expectedCurrent: { id: current.id, revision: current.revision, token } }
@@ -296,19 +340,21 @@ export class CommentDrafts {
296
340
  this.#settling++; this.#touch()
297
341
  try {
298
342
  if (this.#closed || !this.#reader) return false
299
- const values = await this.#reader.read([prefix(this.#scope)], operation?.signal), writing = this.#writing.get(reference.id)
343
+ const values = await this.#reader.read([keyOf(this.#scope, reference.id)], operation?.signal), writing = this.#writing.get(reference.id)
300
344
  const raw = writing && writing.record.revision === reference.revision && await tokenOf(writing.raw) === reference.token ? writing.raw : values.get(keyOf(this.#scope, reference.id))
301
345
  if (this.#closed || typeof raw !== 'string' || await tokenOf(raw) !== reference.token) return false
302
346
  const value: unknown = JSON.parse(raw)
303
347
  if (!valid(value, this.#scope) || value.revision !== reference.revision || this.#closed) return false
304
348
  operation?.signal?.throwIfAborted(); operation?.guard?.()
305
- const committed = await this.#reader!.mark([[markerOf(this.#scope, reference), reference.token]])
349
+ const committed = await this.#reader!.mark([[markerOf(this.#scope, reference), reference.token]], operation)
350
+ operation?.signal?.throwIfAborted(); operation?.guard?.()
351
+ const writtenToken = writing ? await tokenOf(writing.raw) : undefined
306
352
  operation?.signal?.throwIfAborted(); operation?.guard?.()
307
353
  if (!this.#closed) {
308
354
  if (committed) this.#touch()
309
- if (committed && writing && this.#writing.get(reference.id) === writing && writing.record.revision === reference.revision && await tokenOf(writing.raw) === reference.token) { this.#writing.delete(reference.id); writing.store.close() }
355
+ if (committed && writing && this.#writing.get(reference.id) === writing && writing.record.revision === reference.revision && writtenToken === reference.token) { this.#writing.delete(reference.id); writing.store.close() }
310
356
  if (!committed) this.#admissionFailure = true
311
- this.#pending(); await this.refresh()
357
+ this.#pending(); void this.refresh()
312
358
  }
313
359
  return committed
314
360
  } catch (error) { if (operation) throw error; this.#readFailure = true; this.#pending(); return false }
@@ -319,7 +365,7 @@ export class CommentDrafts {
319
365
  if (this.#closed || !this.#reader) return
320
366
  this.#settling++; this.#touch()
321
367
  try {
322
- const values = await this.#reader.read([prefix(this.#scope)], operation?.signal), writing = this.#writing.get(reference.id)
368
+ const values = await this.#reader.read([keyOf(this.#scope, reference.id), markerOf(this.#scope, reference)], operation?.signal), writing = this.#writing.get(reference.id)
323
369
  const raw = writing && writing.record.revision === reference.revision && await tokenOf(writing.raw) === reference.token ? writing.raw : values.get(keyOf(this.#scope, reference.id))
324
370
  if (this.#closed || typeof raw !== 'string' || await tokenOf(raw) !== reference.token || values.get(markerOf(this.#scope, reference)) === reference.token) return
325
371
  const value: unknown = JSON.parse(raw)
@@ -327,7 +373,7 @@ export class CommentDrafts {
327
373
  operation?.signal?.throwIfAborted(); operation?.guard?.()
328
374
  const record: CommentDraftRecord = { ...value, target: isNewCommentDraft(target) ? structuredClone(target) : value.target, id: randomUUID(), owner: this.#owner, revision: 1, updatedAt: Date.now(), version, composing: false, pending: undefined }
329
375
  const store = new DocumentDraftStore(this.#scope, undefined, { family: 'comment', owner: this.#owner }), next = JSON.stringify(record)
330
- if (next.length > MAX_CHARS || !await store.create(keyOf(this.#scope, record.id), next) || this.#closed) { store.close(); if (!this.#closed) { this.#admissionFailure = true; this.#pending() }; return }
376
+ if (next.length > MAX_CHARS || !await store.create(keyOf(this.#scope, record.id), next, operation) || this.#closed) { store.close(); if (!this.#closed) { this.#admissionFailure = true; this.#pending() }; return }
331
377
  try { operation?.signal?.throwIfAborted(); operation?.guard?.() } catch (error) { store.close(); throw error }
332
378
  this.#writing.set(record.id, { record, raw: next, store, generation: 0, pending: false, failed: false, done: Promise.resolve('committed') })
333
379
  this.#touch(); void this.refresh()
package/src/workbench.ts CHANGED
@@ -870,7 +870,7 @@ export class Workbench {
870
870
  ...bodyDrafts.mutate && !locked && !state.isCreatingPage && !state.isEditingPage && !state.isHistoryBusy && !state.isHistoryPreparing && !state.hasDocumentTimingDrafts
871
871
  ? ['body-drafts.restore' as const, 'body-drafts.discard' as const, ...bodyDrafts.current ? ['body-drafts.retry' as const] : []] : [],
872
872
  ...commentDrafts?.readable ? ['comment-drafts.inspect' as const, 'comment-drafts.read' as const] : [],
873
- ...clean && !state.isHistoryBusy && !state.isHistoryPreparing && commentDrafts?.readable && commentDrafts.ownersKnown ? ['comment-drafts.discard' as const, ...state.webView === 'document' && commentDrafts.hasRestoreComposer() ? ['comment-drafts.restore' as const] : []] : [],
873
+ ...this.client.capabilities?.readOnly !== true && clean && !state.isHistoryBusy && !state.isHistoryPreparing && commentDrafts?.readable && commentDrafts.ownersKnown ? ['comment-drafts.discard' as const, ...state.webView === 'document' && commentDrafts.hasRestoreComposer() ? ['comment-drafts.restore' as const] : []] : [],
874
874
  ...source.member?.id && this.#componentPropertyDrafts.readable(source.identity, source.member.id) ? ['component-drafts.inspect' as const, 'component-drafts.read' as const] : [],
875
875
  ...clean && !state.isHistoryBusy && !state.isHistoryPreparing && source.member?.id && this.#componentPropertyDrafts.readable(source.identity, source.member.id) ? ['component-drafts.restore' as const, 'component-drafts.discard' as const] : [],
876
876
  ...this.#canPreparePresentation() ? ['preview.prepare' as const] : [],
@@ -924,7 +924,7 @@ export class Workbench {
924
924
  const guard = () => {
925
925
  owned()
926
926
  const state = this.#state, source = state.authoring
927
- if (!source?.content || source.member?.id !== memberId || !source.version || !source.fingerprint
927
+ if (this.client.capabilities?.readOnly === true || !source?.content || source.member?.id !== memberId || !source.version || !source.fingerprint
928
928
  || !sameSource({ documentId: source.content.id, version: source.version, fingerprint: source.fingerprint }, expected)
929
929
  || source.loading || source.dirty || source.saving || source.composing || source.restored || source.recovering || source.error || isAgentChanging(state)
930
930
  || state.isCreatingPage || state.isEditingPage || state.isHistoryBusy || state.isHistoryPreparing || state.hasDocumentTimingDrafts