@lincyaw/workbench 0.2.0-rc.5 → 0.2.0-rc.50

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 (79) hide show
  1. package/package.json +5 -4
  2. package/src/MediaClipEditor.tsx +1 -1
  3. package/src/audio-recording.ts +27 -5
  4. package/src/authoring-client.ts +10 -10
  5. package/src/authoring-draft-fragment.ts +3 -1
  6. package/src/body-draft-actions.ts +60 -0
  7. package/src/component-property-drafts.ts +5 -5
  8. package/src/components.tsx +10 -28
  9. package/src/context.tsx +2 -1
  10. package/src/diagnostics.ts +1 -1
  11. package/src/document-draft-store.ts +45 -18
  12. package/src/document-drafts.ts +28 -19
  13. package/src/document-editing.ts +484 -0
  14. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  15. package/src/document-editor/ComponentMaterials.tsx +3 -9
  16. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  17. package/src/document-editor/DocumentBlockPreview.tsx +4 -2
  18. package/src/document-editor/DocumentComments.tsx +58 -9
  19. package/src/document-editor/DocumentEditor.tsx +44 -7
  20. package/src/document-editor/DocumentStepNarration.tsx +30 -25
  21. package/src/document-editor/NarrationEditor.tsx +54 -20
  22. package/src/document-editor/NewCommentDrafts.tsx +4 -3
  23. package/src/document-editor/PlaceComment.tsx +150 -0
  24. package/src/document-editor/comment-drafts.ts +16 -14
  25. package/src/document-editor/comments.ts +30 -10
  26. package/src/document-editor/component-label.ts +11 -0
  27. package/src/document-editor/file-input.ts +2 -2
  28. package/src/document-editor/focus.ts +0 -2
  29. package/src/document-editor/insertion-place.ts +60 -0
  30. package/src/document-editor/messages.ts +3 -3
  31. package/src/document-editor/narration-schema.tsx +12 -6
  32. package/src/document-editor/narration.ts +19 -3
  33. package/src/document-editor/page-body.ts +60 -0
  34. package/src/document-editor/projection.ts +2 -2
  35. package/src/document-editor/rich-text.ts +3 -2
  36. package/src/document-editor/selection.ts +13 -0
  37. package/src/document-editor/style.css +12 -1
  38. package/src/document-editor/table-identities.ts +2 -1
  39. package/src/document-production.ts +331 -0
  40. package/src/document-session.ts +190 -51
  41. package/src/history.ts +3 -3
  42. package/src/index.ts +5 -5
  43. package/src/jobs.ts +1 -1
  44. package/src/messages.ts +19 -4
  45. package/src/panels/DocumentView.tsx +66 -26
  46. package/src/panels/DocumentVoiceDialog.tsx +2 -2
  47. package/src/panels/DocumentVoiceField.tsx +1 -1
  48. package/src/panels/ExportPanel.tsx +1 -6
  49. package/src/panels/HistoryPanel.tsx +1 -1
  50. package/src/panels/PageDeleteDialog.tsx +4 -4
  51. package/src/panels/PageRenameDialog.tsx +1 -1
  52. package/src/panels/PreviewPanel.tsx +1 -4
  53. package/src/panels/ProductionCaptionSize.tsx +20 -0
  54. package/src/panels/ProductionCaptionTiming.tsx +7 -7
  55. package/src/panels/ProductionMediaClips.tsx +6 -5
  56. package/src/panels/ProductionPanel.tsx +8 -4
  57. package/src/panels/ProductionRecording.tsx +86 -9
  58. package/src/panels/ProductionRecordingRange.tsx +4 -4
  59. package/src/panels/ProductionTimeline.tsx +6 -1
  60. package/src/panels/ProductionTranscription.tsx +5 -4
  61. package/src/panels/SourceDocumentPanel.tsx +12 -15
  62. package/src/panels/TranscriptionAdoption.tsx +9 -8
  63. package/src/panels/VoiceCloneDialog.tsx +2 -1
  64. package/src/panels/VoiceoverDialog.tsx +1 -1
  65. package/src/places.ts +1 -36
  66. package/src/preview-playback.ts +1 -1
  67. package/src/production-messages.ts +6 -0
  68. package/src/production-playback.ts +1 -1
  69. package/src/production-voice-playback.ts +3 -2
  70. package/src/sha256.ts +9 -0
  71. package/src/styles.css +16 -41
  72. package/src/use-recording-adoption.ts +2 -2
  73. package/src/voiceover-jobs.ts +1 -1
  74. package/src/workbench-state.ts +157 -0
  75. package/src/workbench.ts +177 -943
  76. package/src/workspace-client.ts +6 -5
  77. package/src/assistant-mascot.ts +0 -62
  78. package/src/mascot-preference.ts +0 -37
  79. package/src/panels/ChangeTrail.tsx +0 -79
package/src/workbench.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { applyDocumentCaptionTiming } from '@lincyaw/kernel'
2
- import type { DocumentCaptionTimingAction } from '@lincyaw/kernel'
3
- import { reconcileCaptionTiming } from './caption-timing.ts'
1
+ import { DocumentProduction } from './document-production.ts'
2
+ import { DocumentEditing } from './document-editing.ts'
3
+ import { isAgentChanging } from './workbench-state.ts'
4
+ import type { AgentAnswer, AgentDraft, AgentRequest, PlaybackKey, Pointer, PreviewSink, WebView, WorkbenchMode, WorkbenchState, WorkbenchStore } from './workbench-state.ts'
5
+ import { enableDocumentProduction, randomUUID } from '@lincyaw/kernel'
4
6
  import type { ProjectOperation, ProjectPlan } from '@lincyaw/kernel'
5
- import { undoDepth, redoDepth } from '@tiptap/pm/history'
6
- import { TextSelection } from '@tiptap/pm/state'
7
7
  import { CommentDraftBank } from './document-editor/comment-drafts.ts'
8
8
  import { ComponentPropertyDrafts } from './component-property-drafts.ts'
9
9
  import type { ComponentPropertyDraft } from './component-property-drafts.ts'
