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

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 (80) 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/authoring-window.ts +100 -0
  7. package/src/body-draft-actions.ts +60 -0
  8. package/src/component-property-drafts.ts +5 -5
  9. package/src/components.tsx +10 -28
  10. package/src/context.tsx +2 -1
  11. package/src/diagnostics.ts +1 -1
  12. package/src/document-draft-store.ts +45 -18
  13. package/src/document-drafts.ts +28 -19
  14. package/src/document-editing.ts +484 -0
  15. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  16. package/src/document-editor/ComponentMaterials.tsx +3 -9
  17. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  18. package/src/document-editor/DocumentBlockPreview.tsx +4 -2
  19. package/src/document-editor/DocumentComments.tsx +58 -9
  20. package/src/document-editor/DocumentEditor.tsx +44 -7
  21. package/src/document-editor/DocumentStepNarration.tsx +30 -25
  22. package/src/document-editor/NarrationEditor.tsx +54 -20
  23. package/src/document-editor/NewCommentDrafts.tsx +4 -3
  24. package/src/document-editor/PlaceComment.tsx +150 -0
  25. package/src/document-editor/comment-drafts.ts +16 -14
  26. package/src/document-editor/comments.ts +30 -10
  27. package/src/document-editor/component-label.ts +11 -0
  28. package/src/document-editor/file-input.ts +2 -2
  29. package/src/document-editor/focus.ts +0 -2
  30. package/src/document-editor/insertion-place.ts +60 -0
  31. package/src/document-editor/messages.ts +3 -3
  32. package/src/document-editor/narration-schema.tsx +12 -6
  33. package/src/document-editor/narration.ts +19 -3
  34. package/src/document-editor/page-body.ts +60 -0
  35. package/src/document-editor/projection.ts +2 -2
  36. package/src/document-editor/rich-text.ts +3 -2
  37. package/src/document-editor/selection.ts +13 -0
  38. package/src/document-editor/style.css +12 -1
  39. package/src/document-editor/table-identities.ts +2 -1
  40. package/src/document-production.ts +339 -0
  41. package/src/document-session.ts +193 -53
  42. package/src/history.ts +5 -5
  43. package/src/index.ts +6 -5
  44. package/src/jobs.ts +1 -1
  45. package/src/messages.ts +19 -4
  46. package/src/panels/DocumentView.tsx +66 -26
  47. package/src/panels/DocumentVoiceDialog.tsx +2 -2
  48. package/src/panels/DocumentVoiceField.tsx +1 -1
  49. package/src/panels/ExportPanel.tsx +1 -6
  50. package/src/panels/HistoryPanel.tsx +1 -1
  51. package/src/panels/PageDeleteDialog.tsx +4 -4
  52. package/src/panels/PageRenameDialog.tsx +1 -1
  53. package/src/panels/PreviewPanel.tsx +1 -4
  54. package/src/panels/ProductionCaptionSize.tsx +20 -0
  55. package/src/panels/ProductionCaptionTiming.tsx +7 -7
  56. package/src/panels/ProductionMediaClips.tsx +6 -5
  57. package/src/panels/ProductionPanel.tsx +8 -4
  58. package/src/panels/ProductionRecording.tsx +86 -9
  59. package/src/panels/ProductionRecordingRange.tsx +19 -19
  60. package/src/panels/ProductionTimeline.tsx +6 -1
  61. package/src/panels/ProductionTranscription.tsx +5 -4
  62. package/src/panels/SourceDocumentPanel.tsx +12 -15
  63. package/src/panels/TranscriptionAdoption.tsx +9 -8
  64. package/src/panels/VoiceCloneDialog.tsx +2 -1
  65. package/src/panels/VoiceoverDialog.tsx +1 -1
  66. package/src/places.ts +1 -36
  67. package/src/preview-playback.ts +1 -1
  68. package/src/production-messages.ts +6 -0
  69. package/src/production-playback.ts +1 -1
  70. package/src/production-voice-playback.ts +3 -2
  71. package/src/sha256.ts +9 -0
  72. package/src/styles.css +16 -41
  73. package/src/use-recording-adoption.ts +2 -2
  74. package/src/voiceover-jobs.ts +1 -1
  75. package/src/workbench-state.ts +157 -0
  76. package/src/workbench.ts +246 -948
  77. package/src/workspace-client.ts +21 -11
  78. package/src/assistant-mascot.ts +0 -62
  79. package/src/mascot-preference.ts +0 -37
  80. 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'
4
- import type { ProjectOperation, ProjectPlan } from '@lincyaw/kernel'
5
- import { undoDepth, redoDepth } from '@tiptap/pm/history'
6
- import { TextSelection } from '@tiptap/pm/state'
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'
6
+ import type { ProjectOperation, ProjectPlan, AuthoringWindowSnapshot, AuthoringWindowAction, AuthoringWindowRequest, AuthoringWindowRequestResult } from '@lincyaw/kernel'
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,15 @@ 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 #navigationGuards = new Set<() => boolean>()
122
+ readonly #clientControlListeners = new Set<Listener>()
123
+ #clientControlRevision = 0
299
124
  readonly #commentDrafts = new CommentDraftBank()
300
125
  readonly #componentPropertyDrafts = new ComponentPropertyDrafts()
301
126
  readonly #positionSeed = Array.from(crypto.getRandomValues(new Uint32Array(2)), value => value.toString(36)).join('-')
