@lincyaw/workbench 0.2.0-rc.6 → 0.2.0-rc.61

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 (90) hide show
  1. package/package.json +5 -4
  2. package/src/MediaClipEditor.tsx +4 -3
  3. package/src/StepProductionEditor.tsx +13 -4
  4. package/src/approvals.tsx +6 -1
  5. package/src/audio-recording.ts +27 -5
  6. package/src/authoring-client.ts +10 -10
  7. package/src/authoring-draft-fragment.ts +3 -1
  8. package/src/authoring-window.ts +100 -0
  9. package/src/body-draft-actions.ts +60 -0
  10. package/src/caption-timing-drafts.ts +18 -1
  11. package/src/component-property-drafts.ts +5 -5
  12. package/src/components.tsx +22 -31
  13. package/src/context.tsx +5 -3
  14. package/src/diagnostics.ts +1 -1
  15. package/src/document-draft-store.ts +45 -18
  16. package/src/document-drafts.ts +28 -19
  17. package/src/document-editing.ts +484 -0
  18. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  19. package/src/document-editor/ComponentMaterials.tsx +3 -9
  20. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  21. package/src/document-editor/DocumentBlockPreview.tsx +4 -2
  22. package/src/document-editor/DocumentComments.tsx +85 -14
  23. package/src/document-editor/DocumentEditor.tsx +44 -7
  24. package/src/document-editor/DocumentStepNarration.tsx +33 -25
  25. package/src/document-editor/NarrationEditor.tsx +54 -20
  26. package/src/document-editor/NewCommentDrafts.tsx +114 -31
  27. package/src/document-editor/PlaceComment.tsx +228 -0
  28. package/src/document-editor/comment-draft-actions.ts +40 -20
  29. package/src/document-editor/comment-draft-inspection.ts +2 -2
  30. package/src/document-editor/comment-drafts.ts +73 -25
  31. package/src/document-editor/comments.ts +30 -10
  32. package/src/document-editor/component-label.ts +11 -0
  33. package/src/document-editor/file-input.ts +2 -2
  34. package/src/document-editor/focus.ts +0 -2
  35. package/src/document-editor/insertion-place.ts +60 -0
  36. package/src/document-editor/messages.ts +3 -3
  37. package/src/document-editor/narration-schema.tsx +12 -6
  38. package/src/document-editor/narration.ts +19 -3
  39. package/src/document-editor/page-body.ts +60 -0
  40. package/src/document-editor/projection.ts +2 -2
  41. package/src/document-editor/rich-text.ts +3 -2
  42. package/src/document-editor/selection.ts +13 -0
  43. package/src/document-editor/style.css +12 -1
  44. package/src/document-editor/table-identities.ts +2 -1
  45. package/src/document-production.ts +491 -0
  46. package/src/document-session.ts +193 -53
  47. package/src/document-timing-drafts.ts +22 -2
  48. package/src/history.ts +5 -5
  49. package/src/index.ts +6 -5
  50. package/src/jobs.ts +1 -1
  51. package/src/media-drafts.ts +43 -1
  52. package/src/messages.ts +19 -4
  53. package/src/panels/DocumentView.tsx +66 -26
  54. package/src/panels/DocumentVoiceDialog.tsx +25 -9
  55. package/src/panels/DocumentVoiceField.tsx +1 -1
  56. package/src/panels/ExportPanel.tsx +1 -6
  57. package/src/panels/HistoryPanel.tsx +1 -1
  58. package/src/panels/PageDeleteDialog.tsx +4 -4
  59. package/src/panels/PageRenameDialog.tsx +1 -1
  60. package/src/panels/PreviewPanel.tsx +1 -4
  61. package/src/panels/ProductionCaptionSize.tsx +20 -0
  62. package/src/panels/ProductionCaptionTiming.tsx +12 -9
  63. package/src/panels/ProductionMediaClips.tsx +23 -7
  64. package/src/panels/ProductionPanel.tsx +8 -4
  65. package/src/panels/ProductionRecording.tsx +86 -9
  66. package/src/panels/ProductionRecordingRange.tsx +21 -19
  67. package/src/panels/ProductionTimeline.tsx +6 -1
  68. package/src/panels/ProductionTranscription.tsx +5 -4
  69. package/src/panels/SourceDocumentPanel.tsx +12 -15
  70. package/src/panels/TranscriptionAdoption.tsx +40 -34
  71. package/src/panels/VoiceCloneDialog.tsx +2 -1
  72. package/src/panels/VoiceoverDialog.tsx +1 -1
  73. package/src/places.ts +1 -36
  74. package/src/preview-playback.ts +1 -1
  75. package/src/production-draft-actions.ts +37 -0
  76. package/src/production-messages.ts +6 -0
  77. package/src/production-playback.ts +1 -1
  78. package/src/production-voice-playback.ts +3 -2
  79. package/src/sha256.ts +9 -0
  80. package/src/styles.css +16 -41
  81. package/src/transcription-drafts.ts +124 -0
  82. package/src/use-recording-adoption.ts +2 -2
  83. package/src/voice-drafts.ts +32 -8
  84. package/src/voiceover-jobs.ts +1 -1
  85. package/src/workbench-state.ts +157 -0
  86. package/src/workbench.ts +254 -950
  87. package/src/workspace-client.ts +21 -11
  88. package/src/assistant-mascot.ts +0 -62
  89. package/src/mascot-preference.ts +0 -37
  90. package/src/panels/ChangeTrail.tsx +0 -79
@@ -1,4 +1,4 @@
1
- import { documentPageDefaults, DOCUMENT_PAGE_DEFAULT_TIMING } from '@lincyaw/kernel'
1
+ import { documentPageDefaults, DOCUMENT_PAGE_DEFAULT_TIMING, randomUUID } from '@lincyaw/kernel'
2
2
  import type { DocumentBlock, DocumentPageIds, NarrationNode, RichTextNode, Section, TeachingDocument, TextBlock } from '@lincyaw/kernel'
3
3
  import { productInlineToNative } from './inline.ts'