@@ -12,43 +12,29 @@ import { applyDocumentComponentAction, documentComponentSection, effectiveCompon
12
12
  import type { DocumentAuthoringActionPlan, DocumentComponentAction, AppliedDocumentAuthoringAction } from '@lincyaw/kernel'
13
13
  import { inspectCommentDrafts } from './document-editor/comment-draft-inspection.ts'
14
14
  import { mutateCommentDrafts } from './document-editor/comment-draft-actions.ts'
15
+ import { executeBodyDraftAction } from './body-draft-actions.ts'
15
16
  import { inspectComponentDrafts } from './component-draft-inspection.ts'
16
17
  import { mutateComponentDrafts } from './component-draft-actions.ts'
17
18
  import { DocumentSession } from './document-session.ts'
18
- import { reconcileRecordingAdoption } from './recording-adoption.ts'
19
19
  import { disposeTranscriptionSessions } from './transcription-session.ts'
20
20
  import { documentRecordingActive, disposeDocumentRecordings } from './audio-recording.ts'
21
- import { DOCUMENT_AUDIO_MAX_BYTES } from '@lincyaw/kernel'
22
21
  import type { DocumentSessionState } from './document-session.ts'
23
22
  import type { DocumentDraftReference } from './document-drafts.ts'
24
- import { DocumentReturnPoints, documentReturnStep, documentViewportOffset, restoreDocumentViewport } from './document-return-point.ts'
25
23
  import type { DocumentReturnPoint } from './document-return-point.ts'
26
- import type { DocumentRecordingAdoption, VerifiedDocumentRecordingAdoption, DocumentAudioImportAnswer, DocumentAudioInspectionAnswer, DocumentChangeAnswer, MediaClip, NarrationNode, TeachingDocument, DocumentTranscriptionRequest, TranscriptionTask, TranscriptionAdoptionDraft, TranscriptionAdoptionApply, TranscriptionAdoptionPlan, TranscriptionAdoptionAnswer } from '@lincyaw/kernel'
27
- import type { NativeDocumentEditor } from './document-editor/schema.tsx'
28
- import type { DocumentEditorCommands } from './document-editor/DocumentEditor.tsx'
29
- import { nativeTextPoint, nativeTextPosition } from './document-editor/selection.ts'
30
- import type { NativeTextPoint } from './document-editor/selection.ts'
31
- import type { DocumentFieldBookmark, DocumentFieldRegistration, DocumentHistoryEditor } from './document-editor/focus.ts'
32
- import { duplicateDocumentPage, moveDocumentPage, pageDeletion, removeDocumentPage, renameDocumentPage } from '@lincyaw/kernel'
33
- import { changeStepTiming } from './step-production.ts'
34
- import { changeDocumentVoice } from './document-voices.ts'
35
- import type { DocumentVoiceOptions, DocumentVoiceScope } from './document-voices.ts'
36
- import type { CanonicalSource, VoiceoverJob, VoiceSource } from '@lincyaw/kernel'
37
- import type { StepDurationDraft, StepDurationKey, StepTimingPatch } from './step-production.ts'
38
- import { DocumentTimingDrafts } from './document-timing-drafts.ts'
39
- import { CaptionTimingDrafts } from './caption-timing-drafts.ts'
40
- import type { CaptionTimingDraft } from './caption-timing-drafts.ts'
24
+ import type { DocumentChangeAnswer, TeachingDocument } from '@lincyaw/kernel'
25
+ import type { DocumentInsertionPlace } from './document-editor/insertion-place.ts'
26
+ import type { CanonicalSource, VoiceoverJob } from '@lincyaw/kernel'
41
27
  import { compileDocumentPreview, readPreviewWhenReady, waitForPreviewRequest } from './document-preview.ts'
42
28
  import { readDocumentSnapshot } from './document-preview.ts'
43
29
  import { errorMessage, sameProductionBinding, slideShape, stepKeys, stepTrail, trailStep } from '@lincyaw/kernel'
44
- import type { Diagnostic, DiagnosticSnapshot, DocumentOperation, DocumentsAnswer, Focus, FocusReport, IrAnswer, IrEvent, IRDocument, JobsAnswer, OperationAnswer, PreviewAnchor, PreviewAnswer, PreviewCommand, PreviewDiagnostics, PreviewPoint, PreviewPosition, PreviewRect, PreviewRenderer, PreviewReport, ReviewChange, ReviewSnapshot, RevisionsAnswer, UncommittedFile } from '@lincyaw/kernel'
30
+ import type { Diagnostic, Focus, FocusReport, IrAnswer, IrEvent, OperationAnswer, PreviewAnchor, PreviewCommand, PreviewDiagnostics, PreviewRenderer, PreviewReport, ReviewChange } from '@lincyaw/kernel'
45
31
  import { DocumentDiagnostics } from './diagnostics.ts'
46
32
  import { DocumentHistory } from './history.ts'
47
33
  import { DocumentJobs } from './jobs.ts'
48
34
  import { VoiceoverJobs } from './voiceover-jobs.ts'
49
- import { contentText, localeOf, MESSAGES } from './messages.ts'
35
+ import { localeOf, MESSAGES } from './messages.ts'
50
36
  import type { AgentPlace, Locale } from './messages.ts'
51
- import { changedBlocks, changedPlaces, findPlaceAtLine, findPlaceSource } from './places.ts'
37
+ import { changedPlaces, findPlaceAtLine } from './places.ts'
52
38
  import { OperationLog } from './telemetry.ts'
53
39
  import type { OperationValue } from './telemetry.ts'
54
40
  import { PreviewPlayback } from './preview-playback.ts'
@@ -56,166 +42,22 @@ import { ProductionPlayback } from './production-playback.ts'
56
42
  import type { ProductionBinding, ProductionPlan, ProductionPlaybackCommand, ProductionPlaybackState } from '@lincyaw/kernel'
57
43
  import { workspaceClient, WorkspaceServerError } from './workspace-client.ts'
58
44
  import type { WorkspaceClient } from './workspace-client.ts'
59
- import type { PageDeletePlan } from '@lincyaw/kernel'
60
- import type { AuthoringClientAction, AuthoringClientActionResult, AuthoringClientSnapshot } from '@lincyaw/kernel'
45
+ import type { AuthoringClientAction, AuthoringClientActionType, AuthoringClientActionResult, AuthoringClientSnapshot } from '@lincyaw/kernel'
61
46
  import { PRODUCTION_PLAYBACK_RATES } from '@lincyaw/kernel'
62
47
 
63
- /** `editing`: the canonical document is edited in the parent; `viewing`: a derived snapshot is presented. */
64
- export type WorkbenchMode = 'editing' | 'viewing'
65
-
66
- /**
67
- * How the web form is shown: as a page or as its presentation, whose controls can play a configured lecture.
68
- * Both share one preview page and switch in place with `go.view`.
69
- */
70
- export type WebView = 'document' | 'present'
71
-
72
- /** A playback key pressed in a preview that the workbench plays: Space, and the left and right arrows. */
73
- export type PlaybackKey = 'play-pause' | 'previous' | 'next'
74
-
75
- /** What the author points at in the document: a block (or a section), or a passage selected in it. */
76
- export interface Pointer {
77
- target: PreviewAnchor
78
- step?: number
79
- /** The selected passage. */
80
- quote?: string
81
- /** Its box in the preview's viewport; none while it is out of sight. */
82
- rect?: PreviewRect
83
- obstacles?: PreviewRect[]
84
- point?: PreviewPoint
85
- /** Its text can be edited in place. */
86
- isEditable: boolean
87
- }
88
-
89
- export type SaveState =
90
- | { kind: 'idle' }
91
- | { kind: 'saving' }
92
- | { kind: 'saved', at: string }
93
- | { kind: 'locked' }
94
- | { kind: 'failed', message: string }
95
-
96
- /** A request for the agent of the conversation: its text and what it is about. */
97
- export interface AgentRequest {
98
- text: string
99
- focus: FocusReport[]
100
- }
101
-
102
- /** Where the host put a request: the conversation's session and the request's id, which its user message carries. */
103
- export interface AgentAnswer {
104
- session: string
105
- request: string
106
- }
107
-
108
- export interface WorkbenchState {
109
- locale: Locale
110
- authoring?: DocumentSessionState
111
- /** Unaccepted numeric form input is retained separately from saved canonical timing. */
112
- hasDocumentTimingDrafts?: boolean
113
- documentTimingDraftStorageFailure?: boolean
114
- captionTimingDraftSteps?: string[]
115
- captionTimingDraftStorageFailure?: boolean
116
- isDark: boolean
117
- documents?: DocumentsAnswer
118
- documentsFailure?: string
119
- /** The workspace's routes answer 404: `@lincyaw/dsh` is turned off on the plugins page. */
120
- isBundleDisabled?: boolean
121
- document?: string
122
- ir?: IrAnswer
123
- mode: WorkbenchMode
124
- previewRenderer: PreviewRenderer
125
- /** In the web form: the page or the presentation, both in the same page, switched without loading it again. */
126
- webView: WebView
127
- previewReload: number
128
- preview?: PreviewAnswer
129
- previewFailure?: string
130
- /** The IR revision the preview shows. */
131
- previewIrRevision?: string
132
- isPreparingPresentation?: boolean
133
- presentationFailure?: string
134
- presentationSnapshot?: { version: string, fingerprint: string, revision: string, project: number }
135
- productionPlan?: ProductionPlan
136
- productionPlayback?: ProductionPlaybackState
137
- productionFailure?: string
138
- voiceoverJobs?: VoiceoverJob[]
139
- voiceoverJobsFailure?: string
140
- /** A cache refresh that actually changed the current production binding; it never starts playback. */
141
- voiceoverCacheRefresh?: { source: CanonicalSource, revision: string, sequence: number }
142
- /** Changes when an acknowledged preview connection is attached or detached, including same-revision reloads. */
143
- previewConnection: number
144
- /** Where the preview is: the section the author reads, or the slide and its step. */
145
- position?: PreviewPosition
146
- /** Changes on every position intent, including A → B → A, without changing the source. */
147
- documentPositionToken: string
148
- /** Explicit author navigation, distinct from the player's passive cursor and frame reload reports. */
149
- productionNavigationVersion: number
150
- documentPositionIntent: 'seek' | 'pause'
151
- /** An explicit source navigation request; scrolling updates position without issuing another request. */
152
- documentNavigation?: { section: string, block?: string, request: string }
153
- documentPositionFailure?: 'removed'
154
- isCreatingPage?: boolean
155
- isEditingPage?: boolean
156
- editorHistory?: EditorHistoryState
157
- isHistoryPreparing?: boolean
158
- pageEditFailure?: string
159
- diagnostics?: DiagnosticSnapshot
160
- isDiagnosticsUnavailable: boolean
161
- canRepairDiagnostics: boolean
162
- isRepairingDiagnostics: boolean
163
- diagnosticsRepairFailure?: string
164
- pointer?: Pointer
165
- /** Where the blocks the AI just changed are in the preview, for the kitten to walk to; `id` is new for each change. */
166
- changeTrail?: { id: number, rects: PreviewRect[] }
167
- /** The places the AI just changed, for the kitten in the editor to walk to; `id` is new for each change. */
168
- changedPlaces?: { id: number, targets: PreviewAnchor[] }
169
- save: SaveState
170
- /** What the conversation's agent is told the author points at. */
171
- focus: FocusReport[]
172
- isFocusPending: boolean
173
- focusFailure?: string
174
- review?: ReviewSnapshot
175
- history?: RevisionsAnswer
176
- /** Files changed elsewhere and not yet in the history. */
177
- outside?: UncommittedFile[]
178
- historyFailure?: string
179
- isHistoryBusy: boolean
180
- isAsking: boolean
181
- askFailure?: string
182
- /** What the document can be made into, and its builds and exports (the author's and the AI's). */
183
- jobs?: JobsAnswer
184
- jobsFailure?: string
185
- voiceServiceVersion?: number
186
- jobPreparing?: { target: string, canCancel: boolean }
187
- }
188
-
189
- export interface PreviewSink {
190
- readonly generation?: number
191
- readonly capabilities?: readonly PreviewCommand['type'][]
192
- send(command: PreviewCommand): void
193
- }
194
-
195
- export interface EditorHistoryState { section: string, undo: boolean, redo: boolean, field?: boolean }
196
-
197
48
  type Listener = () => void
198
- const sameSource = (a: CanonicalSource, b: CanonicalSource) => a.documentId === b.documentId && a.version === b.version && a.fingerprint === b.fingerprint
199
-
200
- /** The workbench's state as its parts read and change it. */
201
- export interface WorkbenchStore {
202
- readonly state: WorkbenchState
203
- set(patch: Partial<WorkbenchState>): void
49
+ /** Mounted native controls advertise their own availability and execute the same human actions. */
50
+ export interface AuthoringClientControls {
51
+ identity: string
52
+ actions(): readonly AuthoringClientActionType[]
53
+ snapshot?(): Pick<AuthoringClientSnapshot, 'mode' | 'recording'>
54
+ execute(action: AuthoringClientAction, source: CanonicalSource, signal: AbortSignal, deadline?: number): Promise<void>
204
55
  }
56
+ const sameSource = (a: CanonicalSource, b: CanonicalSource) => a.documentId === b.documentId && a.version === b.version && a.fingerprint === b.fingerprint
205
57
 
206
58
  // The export of the lecture as a video (`@lincyaw/addon-lecture`).
207
59
  export const VIDEO_TARGET = 'video'
208
60
 
209
- /** The document the conversation works on: none when no document is open. */
210
- export function selectedDocument(state: WorkbenchState): string | null {
211
- return state.document ?? null
212
- }
213
-
214
- /** Whether the AI is changing the workspace now, or its change waits for the author. */
215
- export function isAgentChanging(state: WorkbenchState): boolean {
216
- return Boolean(state.review && (state.review.running || state.review.changes.length > 0))
217
- }
218
-
219
61
  /** Whether the document has a slides form (no renderers listed: every form). */
220
62
  export function hasSlides(ir: IrAnswer | undefined): boolean {
221
63
  const renderers = ir?.doc.config.renderers
@@ -270,32 +112,14 @@ export function documentDirFor(title: string, taken: readonly string[]): string
270
112
  export class Workbench {
271
113
  readonly client: WorkspaceClient
272
114
  readonly #documentSession: DocumentSession
273
- readonly #audioImports = new WeakMap<File, { identity: string, version: string, id: string }>()
274
- readonly #audioFingerprints = new WeakMap<File, Promise<string>>()
275
- readonly #documentTimingDrafts = new DocumentTimingDrafts()
276
- readonly #captionTimingDrafts = new CaptionTimingDrafts()
277
- readonly #removedCueTimings = new Map<string, { pauseMs: number }>()
278
- #cueTimingScope?: string
279
- #documentEditor?: NativeDocumentEditor
280
- #documentEditorCommands?: DocumentEditorCommands
281
- #documentEditorBinding?: { identity: string, reset: number }
282
- readonly #documentReturnPoints = new DocumentReturnPoints()
283
- #documentViewport?: { element: HTMLElement, identity: string, returnScrollTop?: number, stop(): void }
284
- #stopDocumentReturnScroll?: () => void
285
- #openingDocument?: { directory: string, scope: number, generation: number, focus?: 'body', initial?: boolean, stop(): void,
286
- basis?: { identity: string, reset: number, version?: string, content: TeachingDocument }, point?: DocumentReturnPoint, fallback?: DocumentReturnPoint }
287
- #stopDocumentLayoutScroll?: () => void
288
- #activeDocumentHistory?: DocumentHistoryEditor
289
- #unsubscribeDocumentHistory?: () => void
290
- #unsubscribeDocumentSelection?: () => void
291
- #documentSelectionGeneration = 0
115
+ readonly production: DocumentProduction
292
116
  #removedDocumentPosition?: { identity: string, documentId: string, sectionId: string, stepId?: string, version: string, fingerprint: string, scope: number, generation: number, token: string }
293
- #pendingDocumentFocus?: { documentId: string, nodeId: string, generation: number, afterSave?: true }
294
- #pendingDocumentSelection?: { documentId: string, anchor: NativeTextPoint, head: NativeTextPoint, focused: boolean }
295
- readonly #documentFields = new Map<string, DocumentFieldRegistration>()
296
- #pendingDocumentField?: { field: Omit<DocumentFieldRegistration, 'focus' | 'editor'>, bookmark: DocumentFieldBookmark, reset: number, generation: number }
117
+ readonly editing: DocumentEditing
297
118
  #state: WorkbenchState
298
119
  readonly #listeners = new Set<Listener>()
120
+ readonly #clientControls = new Set<AuthoringClientControls>()
121
+ readonly #clientControlListeners = new Set<Listener>()
122
+ #clientControlRevision = 0
299
123
  readonly #commentDrafts = new CommentDraftBank()
300
124
  readonly #componentPropertyDrafts = new ComponentPropertyDrafts()
301
125
  readonly #positionSeed = Array.from(crypto.getRandomValues(new Uint32Array(2)), value => value.toString(36)).join('-')
@@ -307,6 +131,7 @@ export class Workbench {
307
131
  readonly #jobs: DocumentJobs
308
132
  readonly #voiceover: VoiceoverJobs
309
133
  readonly #askers = new Set<(request: AgentRequest) => Promise<AgentAnswer | void>>()
134
+ readonly #drafters = new Set<(draft: AgentDraft) => void | Promise<void>>()
310
135
  readonly #previewSinks = new Set<PreviewSink>()
311
136
  readonly #playbackKeys = new Set<(command: PlaybackKey) => void>()
312
137
  #unsubscribeIr?: () => void
@@ -323,13 +148,12 @@ export class Workbench {
323
148
  #documentScope = 0
324
149
  #jobPreparation?: AbortController
325
150
  readonly #playback = new PreviewPlayback(() => ({ document: this.#state.document, scope: this.#documentScope, sinks: this.#previewSinks }))
326
- readonly #production = new ProductionPlayback(() => ({ document: this.#state.document, scope: this.#documentScope, sinks: this.#previewSinks,
151
+ readonly #productionPlayback = new ProductionPlayback(() => ({ document: this.#state.document, scope: this.#documentScope, sinks: this.#previewSinks,
327
152
  binding: this.#state.productionPlan?.binding, ready: this.#productionReady() }), state => this.#set({ productionPlayback: state }))
328
153
  /** A place to show that no preview could take yet (none was attached, e.g. the chat covered the document). */
329
154
  #pendingReveal?: PreviewAnchor
330
155
  /** The AI's changes to show on the document once the preview has them. */
331
156
  #pendingFlash?: ReviewChange[]
332
- #trail = 0
333
157
  #lastPosition?: string
334
158
  #awaitingView?: WebView
335
159
  /** The forms asked for ahead of the author (`web:<dir>`, `slides:<dir>`), and the wait before asking for the slides. */
@@ -369,12 +193,7 @@ export class Workbench {
369
193
  }
370
194
  this.#documentSession = new DocumentSession(this.client, authoring => {
371
195
  if (this.#state.document !== authoring.directory) return
372
- const pendingField = this.#pendingDocumentField
373
- if (pendingField && (pendingField.field.identity !== authoring.identity || authoring.reset > pendingField.reset
374
- || pendingField.field.blockId !== undefined && !authoring.content?.blocks[pendingField.field.blockId]
375
- || !authoring.content?.steps[pendingField.field.stepId])) this.#pendingDocumentField = undefined
376
- const cueTimingScope = JSON.stringify([authoring.identity, authoring.reset])
377
- if (this.#cueTimingScope !== cueTimingScope) { this.#removedCueTimings.clear(); this.#cueTimingScope = cueTimingScope }
196
+ this.editing.sourceChanged(authoring)
378
197
  const previous = this.#state.authoring
379
198
  // A saved timestamp belongs to this client's acknowledged source version.
380
199
  // Remote adoption has no server modification time to display in its place.
@@ -389,40 +208,39 @@ export class Workbench {
389
208
  const removed = this.#state.webView === 'document' && position?.view !== 'present' && position && previous?.identity === authoring.identity
390
209
  && (selected ? !selectedStep || selectedIndex < 0 : !authoring.content?.sectionOrder.includes(position.section))
391
210
  const restoredPosition = !removed && this.#restoredDocumentPosition(authoring)
392
- const scope = this.#documentScope, generation = this.#documentSelectionGeneration
393
- if (removed && authoring.identity) this.#documentReturnPoints.forget(authoring.identity)
211
+ const scope = this.#documentScope, generation = this.editing.generation
212
+ if (removed && authoring.identity) this.editing.returnPoints.forget(authoring.identity)
394
213
  this.#set({ authoring,
395
214
  ...removed ? { position: undefined, documentNavigation: undefined, documentPositionFailure: 'removed' as const } : {},
396
215
  ...restoredPosition ? { documentPositionFailure: undefined } : {},
397
216
  ...moved ? { position: { ...position, section: selectedStep.sectionId, step: selectedIndex, trail: [] } } : {},
398
- hasDocumentTimingDrafts: Boolean(authoring.identity && authoring.content && this.#documentTimingDrafts.has(authoring.identity, authoring.content)),
399
- documentTimingDraftStorageFailure: this.#documentTimingDrafts.failed,
400
- captionTimingDraftSteps: authoring.identity && authoring.member?.id && authoring.content ? this.#captionTimingDrafts.steps({ identity: authoring.identity, memberId: authoring.member.id }, authoring.content) : [],
401
- captionTimingDraftStorageFailure: Boolean(authoring.identity && authoring.member?.id && this.#captionTimingDrafts.failed({ identity: authoring.identity, memberId: authoring.member.id })),
217
+ ...this.production.draftState(authoring),
402
218
  save: authoring.error ? { kind: 'failed', message: authoring.error } : authoring.saving ? { kind: 'saving' } : !authoring.dirty && (previous?.dirty || previous?.saving) ? { kind: 'saved', at: new Date().toISOString() } : adoptedCleanVersion || this.#state.save.kind === 'failed' ? { kind: 'idle' } : this.#state.save })
403
219
  // The deletion owns the token produced above; source restoration only retires its notice.
404
220
  if (removed && previous?.identity && previous.content && previous.version && previous.fingerprint
405
221
  && !previous.loading && !previous.dirty && !previous.saving && !previous.restored && !previous.composing && !previous.recovering && !previous.error
406
- && scope === this.#documentScope && generation === this.#documentSelectionGeneration && !this.#state.position && this.#state.documentPositionFailure === 'removed') {
222
+ && scope === this.#documentScope && generation === this.editing.generation && !this.#state.position && this.#state.documentPositionFailure === 'removed') {
407
223
  this.#removedDocumentPosition = { identity: previous.identity, documentId: previous.content.id, sectionId: position.section,
408
224
  ...selected ? { stepId: selected } : {}, version: previous.version, fingerprint: previous.fingerprint, scope, generation, token: this.#state.documentPositionToken }
409
225
  }
410
- this.#finishOpeningDocument()
226
+ this.editing.finishOpening()
411
227
  // Native insertion can select a page before the source actor receives that new entity.
412
228
  if (position && previous && previous.identity === authoring.identity && !previous.content?.sections[position.section]
413
- && authoring.content?.sections[position.section]) this.#saveDocumentReturnPoint()
414
- if (this.#production.changed()) void this.pausePlayback().catch(() => {})
229
+ && authoring.content?.sections[position.section]) this.editing.saveReturnPoint()
230
+ if (this.#productionPlayback.changed()) void this.pausePlayback().catch(() => {})
415
231
  const acknowledgedSourceChanged = !authoring.dirty && !authoring.loading && !authoring.error && !previous?.loading
416
232
  && previous?.identity === authoring.identity && Boolean(previous?.version && authoring.version)
417
233
  && (previous?.version !== authoring.version || previous?.fingerprint !== authoring.fingerprint)
418
234
  if (!authoring.dirty && previous?.dirty || acknowledgedSourceChanged) { void this.#history.read(authoring.directory); void this.loadDocuments() }
419
- // The source changed under an author with nothing unsaved while the AI holds a review: the AI changed it. The
420
- // editor's kitten walks to the blocks whose content differs.
421
- if (acknowledgedSourceChanged && !previous?.dirty && !previous?.saving && this.#state.review && previous?.content && authoring.content) {
422
- const targets = changedBlocks(previous.content, authoring.content)
423
- if (targets.length) this.#set({ changedPlaces: { id: ++this.#trail, targets } })
424
- }
425
235
  })
236
+ this.production = new DocumentProduction({ store, session: this.#documentSession, client: this.client,
237
+ scope: () => this.#documentScope, document: identity => this.getDocument(identity), flush: signal => this.flushPendingEdits(signal),
238
+ pause: () => this.pausePlayback(), stopAuditions: () => this.stopAuditions(), stopPreviewOutputs: () => this.#playback.stopPreviewOutputs(),
239
+ sourceCurrent: binding => this.#productionSourceCurrent(binding) })
240
+ this.editing = new DocumentEditing({ store, session: this.#documentSession, scope: () => this.#documentScope,
241
+ flush: signal => this.flushPendingEdits(signal), goToSection: section => this.goToSection(section),
242
+ rememberStep: (directory, section, step) => { this.#selectedSteps.set(`${directory}\0${section}`, step) },
243
+ canAskAnimation: () => this.#drafters.size > 0, askAnimation: place => this.draftAnimation(place) })
426
244
  this.#diagnostics = new DocumentDiagnostics(this.client, store)
427
245
  this.#jobs = new DocumentJobs(this.client, store)
428
246
  this.#voiceover = new VoiceoverJobs(this.client, store, (job, signal) => this.#refreshVoiceover(job, signal))
@@ -473,11 +291,31 @@ export class Workbench {
473
291
  /** Only counters enter passive client state; no new form payload is exposed to MCP. */
474
292
  authoringDraftRevision(): string {
475
293
  const source = this.#state.authoring
476
- return JSON.stringify([this.authoringCommentDraftRevision(), source?.identity && source.member?.id ? this.#componentPropertyDrafts.revision(source.identity, source.member.id) : 0])
294
+ return JSON.stringify([this.#documentSession.bodyDraftRevision(), this.authoringCommentDraftRevision(), source?.identity && source.member?.id ? this.#componentPropertyDrafts.revision(source.identity, source.member.id) : 0, this.#clientControlRevision])
477
295
  }
478
296
  subscribeAuthoringDraftChanges(listener: () => void): () => void {
479
297
  const comments = this.#commentDrafts.subscribe(listener), properties = this.#componentPropertyDrafts.subscribe(listener)
480
- return () => { comments(); properties() }
298
+ this.#clientControlListeners.add(listener)
299
+ return () => { comments(); properties(); this.#clientControlListeners.delete(listener) }
300
+ }
301
+
302
+ registerAuthoringClientControls(controls: AuthoringClientControls): () => void {
303
+ this.#clientControls.add(controls); this.refreshAuthoringClientControls()
304
+ return () => { this.#clientControls.delete(controls); this.refreshAuthoringClientControls() }
305
+ }
306
+ refreshAuthoringClientControls(): void {
307
+ this.#clientControlRevision++
308
+ for (const listener of this.#clientControlListeners) listener()
309
+ }
310
+ waitForAuthoringClientState(ready: () => boolean, signal: AbortSignal): Promise<void> {
311
+ return new Promise((resolve, reject) => {
312
+ const finish = (error?: unknown) => { stop(); stopControls(); signal.removeEventListener('abort', aborted); error ? reject(error) : resolve() }
313
+ const check = () => { try { signal.throwIfAborted(); if (ready()) finish() } catch (error) { finish(error) } }
314
+ const aborted = () => finish(signal.reason ?? new Error('client-request-expired'))
315
+ const stop = this.subscribe(check), stopControls = this.subscribeAuthoringDraftChanges(check)
316
+ signal.addEventListener('abort', aborted, { once: true })
317
+ check()
318
+ })
481
319
  }
482
320
 
483
321
  getState = (): WorkbenchState => this.#state
@@ -506,12 +344,18 @@ export class Workbench {
506
344
  return () => this.#askers.delete(asker)
507
345
  }
508
346
 
347
+ /** The host's way to put a request in the conversation's composer for the author to finish; nothing is sent. */
348
+ onAgentDraft = (drafter: (draft: AgentDraft) => void | Promise<void>): (() => void) => {
349
+ this.#drafters.add(drafter)
350
+ return () => this.#drafters.delete(drafter)
351
+ }
352
+
509
353
  #nextDocumentPosition(): string { return `${this.#positionSeed}:${++this.#positionSequence}` }
510
354
 
511
355
  #restoredDocumentPosition(source: DocumentSessionState): boolean {
512
356
  const removed = this.#removedDocumentPosition
513
357
  if (!removed) return false
514
- if (removed.scope !== this.#documentScope || removed.generation !== this.#documentSelectionGeneration || removed.token !== this.#state.documentPositionToken
358
+ if (removed.scope !== this.#documentScope || removed.generation !== this.editing.generation || removed.token !== this.#state.documentPositionToken
515
359
  || removed.identity !== source.identity || this.#state.documentPositionFailure !== 'removed' || source.error) {
516
360
  this.#removedDocumentPosition = undefined
517
361
  return false
@@ -525,9 +369,9 @@ export class Workbench {
525
369
 
526
370
  #set(patch: Partial<WorkbenchState>): void {
527
371
  if (Object.hasOwn(patch, 'position') || Object.hasOwn(patch, 'documentPositionFailure')) this.#removedDocumentPosition = undefined
528
- if (Object.hasOwn(patch, 'position')) { this.#cancelOpeningDocument(); this.#stopDocumentReturnScroll?.() }
372
+ if (Object.hasOwn(patch, 'position')) this.editing.beforePosition()
529
373
  this.#state = { ...this.#state, ...patch, ...Object.hasOwn(patch, 'position') ? { documentPositionToken: this.#nextDocumentPosition(), documentPositionIntent: patch.documentPositionIntent ?? 'seek' } : {} }
530
- if (Object.hasOwn(patch, 'position')) this.#saveDocumentReturnPoint()
374
+ if (Object.hasOwn(patch, 'position')) this.editing.saveReturnPoint()
531
375
  for (const listener of this.#listeners) listener()
532
376
  }
533
377
 
@@ -557,7 +401,7 @@ export class Workbench {
557
401
  }
558
402
 
559
403
  planDocumentOperation(operation: ProjectOperation): Promise<ProjectPlan> {
560
- return this.client.planProjectChange({ id: crypto.randomUUID(), operation })
404
+ return this.client.planProjectChange({ id: randomUUID(), operation })
561
405
  }
562
406
 
563
407
  operateDocument(operation: ProjectOperation, planned?: ProjectPlan): Promise<OperationAnswer> {
@@ -593,163 +437,28 @@ export class Workbench {
593
437
  await this.operateDocument({ op: 'retitle', dir, title })
594
438
  }
595
439
 
596
- #watchOpeningInteraction(cancel: () => void): () => void {
597
- if (typeof document === 'undefined') return () => {}
598
- const focused = document.activeElement, dialog = focused?.closest('[role="dialog"]')
599
- const interact = (event: Event) => {
600
- if (!event.isTrusted) return
601
- if (event.type === 'focusin' && (!(event.target instanceof Element) || event.target === focused || dialog?.contains(event.target))) return
602
- cancel()
603
- }
604
- const events = ['pointerdown', 'keydown', 'beforeinput', 'wheel', 'touchmove', 'focusin']
605
- for (const event of events) document.addEventListener(event, interact, true)
606
- return () => { for (const event of events) document.removeEventListener(event, interact, true) }
607
- }
608
-
609
- #cancelOpeningDocument(): void {
610
- const pending = this.#openingDocument
611
- this.#openingDocument = undefined
612
- pending?.stop()
613
- }
614
-
615
- #beginOpeningDocument(directory: string, focus?: 'body', fallback?: DocumentReturnPoint): void {
616
- this.#cancelOpeningDocument()
617
- this.#openingDocument = { directory, focus, fallback: fallback && { ...fallback }, scope: this.#documentScope, generation: this.#documentSelectionGeneration,
618
- stop: this.#watchOpeningInteraction(() => this.#cancelOpeningDocument()) }
619
- }
620
-
621
- #saveDocumentReturnPoint(): void {
622
- const source = this.#state.authoring, position = this.#state.position
623
- if (!source?.identity || !source.content || source.loading || !position || !source.content.sectionOrder.includes(position.section)) return
624
- const section = source.content.sections[position.section]
625
- let stepId = section?.stepOrder[position.step]
626
- if (this.#state.webView === 'present' || position.view === 'present') {
627
- const snapshot = this.#state.presentationSnapshot, ir = this.#state.ir
628
- if (!snapshot || !ir || source.dirty || source.saving || source.error || snapshot.version !== source.version || snapshot.fingerprint !== source.fingerprint
629
- || snapshot.project !== (source.projectRevision ?? 0) || snapshot.revision !== ir.revision || snapshot.revision !== this.#state.previewIrRevision) return
630
- const ids = ir.doc.sections.find(page => page.id === position.section)?.stepIds
631
- if (!ids || ids.length && !ids[position.step]) return
632
- stepId = ids[position.step]
633
- if (stepId && (!section?.stepOrder.includes(stepId) || source.content.steps[stepId]?.sectionId !== position.section)) return
634
- }
635
- if (!section || !stepId && section.stepOrder.length) return
636
- const viewport = this.#documentViewport, previous = this.#documentReturnPoints.read(source.identity)
637
- const measured = this.#state.webView === 'document' && viewport?.identity === source.identity ? documentViewportOffset(viewport.element, section.id) : undefined
638
- const offset = measured ?? (previous?.sectionId === section.id ? previous.offset : undefined)
639
- this.#documentReturnPoints.write(source.identity, { sectionId: section.id, ...stepId ? { stepId } : {}, ...offset !== undefined ? { offset } : {} })
640
- }
641
-
642
- #finishOpeningDocument(): void {
643
- const pending = this.#openingDocument, source = this.#state.authoring
644
- if (!pending || source?.loading || !source?.identity || !source.content) return
645
- if (source.error === 'document-identity-changed') { this.#cancelOpeningDocument(); return }
646
- if (pending.scope !== this.#documentScope || pending.directory !== this.#state.document || pending.generation !== this.#documentSelectionGeneration) { this.#cancelOpeningDocument(); return }
647
- if (!pending.basis) {
648
- pending.basis = { identity: source.identity, reset: source.reset, version: source.version, content: source.content }
649
- if (!pending.focus) {
650
- pending.point = this.#documentReturnPoints.read(source.identity) ?? pending.fallback
651
- if (!pending.point) {
652
- const section = source.content.sections[source.content.sectionOrder[0]!]
653
- if (!section) { this.#cancelOpeningDocument(); return }
654
- pending.point = { sectionId: section.id, ...section.stepOrder[0] ? { stepId: section.stepOrder[0] } : {} }
655
- pending.initial = true
656
- }
657
- if (documentReturnStep(source.content, pending.point) === undefined) {
658
- this.#documentReturnPoints.forget(source.identity); this.#cancelOpeningDocument()
659
- this.#set({ documentPositionFailure: 'removed' }); return
660
- }
661
- }
662
- }
663
- const basis = pending.basis
664
- if (source.identity !== basis.identity || source.reset !== basis.reset || source.version !== basis.version || source.content !== basis.content) { this.#cancelOpeningDocument(); return }
665
- const editor = this.#documentEditor, binding = this.#documentEditorBinding, viewport = this.#documentViewport
666
- if (!editor || editor.prosemirrorView.isDestroyed || binding?.identity !== source.identity || binding.reset !== source.reset || viewport?.identity !== source.identity) return
667
- // The editor can mount read-only while the source is still loading; a read-only body cannot take the caret yet.
668
- if (pending.focus && !editor.isEditable) return
669
- this.#cancelOpeningDocument()
670
- if (pending.focus) {
671
- const body = (blocks: typeof editor.document, sectionId?: string): { nodeId: string, sectionId: string } | undefined => {
672
- for (const block of blocks) {
673
- if (block.type === 'presmiumPage') sectionId = block.props.sectionId
674
- else if (sectionId && editor.schema.blockSchema[block.type].content === 'inline') return { nodeId: block.id, sectionId }
675
- const nested = body(block.children, sectionId)
676
- if (nested) return nested
677
- }
678
- }
679
- const target = body(editor.document)
680
- if (target && source.content.sections[target.sectionId]) {
681
- this.#set({ position: { section: target.sectionId, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: undefined })
682
- this.#focusDocumentNode(editor, target.nodeId)
683
- }
684
- return
685
- }
686
- const point = pending.point!, step = documentReturnStep(source.content, point)
687
- if (step === undefined) return
688
- this.#selectedSteps.set(`${pending.directory}\0${point.sectionId}`, step)
689
- this.#set({ position: { section: point.sectionId, step, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: undefined })
690
- if (pending.initial) return
691
- const current = () => this.#state.document === pending.directory && this.#state.authoring?.identity === basis.identity
692
- && this.#state.authoring.reset === basis.reset && this.#state.authoring.version === basis.version && this.#state.authoring.content === basis.content
693
- && this.#documentViewport === viewport && this.#state.position?.section === point.sectionId && this.#state.position.step === step
694
- const restore = () => {
695
- if (!current()) { stop(); return }
696
- const top = viewport.element.scrollTop
697
- restoreDocumentViewport(viewport.element, point)
698
- if (viewport.element.scrollTop !== top) viewport.returnScrollTop = viewport.element.scrollTop
699
- }
700
- const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(restore)
701
- let stopInteraction: () => void = () => {}
702
- const stop = () => { observer?.disconnect(); stopInteraction(); viewport.returnScrollTop = undefined; if (this.#stopDocumentReturnScroll === stop) this.#stopDocumentReturnScroll = undefined }
703
- this.#stopDocumentReturnScroll?.(); this.#stopDocumentReturnScroll = stop
704
- stopInteraction = this.#watchOpeningInteraction(stop)
705
- observer?.observe(viewport.element)
706
- observer?.observe(editor.prosemirrorView.dom)
707
- restore()
708
- }
709
-
710
- /** Consume only this viewport owner's actual programmatic destination; user gestures retire it. */
711
- consumeDocumentReturnScroll(element: HTMLElement): boolean {
712
- const viewport = this.#documentViewport, top = viewport?.returnScrollTop
713
- if (viewport?.element !== element || top === undefined) return false
714
- viewport.returnScrollTop = undefined
715
- return element.scrollTop === top
716
- }
717
-
718
- attachDocumentViewport(element: HTMLElement, identity: string): () => void {
719
- this.#documentViewport?.stop()
720
- const scroll = () => { if (!this.#openingDocument) this.#saveDocumentReturnPoint() }
721
- const viewport = { element, identity, stop: () => element.removeEventListener('scroll', scroll) }
722
- this.#documentViewport = viewport
723
- element.addEventListener('scroll', scroll, { passive: true })
724
- this.#finishOpeningDocument()
725
- return () => { if (this.#documentViewport === viewport) { this.#saveDocumentReturnPoint(); this.#stopDocumentReturnScroll?.(); this.#documentViewport = undefined }; viewport.stop() }
726
- }
727
-
728
- /** The body editor became editable: an opening that waits to put the caret in it can finish now. */
729
- documentEditorEditable(): void { this.#finishOpeningDocument() }
730
-
731
440
  async openDocument(dir: string, options: { focus?: 'body', expectedIdentity?: string, fallbackReturnPoint?: DocumentReturnPoint } = {}): Promise<void> {
732
441
  if (this.#state.document === dir) {
733
- if (options.focus) { this.#beginOpeningDocument(dir, options.focus); this.#finishOpeningDocument() }
442
+ if (options.focus) { this.editing.beginOpening(dir, options.focus); this.editing.finishOpening() }
734
443
  return
735
444
  }
736
- this.#saveDocumentReturnPoint()
445
+ this.editing.saveReturnPoint()
737
446
  this.#documentScope++
738
447
  const scope = this.#documentScope
739
448
  this.#stopSubscriptions()
740
449
  this.#history.subscribeReview(dir)
741
450
  this.#set({ ...DOCUMENT_RESET, document: dir, previewRenderer: 'web', webView: 'document' })
742
- this.#beginOpeningDocument(dir, options.focus, options.fallbackReturnPoint)
451
+ this.editing.beginOpening(dir, options.focus, options.fallbackReturnPoint)
743
452
  this.#record('document.open')
744
453
  this.#diagnostics.subscribe(dir)
745
454
  // Authoring is ready from source JSON; compilation and preview are independent.
746
455
  const [opened] = await Promise.all([this.#documentSession.open(dir, options.expectedIdentity), this.#readFocus(dir), this.#history.read(dir)])
747
456
  if (opened === 'identity-changed' && scope === this.#documentScope && this.#state.document === dir) { this.closeDocument(); return }
748
- this.#finishOpeningDocument()
457
+ this.editing.finishOpening()
749
458
  }
750
459
 
751
460
  closeDocument(): void {
752
- this.#saveDocumentReturnPoint()
461
+ this.editing.saveReturnPoint()
753
462
  this.#documentScope++
754
463
  if (this.#state.document !== undefined) this.#record('document.close')
755
464
  this.#stopSubscriptions()
@@ -790,7 +499,6 @@ export class Workbench {
790
499
  this.#pendingFlash = undefined
791
500
  const targets = changedPlaces(ir.doc, changes)
792
501
  if (targets.length === 0) return
793
- this.#trail++
794
502
  this.#broadcast({ type: 'flash', targets })
795
503
  this.#record('ai.change.shown', { 'presmium.places': targets.map(target => [target.section, target.block].filter(Boolean).join(':')).join('\n') })
796
504
  }
@@ -1015,7 +723,7 @@ export class Workbench {
1015
723
  await this.pausePlayback()
1016
724
  signal.throwIfAborted()
1017
725
  if (!current()) return false
1018
- this.#production.reset()
726
+ this.#productionPlayback.reset()
1019
727
  this.#set({ productionPlan: plan, voiceoverCacheRefresh: { source: job.source, revision: job.revision, sequence: (this.#state.voiceoverCacheRefresh?.sequence ?? 0) + 1 } })
1020
728
  // The mounted production loader fetches this new binding in the existing frame.
1021
729
  // Replacing the iframe for every clip would interrupt progressive playback and its connection.
@@ -1072,17 +780,29 @@ export class Workbench {
1072
780
  const plan = state.productionPlan, playback = state.productionPlayback
1073
781
  const ready = clean && plan?.canPreview && this.#productionReady() && playback?.status === 'ready' && sameProductionBinding(plan.binding, playback.binding)
1074
782
  const position = state.position, page = position && content.sections[position.section]
783
+ const bodyDrafts = this.#documentSession.bodyDraftCapabilities()
1075
784
  const commentDrafts = source.member?.id ? this.#commentDrafts.peek(source.identity, source.member.id) : undefined
1076
- const prepared = state.presentationSnapshot, actual = { documentId: content.id, version: source.version, fingerprint: source.fingerprint }
785
+ const prepared = state.presentationSnapshot, actual = this.#documentSession.canonicalSource() ?? { documentId: content.id, version: source.version, fingerprint: source.fingerprint }
1077
786
  const preparedCurrent = clean && prepared && prepared.version === source.version && prepared.fingerprint === source.fingerprint && prepared.project === (source.projectRevision ?? 0)
1078
787
  && state.ir?.revision === prepared.revision && state.ir.doc.source?.version === source.version && state.ir.doc.source.fingerprint === source.fingerprint
1079
- return { revision, source: { documentId: content.id, version: source.version, fingerprint: source.fingerprint }, view: state.webView, editing,
788
+ const controls = [...this.#clientControls].filter(owner => owner.identity === source.identity)
789
+ const advertised = controls.flatMap(owner => owner.actions()), unique = advertised.filter((type, index) => advertised.indexOf(type) === index && advertised.lastIndexOf(type) === index)
790
+ const reported = controls.map(owner => owner.snapshot?.()).filter(value => value !== undefined)
791
+ const mode = reported.find(value => value.mode)?.mode, recording = reported.find(value => value.recording)?.recording
792
+ return { revision, source: actual, view: state.webView, editing,
793
+ ...mode ? { mode } : {}, ...recording ? { recording } : {},
1080
794
  interaction: state.documentPositionToken,
1081
795
  ...page && position ? { position: { sectionId: page.id, ...page.stepOrder[position.step] ? { stepId: page.stepOrder[position.step] } : {} } } : {},
1082
796
  ...plan ? { binding: plan.binding } : {}, ...playback ? { playback } : {},
1083
797
  preview: preparedCurrent ? { status: 'prepared', source: actual, irRevision: prepared.revision, projectRevision: prepared.project }
1084
798
  : { status: state.isPreparingPresentation ? 'preparing' : state.presentationFailure ? 'unavailable' : 'unprepared' },
1085
799
  actions: ['state.read', 'playback.pause', ...safe ? ['source.flush' as const] : [],
800
+ ...safe && state.mode === 'editing' && state.editorHistory?.undo ? ['native-history.undo' as const] : [],
801
+ ...safe && state.mode === 'editing' && state.editorHistory?.redo ? ['native-history.redo' as const] : [],
802
+ ...unique,
803
+ ...bodyDrafts.read ? ['body-drafts.inspect' as const, 'body-drafts.read' as const] : [],
804
+ ...bodyDrafts.mutate && !locked && !state.isCreatingPage && !state.isEditingPage && !state.isHistoryBusy && !state.isHistoryPreparing && !state.hasDocumentTimingDrafts
805
+ ? ['body-drafts.restore' as const, 'body-drafts.discard' as const, ...bodyDrafts.current ? ['body-drafts.retry' as const] : []] : [],
1086
806
  ...commentDrafts?.readable ? ['comment-drafts.inspect' as const, 'comment-drafts.read' as const] : [],
1087
807
  ...clean && !state.isHistoryBusy && !state.isHistoryPreparing && commentDrafts?.readable && commentDrafts.ownersKnown ? ['comment-drafts.discard' as const, ...state.webView === 'document' && commentDrafts.hasRestoreComposer() ? ['comment-drafts.restore' as const] : []] : [],
1088
808
  ...source.member?.id && this.#componentPropertyDrafts.readable(source.identity, source.member.id) ? ['component-drafts.inspect' as const, 'component-drafts.read' as const] : [],
@@ -1096,9 +816,31 @@ export class Workbench {
1096
816
  async executeAuthoringClientAction(action: AuthoringClientAction, expected: CanonicalSource, signal: AbortSignal, deadline?: number, fits?: (result: AuthoringClientActionResult) => boolean): Promise<void | AuthoringClientActionResult> {
1097
817
  const scope = this.#documentScope, identity = this.#state.authoring?.identity, document = this.#state.document, interaction = this.#state.documentPositionToken
1098
818
  const owned = () => { signal.throwIfAborted(); if (scope !== this.#documentScope || identity !== this.#state.authoring?.identity || document !== this.#state.document) throw new Error('client-document-changed') }
1099
- const current = () => { owned(); const state = this.authoringClientSnapshot(0); if (!state || !sameSource(state.source, expected) || !state.actions.includes(action.type)) throw new Error('client-action-unavailable'); return state }
819
+ const current = () => { owned(); const state = this.authoringClientSnapshot(0); if (!state || (action.type === 'body-drafts.retry' ? state.source.documentId !== expected.documentId : !sameSource(state.source, expected)) || !state.actions.includes(action.type)) throw new Error('client-action-unavailable'); return state }
1100
820
  current()
1101
821
  if (action.type === 'state.read') return
822
+ if (action.type === 'native-history.undo' || action.type === 'native-history.redo') {
823
+ if (this.editing.nativeHistory(action.type === 'native-history.undo' ? 'undo' : 'redo') !== true) throw new Error('client-native-history-unavailable')
824
+ owned(); return
825
+ }
826
+ const controls = [...this.#clientControls].filter(owner => owner.identity === identity && owner.actions().includes(action.type))
827
+ if (controls.length) {
828
+ if (controls.length !== 1) throw new Error('client-action-ambiguous')
829
+ const control = controls[0]!
830
+ await control.execute(action, expected, signal, deadline)
831
+ owned()
832
+ if (!this.#clientControls.has(control)) throw new Error('client-action-unavailable')
833
+ return
834
+ }
835
+ if (action.type === 'body-drafts.inspect' || action.type === 'body-drafts.read' || action.type === 'body-drafts.restore' || action.type === 'body-drafts.discard' || action.type === 'body-drafts.retry') {
836
+ if (!identity || !fits) throw new Error('client-body-drafts-unavailable')
837
+ const guard = () => {
838
+ owned()
839
+ const actual = this.#documentSession.canonicalSource()
840
+ if (!actual || actual.documentId !== expected.documentId || action.type !== 'body-drafts.inspect' && action.type !== 'body-drafts.read' && isAgentChanging(this.#state)) throw new Error('client-source-changed')
841
+ }
842
+ return executeBodyDraftAction(this.#documentSession, () => this.#state.authoring, action, { signal, guard, source: expected, ...action.type !== 'body-drafts.retry' ? { localDraft: true as const } : {} }, fits)
843
+ }
1102
844
  if (action.type === 'comment-drafts.inspect' || action.type === 'comment-drafts.read') {
1103
845
  const drafts = identity ? this.documentCommentDrafts(identity) : undefined
1104
846
  if (!drafts?.readable || !fits) throw new Error('client-comment-drafts-unavailable')
@@ -1178,6 +920,7 @@ export class Workbench {
1178
920
  || present && (!result || result.status !== 'ready' || result.position?.sectionId !== action.sectionId || result.position.stepId !== action.stepId || result.position.playing)) throw new Error('client-step-unverified')
1179
921
  return
1180
922
  }
923
+ if (action.type !== 'playback.play' && action.type !== 'playback.seek' && action.type !== 'playback.rate') throw new Error('client-action-unavailable')
1181
924
  const plan = this.#state.productionPlan
1182
925
  if (!plan || !sameProductionBinding(plan.binding, action.binding)) throw new Error('client-playback-binding-changed')
1183
926
  if (action.type === 'playback.seek' && (plan.timing !== 'confirmed' || plan.durationMs === undefined || action.timeMs > plan.durationMs)) throw new Error('client-seek-out-of-range')
@@ -1200,7 +943,7 @@ export class Workbench {
1200
943
  signal.throwIfAborted()
1201
944
  if (scope !== this.#documentScope || this.#state.authoring?.identity !== identity || !this.#productionSourceCurrent(plan.binding)) throw new Error('production-source-changed')
1202
945
  this.#set({ productionPlan: plan })
1203
- if (this.#production.changed()) void this.pausePlayback().catch(() => {})
946
+ if (this.#productionPlayback.changed()) void this.pausePlayback().catch(() => {})
1204
947
  return plan
1205
948
  }
1206
949
 
@@ -1221,7 +964,7 @@ export class Workbench {
1221
964
  await this.pausePlayback()
1222
965
  signal?.throwIfAborted()
1223
966
  }
1224
- return await this.#production.control(control, signal)
967
+ return await this.#productionPlayback.control(control, signal)
1225
968
  } catch (error) {
1226
969
  const code = errorMessage(error), current = this.#state.productionPlan?.binding
1227
970
  if (scope === this.#documentScope && !signal?.aborted && current && sameProductionBinding(current, control.binding) && this.#productionReady()
@@ -1233,7 +976,7 @@ export class Workbench {
1233
976
 
1234
977
  closeProduction(): void {
1235
978
  this.#interruptProductionNavigation()
1236
- this.#production.reset()
979
+ this.#productionPlayback.reset()
1237
980
  this.#set({ productionPlan: undefined, productionFailure: undefined })
1238
981
  }
1239
982
 
@@ -1245,9 +988,7 @@ export class Workbench {
1245
988
  await this.flushPendingEdits()
1246
989
  const source = this.#state.authoring, document = this.getDocument(identity)
1247
990
  if (scope !== this.#documentScope || !document || !source?.version || !source.fingerprint || source.dirty || source.saving || source.composing || source.restored || source.error || isAgentChanging(this.#state)) throw new Error('production-source-changed')
1248
- const plugins = [...new Set([...(document.metadata.plugins ?? []), '@lincyaw/addon-lecture', '@lincyaw/addon-speech'])]
1249
- const next = { ...document, metadata: { ...document.metadata, plugins, renderers: { ...document.metadata.renderers, lecture: document.metadata.renderers?.lecture ?? {} } } }
1250
- this.#documentSession.record(next)
991
+ this.#documentSession.record(enableDocumentProduction(document))
1251
992
  await this.flushPendingEdits()
1252
993
  if (scope !== this.#documentScope || this.#state.authoring?.identity !== identity || this.#state.authoring.dirty || this.#state.authoring.saving || this.#state.authoring.error) throw new Error('production-source-changed')
1253
994
  }
@@ -1263,46 +1004,6 @@ export class Workbench {
1263
1004
  if (this.#state.document !== undefined) void this.#readPreview(this.#state.document)
1264
1005
  }
1265
1006
 
1266
- #pageEditMessage(reason: string): string {
1267
- const t = this.#messages
1268
- if (reason === 'native-unavailable') return t.nativeEditUnavailable
1269
- if (reason.startsWith('native-')) return t.nativeEditDraft
1270
- switch (reason) {
1271
- case 'page-multiple-files': return t.pageEditFiles
1272
- case 'page-boundary': return t.pageEditBoundary
1273
- case 'page-hierarchy': return t.pageEditHierarchy
1274
- case 'page-implicit-title': return t.pageEditImplicitTitle
1275
- case 'page-formatted-title': return t.pageEditFormattedTitle
1276
- case 'page-title': return t.pageEditInvalidTitle
1277
- case 'page-compiler': return t.pageEditCompiler
1278
- case 'page-referenced': return t.pageDeleteReferenced
1279
- case 'page-external-bindings': return t.pageDeleteExternalBindings
1280
- case 'page-references-unavailable': return t.pageDeleteReferencesUnavailable
1281
- case 'page-busy': return t.pageEditBusy
1282
- case 'preview-flush-unavailable': return t.pageEditPreview
1283
- case 'page-context-changed': return t.pageEditChanged
1284
- case 'save-timeout': return t.pageEditFlushTimeout
1285
- case 'source-draft': return t.pageEditSourceDraft
1286
- case 'source-refresh': return t.pageEditRefresh
1287
- case 'page-draft':
1288
- case 'source-conflict':
1289
- case 'narration-conflict':
1290
- case 'revision-conflict': return t.pageEditDraft
1291
- case 'save-locked': return t.saveLocked
1292
- default: return t.pageEditRequestFailed
1293
- }
1294
- }
1295
-
1296
- pageEditCapability(section: string): { rename: boolean, move: boolean, reason?: string } {
1297
- const exists = Boolean(this.#state.authoring?.content?.sections[section])
1298
- const capability = { rename: exists, move: exists }
1299
- if (isAgentChanging(this.#state)) return { rename: false, move: false, reason: this.#messages.saveLocked }
1300
- if (this.#state.isCreatingPage || this.#state.isEditingPage || this.#state.isHistoryBusy) return { rename: false, move: false, reason: this.#messages.pageEditBusy }
1301
- return capability
1302
- }
1303
-
1304
- clearPageEditFailure(): void { this.#set({ pageEditFailure: undefined }) }
1305
-
1306
1007
  /** The preview acknowledges that all registered lecture playback has paused before audition audio starts. */
1307
1008
  pausePlayback(interactive = false): Promise<void> { if (interactive) this.#interruptProductionNavigation(); return this.#playback.pause() }
1308
1009
 
@@ -1334,175 +1035,14 @@ export class Workbench {
1334
1035
  if (!asset || asset.kind !== 'image' || asset.location !== answer.content.assets[answer.assetId]?.location) throw new Error('document-identity-changed')
1335
1036
  return asset.location
1336
1037
  }
1337
- #mediaSource(expected: { identity: string, version: string }): DocumentSessionState {
1338
- const source = this.#state.authoring
1339
- if (!source || !this.getDocument(expected.identity) || source.version !== expected.version || !source.fingerprint
1340
- || source.dirty || source.saving || source.composing || source.restored || source.error || isAgentChanging(this.#state)) throw new Error('production-source-changed')
1341
- return source
1342
- }
1343
- /** Inspects the saved declaration, including a local asset not yet attached to a step. */
1344
- async inspectDocumentAudio(assetId: string, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentAudioInspectionAnswer> {
1345
- const source = this.#mediaSource(expected), scope = this.#documentScope
1346
- const answer = await this.client.readDocumentAudio(source.directory, assetId, expected.version, signal)
1347
- signal?.throwIfAborted()
1348
- if (scope !== this.#documentScope || answer.document !== source.directory || answer.version !== expected.version || answer.fingerprint !== source.fingerprint || answer.inspection.assetId !== assetId) throw new Error('production-source-changed')
1349
- this.#mediaSource(expected)
1350
- return answer
1351
- }
1352
- /** Recognition keeps its captured source even if subsequent author input moves to a newer version. */
1353
- async startDocumentTranscription(request: Omit<DocumentTranscriptionRequest, 'source'>, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<TranscriptionTask> {
1354
- const source = this.#mediaSource(expected)
1355
- if (!source.content || !source.fingerprint) throw new Error('production-source-changed')
1356
- const sent: DocumentTranscriptionRequest = { ...structuredClone(request), source: { documentId: source.content.id, version: expected.version, fingerprint: source.fingerprint } }
1357
- const answer = await this.client.startTranscription(source.directory, sent, signal)
1358
- signal?.throwIfAborted()
1359
- if (answer.document !== source.directory || answer.intent !== sent.intent || answer.source.documentId !== sent.source.documentId
1360
- || 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')
1361
- return answer
1362
- }
1363
- async planDocumentTranscription(draft: TranscriptionAdoptionDraft, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<TranscriptionAdoptionPlan> {
1364
- const source = this.#mediaSource(expected), sent = structuredClone(draft)
1365
- if (sent.source.documentId !== source.content?.id || sent.source.version !== expected.version || sent.source.fingerprint !== source.fingerprint) throw new Error('production-source-changed')
1366
- const answer = await this.client.planTranscriptionAdoption(source.directory, sent, signal)
1367
- signal?.throwIfAborted()
1368
- this.#mediaSource(expected)
1369
- if (answer.document !== source.directory || answer.changeId !== sent.id || answer.source.documentId !== sent.source.documentId
1370
- || answer.source.version !== sent.source.version || answer.source.fingerprint !== sent.source.fingerprint || answer.candidate.id !== sent.candidate.id
1371
- || answer.candidate.revision !== sent.candidate.revision || answer.draftRevision !== sent.draftRevision) throw new Error('transcription-response-changed')
1372
- return answer
1373
- }
1374
- async adoptDocumentTranscription(request: TranscriptionAdoptionApply, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<TranscriptionAdoptionAnswer> {
1375
- const source = this.#mediaSource(expected), sent = structuredClone(request)
1376
- if (sent.source.documentId !== source.content?.id || sent.source.version !== expected.version || sent.source.fingerprint !== source.fingerprint) throw new Error('production-source-changed')
1377
- const answer = await this.#writeDocumentMedia(expected, directory => this.client.applyTranscriptionAdoption(directory, sent, signal), signal)
1378
- if (answer.adoption.planId !== sent.planId || answer.adoption.candidate.id !== sent.candidate.id || answer.adoption.candidate.revision !== sent.candidate.revision
1379
- || answer.adoption.draftRevision !== sent.draftRevision) throw new Error('transcription-response-changed')
1380
- return answer
1381
- }
1382
- async #writeDocumentMedia<T extends DocumentChangeAnswer>(expected: { identity: string, version: string }, write: (directory: string) => Promise<T>, signal?: AbortSignal): Promise<T> {
1383
- const scope = this.#documentScope, source = this.#mediaSource(expected)
1384
- this.stopAuditions()
1385
- await this.pausePlayback()
1386
- await this.flushPendingEdits(signal)
1387
- signal?.throwIfAborted()
1388
- if (scope !== this.#documentScope) throw new Error('production-source-changed')
1389
- this.#mediaSource(expected)
1390
- let answer: T
1391
- try { answer = await write(source.directory) }
1392
- finally { await this.#documentSession.refresh(source.directory) }
1393
- signal?.throwIfAborted()
1394
- if (scope !== this.#documentScope || answer.document !== source.directory || answer.content.id !== source.content?.id) throw new Error('production-source-changed')
1395
- this.#mediaSource({ identity: expected.identity, version: answer.version })
1396
- return answer
1397
- }
1398
- /** Import commits the original file and its declaration together, without creating a clip or narration. */
1399
- async importDocumentAudio(file: File, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentAudioImportAnswer> {
1400
- let request: { identity: string, version: string, id: string } | undefined
1401
- const answer = await this.#writeDocumentMedia(expected, async directory => {
1402
- const existing = this.#audioImports.get(file), first = !existing || existing.identity !== expected.identity
1403
- request = first ? { identity: expected.identity, version: expected.version, id: crypto.randomUUID() } : existing!
1404
- this.#audioImports.set(file, request)
1405
- try { return await this.client.importDocumentAudio(directory, file, { id: request.id, baseDocumentVersion: request.version }, signal) }
1406
- catch (error) {
1407
- if (first && error instanceof WorkspaceServerError && error.status >= 400 && error.status < 500 && this.#audioImports.get(file) === request) this.#audioImports.delete(file)
1408
- throw error
1409
- }
1410
- }, signal)
1411
- if (answer.changeId !== request?.id || answer.inspection.assetId !== answer.assetId || !answer.content.assets[answer.assetId]) throw new Error('production-source-changed')
1412
- if (this.#audioImports.get(file) === request) this.#audioImports.delete(file)
1413
- return answer
1414
- }
1415
- /** Reconcile an ambiguous save against real asset bytes before admitting a new source-bound import. */
1416
- async ensureDocumentAudio(file: File, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentAudioInspectionAnswer> {
1417
- const source = this.#mediaSource(expected)
1418
- if (!file.size || file.size > DOCUMENT_AUDIO_MAX_BYTES) throw new Error('production.asset-size')
1419
- let pending = this.#audioFingerprints.get(file)
1420
- if (!pending) {
1421
- pending = file.arrayBuffer().then(bytes => crypto.subtle.digest('SHA-256', bytes)).then(bytes => [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join(''))
1422
- this.#audioFingerprints.set(file, pending)
1423
- }
1424
- const hash = await pending
1425
- signal?.throwIfAborted(); this.#mediaSource(expected)
1426
- for (const asset of Object.values(source.content?.assets ?? {})) {
1427
- if (asset.kind !== 'audio' || asset.fingerprint !== `sha256:${hash}`) continue
1428
- try {
1429
- const answer = await this.inspectDocumentAudio(asset.id, expected, signal)
1430
- if (answer.inspection.sha256 === hash) return answer
1431
- } catch (error) {
1432
- if (!(error instanceof WorkspaceServerError) || ![404, 413, 422].includes(error.status)) throw error
1433
- }
1434
- }
1435
- signal?.throwIfAborted(); this.#mediaSource(expected)
1436
- const previous = this.#audioImports.get(file)
1437
- if (previous?.identity === expected.identity && previous.version !== expected.version) this.#audioImports.delete(file)
1438
- let imported: DocumentAudioImportAnswer
1439
- try { imported = await this.importDocumentAudio(file, expected, signal) }
1440
- catch (error) {
1441
- if (!previous || this.#audioImports.get(file) !== previous || !(error instanceof WorkspaceServerError)
1442
- || error.status !== 409 || error.message !== 'document-version-changed') throw error
1443
- signal?.throwIfAborted(); this.#mediaSource(expected)
1444
- this.#audioImports.delete(file)
1445
- imported = await this.importDocumentAudio(file, expected, signal)
1446
- }
1447
- return { document: imported.document, version: imported.version, fingerprint: imported.fingerprint, inspection: imported.inspection }
1448
- }
1449
- /** The source actor owns this external transaction; capture is independent from preview output. */
1450
- async adoptDocumentRecording(request: DocumentRecordingAdoption, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<VerifiedDocumentRecordingAdoption> {
1451
- const scope = this.#documentScope, source = this.#mediaSource(expected), sent = structuredClone(request)
1452
- if (sent.source.documentId !== source.content?.id || sent.source.version !== source.version || sent.source.fingerprint !== source.fingerprint
1453
- || !source.content.steps[sent.stepId] || !source.content.assets[sent.assetId]) throw new Error('production-source-changed')
1454
- this.#playback.stopPreviewOutputs()
1455
- await this.pausePlayback()
1456
- await this.flushPendingEdits(signal)
1457
- signal?.throwIfAborted()
1458
- if (scope !== this.#documentScope) throw new Error('production-source-changed')
1459
- this.#mediaSource(expected)
1460
- const answer = await this.#documentSession.commitExternal(expected, async (_before, ownedSignal) => {
1461
- const saved = await this.client.adoptRecording(source.directory, sent, ownedSignal)
1462
- 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')
1463
- return saved
1464
- }, (before, remote, current) => reconcileRecordingAdoption(sent, before, remote, current), signal)
1465
- signal?.throwIfAborted()
1466
- if (scope !== this.#documentScope || this.#state.authoring?.identity !== expected.identity) throw new Error('production-source-changed')
1467
- return answer
1468
- }
1469
- async applyDocumentMediaClip(clip: MediaClip, expected: { identity: string, version: string, binding: ProductionBinding }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
1470
- this.#mediaSource(expected)
1471
- if (!this.#state.productionPlan || !sameProductionBinding(this.#state.productionPlan.binding, expected.binding) || !this.#productionSourceCurrent(expected.binding)) throw new Error('production-source-changed')
1472
- const id = crypto.randomUUID(), value = structuredClone(clip)
1473
- const answer = await this.#writeDocumentMedia(expected, directory => this.client.changeDocumentMediaClip(directory, { id, baseDocumentVersion: expected.version, binding: expected.binding, clip: value }, signal), signal)
1474
- if (answer.changeId !== id) throw new Error('production-source-changed')
1475
- return answer
1476
- }
1477
- async removeDocumentMediaClip(clipId: string, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
1478
- const id = crypto.randomUUID()
1479
- const answer = await this.#writeDocumentMedia(expected, directory => this.client.changeDocumentMediaClip(directory, { id, baseDocumentVersion: expected.version, removeClipId: clipId }, signal), signal)
1480
- if (answer.changeId !== id) throw new Error('production-source-changed')
1481
- return answer
1482
- }
1483
- /** Applies a reviewed voice scope to the current source actor, without replacing body or narration. */
1484
- async applyDocumentVoice(scope: DocumentVoiceScope, value: VoiceSource | null, options: DocumentVoiceOptions, expected: { identity: string, version: string, fingerprint: string }): Promise<boolean> {
1485
- const source = this.#state.authoring, document = this.getDocument(expected.identity), context = this.#documentScope
1486
- if (!source || !document || source.version !== expected.version || source.fingerprint !== expected.fingerprint
1487
- || source.dirty || source.saving || source.composing || source.restored || source.error || isAgentChanging(this.#state)) throw new Error('voice-context-changed')
1488
- const next = changeDocumentVoice(document, scope, value, options)
1489
- if (next === document) return true
1490
- this.stopAuditions()
1491
- this.#documentSession.record(next)
1492
- await this.flushPendingEdits()
1493
- if (context !== this.#documentScope || this.#state.authoring?.identity !== expected.identity) return false
1494
- const saved = this.#state.authoring
1495
- if (!saved || saved.dirty || saved.saving || saved.composing || saved.restored || saved.error) throw new Error('voice-save-unconfirmed')
1496
- return true
1497
- }
1498
1038
  /** Parameter planning is an authoring read; it does not compile, change modes or write the document. */
1499
1039
  async planDocumentComponentAction(action: DocumentComponentAction, id: string, expected: { identity: string, version: string, fingerprint: string }, signal?: AbortSignal): Promise<DocumentAuthoringActionPlan> {
1500
- const source = this.#mediaSource(expected), scope = this.#documentScope
1040
+ const source = this.production.source(expected), scope = this.#documentScope
1501
1041
  if (!source.content || !source.fingerprint || source.fingerprint !== expected.fingerprint) throw new Error('component-source-changed')
1502
1042
  const request = { id, source: componentSource({ content: source.content, version: source.version!, fingerprint: source.fingerprint }), action: structuredClone(action) }
1503
1043
  const answer = await this.client.planDocumentAction(source.directory, request, signal)
1504
1044
  signal?.throwIfAborted()
1505
- const current = this.#mediaSource(expected)
1045
+ const current = this.production.source(expected)
1506
1046
  if (scope !== this.#documentScope || !current.content || !current.fingerprint || answer.document !== source.directory || answer.changeId !== id || answer.effect.kind !== 'component'
1507
1047
  || !sameComponentSource(answer.source, request.source) || JSON.stringify(answer.action) !== JSON.stringify(request.action)) throw new Error('component-source-changed')
1508
1048
  return answer
@@ -1510,13 +1050,13 @@ export class Workbench {
1510
1050
  /** The existing source actor owns adoption and ambiguous-response recovery, including later native input. */
1511
1051
  async applyDocumentComponentPlan(plan: DocumentAuthoringActionPlan, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<{ answer: DocumentChangeAnswer, commitId?: string }> {
1512
1052
  if (plan.effect.kind !== 'component' || !plan.action.type.startsWith('component.')) throw new Error('component-plan-invalid')
1513
- const source = this.#mediaSource(expected), action = plan.action as DocumentComponentAction, scope = this.#documentScope
1053
+ const source = this.production.source(expected), action = plan.action as DocumentComponentAction, scope = this.#documentScope
1514
1054
  if (!source.content || !source.fingerprint || !sameComponentSource(plan.source, componentSource({ content: source.content, version: source.version!, fingerprint: source.fingerprint }))) throw new Error('component-source-changed')
1515
1055
  this.#playback.stopPreviewOutputs()
1516
1056
  await this.pausePlayback()
1517
1057
  let receipt: AppliedDocumentAuthoringAction | undefined
1518
1058
  const remember = (answer: DocumentChangeAnswer) => {
1519
- if (this.#documentEditorBinding?.identity === expected.identity) this.#documentEditorCommands?.rememberComponentConfiguration(answer.content)
1059
+ this.editing.rememberComponent(answer.content, expected.identity)
1520
1060
  return { answer, ...receipt?.commit ? { commitId: receipt.commit.id } : {} }
1521
1061
  }
1522
1062
  try {
@@ -1536,7 +1076,7 @@ export class Workbench {
1536
1076
  && file?.version === current.version && current.version !== plan.source.version) {
1537
1077
  // Canonical acceptance is already known even when later native input has
1538
1078
  // deleted the target. Undoing that deletion must restore its accepted configuration.
1539
- if (this.#documentEditorBinding?.identity === expected.identity) this.#documentEditorCommands?.rememberComponentConfiguration(plan.content)
1079
+ this.editing.rememberComponent(plan.content, expected.identity)
1540
1080
  try {
1541
1081
  if (!applyDocumentComponentAction(current.content, action).effect.changed) return remember({ document: source.directory, content: plan.content,
1542
1082
  version: current.version, fingerprint: current.fingerprint, issues: plan.issues, changeId: plan.changeId, files: plan.files.map(value => ({ path: value.path, version: value.version })) })
@@ -1545,354 +1085,21 @@ export class Workbench {
1545
1085
  throw error
1546
1086
  }
1547
1087
  }
1548
- /** Manual caption times reuse the canonical action plan, media preflight and original source actor. */
1549
- async applyDocumentCaptionTiming(action: DocumentCaptionTimingAction, id: string, expected: { identity: string, version: string, fingerprint: string }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
1550
- const source = this.#mediaSource(expected), scope = this.#documentScope
1551
- if (!source.content || source.fingerprint !== expected.fingerprint) throw new Error('caption-source-changed')
1552
- const request = { id, source: componentSource({ content: source.content, version: source.version!, fingerprint: source.fingerprint! }), action }
1553
- const plan = await this.client.planDocumentAction(source.directory, request, signal)
1554
- signal?.throwIfAborted()
1555
- if (scope !== this.#documentScope || this.#state.authoring?.identity !== expected.identity || plan.effect.kind !== 'caption'
1556
- || plan.changeId !== id || JSON.stringify(plan.action) !== JSON.stringify(action) || !sameComponentSource(plan.source, request.source)) throw new Error('caption-source-changed')
1557
- this.#playback.stopPreviewOutputs()
1558
- await this.pausePlayback()
1559
- try {
1560
- return await this.#documentSession.commitExternal(expected, async (_before, ownedSignal) => {
1561
- const receipt = await this.client.applyDocumentAction(source.directory, { planId: plan.planId, digest: plan.digest, source: plan.source }, ownedSignal)
1562
- const actual = await this.client.readDocument(source.directory)
1563
- if (receipt.planId !== plan.planId || receipt.digest !== plan.digest || receipt.changeId !== id || !receipt.verification.saved || !receipt.verification.actionStateVerified
1564
- || !sameComponentSource(receipt.verification.source, componentSource(actual))) throw new Error('document-confirmation')
1565
- return { ...actual, changeId: id, files: receipt.files }
1566
- }, (before, answer, current) => reconcileCaptionTiming(action, before, answer, current), signal)
1567
- } catch (error) {
1568
- const current = this.#state.authoring, file = plan.files.find(file => file.path === (source.directory ? `${source.directory}/lecture.json` : 'lecture.json'))
1569
- // Lost ACK was independently read by commitExternal; only the exact predicted saved version can settle it.
1570
- if (scope === this.#documentScope && current?.identity === expected.identity && current.content && current.version === file?.version && current.fingerprint && !current.error) {
1571
- try {
1572
- 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 })) }
1573
- } catch { /* A newer target stays pending with the actual request error. */ }
1574
- }
1575
- throw error
1576
- }
1577
- }
1578
- /** Uses the current actor revision so timing edits cannot replace later body or narration input. */
1579
- setDocumentStepProduction(stepId: string, patch: StepTimingPatch, identity?: string): void {
1580
- const document = this.getDocument(identity)
1581
- if (!document || isAgentChanging(this.#state)) return
1582
- const next = changeStepTiming(document, stepId, patch)
1583
- if (next === document) return
1584
- this.stopAuditions()
1585
- this.#documentSession.record(next)
1586
- }
1587
- documentTimingDraft(stepId: string, key: StepDurationKey, identity: string, reset: number): StepDurationDraft | undefined {
1588
- const document = this.getDocument(identity)
1589
- return document && this.#state.authoring?.reset === reset ? this.#documentTimingDrafts.get(identity, document, stepId, key) : undefined
1590
- }
1591
- /** Retains unaccepted numeric input by stable target; it is not authoring content or a second timing source. */
1592
- setDocumentTimingDraft(stepId: string, key: StepDurationKey, draft: StepDurationDraft | undefined, identity: string, reset: number): void {
1593
- const source = this.#state.authoring, document = this.getDocument(identity)
1594
- if (!document?.steps[stepId] || source?.reset !== reset || isAgentChanging(this.#state)) return
1595
- if (!this.#documentTimingDrafts.set(identity, document, stepId, key, draft)) return
1596
- this.#set({ authoring: { ...source }, hasDocumentTimingDrafts: this.#documentTimingDrafts.has(identity, document), documentTimingDraftStorageFailure: this.#documentTimingDrafts.failed })
1597
- }
1598
- captionTimingDraft(stepId: string, identity: string): CaptionTimingDraft | undefined {
1599
- const source = this.#state.authoring
1600
- return source?.identity === identity && source.member?.id ? this.#captionTimingDrafts.get({ identity, memberId: source.member.id }, stepId) : undefined
1601
- }
1602
- setCaptionTimingDraft(stepId: string, draft: CaptionTimingDraft | undefined, identity: string): void {
1603
- const source = this.#state.authoring, document = this.getDocument(identity)
1604
- if (!document?.steps[stepId] || source?.identity !== identity || !source.member?.id) return
1605
- const scope = { identity, memberId: source.member.id }
1606
- this.#captionTimingDrafts.set(scope, stepId, draft)
1607
- this.#set({ captionTimingDraftSteps: this.#captionTimingDrafts.steps(scope, document), captionTimingDraftStorageFailure: this.#captionTimingDrafts.failed(scope) })
1608
- }
1609
- /** Changes one stable narration target without replacing the body editor or derived captions. */
1610
- setDocumentNarration(stepId: string, narrationId: string | undefined, content: NarrationNode[], identity?: string): string | undefined {
1611
- const document = this.getDocument(identity)
1612
- if (!document || isAgentChanging(this.#state) || !Object.hasOwn(document.steps, stepId)) return undefined
1613
- const step = document.steps[stepId]!
1614
- if (!document.sections[step.sectionId]?.stepOrder.includes(stepId)) return undefined
1615
- if (!Array.isArray(content)) throw new Error('document-narration-content')
1616
- let meaningful = false
1617
- for (const node of content) {
1618
- if (!node || typeof node !== 'object') throw new Error('document-narration-content')
1619
- if (node.type === 'text' && typeof node.text === 'string') meaningful ||= Boolean(node.text.trim())
1620
- else if (node.type === 'pronunciation' && typeof node.display === 'string' && typeof node.spoken === 'string') meaningful ||= Boolean(node.display.trim() || node.spoken.trim())
1621
- else if (node.type === 'cue' && typeof node.id === 'string' && node.id && typeof node.action === 'string' && node.action) meaningful = true
1622
- else throw new Error('document-narration-content')
1623
- }
1624
- const target = narrationId ?? step.narrationIds[0]
1625
- const existing = target !== undefined && Object.hasOwn(document.narrations, target) ? document.narrations[target] : undefined
1626
- if (existing && !step.narrationIds.includes(existing.id)) throw new Error('document-narration-target')
1627
- if (!existing && !meaningful) return undefined
1628
- const id = target ?? crypto.randomUUID()
1629
- if (!id || id.length > 200 || /[\u0000-\u001f]/.test(id) || ['__proto__', 'constructor', 'prototype'].includes(id)) throw new Error('document-narration-target')
1630
- if (!existing && (document.id === id || [document.sections, document.blocks, document.steps, document.assets, document.definitions].some(map => Object.hasOwn(map, id)))) throw new Error('document-narration-target')
1631
- if (existing && JSON.stringify(existing.content) === JSON.stringify(content)) return id
1632
- const next: TeachingDocument = { ...document,
1633
- narrations: { ...document.narrations, [id]: { ...existing, id, content: structuredClone(content) } },
1634
- ...step.narrationIds.includes(id) ? {} : { steps: { ...document.steps, [stepId]: { ...step, narrationIds: [...step.narrationIds, id] } } },
1635
- }
1636
- const cueIds = new Set(content.flatMap(node => node.type === 'cue' ? [node.id] : []))
1637
- const previousCues = new Set(existing?.content.flatMap(node => node.type === 'cue' ? [node.id] : []) ?? [])
1638
- if (document.production.cueTimings) {
1639
- const removed = [...previousCues].filter(cue => !cueIds.has(cue) && Object.hasOwn(document.production.cueTimings!, cue)
1640
- && !Object.values(next.narrations).some(narration => narration.content.some(node => node.type === 'cue' && node.id === cue)))
1641
- if (removed.length) {
1642
- const cueTimings = { ...document.production.cueTimings }
1643
- for (const cue of removed) {
1644
- this.#removedCueTimings.delete(cue)
1645
- this.#removedCueTimings.set(cue, { ...cueTimings[cue]! })
1646
- delete cueTimings[cue]
1647
- }
1648
- while (this.#removedCueTimings.size > 512) this.#removedCueTimings.delete(this.#removedCueTimings.keys().next().value!)
1649
- next.production = { ...document.production, cueTimings }
1650
- }
1651
- }
1652
- for (const cue of cueIds) {
1653
- const timing = this.#removedCueTimings.get(cue)
1654
- if (!previousCues.has(cue) && timing && !Object.hasOwn(next.production.cueTimings ?? {}, cue)) {
1655
- next.production = { ...next.production, cueTimings: { ...next.production.cueTimings, [cue]: { ...timing } } }
1656
- this.#removedCueTimings.delete(cue)
1657
- }
1658
- }
1659
- this.stopAuditions()
1660
- this.#documentSession.record(next)
1661
- return id
1662
- }
1663
1088
  recordDocument(content: TeachingDocument): void { if (!isAgentChanging(this.#state)) this.#documentSession.record(content) }
1664
1089
  documentComposition(composing: boolean, owner = 'body', identity?: string): void { this.#documentSession.composition(composing, owner, identity) }
1665
1090
  retryDocument(): Promise<void> { return this.#documentSession.retry() }
1666
- discardDocument(): Promise<void> { return this.#documentSession.discard() }
1091
+ discardDocument(): Promise<void> { return this.#documentSession.discard().then(() => {}) }
1667
1092
  recoverDocumentDraft(value: DocumentDraftReference, identity: string): Promise<void> {
1668
- return this.#state.authoring?.identity === identity && !isAgentChanging(this.#state) ? this.#documentSession.recoverDraft(value) : Promise.resolve()
1093
+ return this.#state.authoring?.identity === identity && !isAgentChanging(this.#state) ? this.#documentSession.recoverDraft(value).then(() => {}) : Promise.resolve()
1669
1094
  }
1670
1095
  forgetDocumentDraft(value: DocumentDraftReference, identity: string): void {
1671
1096
  if (this.#state.authoring?.identity === identity && !isAgentChanging(this.#state)) void this.#documentSession.forgetDraft(value)
1672
1097
  }
1673
1098
  documentError(error: Error): void { this.#set({ save: { kind: 'failed', message: error.message } }) }
1674
- documentInteraction(): void {
1675
- this.#documentSelectionGeneration++; this.#cancelOpeningDocument(); this.#stopDocumentReturnScroll?.()
1676
- if (this.#state.documentPositionFailure) this.#set({ documentPositionFailure: undefined })
1677
- }
1678
- pendingDocumentField(blockId: string | undefined, identity?: string): Pick<DocumentFieldRegistration, 'stepId' | 'narrationId' | 'slot'> | undefined {
1679
- const pending = this.#pendingDocumentField, source = this.#state.authoring
1680
- return pending && pending.generation === this.#documentSelectionGeneration && pending.field.blockId === blockId
1681
- && pending.field.identity === (identity ?? source?.identity) && pending.reset === source?.reset ? pending.field : undefined
1682
- }
1683
- /** A live native field owns its target only while it still has focus in this source. */
1684
- focusedDocumentField(): Readonly<Pick<DocumentFieldRegistration, 'identity' | 'reset' | 'blockId' | 'stepId' | 'narrationId' | 'slot'>> & { readonly editor: DocumentHistoryEditor } | undefined {
1685
- const source = this.#state.authoring, editor = this.#activeDocumentHistory
1686
- if (!source?.identity || !source.content || !editor || editor === this.#documentEditor || editor.prosemirrorView.isDestroyed || !editor.prosemirrorView.hasFocus()) return
1687
- for (const field of this.#documentFields.values()) {
1688
- if (field.editor !== editor || field.identity !== source.identity || field.reset !== source.reset) continue
1689
- const step = source.content.steps[field.stepId], section = step && source.content.sections[step.sectionId]
1690
- if (!step || !section?.stepOrder.includes(field.stepId) || field.slot < 0 || field.slot >= Math.max(1, step.narrationIds.length)
1691
- || step.narrationIds[field.slot] !== undefined && step.narrationIds[field.slot] !== field.narrationId) return
1692
- const { identity, reset, blockId, stepId, narrationId, slot } = field
1693
- return { identity, reset, blockId, stepId, narrationId, slot, editor }
1694
- }
1695
- return undefined
1696
- }
1697
- registerDocumentField(field: DocumentFieldRegistration): () => void {
1698
- if (field.identity !== this.#state.authoring?.identity || field.reset !== this.#state.authoring.reset) return () => {}
1699
- const key = JSON.stringify([field.identity, field.blockId, field.stepId, field.slot, field.narrationId])
1700
- this.#documentFields.set(key, field)
1701
- const pending = this.#pendingDocumentField
1702
- if (pending && pending.reset === field.reset && JSON.stringify([pending.field.identity, pending.field.blockId, pending.field.stepId, pending.field.slot, pending.field.narrationId]) === key) {
1703
- this.#pendingDocumentField = undefined
1704
- if (pending.generation === this.#documentSelectionGeneration && field.identity === this.#state.authoring?.identity && field.reset === this.#state.authoring.reset) field.focus.restore(pending.bookmark)
1705
- }
1706
- return () => {
1707
- if (this.#documentFields.get(key) !== field) return
1708
- this.#documentFields.delete(key)
1709
- if (field.editor && this.#activeDocumentHistory === field.editor) this.activateDocumentHistory(this.#documentEditor)
1710
- }
1711
- }
1712
- /** Toolbar commands use the focused native editor's own history, without replacing the body editor. */
1713
- activateDocumentHistory(editor: DocumentHistoryEditor | undefined): void {
1714
- if (editor && editor !== this.#documentEditor && ![...this.#documentFields.values()].some(field => field.editor === editor && field.identity === this.#state.authoring?.identity)) return
1715
- if (editor === this.#activeDocumentHistory) return
1716
- this.#unsubscribeDocumentHistory?.()
1717
- this.#activeDocumentHistory = editor
1718
- const update = () => this.#set({ editorHistory: editor ? { section: this.#state.position?.section ?? '', undo: undoDepth(editor.prosemirrorState) > 0, redo: redoDepth(editor.prosemirrorState) > 0, field: editor !== this.#documentEditor } : undefined })
1719
- this.#unsubscribeDocumentHistory = editor?.onChange(update)
1720
- update()
1721
- }
1722
- attachDocumentEditor(editor: NativeDocumentEditor | undefined, commands?: DocumentEditorCommands, binding?: { identity: string, reset: number }): void {
1723
- if (binding && (binding.identity !== this.#state.authoring?.identity || binding.reset !== this.#state.authoring.reset)) return
1724
- const wasBody = !this.#activeDocumentHistory || this.#activeDocumentHistory === this.#documentEditor
1725
- if (editor !== this.#documentEditor) this.#documentSession.composition(false, 'body')
1726
- this.#unsubscribeDocumentSelection?.(); this.#stopDocumentLayoutScroll?.(); this.#stopDocumentLayoutScroll = undefined
1727
- this.#documentEditor = editor; this.#documentEditorCommands = commands; this.#documentEditorBinding = editor ? binding : undefined
1728
- if (editor) {
1729
- const focus = this.#pendingDocumentFocus, selection = this.#pendingDocumentSelection
1730
- this.#pendingDocumentFocus = undefined; this.#pendingDocumentSelection = undefined
1731
- if (focus && focus.documentId === this.#state.authoring?.content?.id && focus.generation === this.#documentSelectionGeneration && editor.getBlock(focus.nodeId)) {
1732
- // A deferred page operation adopts its selection only after the source write is acknowledged.
1733
- if (!focus.afterSave) {
1734
- this.#focusDocumentNode(editor, focus.nodeId)
1735
- }
1736
- } else if (!this.#pendingDocumentField && selection && selection.documentId === this.#state.authoring?.content?.id) {
1737
- const anchor = nativeTextPosition(editor, selection.anchor), head = nativeTextPosition(editor, selection.head)
1738
- if (anchor !== undefined && head !== undefined) {
1739
- editor.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, anchor, head)))
1740
- if (selection.focused) editor.focus()
1741
- }
1742
- }
1743
- }
1744
- if (wasBody) this.activateDocumentHistory(editor)
1745
- if (editor) {
1746
- const focus = () => this.activateDocumentHistory(editor)
1747
- const element = editor.prosemirrorView.dom
1748
- element.addEventListener('focusin', focus)
1749
- if (editor.prosemirrorView.hasFocus()) focus()
1750
- const stopSelection = editor.onSelectionChange(() => { this.#documentSelectionGeneration++ })
1751
- this.#unsubscribeDocumentSelection = () => { this.#stopDocumentLayoutScroll?.(); stopSelection(); element.removeEventListener('focusin', focus) }
1752
- } else this.#unsubscribeDocumentSelection = undefined
1753
- this.#finishOpeningDocument()
1754
- }
1755
- #focusDocumentNode(editor: NativeDocumentEditor, nodeId: string): void {
1756
- this.#stopDocumentLayoutScroll?.(); this.#stopDocumentLayoutScroll = undefined
1757
- editor.setTextCursorPosition(nodeId, 'start')
1758
- editor.focus()
1759
- editor.prosemirrorView.dispatch(editor.prosemirrorState.tr.scrollIntoView())
1760
- // React node views can finish sizing after the native editor mounts.
1761
- // Keep only this untouched focus visible through those layout changes.
1762
- if (typeof ResizeObserver !== 'undefined') {
1763
- const view = editor.prosemirrorView, document = view.dom.ownerDocument
1764
- const source = this.#state.authoring!, identity = source.identity, reset = source.reset, documentId = source.content!.id
1765
- const request = this.#state.documentNavigation?.request, selected = editor.prosemirrorState.selection
1766
- let size = view.dom.getBoundingClientRect(), active = true
1767
- const events = ['pointerdown', 'wheel', 'touchmove', 'keydown', 'beforeinput']
1768
- const cancel = () => {
1769
- if (!active) return
1770
- active = false; observer.disconnect(); stopFocus(); stopSelection()
1771
- for (const event of events) document.removeEventListener(event, interact, true)
1772
- }
1773
- const interact = (event: Event) => { if (event.isTrusted) cancel() }
1774
- const stopFocus = editor.onFocusChange((_, { focused }) => { if (!focused) cancel() })
1775
- const stopSelection = editor.onSelectionChange(cancel)
1776
- const observer = new ResizeObserver(() => {
1777
- if (!active) return
1778
- const current = this.#state.authoring
1779
- if (this.#documentEditor !== editor || view.isDestroyed || !current || current.identity !== identity || current.reset !== reset
1780
- || current?.content?.id !== documentId || this.#state.documentNavigation?.request !== request
1781
- || !editor.isFocused() || !editor.prosemirrorState.selection.eq(selected) || editor.getTextCursorPosition().block.id !== nodeId) { cancel(); return }
1782
- const next = view.dom.getBoundingClientRect()
1783
- if (next.width === size.width && next.height === size.height) return
1784
- size = next
1785
- view.dispatch(editor.prosemirrorState.tr.scrollIntoView())
1786
- })
1787
- for (const event of events) document.addEventListener(event, interact, true)
1788
- observer.observe(view.dom)
1789
- this.#stopDocumentLayoutScroll = cancel
1790
- }
1791
- }
1792
1099
  async flushPendingEdits(signal?: AbortSignal): Promise<void> {
1793
1100
  if (isAgentChanging(this.#state)) throw new Error('save-locked')
1794
1101
  await this.#documentSession.flush(signal)
1795
1102
  }
1796
- async #changeDocumentPage(change: (document: TeachingDocument) => void): Promise<boolean> {
1797
- const source = this.#state.authoring, directory = this.#state.document
1798
- if (!source?.content || directory === undefined || isAgentChanging(this.#state)) return false
1799
- const scope = this.#documentScope, identity = source.identity, documentId = source.content.id
1800
- const current = () => scope === this.#documentScope && directory === this.#state.document && identity === this.#state.authoring?.identity && documentId === this.#state.authoring?.content?.id
1801
- this.#set({ isEditingPage: true, pageEditFailure: undefined })
1802
- try {
1803
- await this.flushPendingEdits()
1804
- if (!current()) throw new Error('page-context-changed')
1805
- const document = structuredClone(this.#state.authoring!.content!)
1806
- change(document)
1807
- const editor = this.#documentEditor
1808
- this.#pendingDocumentField = undefined
1809
- const plannedFocus = this.#pendingDocumentFocus
1810
- if (!plannedFocus || plannedFocus.generation !== this.#documentSelectionGeneration) for (const field of this.#documentFields.values()) {
1811
- if (field.identity !== source.identity || field.reset !== this.#state.authoring!.reset || field.blockId !== undefined && !document.blocks[field.blockId] || !document.steps[field.stepId]) continue
1812
- const bookmark = field.focus.capture()
1813
- if (bookmark) {
1814
- const { focus: _focus, editor: _editor, ...target } = field
1815
- this.#pendingDocumentField = { field: target, bookmark, reset: this.#state.authoring!.reset + 1, generation: this.#documentSelectionGeneration }
1816
- this.#pendingDocumentSelection = undefined
1817
- break
1818
- }
1819
- }
1820
- if (editor && !this.#pendingDocumentField) {
1821
- const state = editor.prosemirrorState, anchor = nativeTextPoint(editor, state.selection.anchor), head = nativeTextPoint(editor, state.selection.head)
1822
- if (anchor && head) this.#pendingDocumentSelection = { documentId: document.id, anchor, head, focused: editor.prosemirrorView.hasFocus() }
1823
- }
1824
- this.#documentSession.replace(document)
1825
- await this.#documentSession.flush()
1826
- return current()
1827
- } catch (error) { if (current()) this.#set({ pageEditFailure: this.#pageEditMessage(errorMessage(error)) }); return false }
1828
- finally { if (current()) this.#set({ isEditingPage: false }) }
1829
- }
1830
- renamePage(section: string, title: string): Promise<boolean> {
1831
- return this.#changeDocumentPage(document => { Object.assign(document, renameDocumentPage(document, section, title)) })
1832
- }
1833
- async duplicatePage(section: string): Promise<boolean> {
1834
- if (this.#state.isEditingPage || this.#state.isCreatingPage || this.#state.isHistoryBusy) return false
1835
- const scope = this.#documentScope, identity = this.#state.authoring?.identity, generation = this.#documentSelectionGeneration, navigation = this.#state.documentNavigation?.request
1836
- let copied: string | undefined
1837
- const saved = await this.#changeDocumentPage(document => {
1838
- if (scope !== this.#documentScope || identity !== this.#state.authoring?.identity) throw new Error('page-context-changed')
1839
- const page = document.sections[section]
1840
- if (!page) throw new Error('page-boundary')
1841
- const copy = duplicateDocumentPage(document, section, contentText(document.metadata.lang).copyTitle(page.title), () => crypto.randomUUID())
1842
- copied = copy.section
1843
- Object.assign(document, copy.document)
1844
- if (generation === this.#documentSelectionGeneration) this.#pendingDocumentFocus = { documentId: document.id, nodeId: `page:${copied}`, generation, afterSave: true }
1845
- })
1846
- // Source confirmation owns editing. A later author selection takes precedence over this response.
1847
- if (!saved || !copied || scope !== this.#documentScope || generation !== this.#documentSelectionGeneration || navigation !== this.#state.documentNavigation?.request || !this.#state.authoring?.content?.sections[copied]) return saved
1848
- this.goToSection(copied)
1849
- const editor = this.#documentEditor
1850
- if (editor) {
1851
- const blocks = editor.document, start = blocks.findIndex(block => block.id === `page:${copied}`)
1852
- const first = (nodes: typeof blocks): string | undefined => {
1853
- for (const node of nodes) { if (node.type === 'presmiumPage') break; if (node.content !== undefined) return node.id; const child = first(node.children); if (child) return child }
1854
- return undefined
1855
- }
1856
- const target = start < 0 ? undefined : first(blocks.slice(start + 1)) ?? blocks[start]!.id
1857
- if (target) { editor.setTextCursorPosition(target, 'start'); editor.focus() }
1858
- }
1859
- return true
1860
- }
1861
- movePage(section: string, before: string | null): Promise<boolean> {
1862
- return this.#changeDocumentPage(document => { Object.assign(document, moveDocumentPage(document, section, before)) })
1863
- }
1864
- pageDeleteMessage(reason: string): string { return this.#pageEditMessage(reason) }
1865
- async preparePageDeletion(section: string): Promise<PageDeletePlan> {
1866
- await this.flushPendingEdits()
1867
- const source = this.#state.authoring
1868
- if (!source?.content || !source.version || this.#state.document === undefined) throw new Error('document-unavailable')
1869
- return pageDeletion(source.content, this.#state.document, source.version, section)
1870
- }
1871
- async deletePage(plan: PageDeletePlan): Promise<boolean> {
1872
- if (!plan.allowed || plan.document !== this.#state.document) return false
1873
- return this.#changeDocumentPage(document => {
1874
- if (this.#state.authoring?.version !== plan.source.version) throw new Error('revision-conflict')
1875
- const current = pageDeletion(document, plan.document, plan.source.version, plan.section)
1876
- if (!current.allowed) throw new Error(current.reason)
1877
- Object.assign(document, removeDocumentPage(document, plan.section, () => crypto.randomUUID()))
1878
- this.#set({ position: { section: document.sectionOrder[0]!, step: 0, trail: [], view: 'document' }, documentNavigation: { section: document.sectionOrder[0]!, request: crypto.randomUUID() } })
1879
- })
1880
- }
1881
- createPage(after = this.#state.position?.section): boolean {
1882
- const source = this.#state.authoring, editor = this.#documentEditor, commands = this.#documentEditorCommands
1883
- if (!source?.content || source.loading || source.composing || source.restored || source.error || !editor || !commands
1884
- || editor.prosemirrorView.isDestroyed || isAgentChanging(this.#state) || this.#state.isEditingPage || this.#state.isCreatingPage
1885
- || this.#state.isHistoryBusy || this.#state.isHistoryPreparing) return false
1886
- try {
1887
- this.#set({ pageEditFailure: undefined })
1888
- const created = commands.insertPage(after, contentText(source.content.metadata.lang).newPage)
1889
- this.#pendingDocumentField = undefined; this.#pendingDocumentSelection = undefined; this.#pendingDocumentFocus = undefined
1890
- this.#set({ position: { section: created.sectionId, step: 0, trail: [], view: 'document' }, documentNavigation: { section: created.sectionId, request: crypto.randomUUID() } })
1891
- this.#focusDocumentNode(editor, created.nodeId)
1892
- return true
1893
- } catch (error) { this.#set({ pageEditFailure: this.#pageEditMessage(errorMessage(error)) }); return false }
1894
- }
1895
-
1896
1103
  /** Points at a block or a passage (none: stops pointing): the preview outlines it and the conversation is told. */
1897
1104
  point(pointer: Pointer | undefined): void {
1898
1105
  const pointed = this.#state.pointer !== undefined || this.#state.focus.length > 0
@@ -1966,6 +1173,40 @@ export class Workbench {
1966
1173
  }
1967
1174
  }
1968
1175
 
1176
+ /**
1177
+ * Opens the conversation with a request, for the author to describe and send, to add an animation at `place` of the
1178
+ * open document; the document's focus points the AI at the place's block. Nothing is inserted or sent.
1179
+ */
1180
+ draftAnimation(place: DocumentInsertionPlace): boolean {
1181
+ const document = this.#state.document, content = this.#state.authoring?.content, drafter = [...this.#drafters][0]
1182
+ const section = content?.sections[place.sectionId]
1183
+ if (document === undefined || !content || !section || !drafter) return false
1184
+ const report = (block?: string): FocusReport => ({ id: 'insertion', from: this.#state.previewRenderer, section: place.sectionId, ...block ? { block } : {}, ...place.text ? { quote: place.text.slice(0, 2000) } : {} })
1185
+ const text = this.#messages.animationRequest(content.sectionOrder.indexOf(place.sectionId) + 1, section.title, place)
1186
+ const focus = [report(place.blocks[0])]
1187
+ void this.#focusFirst(document, [...place.blocks.map(block => [report(block)]), [report()], []])
1188
+ const drafted = (attributes: Record<string, OperationValue>) => this.#record('agent.draft', { 'presmium.ask.kind': 'animation', 'presmium.ask.text': text, 'presmium.section': place.sectionId, 'presmium.block': place.blocks[0], ...attributes })
1189
+ this.#set({ askFailure: undefined })
1190
+ void (async () => drafter({ text, focus }))().then(() => drafted({ 'presmium.outcome': 'drafted' }), (error: unknown) => {
1191
+ drafted({ 'presmium.outcome': 'failed', 'presmium.error': errorMessage(error) })
1192
+ if (this.#state.document === document) this.#set({ askFailure: errorMessage(error) })
1193
+ })
1194
+ return true
1195
+ }
1196
+
1197
+ /**
1198
+ * Sets the first of `choices` the service can locate as the document's focus. Its runtime snapshot is compiled from the
1199
+ * saved source, which may not have a block or page created moments ago yet; the last choice leaves no stale focus.
1200
+ */
1201
+ async #focusFirst(document: string, choices: FocusReport[][]): Promise<void> {
1202
+ for (const focus of choices) {
1203
+ this.setFocus(focus)
1204
+ const version = this.#focusVersion
1205
+ await this.#focusWriting
1206
+ if (version !== this.#focusVersion || this.#state.document !== document || !this.#state.focusFailure) return
1207
+ }
1208
+ }
1209
+
1969
1210
  /** A place as the author sees it: the section's title and the passage. */
1970
1211
  #describe(item: FocusReport & Partial<Focus>): AgentPlace {
1971
1212
  const doc = this.#state.ir?.doc
@@ -1989,7 +1230,7 @@ export class Workbench {
1989
1230
  /** Shows a section in the preview: from the navigation pane, the section to read or the slide to show. */
1990
1231
  goToSection(section: string): void {
1991
1232
  if (this.#state.webView === 'document' && this.#state.authoring?.content?.sections[section]) {
1992
- this.#set({ position: { section, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: { section, request: crypto.randomUUID() } }); return
1233
+ this.#set({ position: { section, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: { section, request: randomUUID() } }); return
1993
1234
  }
1994
1235
  this.goToStep(section, this.#selectedSteps.get(`${this.#state.document}\0${section}`) ?? 0)
1995
1236
  }
@@ -2003,7 +1244,7 @@ export class Workbench {
2003
1244
  const visible = (index: number) => Boolean(section.stepOrder[index] && effectiveComponentParameters(document, blockId, section.stepOrder[index]).visual?.visible)
2004
1245
  const step = visible(current) ? current : Math.max(0, section.stepOrder.findIndex((_, index) => visible(index)))
2005
1246
  this.#set({ position: { section: sectionId, step, trail: [], view: 'document' }, documentPositionFailure: undefined,
2006
- documentNavigation: { section: sectionId, block: blockId, request: crypto.randomUUID() } })
1247
+ documentNavigation: { section: sectionId, block: blockId, request: randomUUID() } })
2007
1248
  }
2008
1249
 
2009
1250
  observeDocumentSection(section: string): void {
@@ -2035,7 +1276,7 @@ export class Workbench {
2035
1276
  const plan = this.#state.productionPlan, range = plan?.pages.find(page => page.sectionId === sectionId)?.steps.find(step => step.stepId === stepId)
2036
1277
  if (plan?.canPreview && this.#productionReady() && range?.startMs !== undefined) {
2037
1278
  this.stopAuditions()
2038
- if (this.#production.selecting(sectionId, stepId)) return
1279
+ if (this.#productionPlayback.selecting(sectionId, stepId)) return
2039
1280
  this.#selectedSteps.set(`${this.#state.document}\0${sectionId}`, step)
2040
1281
  this.#set({ position: { section: sectionId, step, trail: [], view: 'present' } })
2041
1282
  return this.controlProduction({ binding: plan.binding, action: 'step', sectionId, stepId }).catch(() => undefined)
@@ -2090,8 +1331,8 @@ export class Workbench {
2090
1331
  return true
2091
1332
  }
2092
1333
 
2093
- undo(): Promise<boolean> { if (this.#state.mode !== 'editing') return Promise.resolve(false); if (this.#activeDocumentHistory && (this.#state.editorHistory?.undo || this.#state.editorHistory?.field)) { this.#activeDocumentHistory.focus(); return Promise.resolve(this.#activeDocumentHistory.undo()) } return this.#changeHistory('undo') }
2094
- redo(): Promise<boolean> { if (this.#state.mode !== 'editing') return Promise.resolve(false); if (this.#activeDocumentHistory && (this.#state.editorHistory?.redo || this.#state.editorHistory?.field)) { this.#activeDocumentHistory.focus(); return Promise.resolve(this.#activeDocumentHistory.redo()) } return this.#changeHistory('redo') }
1334
+ undo(): Promise<boolean> { const result = this.editing.nativeHistory('undo'); return result === undefined ? this.#changeHistory('undo') : Promise.resolve(result) }
1335
+ redo(): Promise<boolean> { const result = this.editing.nativeHistory('redo'); return result === undefined ? this.#changeHistory('redo') : Promise.resolve(result) }
2095
1336
 
2096
1337
  async #changeHistory(action: 'undo' | 'redo' | 'revert', revision?: string): Promise<boolean> {
2097
1338
  if (this.#state.mode !== 'editing' || this.#state.isCreatingPage || this.#state.isEditingPage || this.#state.isHistoryBusy || this.#state.isHistoryPreparing) return false
@@ -2192,7 +1433,7 @@ export class Workbench {
2192
1433
  sink.send({ type: 'highlight', target: reveal ?? this.#state.pointer?.target ?? null })
2193
1434
  return () => {
2194
1435
  this.#previewSinks.delete(sink)
2195
- this.#production.detach(sink)
1436
+ this.#productionPlayback.detach(sink)
2196
1437
  this.#set({ previewConnection: this.#state.previewConnection + 1 })
2197
1438
  this.#playback.detach(sink)
2198
1439
  }
@@ -2209,7 +1450,7 @@ export class Workbench {
2209
1450
  if (report.type === 'page-create') { origin?.send({ type: 'page-created', section: report.section, request: report.request, error: unsupported }); return }
2210
1451
  if (document !== this.#state.document || renderer !== this.#state.previewRenderer) return
2211
1452
  this.#playback.report(document, report, origin)
2212
- this.#production.report(document, report, origin)
1453
+ this.#productionPlayback.report(document, report, origin)
2213
1454
  switch (report.type) {
2214
1455
  case 'ready':
2215
1456
  case 'updated':
@@ -2236,9 +1477,6 @@ export class Workbench {
2236
1477
  } else if (this.#state.pointer?.quote) this.point(undefined)
2237
1478
  break
2238
1479
  }
2239
- case 'flashed':
2240
- if (this.#trail) this.#set({ changeTrail: { id: this.#trail, rects: report.rects } })
2241
- break
2242
1480
  case 'rect':
2243
1481
  if (this.#state.pointer) this.#set({ pointer: { ...this.#state.pointer, rect: report.rect ?? undefined, obstacles: report.obstacles } })
2244
1482
  break
@@ -2247,7 +1485,7 @@ export class Workbench {
2247
1485
  if (snapshot && source && (source.dirty || source.loading || source.version !== snapshot.version || source.fingerprint !== snapshot.fingerprint)) break
2248
1486
  // An initial loader can report its old cursor while a newer stable selection is preparing.
2249
1487
  // Explicit native exits still reach the outer document workspace.
2250
- if (report.view !== 'document' && this.#production.selecting()) break
1488
+ if (report.view !== 'document' && this.#productionPlayback.selecting()) break
2251
1489
  // A fresh frame announces its document view before applying the queued
2252
1490
  // presentation command. Only the requested view completes that switch.
2253
1491
  if (renderer === 'web' && this.#awaitingView) {
@@ -2286,19 +1524,14 @@ export class Workbench {
2286
1524
 
2287
1525
  #stopSubscriptions(): void {
2288
1526
  this.#componentPropertyDrafts.stopAgentRead()
2289
- this.#saveDocumentReturnPoint(); this.#cancelOpeningDocument(); this.#stopDocumentReturnScroll?.()
2290
- this.#documentViewport?.stop(); this.#documentViewport = undefined; this.#documentEditorBinding = undefined
1527
+ this.editing.reset()
2291
1528
  this.#presentationPreparation++
2292
1529
  this.#presentationController?.abort(new Error('client-document-changed'))
2293
1530
  this.#voiceover.stop()
2294
- this.#production.reset()
1531
+ this.#productionPlayback.reset()
2295
1532
  this.#set({ isPreparingPresentation: false, presentationFailure: undefined, presentationSnapshot: undefined, productionPlan: undefined, productionFailure: undefined })
2296
- this.#removedCueTimings.clear(); this.#cueTimingScope = undefined
1533
+ this.production.reset()
2297
1534
  this.#documentSession.close()
2298
- this.#unsubscribeDocumentHistory?.(); this.#unsubscribeDocumentHistory = undefined; this.#activeDocumentHistory = undefined; this.#documentEditor = undefined
2299
- this.#unsubscribeDocumentSelection?.(); this.#unsubscribeDocumentSelection = undefined
2300
- this.#pendingDocumentFocus = undefined; this.#pendingDocumentSelection = undefined; this.#documentSelectionGeneration++
2301
- this.#documentFields.clear(); this.#pendingDocumentField = undefined
2302
1535
  this.#playback.reset()
2303
1536
  this.#focusVersion++
2304
1537
  this.#pendingReveal = undefined
@@ -2321,8 +1554,9 @@ export class Workbench {
2321
1554
  this.#documentSession.dispose()
2322
1555
  this.#commentDrafts.close()
2323
1556
  this.#componentPropertyDrafts.close()
2324
- this.#captionTimingDrafts.close()
1557
+ this.production.dispose()
2325
1558
  disposeTranscriptionSessions(this.client)
2326
1559
  disposeDocumentRecordings(this)
1560
+ this.#clientControls.clear(); this.#clientControlListeners.clear()
2327
1561
  }
2328
1562
  }