@@ -307,6 +132,7 @@ export class Workbench {
307
132
  readonly #jobs: DocumentJobs
308
133
  readonly #voiceover: VoiceoverJobs
309
134
  readonly #askers = new Set<(request: AgentRequest) => Promise<AgentAnswer | void>>()
135
+ readonly #drafters = new Set<(draft: AgentDraft) => void | Promise<void>>()
310
136
  readonly #previewSinks = new Set<PreviewSink>()
311
137
  readonly #playbackKeys = new Set<(command: PlaybackKey) => void>()
312
138
  #unsubscribeIr?: () => void
@@ -323,13 +149,12 @@ export class Workbench {
323
149
  #documentScope = 0
324
150
  #jobPreparation?: AbortController
325
151
  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,
152
+ readonly #productionPlayback = new ProductionPlayback(() => ({ document: this.#state.document, scope: this.#documentScope, sinks: this.#previewSinks,
327
153
  binding: this.#state.productionPlan?.binding, ready: this.#productionReady() }), state => this.#set({ productionPlayback: state }))
328
154
  /** A place to show that no preview could take yet (none was attached, e.g. the chat covered the document). */
329
155
  #pendingReveal?: PreviewAnchor
330
156
  /** The AI's changes to show on the document once the preview has them. */
331
157
  #pendingFlash?: ReviewChange[]
332
- #trail = 0
333
158
  #lastPosition?: string
334
159
  #awaitingView?: WebView
335
160
  /** The forms asked for ahead of the author (`web:<dir>`, `slides:<dir>`), and the wait before asking for the slides. */
@@ -369,12 +194,7 @@ export class Workbench {
369
194
  }
370
195
  this.#documentSession = new DocumentSession(this.client, authoring => {
371
196
  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 }
197
+ this.editing.sourceChanged(authoring)
378
198
  const previous = this.#state.authoring
379
199
  // A saved timestamp belongs to this client's acknowledged source version.
380
200
  // Remote adoption has no server modification time to display in its place.
@@ -389,40 +209,39 @@ export class Workbench {
389
209
  const removed = this.#state.webView === 'document' && position?.view !== 'present' && position && previous?.identity === authoring.identity
390
210
  && (selected ? !selectedStep || selectedIndex < 0 : !authoring.content?.sectionOrder.includes(position.section))
391
211
  const restoredPosition = !removed && this.#restoredDocumentPosition(authoring)
392
- const scope = this.#documentScope, generation = this.#documentSelectionGeneration
393
- if (removed && authoring.identity) this.#documentReturnPoints.forget(authoring.identity)
212
+ const scope = this.#documentScope, generation = this.editing.generation
213
+ if (removed && authoring.identity) this.editing.returnPoints.forget(authoring.identity)
394
214
  this.#set({ authoring,
395
215
  ...removed ? { position: undefined, documentNavigation: undefined, documentPositionFailure: 'removed' as const } : {},
396
216
  ...restoredPosition ? { documentPositionFailure: undefined } : {},
397
217
  ...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 })),
218
+ ...this.production.draftState(authoring),
402
219
  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
220
  // The deletion owns the token produced above; source restoration only retires its notice.
404
221
  if (removed && previous?.identity && previous.content && previous.version && previous.fingerprint
405
222
  && !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') {
223
+ && scope === this.#documentScope && generation === this.editing.generation && !this.#state.position && this.#state.documentPositionFailure === 'removed') {
407
224
  this.#removedDocumentPosition = { identity: previous.identity, documentId: previous.content.id, sectionId: position.section,
408
225
  ...selected ? { stepId: selected } : {}, version: previous.version, fingerprint: previous.fingerprint, scope, generation, token: this.#state.documentPositionToken }
409
226
  }
410
- this.#finishOpeningDocument()
227
+ this.editing.finishOpening()
411
228
  // Native insertion can select a page before the source actor receives that new entity.
412
229
  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(() => {})
230
+ && authoring.content?.sections[position.section]) this.editing.saveReturnPoint()
231
+ if (this.#productionPlayback.changed()) void this.pausePlayback().catch(() => {})
415
232
  const acknowledgedSourceChanged = !authoring.dirty && !authoring.loading && !authoring.error && !previous?.loading
416
233
  && previous?.identity === authoring.identity && Boolean(previous?.version && authoring.version)
417
234
  && (previous?.version !== authoring.version || previous?.fingerprint !== authoring.fingerprint)
418
235
  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
236
  })