4
4
  import { captureRichBaseline, createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
@@ -17,7 +17,7 @@ export interface DocumentProjection extends RichProjection {
17
17
  componentConfiguration: Map<string, string>
18
18
  }
19
19
  export type NativePageCreation = DocumentPageIds
20
- const newId = () => crypto.randomUUID()
20
+ const newId = () => randomUUID()
21
21
  export const pageId = (sectionId: string) => `page:${sectionId}`
22
22
  function plain(nodes: readonly { type: string, text?: string, children?: readonly unknown[] }[]): string {
23
23
  return nodes.map(node => node.type === 'text' ? node.text ?? '' : node.type === 'break' ? '\n' : node.children ? plain(node.children as Parameters<typeof plain>[0]) : '').join('')
@@ -1,4 +1,5 @@
1
1
  import type { InlineNode, JsonValue, ListItemNode, RichTextNode, TableNode } from '@lincyaw/kernel'
2
+ import { randomUUID } from '@lincyaw/kernel'
2
3
  import type { TableCellProps } from '@blocknote/core'
3
4
  import { nativeInlineToProduct, nativeTextStyleToProduct, productInlineToNative, productTextStyleToNative } from './inline.ts'
4
5
  import type { InlineProjectionContext, NativeInline } from './inline.ts'
@@ -27,12 +28,12 @@ export interface RichProjection extends InlineProjectionContext {
27
28
  tables: Map<string, { id: string, cells: string[] }[]>
28
29
  }
29
30
  export function createRichProjection(): RichProjection {
30
- return { rich: new Map(), baseline: new Map(), tables: new Map(), opaqueInline: new Map(), newInlineId: () => crypto.randomUUID() }
31
+ return { rich: new Map(), baseline: new Map(), tables: new Map(), opaqueInline: new Map(), newInlineId: () => randomUUID() }
31
32
  }
32
33
  export function captureRichBaseline(blocks: readonly DocumentEditorBlock[], context: RichProjection): void {
33
34
  for (const block of blocks) { context.baseline.set(block.id, JSON.stringify(block)); captureRichBaseline(block.children, context) }
34
35
  }
35
- const id = () => crypto.randomUUID()
36
+ const id = () => randomUUID()
36
37
  const atom = (node: RichTextNode): DocumentEditorInput => ({ id: node.id, type: 'presmiumAtom', props: { entityId: node.id, kind: `rich:${node.type}`, label: node.type === 'extension' ? fallbackText(node.fallback) : fallbackText(node) } })
37
38
 
38
39
  /** The projection records structural identities; the saved document owns all content. */
@@ -120,6 +120,19 @@ export function nativeTextPosition(editor: NativeDocumentEditor, point: { blockI
120
120
  return nativeTextPositionInDocument(editor.prosemirrorState.doc, point)
121
121
  }
122
122
 
123
+ /** The native range of a block's whole inline text, to select it. */
124
+ export function nativeBlockText(editor: NativeDocumentEditor, blockId: string): { from: number, to: number } | undefined {
125
+ let range: { from: number, to: number } | undefined
126
+ editor.prosemirrorState.doc.descendants((node, beforePos) => {
127
+ if (range) return false
128
+ if (node.attrs.id !== blockId) return
129
+ const info = getBlockInfoFromNode(node, beforePos)
130
+ if (info.hasContent && info.contentKind === 'inline') range = { from: info.contentStart, to: info.contentEnd }
131
+ return false
132
+ })
133
+ return range
134
+ }
135
+
123
136
  /** Stable anchor lookup against a captured native transaction’s input document. */
124
137
  export function nativeTextPositionInDocument(document: ProseMirrorNode, point: { blockId: string, offset: number }): number | undefined {
125
138
  let position: number | undefined
@@ -1,4 +1,8 @@
1
- .pm-document-editor { min-width: 0; }
1
+ .pm-document-editor { display: flex; flex: 1 0 auto; flex-direction: column; min-width: 0; }
2
+ /* The page below the last block, down to the sheet's end: a press there continues the document at its end. */
3
+ .pm-document-editor__end { flex: 1 0 auto; min-height: var(--pm-space-4); }
4
+ .pm-document-editor__end[data-editable] { cursor: text; }
5
+ .pm-document-editor .bn-block-content[data-page-end]:has(.ProseMirror-trailingBreak:only-child)::after { content: attr(data-placeholder); }
2
6
  .pm-document-editor__file-errors { display: flex; align-items: flex-start; gap: var(--pm-space-2); }
3
7
  .pm-document-editor__file-errors ul { flex: 1; min-width: 0; margin: 0; padding-inline-start: var(--pm-space-4); overflow-wrap: anywhere; }
4
8
  .pm-document-editor .pm-document-editor__page-title { margin-block: var(--pm-space-5) var(--pm-space-3); font-family: var(--pm-font-sans); font-size: var(--pm-text-title); font-weight: var(--pm-weight-semibold); line-height: var(--pm-leading-tight); }
@@ -7,3 +11,10 @@
7
11
  .pm-document-editor__fallback { display: grid; gap: var(--pm-space-2); min-width: 0; }
8
12
  .pm-document-editor__fallback p { margin: 0; white-space: pre-wrap; }
9
13
  .pm-document-editor__comment-tools { position: sticky; top: var(--pm-space-2); z-index: var(--pm-z-site-header); width: fit-content; margin-inline-start: var(--pm-space-5); }
14
+
15
+ /* A place comment's popover: the comment editor, a position picker and its actions. */
16
+ .pm-document-place-comment { width: min(var(--pm-comment-width), calc(100vw - var(--pm-space-8))); }
17
+ .pm-document-place-comment__body { display: grid; gap: var(--pm-space-2); min-width: 0; }
18
+ .pm-document-place-comment__editor { min-width: 0; }
19
+ .pm-document-place-comment__editor .bn-editor { max-height: min(var(--pm-comment-editor-max-height), 45vh); overflow-y: auto; overflow-wrap: anywhere; }
20
+ .pm-document-place-comment__actions { display: flex; justify-content: end; gap: var(--pm-space-2); }
@@ -1,6 +1,7 @@
1
1
  import { createExtension, getBlockInfoNearPos, getNodeId } from '@blocknote/core'
2
2
  import { Extension } from '@tiptap/core'
3
3
  import { Plugin } from '@tiptap/pm/state'
4
+ import { randomUUID } from '@lincyaw/kernel'
4
5
  import type { NativeDocumentEditor } from './schema.tsx'
5
6
  import type { RichProjection } from './rich-text.ts'
6
7
 
@@ -24,7 +25,7 @@ export const tableIdentityExtension = createExtension({
24
25
  after.doc.descendants((node, position) => {
25
26
  if (!TYPES.includes(node.type.name)) return
26
27
  let id = node.attrs[ATTR] as string | null
27
- if (!id || used.has(id)) { id = crypto.randomUUID(); transaction.setNodeMarkup(position, undefined, { ...node.attrs, [ATTR]: id }) }
28
+ if (!id || used.has(id)) { id = randomUUID(); transaction.setNodeMarkup(position, undefined, { ...node.attrs, [ATTR]: id }) }
28
29
  used.add(id)
29
30
  })
30
31
  if (transaction.steps.length) return transaction.setMeta('addToHistory', false)
@@ -0,0 +1,491 @@
1
+ import { applyDocumentCaptionTiming, changeDocumentCaptionScale, DOCUMENT_AUDIO_MAX_BYTES, randomUUID, replaceStepNarrations, sameProductionBinding, validateDocument } from '@lincyaw/kernel'
2
+ import type { DocumentAudioImportAnswer, DocumentAudioInspectionAnswer, DocumentCaptionTimingAction, DocumentChangeAnswer, DocumentRecordingAdoption, DocumentTranscriptionRequest, MediaClip, Narration, ProductionBinding, TeachingDocument, TimeRange, TranscriptionAdoptionAnswer, TranscriptionAdoptionApply, TranscriptionAdoptionDraft, TranscriptionAdoptionPlan, TranscriptionTask, VerifiedDocumentRecordingAdoption, VoiceSource } from '@lincyaw/kernel'
3
+ import { isAgentChanging } from './workbench-state.ts'
4
+ import type { WorkbenchStore } from './workbench-state.ts'
5
+ import type { DocumentSession, DocumentSessionState } from './document-session.ts'
6
+ import { WorkspaceServerError } from './workspace-client.ts'
7
+ import type { WorkspaceClient } from './workspace-client.ts'
8
+ import { sha256 } from './sha256.ts'
9
+ import { reconcileRecordingAdoption } from './recording-adoption.ts'
10
+ import { changeDocumentVoice } from './document-voices.ts'
11
+ import type { DocumentVoiceOptions, DocumentVoiceScope } from './document-voices.ts'
12
+ import { componentSource, sameComponentSource } from './component-properties.ts'
13
+ import { reconcileCaptionTiming } from './caption-timing.ts'
14
+ import { changeStepTiming } from './step-production.ts'
15
+ import type { StepDurationDraft, StepDurationKey, StepTimingPatch } from './step-production.ts'
16
+ import { DocumentTimingDrafts } from './document-timing-drafts.ts'
17
+ import { CaptionTimingDrafts } from './caption-timing-drafts.ts'
18
+ import type { CaptionTimingDraft } from './caption-timing-drafts.ts'
19
+ import type { ClientProductionDraftMetadata } from '@lincyaw/kernel'
20
+ import { clearVoiceDraft, keepVoiceDraft, voiceDraftSnapshot } from './voice-drafts.ts'
21
+ import type { VoiceDraft } from './voice-drafts.ts'
22
+ import { discardMediaDraft, keepMediaDrafts, mediaDraftSnapshot } from './media-drafts.ts'
23
+ import type { MediaDrafts } from './media-drafts.ts'
24
+ import { TranscriptionCorrections } from './transcription-drafts.ts'
25
+ import type { TranscriptionCorrection, TranscriptionCorrectionTarget } from './transcription-drafts.ts'
26
+
27
+ interface ProductionOptions {
28
+ store: WorkbenchStore
29
+ session: DocumentSession
30
+ client: WorkspaceClient
31
+ scope(): number
32
+ document(identity?: string): TeachingDocument | undefined
33
+ flush(signal?: AbortSignal): Promise<void>
34
+ pause(): Promise<void>
35
+ stopAuditions(): void
36
+ stopPreviewOutputs(): void
37
+ sourceCurrent(binding: ProductionBinding): boolean
38
+ }
39
+ export interface RecordingRangeDraft { version: string, voice: Extract<VoiceSource, { type: 'recording' }>, range?: TimeRange, startText?: string, endText?: string }
40
+ export interface ProductionDraftView {
41
+ identity: string
42
+ kind: ClientProductionDraftMetadata['kind']
43
+ has(key: string): boolean
44
+ blocked(): boolean
45
+ clear(key: string): void
46
+ }
47
+ export interface ProductionDraftSnapshot {
48
+ stamp: string
49
+ coverage: 'tab-state' | 'partial'
50
+ candidates: { key: string, metadata: Omit<ClientProductionDraftMetadata, 'draft'>, value: unknown, discard(): void }[]
51
+ guard(): void
52
+ }
53
+
54
+ /** Source-bound media transactions, timing drafts and narration edits share the document actor. */
55
+ export class DocumentProduction {
56
+ readonly #audioImports = new WeakMap<File, { identity: string, version: string, id: string }>()
57
+ readonly #audioFingerprints = new WeakMap<File, Promise<string>>()
58
+ readonly #documentTimingDrafts = new DocumentTimingDrafts()
59
+ readonly #captionTimingDrafts = new CaptionTimingDrafts()
60
+ readonly #recordingRangeDrafts = new Map<string, Map<string, RecordingRangeDraft>>()
61
+ readonly #transcriptionCorrections = new TranscriptionCorrections()
62
+ readonly #draftViews = new Set<ProductionDraftView>()
63
+ readonly #draftSalt = randomUUID()
64
+ #draftRevision = 0
65
+ #unknownDraftViews = 0
66
+ #closed = false
67
+ readonly #removedCueTimings = new Map<string, { pauseMs: number }>()
68
+ readonly #removedNarrations = new Map<string, { narration: Narration, override?: { narrationStart: 'with-animation' | 'after-animation' } }>()
69
+ #cueTimingScope?: string
70
+ readonly #options: ProductionOptions
71
+ constructor(options: ProductionOptions) { this.#options = options }
72
+ draftState(authoring: DocumentSessionState) {
73
+ const scope = JSON.stringify([authoring.identity, authoring.reset])
74
+ if (this.#cueTimingScope !== scope) { this.#removedCueTimings.clear(); this.#removedNarrations.clear(); this.#cueTimingScope = scope }
75
+ return {
76
+ hasDocumentTimingDrafts: Boolean(authoring.identity && authoring.content && this.#documentTimingDrafts.has(authoring.identity, authoring.content)),
77
+ documentTimingDraftStorageFailure: this.#documentTimingDrafts.failed,
78
+ captionTimingDraftSteps: authoring.identity && authoring.member?.id && authoring.content ? this.#captionTimingDrafts.steps({ identity: authoring.identity, memberId: authoring.member.id }, authoring.content) : [],
79
+ captionTimingDraftStorageFailure: Boolean(authoring.identity && authoring.member?.id && this.#captionTimingDrafts.failed({ identity: authoring.identity, memberId: authoring.member.id })),
80
+ }
81
+ }
82
+ reset(): void { this.#removedCueTimings.clear(); this.#removedNarrations.clear(); this.#cueTimingScope = undefined }
83
+ dispose(): void { this.#closed = true; this.reset(); this.#captionTimingDrafts.close(); this.#transcriptionCorrections.close(); this.#recordingRangeDrafts.clear(); this.#draftViews.clear() }
84
+ get draftRevision(): number { return this.#draftRevision }
85
+ get productionDraftsBlocked(): boolean {
86
+ const identity = this.#options.store.state.authoring?.identity
87
+ return this.#closed || Boolean(this.#unknownDraftViews) || this.#options.session.hasPendingAssetWrite()
88
+ || [...this.#draftViews].some(view => view.identity === identity && view.blocked())
89
+ }
90
+ #draftChanged(): void {
91
+ if (this.#closed) return
92
+ this.#draftRevision++
93
+ const source = this.#options.store.state.authoring
94
+ if (source) this.#options.store.set({ authoring: { ...source }, ...this.draftState(source) })
95
+ }
96
+ registerDraftView(view: ProductionDraftView): () => void {
97
+ if (this.#closed) return () => {}
98
+ let closed = false
99
+ if (this.#draftViews.size >= 128) {
100
+ this.#unknownDraftViews++; this.#draftChanged()
101
+ return () => { if (closed) return; closed = true; this.#unknownDraftViews--; this.#draftChanged() }
102
+ }
103
+ this.#draftViews.add(view); this.#draftChanged()
104
+ return () => { if (closed) return; closed = true; this.#draftViews.delete(view); this.#draftChanged() }
105
+ }
106
+ keepVoiceDraft(identity: string, stepId: string, value: VoiceDraft): boolean {
107
+ const kept = keepVoiceDraft(this.#options.client, identity, stepId, value)
108
+ this.#draftChanged(); return kept
109
+ }
110
+ clearVoiceDraft(identity: string, stepId: string, expected: VoiceDraft): boolean {
111
+ const cleared = clearVoiceDraft(this.#options.client, identity, stepId, expected)
112
+ this.#draftChanged(); return cleared
113
+ }
114
+ keepMediaDrafts(identity: string, stepId: string, value: MediaDrafts): boolean {
115
+ const kept = keepMediaDrafts(this.#options.client, identity, stepId, value)
116
+ this.#draftChanged(); return kept
117
+ }
118
+ transcriptionCorrection(target: TranscriptionCorrectionTarget) { return this.#transcriptionCorrections.read(target) }
119
+ keepTranscriptionCorrection(target: TranscriptionCorrectionTarget, draft: TranscriptionCorrection): boolean {
120
+ const kept = this.#transcriptionCorrections.keep(target, draft)
121
+ this.#draftChanged(); return kept
122
+ }
123
+ completeTranscriptionCorrection(target: TranscriptionCorrectionTarget, expected: TranscriptionCorrection, next: TranscriptionCorrection): boolean {
124
+ const completed = this.#transcriptionCorrections.complete(target, expected, next)
125
+ this.#draftChanged(); return completed
126
+ }
127
+ /** Native pending range input survives mode and document changes within this workbench. */
128
+ recordingRangeDrafts(identity: string): ReadonlyMap<string, RecordingRangeDraft> {
129
+ let values = this.#recordingRangeDrafts.get(identity)
130
+ if (!values) { values = new Map(); this.#recordingRangeDrafts.set(identity, values) }
131
+ return values
132
+ }
133
+ setRecordingRangeDraft(identity: string, key: string, value: RecordingRangeDraft | undefined): void {
134
+ this.recordingRangeDrafts(identity)
135
+ const values = this.#recordingRangeDrafts.get(identity)!
136
+ if (value) values.set(key, value); else values.delete(key)
137
+ this.#draftChanged()
138
+ }
139
+
140
+ /** Native banks remain the sole content owners. A snapshot exposes metadata until an explicit read. */
141
+ productionDraftSnapshot(): ProductionDraftSnapshot {
142
+ const state = this.#options.store.state, source = state.authoring, identity = source?.identity, memberId = source?.member?.id, content = source?.content
143
+ if (this.#closed || !source || !identity || !memberId || !content || !source.version || !source.fingerprint || source.loading) throw new Error('client-production-drafts-unavailable')
144
+ const revision = this.#draftRevision, version = source.version, reset = source.reset
145
+ const corrections = this.#transcriptionCorrections.snapshot(identity)
146
+ const views = [...this.#draftViews].filter(view => view.identity === identity)
147
+ const viewState = () => JSON.stringify(views.map(view => view.blocked()))
148
+ const blocked = viewState()
149
+ const clean = () => {
150
+ const value = this.#options.store.state, current = value.authoring
151
+ return Boolean(this.#options.client.capabilities?.readOnly !== true && current && !current.loading && !current.dirty && !current.saving && !current.composing && !current.restored && !current.recovering && !current.error
152
+ && !isAgentChanging(value) && !value.isCreatingPage && !value.isEditingPage && !value.isHistoryBusy && !value.isHistoryPreparing && !this.productionDraftsBlocked)
153
+ }
154
+ const guard = () => {
155
+ corrections.guard()
156
+ const current = this.#options.store.state.authoring
157
+ if (!current || current.identity !== identity || current.member?.id !== memberId || current.content !== content || current.version !== version || current.reset !== reset
158
+ || current.loading || revision !== this.#draftRevision || viewState() !== blocked) throw new Error('client-production-drafts-changed')
159
+ }
160
+ const candidates: ProductionDraftSnapshot['candidates'] = []
161
+ const add = (kind: ClientProductionDraftMetadata['kind'], key: string, stepId: string, value: unknown, requiresReview: boolean, storage: 'tab' | 'memory', remove: () => boolean, extra: { field?: StepDurationKey, assetId?: string, clipId?: string } = {}, readable = true) => {
162
+ const matches = views.filter(view => view.kind === kind && view.has(key))
163
+ const discardable = readable && clean() && !this.#unknownDraftViews && !matches.some(view => view.blocked())
164
+ candidates.push({ key: JSON.stringify([kind, key]), metadata: { kind, stepId, ...extra, targetAvailable: Object.hasOwn(content.steps, stepId), requiresReview, storage, discardable }, value,
165
+ discard: () => {
166
+ guard()
167
+ const activeViews = views.filter(view => view.kind === kind && view.has(key))
168
+ if (!discardable || !clean() || activeViews.some(view => view.blocked())) throw new Error('client-production-draft-needs-human')
169
+ if (!remove()) { this.#draftChanged(); throw new Error('client-production-draft-storage-unavailable') }
170
+ for (const view of activeViews) view.clear(key)
171
+ this.#draftChanged()
172
+ } })
173
+ }
174
+ const timingPartial = this.#documentTimingDrafts.partial(identity), scope = { identity, memberId }
175
+ for (const [key, value] of this.#documentTimingDrafts.entries(identity)) {
176
+ const [stepId, field] = JSON.parse(key) as [string, StepDurationKey]
177
+ add('step-timing', key, stepId, value, !Object.hasOwn(content.steps, stepId) || (this.#documentTimingDrafts.get(identity, content, stepId, field)?.review ?? true), this.#documentTimingDrafts.failed || timingPartial ? 'memory' : 'tab', () => this.#documentTimingDrafts.discard(identity, key), { field }, !timingPartial)
178
+ }
179
+ const captionPartial = this.#captionTimingDrafts.partial(scope)
180
+ for (const [stepId, value] of this.#captionTimingDrafts.entries(scope)) {
181
+ const basis = state.productionPlan?.pages.flatMap(page => page.steps).find(step => step.stepId === stepId)?.captionTiming
182
+ add('caption-timing', stepId, stepId, value, value.version !== version || !basis || JSON.stringify(basis) !== JSON.stringify(value.basis), this.#captionTimingDrafts.failed(scope) || captionPartial ? 'memory' : 'tab', () => this.#captionTimingDrafts.discard(scope, stepId), {}, !captionPartial)
183
+ }
184
+ for (const [key, value] of this.#recordingRangeDrafts.get(identity) ?? []) {
185
+ const [stepId] = JSON.parse(key) as [string]
186
+ add('recording-range', key, stepId, value, value.version !== version, 'memory', () => this.#recordingRangeDrafts.get(identity)!.delete(key), { assetId: value.voice.assetId })
187
+ }
188
+ const voices = voiceDraftSnapshot(this.#options.client, identity)
189
+ for (const { stepId, value, persisted } of voices.entries) {
190
+ add('voice', stepId, stepId, value, value.version !== version, persisted ? 'tab' : 'memory', () => clearVoiceDraft(this.#options.client, identity, stepId, value), {}, !voices.partial)
191
+ }
192
+ const media = mediaDraftSnapshot(this.#options.client, identity)
193
+ for (const { stepId, value, persisted } of media.entries) for (const [name, draft] of Object.entries(value.entries)) {
194
+ const original = content.production.mediaClips.find(clip => clip.id === draft.clip.id)
195
+ add('media-clip', JSON.stringify([stepId, name]), stepId, draft, draft.version !== version || Boolean(draft.baseClip && JSON.stringify(draft.baseClip) !== JSON.stringify(original)), persisted ? 'tab' : 'memory',
196
+ () => discardMediaDraft(this.#options.client, identity, stepId, name, value), { clipId: draft.clip.id, ...draft.clip.assetId ? { assetId: draft.clip.assetId } : {} }, !media.partial)
197
+ }
198
+ for (const { key, target, draft, persisted } of corrections.entries) {
199
+ const { identity: _identity, ...binding } = target
200
+ add('transcription', key, target.stepId, { ...binding, draft }, true, persisted ? 'tab' : 'memory',
201
+ () => this.#transcriptionCorrections.discard(key, draft), {}, !corrections.partial)
202
+ }
203
+ candidates.sort((a, b) => a.key.localeCompare(b.key))
204
+ guard()
205
+ return { stamp: JSON.stringify([this.#draftSalt, identity, memberId, version, reset, revision]), coverage: timingPartial || captionPartial || voices.partial || media.partial || corrections.partial ? 'partial' : 'tab-state', candidates, guard }
206
+ }
207
+
208
+ source(expected: { identity: string, version: string }): DocumentSessionState {
209
+ const source = this.#options.store.state.authoring
210
+ if (!source || !this.#options.document(expected.identity) || source.version !== expected.version || !source.fingerprint
211
+ || source.dirty || source.saving || source.composing || source.restored || source.error || isAgentChanging(this.#options.store.state)) throw new Error('production-source-changed')
212
+ return source
213
+ }
214
+ /** Inspects the saved declaration, including a local asset not yet attached to a step. */
215
+ async inspectAudio(assetId: string, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentAudioInspectionAnswer> {
216
+ const source = this.source(expected), scope = this.#options.scope()
217
+ const answer = await this.#options.client.readDocumentAudio(source.directory, assetId, expected.version, signal)
218
+ signal?.throwIfAborted()
219
+ if (scope !== this.#options.scope() || answer.document !== source.directory || answer.version !== expected.version || answer.fingerprint !== source.fingerprint || answer.inspection.assetId !== assetId) throw new Error('production-source-changed')
220
+ this.source(expected)
221
+ return answer
222
+ }
223
+ /** Recognition keeps its captured source even if subsequent author input moves to a newer version. */
224
+ async startTranscription(request: Omit<DocumentTranscriptionRequest, 'source'>, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<TranscriptionTask> {
225
+ const source = this.source(expected)
226
+ if (!source.content || !source.fingerprint) throw new Error('production-source-changed')
227
+ const sent: DocumentTranscriptionRequest = { ...structuredClone(request), source: { documentId: source.content.id, version: expected.version, fingerprint: source.fingerprint } }
228
+ const answer = await this.#options.client.startTranscription(source.directory, sent, signal)
229
+ signal?.throwIfAborted()
230
+ if (answer.document !== source.directory || answer.intent !== sent.intent || answer.source.documentId !== sent.source.documentId
231
+ || answer.source.version !== sent.source.version || answer.source.fingerprint !== sent.source.fingerprint || answer.audio.assetId !== sent.assetId || answer.audio.sha256 !== sent.audioSha256) throw new Error('transcription-response-changed')
232
+ return answer
233
+ }
234
+ async planTranscription(draft: TranscriptionAdoptionDraft, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<TranscriptionAdoptionPlan> {
235
+ const source = this.source(expected), sent = structuredClone(draft)
236
+ if (sent.source.documentId !== source.content?.id || sent.source.version !== expected.version || sent.source.fingerprint !== source.fingerprint) throw new Error('production-source-changed')
237
+ const answer = await this.#options.client.planTranscriptionAdoption(source.directory, sent, signal)
238
+ signal?.throwIfAborted()
239
+ this.source(expected)
240
+ if (answer.document !== source.directory || answer.changeId !== sent.id || answer.source.documentId !== sent.source.documentId
241
+ || answer.source.version !== sent.source.version || answer.source.fingerprint !== sent.source.fingerprint || answer.candidate.id !== sent.candidate.id
242
+ || answer.candidate.revision !== sent.candidate.revision || answer.draftRevision !== sent.draftRevision) throw new Error('transcription-response-changed')
243
+ return answer
244
+ }
245
+ async adoptTranscription(request: TranscriptionAdoptionApply, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<TranscriptionAdoptionAnswer> {
246
+ const source = this.source(expected), sent = structuredClone(request)
247
+ if (sent.source.documentId !== source.content?.id || sent.source.version !== expected.version || sent.source.fingerprint !== source.fingerprint) throw new Error('production-source-changed')
248
+ const answer = await this.#writeDocumentMedia(expected, directory => this.#options.client.applyTranscriptionAdoption(directory, sent, signal), signal)
249
+ if (answer.adoption.planId !== sent.planId || answer.adoption.candidate.id !== sent.candidate.id || answer.adoption.candidate.revision !== sent.candidate.revision
250
+ || answer.adoption.draftRevision !== sent.draftRevision) throw new Error('transcription-response-changed')
251
+ return answer
252
+ }
253
+ async #writeDocumentMedia<T extends DocumentChangeAnswer>(expected: { identity: string, version: string }, write: (directory: string) => Promise<T>, signal?: AbortSignal): Promise<T> {
254
+ const scope = this.#options.scope(), source = this.source(expected)
255
+ this.#options.stopAuditions()
256
+ await this.#options.pause()
257
+ await this.#options.flush(signal)
258
+ signal?.throwIfAborted()
259
+ if (scope !== this.#options.scope()) throw new Error('production-source-changed')
260
+ this.source(expected)
261
+ let answer: T
262
+ try { answer = await write(source.directory) }
263
+ finally { await this.#options.session.refresh(source.directory) }
264
+ signal?.throwIfAborted()
265
+ if (scope !== this.#options.scope() || answer.document !== source.directory || answer.content.id !== source.content?.id) throw new Error('production-source-changed')
266
+ this.source({ identity: expected.identity, version: answer.version })
267
+ return answer
268
+ }
269
+ /** Import commits the original file and its declaration together, without creating a clip or narration. */
270
+ async importAudio(file: File, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentAudioImportAnswer> {
271
+ let request: { identity: string, version: string, id: string } | undefined
272
+ const answer = await this.#writeDocumentMedia(expected, async directory => {
273
+ const existing = this.#audioImports.get(file), first = !existing || existing.identity !== expected.identity
274
+ request = first ? { identity: expected.identity, version: expected.version, id: randomUUID() } : existing!
275
+ this.#audioImports.set(file, request)
276
+ try { return await this.#options.client.importDocumentAudio(directory, file, { id: request.id, baseDocumentVersion: request.version }, signal) }
277
+ catch (error) {
278
+ if (first && error instanceof WorkspaceServerError && error.status >= 400 && error.status < 500 && this.#audioImports.get(file) === request) this.#audioImports.delete(file)
279
+ throw error
280
+ }
281
+ }, signal)
282
+ if (answer.changeId !== request?.id || answer.inspection.assetId !== answer.assetId || !answer.content.assets[answer.assetId]) throw new Error('production-source-changed')
283
+ if (this.#audioImports.get(file) === request) this.#audioImports.delete(file)
284
+ return answer
285
+ }
286
+ /** Reconcile an ambiguous save against real asset bytes before admitting a new source-bound import. */
287
+ async ensureAudio(file: File, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentAudioInspectionAnswer> {
288
+ const source = this.source(expected)
289
+ if (!file.size || file.size > DOCUMENT_AUDIO_MAX_BYTES) throw new Error('production.asset-size')
290
+ let pending = this.#audioFingerprints.get(file)
291
+ if (!pending) {
292
+ pending = file.arrayBuffer().then(sha256)
293
+ this.#audioFingerprints.set(file, pending)
294
+ }
295
+ const hash = await pending
296
+ signal?.throwIfAborted(); this.source(expected)
297
+ for (const asset of Object.values(source.content?.assets ?? {})) {
298
+ if (asset.kind !== 'audio' || asset.fingerprint !== `sha256:${hash}`) continue
299
+ try {
300
+ const answer = await this.inspectAudio(asset.id, expected, signal)
301
+ if (answer.inspection.sha256 === hash) return answer
302
+ } catch (error) {
303
+ if (!(error instanceof WorkspaceServerError) || ![404, 413, 422].includes(error.status)) throw error
304
+ }
305
+ }
306
+ signal?.throwIfAborted(); this.source(expected)
307
+ const previous = this.#audioImports.get(file)
308
+ if (previous?.identity === expected.identity && previous.version !== expected.version) this.#audioImports.delete(file)
309
+ let imported: DocumentAudioImportAnswer
310
+ try { imported = await this.importAudio(file, expected, signal) }
311
+ catch (error) {
312
+ if (!previous || this.#audioImports.get(file) !== previous || !(error instanceof WorkspaceServerError)
313
+ || error.status !== 409 || error.message !== 'document-version-changed') throw error
314
+ signal?.throwIfAborted(); this.source(expected)
315
+ this.#audioImports.delete(file)
316
+ imported = await this.importAudio(file, expected, signal)
317
+ }
318
+ return { document: imported.document, version: imported.version, fingerprint: imported.fingerprint, inspection: imported.inspection }
319
+ }
320
+ /** The source actor owns this external transaction; capture is independent from preview output. */
321
+ async adoptRecording(request: DocumentRecordingAdoption, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<VerifiedDocumentRecordingAdoption> {
322
+ const scope = this.#options.scope(), source = this.source(expected), sent = structuredClone(request)
323
+ if (sent.source.documentId !== source.content?.id || sent.source.version !== source.version || sent.source.fingerprint !== source.fingerprint
324
+ || !source.content.steps[sent.stepId] || !source.content.assets[sent.assetId]) throw new Error('production-source-changed')
325
+ this.#options.stopPreviewOutputs()
326
+ await this.#options.pause()
327
+ await this.#options.flush(signal)
328
+ signal?.throwIfAborted()
329
+ if (scope !== this.#options.scope()) throw new Error('production-source-changed')
330
+ this.source(expected)
331
+ const answer = await this.#options.session.commitExternal(expected, async (_before, ownedSignal) => {
332
+ const saved = await this.#options.client.adoptRecording(source.directory, sent, ownedSignal)
333
+ if (saved.changeId !== sent.id || saved.verification.stepId !== sent.stepId || saved.verification.assetId !== sent.assetId || saved.verification.sha256 !== sent.sha256) throw new Error('document-confirmation')
334
+ return saved
335
+ }, (before, remote, current) => reconcileRecordingAdoption(sent, before, remote, current), signal)
336
+ signal?.throwIfAborted()
337
+ if (scope !== this.#options.scope() || this.#options.store.state.authoring?.identity !== expected.identity) throw new Error('production-source-changed')
338
+ return answer
339
+ }
340
+ async applyMediaClip(clip: MediaClip, expected: { identity: string, version: string, binding: ProductionBinding }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
341
+ this.source(expected)
342
+ if (!this.#options.store.state.productionPlan || !sameProductionBinding(this.#options.store.state.productionPlan.binding, expected.binding) || !this.#options.sourceCurrent(expected.binding)) throw new Error('production-source-changed')
343
+ const id = randomUUID(), value = structuredClone(clip)
344
+ const answer = await this.#writeDocumentMedia(expected, directory => this.#options.client.changeDocumentMediaClip(directory, { id, baseDocumentVersion: expected.version, binding: expected.binding, clip: value }, signal), signal)
345
+ if (answer.changeId !== id) throw new Error('production-source-changed')
346
+ return answer
347
+ }
348
+ async removeMediaClip(clipId: string, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
349
+ const id = randomUUID()
350
+ const answer = await this.#writeDocumentMedia(expected, directory => this.#options.client.changeDocumentMediaClip(directory, { id, baseDocumentVersion: expected.version, removeClipId: clipId }, signal), signal)
351
+ if (answer.changeId !== id) throw new Error('production-source-changed')
352
+ return answer
353
+ }
354
+ /** Applies a reviewed voice scope to the current source actor, without replacing body or narration. */
355
+ async applyVoice(scope: DocumentVoiceScope, value: VoiceSource | null, options: DocumentVoiceOptions, expected: { identity: string, version: string, fingerprint: string }): Promise<boolean> {
356
+ const source = this.#options.store.state.authoring, document = this.#options.document(expected.identity), context = this.#options.scope()
357
+ if (!source || !document || source.version !== expected.version || source.fingerprint !== expected.fingerprint
358
+ || source.dirty || source.saving || source.composing || source.restored || source.error || isAgentChanging(this.#options.store.state)) throw new Error('voice-context-changed')
359
+ const next = changeDocumentVoice(document, scope, value, options)
360
+ if (next === document) return true
361
+ this.#options.stopAuditions()
362
+ this.#options.session.record(next)
363
+ await this.#options.flush()
364
+ if (context !== this.#options.scope() || this.#options.store.state.authoring?.identity !== expected.identity) return false
365
+ const saved = this.#options.store.state.authoring
366
+ if (!saved || saved.dirty || saved.saving || saved.composing || saved.restored || saved.error) throw new Error('voice-save-unconfirmed')
367
+ return true
368
+ }
369
+
370
+ /** Manual caption times reuse the canonical action plan, media preflight and original source actor. */
371
+ async applyCaptionTiming(action: DocumentCaptionTimingAction, id: string, expected: { identity: string, version: string, fingerprint: string }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
372
+ const source = this.source(expected), scope = this.#options.scope()
373
+ if (!source.content || source.fingerprint !== expected.fingerprint) throw new Error('caption-source-changed')
374
+ const request = { id, source: componentSource({ content: source.content, version: source.version!, fingerprint: source.fingerprint! }), action }
375
+ const plan = await this.#options.client.planDocumentAction(source.directory, request, signal)
376
+ signal?.throwIfAborted()
377
+ if (scope !== this.#options.scope() || this.#options.store.state.authoring?.identity !== expected.identity || plan.effect.kind !== 'caption'
378
+ || plan.changeId !== id || JSON.stringify(plan.action) !== JSON.stringify(action) || !sameComponentSource(plan.source, request.source)) throw new Error('caption-source-changed')
379
+ this.#options.stopPreviewOutputs()
380
+ await this.#options.pause()
381
+ try {
382
+ return await this.#options.session.commitExternal(expected, async (_before, ownedSignal) => {
383
+ const receipt = await this.#options.client.applyDocumentAction(source.directory, { planId: plan.planId, digest: plan.digest, source: plan.source }, ownedSignal)
384
+ const actual = await this.#options.client.readDocument(source.directory)
385
+ if (receipt.planId !== plan.planId || receipt.digest !== plan.digest || receipt.changeId !== id || !receipt.verification.saved || !receipt.verification.actionStateVerified
386
+ || !sameComponentSource(receipt.verification.source, componentSource(actual))) throw new Error('document-confirmation')
387
+ return { ...actual, changeId: id, files: receipt.files }
388
+ }, (before, answer, current) => reconcileCaptionTiming(action, before, answer, current), signal)
389
+ } catch (error) {
390
+ const current = this.#options.store.state.authoring, file = plan.files.find(file => file.path === (source.directory ? `${source.directory}/lecture.json` : 'lecture.json'))
391
+ // Lost ACK was independently read by commitExternal; only the exact predicted saved version can settle it.
392
+ if (scope === this.#options.scope() && current?.identity === expected.identity && current.content && current.version === file?.version && current.fingerprint && !current.error) {
393
+ try {
394
+ if (!applyDocumentCaptionTiming(current.content, action).effect.changed) return { document: source.directory, content: plan.content, version: current.version!, fingerprint: current.fingerprint, changeId: id, issues: plan.issues, files: plan.files.map(({ path, version }) => ({ path, version })) }
395
+ } catch { /* A newer target stays pending with the actual request error. */ }
396
+ }
397
+ throw error
398
+ }
399
+ }
400
+ /** Uses the current actor revision so timing edits cannot replace later body or narration input. */
401
+ setStepTiming(stepId: string, patch: StepTimingPatch, identity?: string): void {
402
+ const document = this.#options.document(identity)
403
+ if (!document || isAgentChanging(this.#options.store.state)) return
404
+ const next = changeStepTiming(document, stepId, patch)
405
+ if (next === document) return
406
+ this.#options.stopAuditions()
407
+ this.#options.session.record(next)
408
+ }
409
+ /** The whole document's caption size (`production.captions.scale`), recorded like a step's timing. */
410
+ setCaptionScale(scale: number, identity?: string): void {
411
+ const document = this.#options.document(identity)
412
+ if (!document || isAgentChanging(this.#options.store.state)) return
413
+ const next = changeDocumentCaptionScale(document, scale)
414
+ if (next === document) return
415
+ this.#options.session.record(next)
416
+ }
417
+ timingDraft(stepId: string, key: StepDurationKey, identity: string, reset: number): StepDurationDraft | undefined {
418
+ const document = this.#options.document(identity)
419
+ return document && this.#options.store.state.authoring?.reset === reset ? this.#documentTimingDrafts.get(identity, document, stepId, key) : undefined
420
+ }
421
+ /** Retains unaccepted numeric input by stable target; it is not authoring content or a second timing source. */
422
+ setTimingDraft(stepId: string, key: StepDurationKey, draft: StepDurationDraft | undefined, identity: string, reset: number): void {
423
+ const source = this.#options.store.state.authoring, document = this.#options.document(identity)
424
+ if (!document?.steps[stepId] || source?.reset !== reset || isAgentChanging(this.#options.store.state)) return
425
+ if (!this.#documentTimingDrafts.set(identity, document, stepId, key, draft)) return
426
+ this.#draftRevision++
427
+ this.#options.store.set({ authoring: { ...source }, hasDocumentTimingDrafts: this.#documentTimingDrafts.has(identity, document), documentTimingDraftStorageFailure: this.#documentTimingDrafts.failed })
428
+ }
429
+ captionTimingDraft(stepId: string, identity: string): CaptionTimingDraft | undefined {
430
+ const source = this.#options.store.state.authoring
431
+ return source?.identity === identity && source.member?.id ? this.#captionTimingDrafts.get({ identity, memberId: source.member.id }, stepId) : undefined
432
+ }
433
+ setCaptionTimingDraft(stepId: string, draft: CaptionTimingDraft | undefined, identity: string): void {
434
+ const source = this.#options.store.state.authoring, document = this.#options.document(identity)
435
+ if (!document?.steps[stepId] || source?.identity !== identity || !source.member?.id) return
436
+ const scope = { identity, memberId: source.member.id }
437
+ this.#captionTimingDrafts.set(scope, stepId, draft)
438
+ this.#draftRevision++
439
+ this.#options.store.set({ captionTimingDraftSteps: this.#captionTimingDrafts.steps(scope, document), captionTimingDraftStorageFailure: this.#captionTimingDrafts.failed(scope) })
440
+ }
441
+ discardCaptionTimingDraft(stepId: string, identity: string): boolean {
442
+ const source = this.#options.store.state.authoring
443
+ if (source?.identity !== identity || !source.member?.id) return false
444
+ const discarded = this.#captionTimingDrafts.discard({ identity, memberId: source.member.id }, stepId)
445
+ this.#draftChanged()
446
+ return discarded
447
+ }
448
+ copyNarrationCueTiming(from: string, to: string, identity: string): void {
449
+ const document = this.#options.document(identity)
450
+ if (!document || isAgentChanging(this.#options.store.state)) return
451
+ const timing = document.production.cueTimings?.[from] ?? this.#removedCueTimings.get(from)
452
+ if (timing) this.#removedCueTimings.set(to, { ...timing })
453
+ }
454
+ /** Native block identity and order own the current step's complete script. */
455
+ setNarrations(stepId: string, narrations: Narration[], identity?: string): void {
456
+ const document = this.#options.document(identity)
457
+ if (!document || isAgentChanging(this.#options.store.state) || !Object.hasOwn(document.steps, stepId)) return
458
+ const step = document.steps[stepId]!
459
+ if (!document.sections[step.sectionId]?.stepOrder.includes(stepId)) return
460
+ const values = narrations.map(narration => {
461
+ const previous = document.narrations[narration.id] ?? this.#removedNarrations.get(narration.id)?.narration
462
+ return { ...previous, ...narration }
463
+ })
464
+ if (JSON.stringify(step.narrationIds.map(id => document.narrations[id])) === JSON.stringify(values)) return
465
+ const next = replaceStepNarrations(document, stepId, values)
466
+ for (const narration of values) {
467
+ const override = this.#removedNarrations.get(narration.id)?.override
468
+ if (override && !document.narrations[narration.id]) next.production.narrationOverrides = { ...next.production.narrationOverrides, [narration.id]: { ...override } }
469
+ }
470
+ const cueIds = new Set(values.flatMap(narration => narration.content.flatMap(node => node.type === 'cue' ? [node.id] : [])))
471
+ for (const cue of cueIds) {
472
+ const timing = this.#removedCueTimings.get(cue)
473
+ if (timing && !Object.hasOwn(next.production.cueTimings ?? {}, cue)) next.production.cueTimings = { ...next.production.cueTimings, [cue]: { ...timing } }
474
+ }
475
+ const references = (values: Narration[]) => JSON.stringify(values.map(narration => [narration.id, narration.provenance, narration.content.filter(node => node.type === 'cue')]))
476
+ if (references(step.narrationIds.map(id => document.narrations[id]!)) !== references(values)
477
+ && validateDocument(next).issues.some(issue => issue.severity === 'error')) throw new Error('document-narration-content')
478
+ for (const id of step.narrationIds) if (!next.steps[stepId]!.narrationIds.includes(id)) {
479
+ this.#removedNarrations.delete(id)
480
+ this.#removedNarrations.set(id, { narration: document.narrations[id]!, override: document.production.narrationOverrides?.[id] })
481
+ }
482
+ for (const [id, timing] of Object.entries(document.production.cueTimings ?? {})) if (!Object.hasOwn(next.production.cueTimings ?? {}, id)) {
483
+ this.#removedCueTimings.delete(id)
484
+ this.#removedCueTimings.set(id, { ...timing })
485
+ }
486
+ while (this.#removedNarrations.size > 512) this.#removedNarrations.delete(this.#removedNarrations.keys().next().value!)
487
+ while (this.#removedCueTimings.size > 512) this.#removedCueTimings.delete(this.#removedCueTimings.keys().next().value!)
488
+ this.#options.stopAuditions()
489
+ this.#options.session.record(next)
490
+ }
491
+ }