237
+ this.production = new DocumentProduction({ store, session: this.#documentSession, client: this.client,
238
+ scope: () => this.#documentScope, document: identity => this.getDocument(identity), flush: signal => this.flushPendingEdits(signal),
239
+ pause: () => this.pausePlayback(), stopAuditions: () => this.stopAuditions(), stopPreviewOutputs: () => this.#playback.stopPreviewOutputs(),
240
+ sourceCurrent: binding => this.#productionSourceCurrent(binding) })
241
+ this.editing = new DocumentEditing({ store, session: this.#documentSession, scope: () => this.#documentScope,
242
+ flush: signal => this.flushPendingEdits(signal), goToSection: section => this.goToSection(section),
243
+ rememberStep: (directory, section, step) => { this.#selectedSteps.set(`${directory}\0${section}`, step) },
244
+ canAskAnimation: () => this.#drafters.size > 0, askAnimation: place => this.draftAnimation(place) })
426
245
  this.#diagnostics = new DocumentDiagnostics(this.client, store)
427
246
  this.#jobs = new DocumentJobs(this.client, store)
428
247
  this.#voiceover = new VoiceoverJobs(this.client, store, (job, signal) => this.#refreshVoiceover(job, signal))
@@ -473,11 +292,36 @@ export class Workbench {
473
292
  /** Only counters enter passive client state; no new form payload is exposed to MCP. */
474
293
  authoringDraftRevision(): string {
475
294
  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])
295
+ 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
296
  }
478
297
  subscribeAuthoringDraftChanges(listener: () => void): () => void {
479
298
  const comments = this.#commentDrafts.subscribe(listener), properties = this.#componentPropertyDrafts.subscribe(listener)
480
- return () => { comments(); properties() }
299
+ this.#clientControlListeners.add(listener)
300
+ return () => { comments(); properties(); this.#clientControlListeners.delete(listener) }
301
+ }
302
+
303
+ registerAuthoringClientControls(controls: AuthoringClientControls): () => void {
304
+ this.#clientControls.add(controls); this.refreshAuthoringClientControls()
305
+ return () => { this.#clientControls.delete(controls); this.refreshAuthoringClientControls() }
306
+ }
307
+ refreshAuthoringClientControls(): void {
308
+ this.#clientControlRevision++
309
+ for (const listener of this.#clientControlListeners) listener()
310
+ }
311
+ /** A mounted native form owns any input/transaction that cannot safely leave its view. */
312
+ registerNavigationGuard(blocked: () => boolean): () => void {
313
+ this.#navigationGuards.add(blocked); this.refreshAuthoringClientControls()
314
+ return () => { this.#navigationGuards.delete(blocked); this.refreshAuthoringClientControls() }
315
+ }
316
+ waitForAuthoringClientState(ready: () => boolean, signal: AbortSignal): Promise<void> {
317
+ return new Promise((resolve, reject) => {
318
+ const finish = (error?: unknown) => { stop(); stopControls(); signal.removeEventListener('abort', aborted); error ? reject(error) : resolve() }
319
+ const check = () => { try { signal.throwIfAborted(); if (ready()) finish() } catch (error) { finish(error) } }
320
+ const aborted = () => finish(signal.reason ?? new Error('client-request-expired'))
321
+ const stop = this.subscribe(check), stopControls = this.subscribeAuthoringDraftChanges(check)
322
+ signal.addEventListener('abort', aborted, { once: true })
323
+ check()
324
+ })
481
325
  }
482
326
 
483
327
  getState = (): WorkbenchState => this.#state
@@ -506,12 +350,18 @@ export class Workbench {
506
350
  return () => this.#askers.delete(asker)
507
351
  }
508
352
 
353
+ /** The host's way to put a request in the conversation's composer for the author to finish; nothing is sent. */
354
+ onAgentDraft = (drafter: (draft: AgentDraft) => void | Promise<void>): (() => void) => {
355
+ this.#drafters.add(drafter)
356
+ return () => this.#drafters.delete(drafter)
357
+ }
358
+
509
359
  #nextDocumentPosition(): string { return `${this.#positionSeed}:${++this.#positionSequence}` }
510
360
 
511
361
  #restoredDocumentPosition(source: DocumentSessionState): boolean {
512
362
  const removed = this.#removedDocumentPosition
513
363
  if (!removed) return false
514
- if (removed.scope !== this.#documentScope || removed.generation !== this.#documentSelectionGeneration || removed.token !== this.#state.documentPositionToken
364
+ if (removed.scope !== this.#documentScope || removed.generation !== this.editing.generation || removed.token !== this.#state.documentPositionToken
515
365
  || removed.identity !== source.identity || this.#state.documentPositionFailure !== 'removed' || source.error) {
516
366
  this.#removedDocumentPosition = undefined
517
367
  return false
@@ -525,9 +375,9 @@ export class Workbench {
525
375
 
526
376
  #set(patch: Partial<WorkbenchState>): void {
527
377
  if (Object.hasOwn(patch, 'position') || Object.hasOwn(patch, 'documentPositionFailure')) this.#removedDocumentPosition = undefined
528
- if (Object.hasOwn(patch, 'position')) { this.#cancelOpeningDocument(); this.#stopDocumentReturnScroll?.() }
378
+ if (Object.hasOwn(patch, 'position')) this.editing.beforePosition()
529
379
  this.#state = { ...this.#state, ...patch, ...Object.hasOwn(patch, 'position') ? { documentPositionToken: this.#nextDocumentPosition(), documentPositionIntent: patch.documentPositionIntent ?? 'seek' } : {} }
530
- if (Object.hasOwn(patch, 'position')) this.#saveDocumentReturnPoint()
380
+ if (Object.hasOwn(patch, 'position')) this.editing.saveReturnPoint()
531
381
  for (const listener of this.#listeners) listener()
532
382
  }
533
383
 
@@ -557,7 +407,7 @@ export class Workbench {
557
407
  }
558
408
 
559
409
  planDocumentOperation(operation: ProjectOperation): Promise<ProjectPlan> {
560
- return this.client.planProjectChange({ id: crypto.randomUUID(), operation })
410
+ return this.client.planProjectChange({ id: randomUUID(), operation })
561
411
  }
562
412
 
563
413
  operateDocument(operation: ProjectOperation, planned?: ProjectPlan): Promise<OperationAnswer> {
@@ -593,163 +443,28 @@ export class Workbench {
593
443
  await this.operateDocument({ op: 'retitle', dir, title })
594
444
  }
595
445
 
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
- async openDocument(dir: string, options: { focus?: 'body', expectedIdentity?: string, fallbackReturnPoint?: DocumentReturnPoint } = {}): Promise<void> {
446
+ async openDocument(dir: string, options: { focus?: 'body', expectedIdentity?: string, fallbackReturnPoint?: DocumentReturnPoint, signal?: AbortSignal } = {}): Promise<void> {
732
447
  if (this.#state.document === dir) {
733
- if (options.focus) { this.#beginOpeningDocument(dir, options.focus); this.#finishOpeningDocument() }
448
+ if (options.focus) { this.editing.beginOpening(dir, options.focus); this.editing.finishOpening() }
734
449
  return
735
450
  }
736
- this.#saveDocumentReturnPoint()
451
+ this.editing.saveReturnPoint()
737
452
  this.#documentScope++
738
453
  const scope = this.#documentScope
739
454
  this.#stopSubscriptions()
740
455
  this.#history.subscribeReview(dir)
741
456
  this.#set({ ...DOCUMENT_RESET, document: dir, previewRenderer: 'web', webView: 'document' })
742
- this.#beginOpeningDocument(dir, options.focus, options.fallbackReturnPoint)
457
+ this.editing.beginOpening(dir, options.focus, options.fallbackReturnPoint)
743
458
  this.#record('document.open')
744
459
  this.#diagnostics.subscribe(dir)
745
460
  // Authoring is ready from source JSON; compilation and preview are independent.
746
- const [opened] = await Promise.all([this.#documentSession.open(dir, options.expectedIdentity), this.#readFocus(dir), this.#history.read(dir)])
461
+ const [opened] = await Promise.all([this.#documentSession.open(dir, options.expectedIdentity, options.signal), this.#readFocus(dir, options.signal), this.#history.read(dir, options.signal)])
747
462
  if (opened === 'identity-changed' && scope === this.#documentScope && this.#state.document === dir) { this.closeDocument(); return }
748
- this.#finishOpeningDocument()
463
+ if (scope === this.#documentScope && this.#state.document === dir) this.editing.finishOpening()
749
464
  }
750
465
 
751
466
  closeDocument(): void {
752
- this.#saveDocumentReturnPoint()
467
+ this.editing.saveReturnPoint()
753
468
  this.#documentScope++
754
469
  if (this.#state.document !== undefined) this.#record('document.close')
755
470
  this.#stopSubscriptions()
@@ -758,10 +473,10 @@ export class Workbench {
758
473
  void this.loadDocuments()
759
474
  }
760
475
 
761
- async #readFocus(dir: string): Promise<void> {
476
+ async #readFocus(dir: string, signal?: AbortSignal): Promise<void> {
762
477
  const version = this.#focusVersion
763
478
  try {
764
- const answer = await this.client.readFocus(dir)
479
+ const answer = await this.client.readFocus(dir, signal)
765
480
  if (this.#state.document === dir && version === this.#focusVersion) this.#set({ focus: answer.focus ?? [] })
766
481
  } catch {
767
482
  }
@@ -790,7 +505,6 @@ export class Workbench {
790
505
  this.#pendingFlash = undefined
791
506
  const targets = changedPlaces(ir.doc, changes)
792
507
  if (targets.length === 0) return
793
- this.#trail++
794
508
  this.#broadcast({ type: 'flash', targets })
795
509
  this.#record('ai.change.shown', { 'presmium.places': targets.map(target => [target.section, target.block].filter(Boolean).join(':')).join('\n') })
796
510
  }
@@ -1015,7 +729,7 @@ export class Workbench {
1015
729
  await this.pausePlayback()
1016
730
  signal.throwIfAborted()
1017
731
  if (!current()) return false
1018
- this.#production.reset()
732
+ this.#productionPlayback.reset()
1019
733
  this.#set({ productionPlan: plan, voiceoverCacheRefresh: { source: job.source, revision: job.revision, sequence: (this.#state.voiceoverCacheRefresh?.sequence ?? 0) + 1 } })
1020
734
  // The mounted production loader fetches this new binding in the existing frame.
1021
735
  // Replacing the iframe for every clip would interrupt progressive playback and its connection.
@@ -1061,6 +775,64 @@ export class Workbench {
1061
775
  && !state.hasDocumentTimingDrafts && !state.documentTimingDraftStorageFailure)
1062
776
  }
1063
777
 
778
+ /** Home is distinct from the root document, whose directory is the empty string. */
779
+ authoringWindowSnapshot(revision: number): AuthoringWindowSnapshot {
780
+ const state = this.#state, source = state.authoring
781
+ const recording = this.authoringClientSnapshot(0)?.recording
782
+ const guarded = !isAgentChanging(state) && !source?.composing && !source?.recovering && !state.isCreatingPage && !state.isEditingPage
783
+ && !state.isHistoryBusy && !state.isHistoryPreparing && !state.isPreparingPresentation && !state.hasDocumentTimingDrafts
784
+ && !this.#documentSession.hasPendingAssetWrite() && ![...this.#navigationGuards].some(blocked => blocked())
785
+ && !this.#previewModalOpen() && !(recording && (['requesting', 'recording', 'stopping'].includes(recording.phase) || recording.candidate && !recording.candidate.assetId))
786
+ return { revision, location: state.document === undefined ? { type: 'home' } : { type: 'document', document: state.document,
787
+ ...source?.directory === state.document && source.content ? { documentId: source.content.id } : {},
788
+ status: source?.directory !== state.document || source.loading ? 'loading' : source.content ? 'ready' : 'failed' },
789
+ actions: ['window.read', ...guarded ? ['document.open' as const, 'document.close' as const] : []] }
790
+ }
791
+
792
+ /** Uses the same native navigation and retained document actors; it never implicitly saves or discards. */
793
+ async executeAuthoringWindowAction(request: AuthoringWindowRequest, signal: AbortSignal): Promise<AuthoringWindowRequestResult['outcome']> {
794
+ const action = request.action
795
+ signal.throwIfAborted()
796
+ if (action.type === 'window.read') return 'observed'
797
+ const scope = this.#documentScope, content = this.#state.authoring?.content, identity = this.#state.authoring?.identity,
798
+ drafts = this.authoringDraftRevision(), view = this.#state.webView, playback = this.#state.productionNavigationVersion
799
+ const guard = () => {
800
+ signal.throwIfAborted()
801
+ if (scope !== this.#documentScope || identity !== this.#state.authoring?.identity || content !== this.#state.authoring?.content || drafts !== this.authoringDraftRevision()
802
+ || view !== this.#state.webView || playback !== this.#state.productionNavigationVersion || !this.authoringWindowSnapshot(0).actions.includes(action.type)) throw new Error('window-state-changed')
803
+ }
804
+ guard()
805
+ await waitForPreviewRequest(this.pausePlayback(), signal)
806
+ guard(); this.stopAuditions()
807
+ if (action.type === 'document.close') {
808
+ if (this.#state.document === undefined) return 'unchanged'
809
+ this.closeDocument(); return 'closed'
810
+ }
811
+ const target = request.target
812
+ if (!target || target.document !== action.document) throw new Error('window-target-changed')
813
+ const [answer, info] = await waitForPreviewRequest(Promise.all([this.client.readDocument(target.document, signal), this.client.readWorkbenchInfo()]), signal)
814
+ guard()
815
+ if (answer.document !== target.document || answer.content.id !== target.documentId || !info.root) throw new Error('window-target-changed')
816
+ if (this.#state.document === target.document && this.#state.authoring?.content?.id === target.documentId) return 'unchanged'
817
+ let navigationScope: number | undefined
818
+ const cancel = () => {
819
+ // A later human navigation owns its own scope. Never roll that view back.
820
+ if (navigationScope !== undefined && navigationScope === this.#documentScope && this.#state.document === target.document
821
+ && (this.#state.authoring?.loading || !this.#state.authoring?.content)) this.closeDocument()
822
+ }
823
+ signal.addEventListener('abort', cancel, { once: true })
824
+ try {
825
+ const opening = this.openDocument(target.document, { expectedIdentity: JSON.stringify([info.root, target.documentId]), signal })
826
+ navigationScope = this.#documentScope
827
+ await waitForPreviewRequest(opening, signal)
828
+ signal.throwIfAborted()
829
+ const location = this.authoringWindowSnapshot(0).location
830
+ if (navigationScope !== this.#documentScope || location.type !== 'document' || location.document !== target.document || location.documentId !== target.documentId
831
+ || location.status !== 'ready' || this.#state.authoring?.error) throw new Error('window-target-not-verified')
832
+ return 'opened'
833
+ } finally { signal.removeEventListener('abort', cancel) }
834
+ }
835
+
1064
836
  /** Bounded observations, without reading or publishing any unsubmitted editor content. */
1065
837
  authoringClientSnapshot(revision: number): AuthoringClientSnapshot | undefined {
1066
838
  const state = this.#state, source = state.authoring, content = source?.content
@@ -1072,17 +844,29 @@ export class Workbench {
1072
844
  const plan = state.productionPlan, playback = state.productionPlayback
1073
845
  const ready = clean && plan?.canPreview && this.#productionReady() && playback?.status === 'ready' && sameProductionBinding(plan.binding, playback.binding)
1074
846
  const position = state.position, page = position && content.sections[position.section]
847
+ const bodyDrafts = this.#documentSession.bodyDraftCapabilities()
1075
848
  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 }
849
+ const prepared = state.presentationSnapshot, actual = this.#documentSession.canonicalSource() ?? { documentId: content.id, version: source.version, fingerprint: source.fingerprint }
1077
850
  const preparedCurrent = clean && prepared && prepared.version === source.version && prepared.fingerprint === source.fingerprint && prepared.project === (source.projectRevision ?? 0)
1078
851
  && 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,
852
+ const controls = [...this.#clientControls].filter(owner => owner.identity === source.identity)
853
+ const advertised = controls.flatMap(owner => owner.actions()), unique = advertised.filter((type, index) => advertised.indexOf(type) === index && advertised.lastIndexOf(type) === index)
854
+ const reported = controls.map(owner => owner.snapshot?.()).filter(value => value !== undefined)
855
+ const mode = reported.find(value => value.mode)?.mode, recording = reported.find(value => value.recording)?.recording
856
+ return { revision, source: actual, view: state.webView, editing,
857
+ ...mode ? { mode } : {}, ...recording ? { recording } : {},
1080
858
  interaction: state.documentPositionToken,
1081
859
  ...page && position ? { position: { sectionId: page.id, ...page.stepOrder[position.step] ? { stepId: page.stepOrder[position.step] } : {} } } : {},
1082
860
  ...plan ? { binding: plan.binding } : {}, ...playback ? { playback } : {},
1083
861
  preview: preparedCurrent ? { status: 'prepared', source: actual, irRevision: prepared.revision, projectRevision: prepared.project }
1084
862
  : { status: state.isPreparingPresentation ? 'preparing' : state.presentationFailure ? 'unavailable' : 'unprepared' },
1085
863
  actions: ['state.read', 'playback.pause', ...safe ? ['source.flush' as const] : [],
864
+ ...safe && state.mode === 'editing' && state.editorHistory?.undo ? ['native-history.undo' as const] : [],
865
+ ...safe && state.mode === 'editing' && state.editorHistory?.redo ? ['native-history.redo' as const] : [],
866
+ ...unique,
867
+ ...bodyDrafts.read ? ['body-drafts.inspect' as const, 'body-drafts.read' as const] : [],
868
+ ...bodyDrafts.mutate && !locked && !state.isCreatingPage && !state.isEditingPage && !state.isHistoryBusy && !state.isHistoryPreparing && !state.hasDocumentTimingDrafts
869
+ ? ['body-drafts.restore' as const, 'body-drafts.discard' as const, ...bodyDrafts.current ? ['body-drafts.retry' as const] : []] : [],
1086
870
  ...commentDrafts?.readable ? ['comment-drafts.inspect' as const, 'comment-drafts.read' as const] : [],
1087
871
  ...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
872
  ...source.member?.id && this.#componentPropertyDrafts.readable(source.identity, source.member.id) ? ['component-drafts.inspect' as const, 'component-drafts.read' as const] : [],
@@ -1096,9 +880,31 @@ export class Workbench {
1096
880
  async executeAuthoringClientAction(action: AuthoringClientAction, expected: CanonicalSource, signal: AbortSignal, deadline?: number, fits?: (result: AuthoringClientActionResult) => boolean): Promise<void | AuthoringClientActionResult> {
1097
881
  const scope = this.#documentScope, identity = this.#state.authoring?.identity, document = this.#state.document, interaction = this.#state.documentPositionToken
1098
882
  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 }
883
+ 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
884
  current()
1101
885
  if (action.type === 'state.read') return
886
+ if (action.type === 'native-history.undo' || action.type === 'native-history.redo') {
887
+ if (this.editing.nativeHistory(action.type === 'native-history.undo' ? 'undo' : 'redo') !== true) throw new Error('client-native-history-unavailable')
888
+ owned(); return
889
+ }
890
+ const controls = [...this.#clientControls].filter(owner => owner.identity === identity && owner.actions().includes(action.type))
891
+ if (controls.length) {
892
+ if (controls.length !== 1) throw new Error('client-action-ambiguous')
893
+ const control = controls[0]!
894
+ await control.execute(action, expected, signal, deadline)
895
+ owned()
896
+ if (!this.#clientControls.has(control)) throw new Error('client-action-unavailable')
897
+ return
898
+ }
899
+ 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') {
900
+ if (!identity || !fits) throw new Error('client-body-drafts-unavailable')
901
+ const guard = () => {
902
+ owned()
903
+ const actual = this.#documentSession.canonicalSource()
904
+ 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')
905
+ }
906
+ return executeBodyDraftAction(this.#documentSession, () => this.#state.authoring, action, { signal, guard, source: expected, ...action.type !== 'body-drafts.retry' ? { localDraft: true as const } : {} }, fits)
907
+ }
1102
908
  if (action.type === 'comment-drafts.inspect' || action.type === 'comment-drafts.read') {
1103
909
  const drafts = identity ? this.documentCommentDrafts(identity) : undefined
1104
910
  if (!drafts?.readable || !fits) throw new Error('client-comment-drafts-unavailable')
@@ -1178,6 +984,7 @@ export class Workbench {
1178
984
  || 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
985
  return
1180
986
  }
987
+ if (action.type !== 'playback.play' && action.type !== 'playback.seek' && action.type !== 'playback.rate') throw new Error('client-action-unavailable')
1181
988
  const plan = this.#state.productionPlan
1182
989
  if (!plan || !sameProductionBinding(plan.binding, action.binding)) throw new Error('client-playback-binding-changed')
1183
990
  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 +1007,7 @@ export class Workbench {
1200
1007
  signal.throwIfAborted()
1201
1008
  if (scope !== this.#documentScope || this.#state.authoring?.identity !== identity || !this.#productionSourceCurrent(plan.binding)) throw new Error('production-source-changed')
1202
1009
  this.#set({ productionPlan: plan })
1203
- if (this.#production.changed()) void this.pausePlayback().catch(() => {})
1010
+ if (this.#productionPlayback.changed()) void this.pausePlayback().catch(() => {})
1204
1011
  return plan
1205
1012
  }
1206
1013
 
@@ -1221,7 +1028,7 @@ export class Workbench {
1221
1028
  await this.pausePlayback()
1222
1029
  signal?.throwIfAborted()
1223
1030
  }
1224
- return await this.#production.control(control, signal)
1031
+ return await this.#productionPlayback.control(control, signal)
1225
1032
  } catch (error) {
1226
1033
  const code = errorMessage(error), current = this.#state.productionPlan?.binding
1227
1034
  if (scope === this.#documentScope && !signal?.aborted && current && sameProductionBinding(current, control.binding) && this.#productionReady()
@@ -1233,7 +1040,7 @@ export class Workbench {
1233
1040
 
1234
1041
  closeProduction(): void {
1235
1042
  this.#interruptProductionNavigation()
1236
- this.#production.reset()
1043
+ this.#productionPlayback.reset()
1237
1044
  this.#set({ productionPlan: undefined, productionFailure: undefined })
1238
1045
  }
1239
1046
 
@@ -1245,9 +1052,7 @@ export class Workbench {
1245
1052
  await this.flushPendingEdits()
1246
1053
  const source = this.#state.authoring, document = this.getDocument(identity)
1247
1054
  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)
1055
+ this.#documentSession.record(enableDocumentProduction(document))
1251
1056
  await this.flushPendingEdits()
1252
1057
  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
1058
  }
@@ -1263,46 +1068,6 @@ export class Workbench {
1263
1068
  if (this.#state.document !== undefined) void this.#readPreview(this.#state.document)
1264
1069
  }
1265
1070
 
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
1071
  /** The preview acknowledges that all registered lecture playback has paused before audition audio starts. */
1307
1072
  pausePlayback(interactive = false): Promise<void> { if (interactive) this.#interruptProductionNavigation(); return this.#playback.pause() }
1308
1073
 
@@ -1334,175 +1099,14 @@ export class Workbench {
1334
1099
  if (!asset || asset.kind !== 'image' || asset.location !== answer.content.assets[answer.assetId]?.location) throw new Error('document-identity-changed')
1335
1100
  return asset.location
1336
1101
  }
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
1102
  /** Parameter planning is an authoring read; it does not compile, change modes or write the document. */
1499
1103
  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
1104
+ const source = this.production.source(expected), scope = this.#documentScope
1501
1105
  if (!source.content || !source.fingerprint || source.fingerprint !== expected.fingerprint) throw new Error('component-source-changed')
1502
1106
  const request = { id, source: componentSource({ content: source.content, version: source.version!, fingerprint: source.fingerprint }), action: structuredClone(action) }
1503
1107
  const answer = await this.client.planDocumentAction(source.directory, request, signal)
1504
1108
  signal?.throwIfAborted()
1505
- const current = this.#mediaSource(expected)
1109
+ const current = this.production.source(expected)
1506
1110
  if (scope !== this.#documentScope || !current.content || !current.fingerprint || answer.document !== source.directory || answer.changeId !== id || answer.effect.kind !== 'component'
1507
1111
  || !sameComponentSource(answer.source, request.source) || JSON.stringify(answer.action) !== JSON.stringify(request.action)) throw new Error('component-source-changed')
1508
1112
  return answer
@@ -1510,13 +1114,13 @@ export class Workbench {
1510
1114
  /** The existing source actor owns adoption and ambiguous-response recovery, including later native input. */
1511
1115
  async applyDocumentComponentPlan(plan: DocumentAuthoringActionPlan, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<{ answer: DocumentChangeAnswer, commitId?: string }> {
1512
1116
  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
1117
+ const source = this.production.source(expected), action = plan.action as DocumentComponentAction, scope = this.#documentScope
1514
1118
  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
1119
  this.#playback.stopPreviewOutputs()
1516
1120
  await this.pausePlayback()
1517
1121
  let receipt: AppliedDocumentAuthoringAction | undefined
1518
1122
  const remember = (answer: DocumentChangeAnswer) => {
1519
- if (this.#documentEditorBinding?.identity === expected.identity) this.#documentEditorCommands?.rememberComponentConfiguration(answer.content)
1123
+ this.editing.rememberComponent(answer.content, expected.identity)
1520
1124
  return { answer, ...receipt?.commit ? { commitId: receipt.commit.id } : {} }
1521
1125
  }
1522
1126
  try {
@@ -1536,7 +1140,7 @@ export class Workbench {
1536
1140
  && file?.version === current.version && current.version !== plan.source.version) {
1537
1141
  // Canonical acceptance is already known even when later native input has
1538
1142
  // deleted the target. Undoing that deletion must restore its accepted configuration.
1539
- if (this.#documentEditorBinding?.identity === expected.identity) this.#documentEditorCommands?.rememberComponentConfiguration(plan.content)
1143
+ this.editing.rememberComponent(plan.content, expected.identity)
1540
1144
  try {
1541
1145
  if (!applyDocumentComponentAction(current.content, action).effect.changed) return remember({ document: source.directory, content: plan.content,
1542
1146
  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 +1149,21 @@ export class Workbench {
1545
1149
  throw error
1546
1150
  }
1547
1151
  }
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
1152
  recordDocument(content: TeachingDocument): void { if (!isAgentChanging(this.#state)) this.#documentSession.record(content) }
1664
1153
  documentComposition(composing: boolean, owner = 'body', identity?: string): void { this.#documentSession.composition(composing, owner, identity) }
1665
1154
  retryDocument(): Promise<void> { return this.#documentSession.retry() }
1666
- discardDocument(): Promise<void> { return this.#documentSession.discard() }
1155
+ discardDocument(): Promise<void> { return this.#documentSession.discard().then(() => {}) }
1667
1156
  recoverDocumentDraft(value: DocumentDraftReference, identity: string): Promise<void> {
1668
- return this.#state.authoring?.identity === identity && !isAgentChanging(this.#state) ? this.#documentSession.recoverDraft(value) : Promise.resolve()
1157
+ return this.#state.authoring?.identity === identity && !isAgentChanging(this.#state) ? this.#documentSession.recoverDraft(value).then(() => {}) : Promise.resolve()
1669
1158
  }
1670
1159
  forgetDocumentDraft(value: DocumentDraftReference, identity: string): void {
1671
1160
  if (this.#state.authoring?.identity === identity && !isAgentChanging(this.#state)) void this.#documentSession.forgetDraft(value)
1672
1161
  }
1673
1162
  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
1163
  async flushPendingEdits(signal?: AbortSignal): Promise<void> {
1793
1164
  if (isAgentChanging(this.#state)) throw new Error('save-locked')
1794
1165
  await this.#documentSession.flush(signal)
1795
1166
  }
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
1167
  /** Points at a block or a passage (none: stops pointing): the preview outlines it and the conversation is told. */
1897
1168
  point(pointer: Pointer | undefined): void {
1898
1169
  const pointed = this.#state.pointer !== undefined || this.#state.focus.length > 0
@@ -1966,6 +1237,40 @@ export class Workbench {
1966
1237
  }
1967
1238
  }
1968
1239
 
1240
+ /**
1241
+ * Opens the conversation with a request, for the author to describe and send, to add an animation at `place` of the
1242
+ * open document; the document's focus points the AI at the place's block. Nothing is inserted or sent.
1243
+ */
1244
+ draftAnimation(place: DocumentInsertionPlace): boolean {
1245
+ const document = this.#state.document, content = this.#state.authoring?.content, drafter = [...this.#drafters][0]
1246
+ const section = content?.sections[place.sectionId]
1247
+ if (document === undefined || !content || !section || !drafter) return false
1248
+ const report = (block?: string): FocusReport => ({ id: 'insertion', from: this.#state.previewRenderer, section: place.sectionId, ...block ? { block } : {}, ...place.text ? { quote: place.text.slice(0, 2000) } : {} })
1249
+ const text = this.#messages.animationRequest(content.sectionOrder.indexOf(place.sectionId) + 1, section.title, place)
1250
+ const focus = [report(place.blocks[0])]
1251
+ void this.#focusFirst(document, [...place.blocks.map(block => [report(block)]), [report()], []])
1252
+ 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 })
1253
+ this.#set({ askFailure: undefined })
1254
+ void (async () => drafter({ text, focus }))().then(() => drafted({ 'presmium.outcome': 'drafted' }), (error: unknown) => {
1255
+ drafted({ 'presmium.outcome': 'failed', 'presmium.error': errorMessage(error) })
1256
+ if (this.#state.document === document) this.#set({ askFailure: errorMessage(error) })
1257
+ })
1258
+ return true
1259
+ }
1260
+
1261
+ /**
1262
+ * Sets the first of `choices` the service can locate as the document's focus. Its runtime snapshot is compiled from the
1263
+ * saved source, which may not have a block or page created moments ago yet; the last choice leaves no stale focus.
1264
+ */
1265
+ async #focusFirst(document: string, choices: FocusReport[][]): Promise<void> {
1266
+ for (const focus of choices) {
1267
+ this.setFocus(focus)
1268
+ const version = this.#focusVersion
1269
+ await this.#focusWriting
1270
+ if (version !== this.#focusVersion || this.#state.document !== document || !this.#state.focusFailure) return
1271
+ }
1272
+ }
1273
+
1969
1274
  /** A place as the author sees it: the section's title and the passage. */
1970
1275
  #describe(item: FocusReport & Partial<Focus>): AgentPlace {
1971
1276
  const doc = this.#state.ir?.doc
@@ -1989,7 +1294,7 @@ export class Workbench {
1989
1294
  /** Shows a section in the preview: from the navigation pane, the section to read or the slide to show. */
1990
1295
  goToSection(section: string): void {
1991
1296
  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
1297
+ this.#set({ position: { section, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: { section, request: randomUUID() } }); return
1993
1298
  }
1994
1299
  this.goToStep(section, this.#selectedSteps.get(`${this.#state.document}\0${section}`) ?? 0)
1995
1300
  }
@@ -2003,7 +1308,7 @@ export class Workbench {
2003
1308
  const visible = (index: number) => Boolean(section.stepOrder[index] && effectiveComponentParameters(document, blockId, section.stepOrder[index]).visual?.visible)
2004
1309
  const step = visible(current) ? current : Math.max(0, section.stepOrder.findIndex((_, index) => visible(index)))
2005
1310
  this.#set({ position: { section: sectionId, step, trail: [], view: 'document' }, documentPositionFailure: undefined,
2006
- documentNavigation: { section: sectionId, block: blockId, request: crypto.randomUUID() } })
1311
+ documentNavigation: { section: sectionId, block: blockId, request: randomUUID() } })
2007
1312
  }
2008
1313
 
2009
1314
  observeDocumentSection(section: string): void {
@@ -2035,7 +1340,7 @@ export class Workbench {
2035
1340
  const plan = this.#state.productionPlan, range = plan?.pages.find(page => page.sectionId === sectionId)?.steps.find(step => step.stepId === stepId)
2036
1341
  if (plan?.canPreview && this.#productionReady() && range?.startMs !== undefined) {
2037
1342
  this.stopAuditions()
2038
- if (this.#production.selecting(sectionId, stepId)) return
1343
+ if (this.#productionPlayback.selecting(sectionId, stepId)) return
2039
1344
  this.#selectedSteps.set(`${this.#state.document}\0${sectionId}`, step)
2040
1345
  this.#set({ position: { section: sectionId, step, trail: [], view: 'present' } })
2041
1346
  return this.controlProduction({ binding: plan.binding, action: 'step', sectionId, stepId }).catch(() => undefined)
@@ -2090,8 +1395,8 @@ export class Workbench {
2090
1395
  return true
2091
1396
  }
2092
1397
 
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') }
1398
+ undo(): Promise<boolean> { const result = this.editing.nativeHistory('undo'); return result === undefined ? this.#changeHistory('undo') : Promise.resolve(result) }
1399
+ redo(): Promise<boolean> { const result = this.editing.nativeHistory('redo'); return result === undefined ? this.#changeHistory('redo') : Promise.resolve(result) }
2095
1400
 
2096
1401
  async #changeHistory(action: 'undo' | 'redo' | 'revert', revision?: string): Promise<boolean> {
2097
1402
  if (this.#state.mode !== 'editing' || this.#state.isCreatingPage || this.#state.isEditingPage || this.#state.isHistoryBusy || this.#state.isHistoryPreparing) return false
@@ -2192,7 +1497,7 @@ export class Workbench {
2192
1497
  sink.send({ type: 'highlight', target: reveal ?? this.#state.pointer?.target ?? null })
2193
1498
  return () => {
2194
1499
  this.#previewSinks.delete(sink)
2195
- this.#production.detach(sink)
1500
+ this.#productionPlayback.detach(sink)
2196
1501
  this.#set({ previewConnection: this.#state.previewConnection + 1 })
2197
1502
  this.#playback.detach(sink)
2198
1503
  }
@@ -2209,7 +1514,7 @@ export class Workbench {
2209
1514
  if (report.type === 'page-create') { origin?.send({ type: 'page-created', section: report.section, request: report.request, error: unsupported }); return }
2210
1515
  if (document !== this.#state.document || renderer !== this.#state.previewRenderer) return
2211
1516
  this.#playback.report(document, report, origin)
2212
- this.#production.report(document, report, origin)
1517
+ this.#productionPlayback.report(document, report, origin)
2213
1518
  switch (report.type) {
2214
1519
  case 'ready':
2215
1520
  case 'updated':
@@ -2236,9 +1541,6 @@ export class Workbench {
2236
1541
  } else if (this.#state.pointer?.quote) this.point(undefined)
2237
1542
  break
2238
1543
  }
2239
- case 'flashed':
2240
- if (this.#trail) this.#set({ changeTrail: { id: this.#trail, rects: report.rects } })
2241
- break
2242
1544
  case 'rect':
2243
1545
  if (this.#state.pointer) this.#set({ pointer: { ...this.#state.pointer, rect: report.rect ?? undefined, obstacles: report.obstacles } })
2244
1546
  break
@@ -2247,7 +1549,7 @@ export class Workbench {
2247
1549
  if (snapshot && source && (source.dirty || source.loading || source.version !== snapshot.version || source.fingerprint !== snapshot.fingerprint)) break
2248
1550
  // An initial loader can report its old cursor while a newer stable selection is preparing.
2249
1551
  // Explicit native exits still reach the outer document workspace.
2250
- if (report.view !== 'document' && this.#production.selecting()) break
1552
+ if (report.view !== 'document' && this.#productionPlayback.selecting()) break
2251
1553
  // A fresh frame announces its document view before applying the queued
2252
1554
  // presentation command. Only the requested view completes that switch.
2253
1555
  if (renderer === 'web' && this.#awaitingView) {
@@ -2286,19 +1588,14 @@ export class Workbench {
2286
1588
 
2287
1589
  #stopSubscriptions(): void {
2288
1590
  this.#componentPropertyDrafts.stopAgentRead()
2289
- this.#saveDocumentReturnPoint(); this.#cancelOpeningDocument(); this.#stopDocumentReturnScroll?.()
2290
- this.#documentViewport?.stop(); this.#documentViewport = undefined; this.#documentEditorBinding = undefined
1591
+ this.editing.reset()
2291
1592
  this.#presentationPreparation++
2292
1593
  this.#presentationController?.abort(new Error('client-document-changed'))
2293
1594
  this.#voiceover.stop()
2294
- this.#production.reset()
1595
+ this.#productionPlayback.reset()
2295
1596
  this.#set({ isPreparingPresentation: false, presentationFailure: undefined, presentationSnapshot: undefined, productionPlan: undefined, productionFailure: undefined })
2296
- this.#removedCueTimings.clear(); this.#cueTimingScope = undefined
1597
+ this.production.reset()
2297
1598
  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
1599
  this.#playback.reset()
2303
1600
  this.#focusVersion++
2304
1601
  this.#pendingReveal = undefined
@@ -2321,8 +1618,9 @@ export class Workbench {
2321
1618
  this.#documentSession.dispose()
2322
1619
  this.#commentDrafts.close()
2323
1620
  this.#componentPropertyDrafts.close()
2324
- this.#captionTimingDrafts.close()
1621
+ this.production.dispose()
2325
1622
  disposeTranscriptionSessions(this.client)
2326
1623
  disposeDocumentRecordings(this)
1624
+ this.#clientControls.clear(); this.#navigationGuards.clear(); this.#clientControlListeners.clear()
2327
1625
  }
2328
1626
  }