@lincyaw/workbench 0.2.0-rc.11 → 0.2.0-rc.110

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 (108) hide show
  1. package/package.json +5 -4
  2. package/src/AgentActivityBar.tsx +25 -0
  3. package/src/MediaClipEditor.tsx +4 -3
  4. package/src/StepProductionEditor.tsx +13 -4
  5. package/src/agent-activity-messages.ts +14 -0
  6. package/src/agent-activity.ts +38 -0
  7. package/src/approvals.tsx +6 -1
  8. package/src/audio-recording-messages.ts +5 -5
  9. package/src/audio-recording.ts +27 -5
  10. package/src/authoring-client.ts +10 -10
  11. package/src/authoring-draft-fragment.ts +3 -1
  12. package/src/authoring-window.ts +100 -0
  13. package/src/base-controls.tsx +2 -2
  14. package/src/body-draft-actions.ts +60 -0
  15. package/src/caption-timing-drafts.ts +18 -1
  16. package/src/caption-timing-messages.ts +2 -2
  17. package/src/component-property-drafts.ts +5 -5
  18. package/src/components.tsx +34 -36
  19. package/src/container-layout.ts +21 -0
  20. package/src/context.tsx +5 -3
  21. package/src/diagnostics.ts +1 -1
  22. package/src/document-draft-store.ts +45 -18
  23. package/src/document-drafts.ts +28 -19
  24. package/src/document-editing.ts +484 -0
  25. package/src/document-editor/BlockNoteSurface.tsx +39 -13
  26. package/src/document-editor/CommentComposer.tsx +24 -0
  27. package/src/document-editor/ComponentMaterials.tsx +3 -9
  28. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  29. package/src/document-editor/DocumentBlockPreview.tsx +11 -4
  30. package/src/document-editor/DocumentComments.tsx +85 -14
  31. package/src/document-editor/DocumentEditor.tsx +56 -7
  32. package/src/document-editor/DocumentStepNarration.tsx +37 -26
  33. package/src/document-editor/NarrationEditor.tsx +54 -20
  34. package/src/document-editor/NewCommentDrafts.tsx +120 -37
  35. package/src/document-editor/PlaceComment.tsx +252 -0
  36. package/src/document-editor/agent-targets.ts +34 -0
  37. package/src/document-editor/blocknote-messages.ts +2 -0
  38. package/src/document-editor/comment-draft-actions.ts +40 -20
  39. package/src/document-editor/comment-draft-inspection.ts +2 -2
  40. package/src/document-editor/comment-drafts.ts +73 -25
  41. package/src/document-editor/comments.ts +30 -10
  42. package/src/document-editor/component-label.ts +11 -0
  43. package/src/document-editor/file-input.ts +2 -2
  44. package/src/document-editor/focus.ts +0 -2
  45. package/src/document-editor/insertion-place.ts +60 -0
  46. package/src/document-editor/messages.ts +3 -3
  47. package/src/document-editor/narration-schema.tsx +12 -6
  48. package/src/document-editor/narration.ts +19 -3
  49. package/src/document-editor/page-body.ts +60 -0
  50. package/src/document-editor/popover.tsx +4 -2
  51. package/src/document-editor/projection.ts +2 -2
  52. package/src/document-editor/rich-text.ts +3 -2
  53. package/src/document-editor/selection.ts +13 -0
  54. package/src/document-editor/style.css +7 -1
  55. package/src/document-editor/table-identities.ts +2 -1
  56. package/src/document-production.ts +491 -0
  57. package/src/document-session.ts +202 -56
  58. package/src/document-timing-drafts.ts +22 -2
  59. package/src/history.ts +5 -5
  60. package/src/index.ts +11 -5
  61. package/src/jobs.ts +1 -1
  62. package/src/mcp-settings-messages.ts +39 -0
  63. package/src/media-drafts.ts +43 -1
  64. package/src/messages.ts +33 -16
  65. package/src/panels/DocumentNarrationPanel.tsx +2 -2
  66. package/src/panels/DocumentView.tsx +97 -65
  67. package/src/panels/DocumentVoiceDialog.tsx +25 -9
  68. package/src/panels/DocumentVoiceField.tsx +1 -1
  69. package/src/panels/ExportPanel.tsx +2 -10
  70. package/src/panels/HistoryPanel.tsx +34 -7
  71. package/src/panels/HomePanel.tsx +3 -1
  72. package/src/panels/McpSettingsPanel.tsx +86 -0
  73. package/src/panels/PageDeleteDialog.tsx +4 -4
  74. package/src/panels/PageRenameDialog.tsx +1 -1
  75. package/src/panels/PreviewPanel.tsx +1 -4
  76. package/src/panels/ProductionCaptionSize.tsx +20 -0
  77. package/src/panels/ProductionCaptionTiming.tsx +12 -9
  78. package/src/panels/ProductionMediaClips.tsx +23 -7
  79. package/src/panels/ProductionPanel.tsx +16 -13
  80. package/src/panels/ProductionRecording.tsx +86 -9
  81. package/src/panels/ProductionRecordingRange.tsx +21 -19
  82. package/src/panels/ProductionTimeline.tsx +6 -1
  83. package/src/panels/ProductionTranscription.tsx +5 -4
  84. package/src/panels/SourceDocumentPanel.tsx +18 -36
  85. package/src/panels/SpeechSettingsPanel.tsx +1 -1
  86. package/src/panels/TranscriptionAdoption.tsx +40 -34
  87. package/src/panels/VoiceCloneDialog.tsx +2 -1
  88. package/src/panels/VoiceoverDialog.tsx +1 -1
  89. package/src/places.ts +1 -36
  90. package/src/preview-playback.ts +1 -1
  91. package/src/production-draft-actions.ts +37 -0
  92. package/src/production-messages.ts +6 -0
  93. package/src/production-playback.ts +1 -1
  94. package/src/production-voice-playback.ts +3 -2
  95. package/src/sha256.ts +9 -0
  96. package/src/speech-settings-messages.ts +5 -5
  97. package/src/styles.css +43 -79
  98. package/src/transcription-drafts.ts +124 -0
  99. package/src/use-recording-adoption.ts +2 -2
  100. package/src/voice-drafts.ts +32 -8
  101. package/src/voice-messages.ts +9 -9
  102. package/src/voiceover-jobs.ts +1 -1
  103. package/src/workbench-state.ts +159 -0
  104. package/src/workbench.ts +303 -952
  105. package/src/workspace-client.ts +30 -11
  106. package/src/assistant-mascot.ts +0 -62
  107. package/src/mascot-preference.ts +0 -37
  108. 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,30 @@ 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'
16
+ import { executeProductionDraftAction } from './production-draft-actions.ts'
15
17
  import { inspectComponentDrafts } from './component-draft-inspection.ts'
16
18
  import { mutateComponentDrafts } from './component-draft-actions.ts'
17
19
  import { DocumentSession } from './document-session.ts'
18
- import { reconcileRecordingAdoption } from './recording-adoption.ts'
19
20
  import { disposeTranscriptionSessions } from './transcription-session.ts'
20
21
  import { documentRecordingActive, disposeDocumentRecordings } from './audio-recording.ts'
21
- import { DOCUMENT_AUDIO_MAX_BYTES } from '@lincyaw/kernel'
22
22
  import type { DocumentSessionState } from './document-session.ts'
23
23
  import type { DocumentDraftReference } from './document-drafts.ts'
24
- import { DocumentReturnPoints, documentReturnStep, documentViewportOffset, restoreDocumentViewport } from './document-return-point.ts'
25
24
  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'
25
+ import type { DocumentChangeAnswer, TeachingDocument } from '@lincyaw/kernel'
26
+ import type { DocumentInsertionPlace } from './document-editor/insertion-place.ts'
27
+ import type { CanonicalSource, VoiceoverJob } from '@lincyaw/kernel'
41
28
  import { compileDocumentPreview, readPreviewWhenReady, waitForPreviewRequest } from './document-preview.ts'
42
29
  import { readDocumentSnapshot } from './document-preview.ts'
43
30
  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'
31
+ import type { Diagnostic, Focus, FocusReport, IrAnswer, IrEvent, OperationAnswer, PreviewAnchor, PreviewCommand, PreviewDiagnostics, PreviewRenderer, PreviewReport, ReviewChange } from '@lincyaw/kernel'
45
32
  import { DocumentDiagnostics } from './diagnostics.ts'
46
33
  import { DocumentHistory } from './history.ts'
47
34
  import { DocumentJobs } from './jobs.ts'
48
35
  import { VoiceoverJobs } from './voiceover-jobs.ts'
49
- import { contentText, localeOf, MESSAGES } from './messages.ts'
36
+ import { localeOf, MESSAGES } from './messages.ts'
50
37
  import type { AgentPlace, Locale } from './messages.ts'
51
- import { changedBlocks, changedPlaces, findPlaceAtLine, findPlaceSource } from './places.ts'
38
+ import { changedPlaces, findPlaceAtLine } from './places.ts'
52
39
  import { OperationLog } from './telemetry.ts'
53
40
  import type { OperationValue } from './telemetry.ts'
54
41
  import { PreviewPlayback } from './preview-playback.ts'
@@ -56,166 +43,22 @@ import { ProductionPlayback } from './production-playback.ts'
56
43
  import type { ProductionBinding, ProductionPlan, ProductionPlaybackCommand, ProductionPlaybackState } from '@lincyaw/kernel'
57
44
  import { workspaceClient, WorkspaceServerError } from './workspace-client.ts'
58
45
  import type { WorkspaceClient } from './workspace-client.ts'
59
- import type { PageDeletePlan } from '@lincyaw/kernel'
60
- import type { AuthoringClientAction, AuthoringClientActionResult, AuthoringClientSnapshot } from '@lincyaw/kernel'
46
+ import type { AuthoringClientAction, AuthoringClientActionType, AuthoringClientActionResult, AuthoringClientSnapshot } from '@lincyaw/kernel'
61
47
  import { PRODUCTION_PLAYBACK_RATES } from '@lincyaw/kernel'
62
48
 
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
49
  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
50
+ /** Mounted native controls advertise their own availability and execute the same human actions. */
51
+ export interface AuthoringClientControls {
52
+ identity: string
53
+ actions(): readonly AuthoringClientActionType[]
54
+ snapshot?(): Pick<AuthoringClientSnapshot, 'mode' | 'recording'>
55
+ execute(action: AuthoringClientAction, source: CanonicalSource, signal: AbortSignal, deadline?: number): Promise<void>
204
56
  }
57
+ const sameSource = (a: CanonicalSource, b: CanonicalSource) => a.documentId === b.documentId && a.version === b.version && a.fingerprint === b.fingerprint
205
58
 
206
59
  // The export of the lecture as a video (`@lincyaw/addon-lecture`).
207
60
  export const VIDEO_TARGET = 'video'
208
61
 
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
62
  /** Whether the document has a slides form (no renderers listed: every form). */
220
63
  export function hasSlides(ir: IrAnswer | undefined): boolean {
221
64
  const renderers = ir?.doc.config.renderers
@@ -270,32 +113,15 @@ export function documentDirFor(title: string, taken: readonly string[]): string
270
113
  export class Workbench {
271
114
  readonly client: WorkspaceClient
272
115
  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
116
+ readonly production: DocumentProduction
292
117
  #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 }
118
+ readonly editing: DocumentEditing
297
119
  #state: WorkbenchState
298
120
  readonly #listeners = new Set<Listener>()
121
+ readonly #clientControls = new Set<AuthoringClientControls>()
122
+ readonly #navigationGuards = new Set<() => boolean>()
123
+ readonly #clientControlListeners = new Set<Listener>()
124
+ #clientControlRevision = 0
299
125
  readonly #commentDrafts = new CommentDraftBank()
300
126
  readonly #componentPropertyDrafts = new ComponentPropertyDrafts()
301
127
  readonly #positionSeed = Array.from(crypto.getRandomValues(new Uint32Array(2)), value => value.toString(36)).join('-')
@@ -307,6 +133,7 @@ export class Workbench {
307
133
  readonly #jobs: DocumentJobs
308
134
  readonly #voiceover: VoiceoverJobs
309
135
  readonly #askers = new Set<(request: AgentRequest) => Promise<AgentAnswer | void>>()
136
+ readonly #drafters = new Set<(draft: AgentDraft) => void | Promise<void>>()
310
137
  readonly #previewSinks = new Set<PreviewSink>()
311
138
  readonly #playbackKeys = new Set<(command: PlaybackKey) => void>()
312
139
  #unsubscribeIr?: () => void
@@ -323,13 +150,12 @@ export class Workbench {
323
150
  #documentScope = 0
324
151
  #jobPreparation?: AbortController
325
152
  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,
153
+ readonly #productionPlayback = new ProductionPlayback(() => ({ document: this.#state.document, scope: this.#documentScope, sinks: this.#previewSinks,
327
154
  binding: this.#state.productionPlan?.binding, ready: this.#productionReady() }), state => this.#set({ productionPlayback: state }))
328
155
  /** A place to show that no preview could take yet (none was attached, e.g. the chat covered the document). */
329
156
  #pendingReveal?: PreviewAnchor
330
157
  /** The AI's changes to show on the document once the preview has them. */
331
158
  #pendingFlash?: ReviewChange[]
332
- #trail = 0
333
159
  #lastPosition?: string
334
160
  #awaitingView?: WebView
335
161
  /** The forms asked for ahead of the author (`web:<dir>`, `slides:<dir>`), and the wait before asking for the slides. */
@@ -369,12 +195,7 @@ export class Workbench {
369
195
  }
370
196
  this.#documentSession = new DocumentSession(this.client, authoring => {
371
197
  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 }
198
+ this.editing.sourceChanged(authoring)
378
199
  const previous = this.#state.authoring
379
200
  // A saved timestamp belongs to this client's acknowledged source version.
380
201
  // Remote adoption has no server modification time to display in its place.
@@ -389,40 +210,39 @@ export class Workbench {
389
210
  const removed = this.#state.webView === 'document' && position?.view !== 'present' && position && previous?.identity === authoring.identity
390
211
  && (selected ? !selectedStep || selectedIndex < 0 : !authoring.content?.sectionOrder.includes(position.section))
391
212
  const restoredPosition = !removed && this.#restoredDocumentPosition(authoring)
392
- const scope = this.#documentScope, generation = this.#documentSelectionGeneration
393
- if (removed && authoring.identity) this.#documentReturnPoints.forget(authoring.identity)
213
+ const scope = this.#documentScope, generation = this.editing.generation
214
+ if (removed && authoring.identity) this.editing.returnPoints.forget(authoring.identity)
394
215
  this.#set({ authoring,
395
216
  ...removed ? { position: undefined, documentNavigation: undefined, documentPositionFailure: 'removed' as const } : {},
396
217
  ...restoredPosition ? { documentPositionFailure: undefined } : {},
397
218
  ...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 })),
219
+ ...this.production.draftState(authoring),
402
220
  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
221
  // The deletion owns the token produced above; source restoration only retires its notice.
404
222
  if (removed && previous?.identity && previous.content && previous.version && previous.fingerprint
405
223
  && !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') {
224
+ && scope === this.#documentScope && generation === this.editing.generation && !this.#state.position && this.#state.documentPositionFailure === 'removed') {
407
225
  this.#removedDocumentPosition = { identity: previous.identity, documentId: previous.content.id, sectionId: position.section,
408
226
  ...selected ? { stepId: selected } : {}, version: previous.version, fingerprint: previous.fingerprint, scope, generation, token: this.#state.documentPositionToken }
409
227
  }
410
- this.#finishOpeningDocument()
228
+ this.editing.finishOpening()
411
229
  // Native insertion can select a page before the source actor receives that new entity.
412
230
  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(() => {})
231
+ && authoring.content?.sections[position.section]) this.editing.saveReturnPoint()
232
+ if (this.#productionPlayback.changed()) void this.pausePlayback().catch(() => {})
415
233
  const acknowledgedSourceChanged = !authoring.dirty && !authoring.loading && !authoring.error && !previous?.loading
416
234
  && previous?.identity === authoring.identity && Boolean(previous?.version && authoring.version)
417
235
  && (previous?.version !== authoring.version || previous?.fingerprint !== authoring.fingerprint)
418
236
  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
237
  })
238
+ this.production = new DocumentProduction({ store, session: this.#documentSession, client: this.client,
239
+ scope: () => this.#documentScope, document: identity => this.getDocument(identity), flush: signal => this.flushPendingEdits(signal),
240
+ pause: () => this.pausePlayback(), stopAuditions: () => this.stopAuditions(), stopPreviewOutputs: () => this.#playback.stopPreviewOutputs(),
241
+ sourceCurrent: binding => this.#productionSourceCurrent(binding) })
242
+ this.editing = new DocumentEditing({ store, session: this.#documentSession, scope: () => this.#documentScope,
243
+ flush: signal => this.flushPendingEdits(signal), goToSection: section => this.goToSection(section),
244
+ rememberStep: (directory, section, step) => { this.#selectedSteps.set(`${directory}\0${section}`, step) },
245
+ canAskAnimation: () => this.#drafters.size > 0, askAnimation: place => this.draftAnimation(place) })
426
246
  this.#diagnostics = new DocumentDiagnostics(this.client, store)
427
247
  this.#jobs = new DocumentJobs(this.client, store)
428
248
  this.#voiceover = new VoiceoverJobs(this.client, store, (job, signal) => this.#refreshVoiceover(job, signal))
@@ -473,11 +293,36 @@ export class Workbench {
473
293
  /** Only counters enter passive client state; no new form payload is exposed to MCP. */
474
294
  authoringDraftRevision(): string {
475
295
  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])
296
+ return JSON.stringify([this.#documentSession.bodyDraftRevision(), this.authoringCommentDraftRevision(), source?.identity && source.member?.id ? this.#componentPropertyDrafts.revision(source.identity, source.member.id) : 0, this.production.draftRevision, this.#clientControlRevision])
477
297
  }
478
298
  subscribeAuthoringDraftChanges(listener: () => void): () => void {
479
299
  const comments = this.#commentDrafts.subscribe(listener), properties = this.#componentPropertyDrafts.subscribe(listener)
480
- return () => { comments(); properties() }
300
+ this.#clientControlListeners.add(listener)
301
+ return () => { comments(); properties(); this.#clientControlListeners.delete(listener) }
302
+ }
303
+
304
+ registerAuthoringClientControls(controls: AuthoringClientControls): () => void {
305
+ this.#clientControls.add(controls); this.refreshAuthoringClientControls()
306
+ return () => { this.#clientControls.delete(controls); this.refreshAuthoringClientControls() }
307
+ }
308
+ refreshAuthoringClientControls(): void {
309
+ this.#clientControlRevision++
310
+ for (const listener of this.#clientControlListeners) listener()
311
+ }
312
+ /** A mounted native form owns any input/transaction that cannot safely leave its view. */
313
+ registerNavigationGuard(blocked: () => boolean): () => void {
314
+ this.#navigationGuards.add(blocked); this.refreshAuthoringClientControls()
315
+ return () => { this.#navigationGuards.delete(blocked); this.refreshAuthoringClientControls() }
316
+ }
317
+ waitForAuthoringClientState(ready: () => boolean, signal: AbortSignal): Promise<void> {
318
+ return new Promise((resolve, reject) => {
319
+ const finish = (error?: unknown) => { stop(); stopControls(); signal.removeEventListener('abort', aborted); error ? reject(error) : resolve() }
320
+ const check = () => { try { signal.throwIfAborted(); if (ready()) finish() } catch (error) { finish(error) } }
321
+ const aborted = () => finish(signal.reason ?? new Error('client-request-expired'))
322
+ const stop = this.subscribe(check), stopControls = this.subscribeAuthoringDraftChanges(check)
323
+ signal.addEventListener('abort', aborted, { once: true })
324
+ check()
325
+ })
481
326
  }
482
327
 
483
328
  getState = (): WorkbenchState => this.#state
@@ -506,12 +351,18 @@ export class Workbench {
506
351
  return () => this.#askers.delete(asker)
507
352
  }
508
353
 
354
+ /** The host's way to put a request in the conversation's composer for the author to finish; nothing is sent. */
355
+ onAgentDraft = (drafter: (draft: AgentDraft) => void | Promise<void>): (() => void) => {
356
+ this.#drafters.add(drafter)
357
+ return () => this.#drafters.delete(drafter)
358
+ }
359
+
509
360
  #nextDocumentPosition(): string { return `${this.#positionSeed}:${++this.#positionSequence}` }
510
361
 
511
362
  #restoredDocumentPosition(source: DocumentSessionState): boolean {
512
363
  const removed = this.#removedDocumentPosition
513
364
  if (!removed) return false
514
- if (removed.scope !== this.#documentScope || removed.generation !== this.#documentSelectionGeneration || removed.token !== this.#state.documentPositionToken
365
+ if (removed.scope !== this.#documentScope || removed.generation !== this.editing.generation || removed.token !== this.#state.documentPositionToken
515
366
  || removed.identity !== source.identity || this.#state.documentPositionFailure !== 'removed' || source.error) {
516
367
  this.#removedDocumentPosition = undefined
517
368
  return false
@@ -525,12 +376,48 @@ export class Workbench {
525
376
 
526
377
  #set(patch: Partial<WorkbenchState>): void {
527
378
  if (Object.hasOwn(patch, 'position') || Object.hasOwn(patch, 'documentPositionFailure')) this.#removedDocumentPosition = undefined
528
- if (Object.hasOwn(patch, 'position')) { this.#cancelOpeningDocument(); this.#stopDocumentReturnScroll?.() }
379
+ if (Object.hasOwn(patch, 'position')) this.editing.beforePosition()
529
380
  this.#state = { ...this.#state, ...patch, ...Object.hasOwn(patch, 'position') ? { documentPositionToken: this.#nextDocumentPosition(), documentPositionIntent: patch.documentPositionIntent ?? 'seek' } : {} }
530
- if (Object.hasOwn(patch, 'position')) this.#saveDocumentReturnPoint()
381
+ if (Object.hasOwn(patch, 'position')) this.editing.saveReturnPoint()
531
382
  for (const listener of this.#listeners) listener()
532
383
  }
533
384
 
385
+ setAgentActivities(activities: import('@lincyaw/kernel').AgentActivity[]): void { this.#set({ agentActivities: activities }) }
386
+ setAgentFollowing(following: boolean): void { this.#set({ agentFollowing: following }) }
387
+
388
+ /** Presence never owns drafts or playback. Human input aborts this read-only navigation. */
389
+ async followAgentActivity(activity: import('@lincyaw/kernel').AgentActivity, signal: AbortSignal): Promise<void> {
390
+ const state = this.#state, source = state.authoring
391
+ if (activity.document === undefined || !state.agentFollowing || state.mode !== 'editing' || source?.loading || source?.dirty || source?.saving || source?.composing || source?.recovering || source?.restored || source?.error
392
+ || !this.authoringWindowSnapshot(0).actions.includes('document.open')) return
393
+ signal.throwIfAborted()
394
+ let navigationScope: number | undefined
395
+ const cancel = () => {
396
+ if (navigationScope !== undefined && navigationScope === this.#documentScope && this.#state.document === activity.document
397
+ && (this.#state.authoring?.loading || !this.#state.authoring?.content)) this.closeDocument()
398
+ }
399
+ signal.addEventListener('abort', cancel, { once: true })
400
+ try {
401
+ const opening = this.openDocument(activity.document, { signal })
402
+ navigationScope = this.#documentScope
403
+ await opening
404
+ } finally { signal.removeEventListener('abort', cancel) }
405
+ signal.throwIfAborted()
406
+ if (!this.#state.agentFollowing || this.#state.document !== activity.document) return
407
+ const content = this.#state.authoring?.content, target = activity.targets[0]
408
+ if (!content || !target) return
409
+ const contains = (ids: string[], block: string): boolean => ids.some(id => {
410
+ const value = content.blocks[id]
411
+ return id === block || Boolean(value && 'children' in value && value.children && contains(value.children, block))
412
+ })
413
+ const section = target.section ?? (target.step ? content.steps[target.step]?.sectionId : undefined)
414
+ ?? (target.block ? content.sectionOrder.find(id => contains(content.sections[id]!.children, target.block!)) : undefined)
415
+ if (section && content.sections[section]) {
416
+ if (target.step && content.steps[target.step]?.sectionId === section) await this.selectDocumentStep(section, target.step)
417
+ else this.goToSection(section)
418
+ }
419
+ }
420
+
534
421
  get #messages() {
535
422
  return MESSAGES[this.#state.locale]
536
423
  }
@@ -557,7 +444,7 @@ export class Workbench {
557
444
  }
558
445
 
559
446
  planDocumentOperation(operation: ProjectOperation): Promise<ProjectPlan> {
560
- return this.client.planProjectChange({ id: crypto.randomUUID(), operation })
447
+ return this.client.planProjectChange({ id: randomUUID(), operation })
561
448
  }
562
449
 
563
450
  operateDocument(operation: ProjectOperation, planned?: ProjectPlan): Promise<OperationAnswer> {
@@ -593,163 +480,28 @@ export class Workbench {
593
480
  await this.operateDocument({ op: 'retitle', dir, title })
594
481
  }
595
482
 
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> {
483
+ async openDocument(dir: string, options: { focus?: 'body', expectedIdentity?: string, fallbackReturnPoint?: DocumentReturnPoint, signal?: AbortSignal } = {}): Promise<void> {
732
484
  if (this.#state.document === dir) {
733
- if (options.focus) { this.#beginOpeningDocument(dir, options.focus); this.#finishOpeningDocument() }
485
+ if (options.focus) { this.editing.beginOpening(dir, options.focus); this.editing.finishOpening() }
734
486
  return
735
487
  }
736
- this.#saveDocumentReturnPoint()
488
+ this.editing.saveReturnPoint()
737
489
  this.#documentScope++
738
490
  const scope = this.#documentScope
739
491
  this.#stopSubscriptions()
740
492
  this.#history.subscribeReview(dir)
741
493
  this.#set({ ...DOCUMENT_RESET, document: dir, previewRenderer: 'web', webView: 'document' })
742
- this.#beginOpeningDocument(dir, options.focus, options.fallbackReturnPoint)
494
+ this.editing.beginOpening(dir, options.focus, options.fallbackReturnPoint)
743
495
  this.#record('document.open')
744
496
  this.#diagnostics.subscribe(dir)
745
497
  // 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)])
498
+ 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
499
  if (opened === 'identity-changed' && scope === this.#documentScope && this.#state.document === dir) { this.closeDocument(); return }
748
- this.#finishOpeningDocument()
500
+ if (scope === this.#documentScope && this.#state.document === dir) this.editing.finishOpening()
749
501
  }
750
502
 
751
503
  closeDocument(): void {
752
- this.#saveDocumentReturnPoint()
504
+ this.editing.saveReturnPoint()
753
505
  this.#documentScope++
754
506
  if (this.#state.document !== undefined) this.#record('document.close')
755
507
  this.#stopSubscriptions()
@@ -758,10 +510,10 @@ export class Workbench {
758
510
  void this.loadDocuments()
759
511
  }
760
512
 
761
- async #readFocus(dir: string): Promise<void> {
513
+ async #readFocus(dir: string, signal?: AbortSignal): Promise<void> {
762
514
  const version = this.#focusVersion
763
515
  try {
764
- const answer = await this.client.readFocus(dir)
516
+ const answer = await this.client.readFocus(dir, signal)
765
517
  if (this.#state.document === dir && version === this.#focusVersion) this.#set({ focus: answer.focus ?? [] })
766
518
  } catch {
767
519
  }
@@ -790,7 +542,6 @@ export class Workbench {
790
542
  this.#pendingFlash = undefined
791
543
  const targets = changedPlaces(ir.doc, changes)
792
544
  if (targets.length === 0) return
793
- this.#trail++
794
545
  this.#broadcast({ type: 'flash', targets })
795
546
  this.#record('ai.change.shown', { 'presmium.places': targets.map(target => [target.section, target.block].filter(Boolean).join(':')).join('\n') })
796
547
  }
@@ -1015,7 +766,7 @@ export class Workbench {
1015
766
  await this.pausePlayback()
1016
767
  signal.throwIfAborted()
1017
768
  if (!current()) return false
1018
- this.#production.reset()
769
+ this.#productionPlayback.reset()
1019
770
  this.#set({ productionPlan: plan, voiceoverCacheRefresh: { source: job.source, revision: job.revision, sequence: (this.#state.voiceoverCacheRefresh?.sequence ?? 0) + 1 } })
1020
771
  // The mounted production loader fetches this new binding in the existing frame.
1021
772
  // Replacing the iframe for every clip would interrupt progressive playback and its connection.
@@ -1061,6 +812,64 @@ export class Workbench {
1061
812
  && !state.hasDocumentTimingDrafts && !state.documentTimingDraftStorageFailure)
1062
813
  }
1063
814
 
815
+ /** Home is distinct from the root document, whose directory is the empty string. */
816
+ authoringWindowSnapshot(revision: number): AuthoringWindowSnapshot {
817
+ const state = this.#state, source = state.authoring
818
+ const recording = this.authoringClientSnapshot(0)?.recording
819
+ const guarded = !isAgentChanging(state) && !source?.composing && !source?.recovering && !state.isCreatingPage && !state.isEditingPage
820
+ && !state.isHistoryBusy && !state.isHistoryPreparing && !state.isPreparingPresentation && !state.hasDocumentTimingDrafts
821
+ && !this.#documentSession.hasPendingAssetWrite() && ![...this.#navigationGuards].some(blocked => blocked())
822
+ && !this.#previewModalOpen() && !(recording && (['requesting', 'recording', 'stopping'].includes(recording.phase) || recording.candidate && !recording.candidate.assetId))
823
+ return { revision, location: state.document === undefined ? { type: 'home' } : { type: 'document', document: state.document,
824
+ ...source?.directory === state.document && source.content ? { documentId: source.content.id } : {},
825
+ status: source?.directory !== state.document || source.loading ? 'loading' : source.content ? 'ready' : 'failed' },
826
+ actions: ['window.read', ...guarded ? ['document.open' as const, 'document.close' as const] : []] }
827
+ }
828
+
829
+ /** Uses the same native navigation and retained document actors; it never implicitly saves or discards. */
830
+ async executeAuthoringWindowAction(request: AuthoringWindowRequest, signal: AbortSignal): Promise<AuthoringWindowRequestResult['outcome']> {
831
+ const action = request.action
832
+ signal.throwIfAborted()
833
+ if (action.type === 'window.read') return 'observed'
834
+ const scope = this.#documentScope, content = this.#state.authoring?.content, identity = this.#state.authoring?.identity,
835
+ drafts = this.authoringDraftRevision(), view = this.#state.webView, playback = this.#state.productionNavigationVersion
836
+ const guard = () => {
837
+ signal.throwIfAborted()
838
+ if (scope !== this.#documentScope || identity !== this.#state.authoring?.identity || content !== this.#state.authoring?.content || drafts !== this.authoringDraftRevision()
839
+ || view !== this.#state.webView || playback !== this.#state.productionNavigationVersion || !this.authoringWindowSnapshot(0).actions.includes(action.type)) throw new Error('window-state-changed')
840
+ }
841
+ guard()
842
+ await waitForPreviewRequest(this.pausePlayback(), signal)
843
+ guard(); this.stopAuditions()
844
+ if (action.type === 'document.close') {
845
+ if (this.#state.document === undefined) return 'unchanged'
846
+ this.closeDocument(); return 'closed'
847
+ }
848
+ const target = request.target
849
+ if (!target || target.document !== action.document) throw new Error('window-target-changed')
850
+ const [answer, info] = await waitForPreviewRequest(Promise.all([this.client.readDocument(target.document, signal), this.client.readWorkbenchInfo()]), signal)
851
+ guard()
852
+ if (answer.document !== target.document || answer.content.id !== target.documentId || !info.root) throw new Error('window-target-changed')
853
+ if (this.#state.document === target.document && this.#state.authoring?.content?.id === target.documentId) return 'unchanged'
854
+ let navigationScope: number | undefined
855
+ const cancel = () => {
856
+ // A later human navigation owns its own scope. Never roll that view back.
857
+ if (navigationScope !== undefined && navigationScope === this.#documentScope && this.#state.document === target.document
858
+ && (this.#state.authoring?.loading || !this.#state.authoring?.content)) this.closeDocument()
859
+ }
860
+ signal.addEventListener('abort', cancel, { once: true })
861
+ try {
862
+ const opening = this.openDocument(target.document, { expectedIdentity: JSON.stringify([info.root, target.documentId]), signal })
863
+ navigationScope = this.#documentScope
864
+ await waitForPreviewRequest(opening, signal)
865
+ signal.throwIfAborted()
866
+ const location = this.authoringWindowSnapshot(0).location
867
+ if (navigationScope !== this.#documentScope || location.type !== 'document' || location.document !== target.document || location.documentId !== target.documentId
868
+ || location.status !== 'ready' || this.#state.authoring?.error) throw new Error('window-target-not-verified')
869
+ return 'opened'
870
+ } finally { signal.removeEventListener('abort', cancel) }
871
+ }
872
+
1064
873
  /** Bounded observations, without reading or publishing any unsubmitted editor content. */
1065
874
  authoringClientSnapshot(revision: number): AuthoringClientSnapshot | undefined {
1066
875
  const state = this.#state, source = state.authoring, content = source?.content
@@ -1072,23 +881,36 @@ export class Workbench {
1072
881
  const plan = state.productionPlan, playback = state.productionPlayback
1073
882
  const ready = clean && plan?.canPreview && this.#productionReady() && playback?.status === 'ready' && sameProductionBinding(plan.binding, playback.binding)
1074
883
  const position = state.position, page = position && content.sections[position.section]
884
+ const bodyDrafts = this.#documentSession.bodyDraftCapabilities()
1075
885
  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 }
886
+ const prepared = state.presentationSnapshot, actual = this.#documentSession.canonicalSource() ?? { documentId: content.id, version: source.version, fingerprint: source.fingerprint }
1077
887
  const preparedCurrent = clean && prepared && prepared.version === source.version && prepared.fingerprint === source.fingerprint && prepared.project === (source.projectRevision ?? 0)
1078
888
  && 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,
889
+ const controls = [...this.#clientControls].filter(owner => owner.identity === source.identity)
890
+ const advertised = controls.flatMap(owner => owner.actions()), unique = advertised.filter((type, index) => advertised.indexOf(type) === index && advertised.lastIndexOf(type) === index)
891
+ const reported = controls.map(owner => owner.snapshot?.()).filter(value => value !== undefined)
892
+ const mode = reported.find(value => value.mode)?.mode, recording = reported.find(value => value.recording)?.recording
893
+ return { revision, source: actual, view: state.webView, editing,
894
+ ...mode ? { mode } : {}, ...recording ? { recording } : {},
1080
895
  interaction: state.documentPositionToken,
1081
896
  ...page && position ? { position: { sectionId: page.id, ...page.stepOrder[position.step] ? { stepId: page.stepOrder[position.step] } : {} } } : {},
1082
897
  ...plan ? { binding: plan.binding } : {}, ...playback ? { playback } : {},
1083
898
  preview: preparedCurrent ? { status: 'prepared', source: actual, irRevision: prepared.revision, projectRevision: prepared.project }
1084
899
  : { status: state.isPreparingPresentation ? 'preparing' : state.presentationFailure ? 'unavailable' : 'unprepared' },
1085
900
  actions: ['state.read', 'playback.pause', ...safe ? ['source.flush' as const] : [],
901
+ ...safe && state.mode === 'editing' && state.editorHistory?.undo ? ['native-history.undo' as const] : [],
902
+ ...safe && state.mode === 'editing' && state.editorHistory?.redo ? ['native-history.redo' as const] : [],
903
+ ...unique,
904
+ ...source.member?.id ? ['production-drafts.inspect' as const, 'production-drafts.read' as const, ...this.client.capabilities?.readOnly !== true && safe && !source.dirty && !source.saving && !state.isHistoryBusy && !state.isHistoryPreparing && !this.production.productionDraftsBlocked ? ['production-drafts.discard' as const] : []] : [],
905
+ ...bodyDrafts.read ? ['body-drafts.inspect' as const, 'body-drafts.read' as const] : [],
906
+ ...bodyDrafts.mutate && !locked && !state.isCreatingPage && !state.isEditingPage && !state.isHistoryBusy && !state.isHistoryPreparing && !state.hasDocumentTimingDrafts
907
+ ? ['body-drafts.restore' as const, 'body-drafts.discard' as const, ...bodyDrafts.current ? ['body-drafts.retry' as const] : []] : [],
1086
908
  ...commentDrafts?.readable ? ['comment-drafts.inspect' as const, 'comment-drafts.read' as const] : [],
1087
- ...clean && !state.isHistoryBusy && !state.isHistoryPreparing && commentDrafts?.readable && commentDrafts.ownersKnown ? ['comment-drafts.discard' as const, ...state.webView === 'document' && commentDrafts.hasRestoreComposer() ? ['comment-drafts.restore' as const] : []] : [],
909
+ ...this.client.capabilities?.readOnly !== true && clean && !state.isHistoryBusy && !state.isHistoryPreparing && commentDrafts?.readable && commentDrafts.ownersKnown ? ['comment-drafts.discard' as const, ...state.webView === 'document' && commentDrafts.hasRestoreComposer() ? ['comment-drafts.restore' as const] : []] : [],
1088
910
  ...source.member?.id && this.#componentPropertyDrafts.readable(source.identity, source.member.id) ? ['component-drafts.inspect' as const, 'component-drafts.read' as const] : [],
1089
911
  ...clean && !state.isHistoryBusy && !state.isHistoryPreparing && source.member?.id && this.#componentPropertyDrafts.readable(source.identity, source.member.id) ? ['component-drafts.restore' as const, 'component-drafts.discard' as const] : [],
1090
912
  ...this.#canPreparePresentation() ? ['preview.prepare' as const] : [],
1091
- ...clean && (state.webView === 'document' || ready) ? ['position.step' as const] : [],
913
+ ...clean && (state.webView === 'document' || state.webView === 'scrolly' && preparedCurrent && this.#previewSinks.size === 1 && state.previewIrRevision === prepared.revision || ready) ? ['position.step' as const] : [],
1092
914
  ...ready ? ['playback.play' as const, 'playback.rate' as const, ...plan?.timing === 'confirmed' ? ['playback.seek' as const] : []] : []], unsubmittedContent: 'not-inspected' }
1093
915
  }
1094
916
 
@@ -1096,9 +918,35 @@ export class Workbench {
1096
918
  async executeAuthoringClientAction(action: AuthoringClientAction, expected: CanonicalSource, signal: AbortSignal, deadline?: number, fits?: (result: AuthoringClientActionResult) => boolean): Promise<void | AuthoringClientActionResult> {
1097
919
  const scope = this.#documentScope, identity = this.#state.authoring?.identity, document = this.#state.document, interaction = this.#state.documentPositionToken
1098
920
  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 }
921
+ 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
922
  current()
1101
923
  if (action.type === 'state.read') return
924
+ if (action.type === 'native-history.undo' || action.type === 'native-history.redo') {
925
+ if (this.editing.nativeHistory(action.type === 'native-history.undo' ? 'undo' : 'redo') !== true) throw new Error('client-native-history-unavailable')
926
+ owned(); return
927
+ }
928
+ const controls = [...this.#clientControls].filter(owner => owner.identity === identity && owner.actions().includes(action.type))
929
+ if (controls.length) {
930
+ if (controls.length !== 1) throw new Error('client-action-ambiguous')
931
+ const control = controls[0]!
932
+ await control.execute(action, expected, signal, deadline)
933
+ owned()
934
+ if (!this.#clientControls.has(control)) throw new Error('client-action-unavailable')
935
+ return
936
+ }
937
+ 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') {
938
+ if (!identity || !fits) throw new Error('client-body-drafts-unavailable')
939
+ const guard = () => {
940
+ owned()
941
+ const actual = this.#documentSession.canonicalSource()
942
+ 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')
943
+ }
944
+ return executeBodyDraftAction(this.#documentSession, () => this.#state.authoring, action, { signal, guard, source: expected, ...action.type !== 'body-drafts.retry' ? { localDraft: true as const } : {} }, fits)
945
+ }
946
+ if (action.type === 'production-drafts.inspect' || action.type === 'production-drafts.read' || action.type === 'production-drafts.discard') {
947
+ if (!identity || !this.#state.authoring?.member?.id || !fits) throw new Error('client-production-drafts-unavailable')
948
+ return executeProductionDraftAction(this.production, action, signal, () => { owned(); current() }, fits)
949
+ }
1102
950
  if (action.type === 'comment-drafts.inspect' || action.type === 'comment-drafts.read') {
1103
951
  const drafts = identity ? this.documentCommentDrafts(identity) : undefined
1104
952
  if (!drafts?.readable || !fits) throw new Error('client-comment-drafts-unavailable')
@@ -1112,7 +960,7 @@ export class Workbench {
1112
960
  const guard = () => {
1113
961
  owned()
1114
962
  const state = this.#state, source = state.authoring
1115
- if (!source?.content || source.member?.id !== memberId || !source.version || !source.fingerprint
963
+ if (this.client.capabilities?.readOnly === true || !source?.content || source.member?.id !== memberId || !source.version || !source.fingerprint
1116
964
  || !sameSource({ documentId: source.content.id, version: source.version, fingerprint: source.fingerprint }, expected)
1117
965
  || source.loading || source.dirty || source.saving || source.composing || source.restored || source.recovering || source.error || isAgentChanging(state)
1118
966
  || state.isCreatingPage || state.isEditingPage || state.isHistoryBusy || state.isHistoryPreparing || state.hasDocumentTimingDrafts
@@ -1171,13 +1019,22 @@ export class Workbench {
1171
1019
  await this.pausePlayback(); current()
1172
1020
  if (interaction !== this.#state.documentPositionToken) throw new Error('client-position-changed')
1173
1021
  const present = this.#state.webView === 'present'
1022
+ const reading = this.#state.webView === 'scrolly', connection = this.#state.previewConnection
1174
1023
  const result = await this.selectDocumentStep(action.sectionId, action.stepId)
1175
1024
  owned()
1025
+ if (reading) await this.waitForAuthoringClientState(() => {
1026
+ owned()
1027
+ if (this.#state.webView !== 'scrolly' || this.#state.previewConnection !== connection || this.#previewSinks.size !== 1) throw new Error('client-preview-unavailable')
1028
+ const state = this.authoringClientSnapshot(0)
1029
+ return this.#lastPosition !== undefined && state?.view === 'scrolly' && sameSource(state.source, expected)
1030
+ && state.position?.sectionId === action.sectionId && state.position.stepId === action.stepId
1031
+ }, signal)
1176
1032
  const state = this.authoringClientSnapshot(0)
1177
1033
  if (!state || !sameSource(state.source, expected) || state.position?.sectionId !== action.sectionId || state.position.stepId !== action.stepId
1178
1034
  || 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
1035
  return
1180
1036
  }
1037
+ if (action.type !== 'playback.play' && action.type !== 'playback.seek' && action.type !== 'playback.rate') throw new Error('client-action-unavailable')
1181
1038
  const plan = this.#state.productionPlan
1182
1039
  if (!plan || !sameProductionBinding(plan.binding, action.binding)) throw new Error('client-playback-binding-changed')
1183
1040
  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 +1057,7 @@ export class Workbench {
1200
1057
  signal.throwIfAborted()
1201
1058
  if (scope !== this.#documentScope || this.#state.authoring?.identity !== identity || !this.#productionSourceCurrent(plan.binding)) throw new Error('production-source-changed')
1202
1059
  this.#set({ productionPlan: plan })
1203
- if (this.#production.changed()) void this.pausePlayback().catch(() => {})
1060
+ if (this.#productionPlayback.changed()) void this.pausePlayback().catch(() => {})
1204
1061
  return plan
1205
1062
  }
1206
1063
 
@@ -1221,7 +1078,7 @@ export class Workbench {
1221
1078
  await this.pausePlayback()
1222
1079
  signal?.throwIfAborted()
1223
1080
  }
1224
- return await this.#production.control(control, signal)
1081
+ return await this.#productionPlayback.control(control, signal)
1225
1082
  } catch (error) {
1226
1083
  const code = errorMessage(error), current = this.#state.productionPlan?.binding
1227
1084
  if (scope === this.#documentScope && !signal?.aborted && current && sameProductionBinding(current, control.binding) && this.#productionReady()
@@ -1233,7 +1090,7 @@ export class Workbench {
1233
1090
 
1234
1091
  closeProduction(): void {
1235
1092
  this.#interruptProductionNavigation()
1236
- this.#production.reset()
1093
+ this.#productionPlayback.reset()
1237
1094
  this.#set({ productionPlan: undefined, productionFailure: undefined })
1238
1095
  }
1239
1096
 
@@ -1245,9 +1102,7 @@ export class Workbench {
1245
1102
  await this.flushPendingEdits()
1246
1103
  const source = this.#state.authoring, document = this.getDocument(identity)
1247
1104
  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)
1105
+ this.#documentSession.record(enableDocumentProduction(document))
1251
1106
  await this.flushPendingEdits()
1252
1107
  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
1108
  }
@@ -1263,46 +1118,6 @@ export class Workbench {
1263
1118
  if (this.#state.document !== undefined) void this.#readPreview(this.#state.document)
1264
1119
  }
1265
1120
 
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
1121
  /** The preview acknowledges that all registered lecture playback has paused before audition audio starts. */
1307
1122
  pausePlayback(interactive = false): Promise<void> { if (interactive) this.#interruptProductionNavigation(); return this.#playback.pause() }
1308
1123
 
@@ -1334,175 +1149,14 @@ export class Workbench {
1334
1149
  if (!asset || asset.kind !== 'image' || asset.location !== answer.content.assets[answer.assetId]?.location) throw new Error('document-identity-changed')
1335
1150
  return asset.location
1336
1151
  }
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
1152
  /** Parameter planning is an authoring read; it does not compile, change modes or write the document. */
1499
1153
  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
1154
+ const source = this.production.source(expected), scope = this.#documentScope
1501
1155
  if (!source.content || !source.fingerprint || source.fingerprint !== expected.fingerprint) throw new Error('component-source-changed')
1502
1156
  const request = { id, source: componentSource({ content: source.content, version: source.version!, fingerprint: source.fingerprint }), action: structuredClone(action) }
1503
1157
  const answer = await this.client.planDocumentAction(source.directory, request, signal)
1504
1158
  signal?.throwIfAborted()
1505
- const current = this.#mediaSource(expected)
1159
+ const current = this.production.source(expected)
1506
1160
  if (scope !== this.#documentScope || !current.content || !current.fingerprint || answer.document !== source.directory || answer.changeId !== id || answer.effect.kind !== 'component'
1507
1161
  || !sameComponentSource(answer.source, request.source) || JSON.stringify(answer.action) !== JSON.stringify(request.action)) throw new Error('component-source-changed')
1508
1162
  return answer
@@ -1510,13 +1164,13 @@ export class Workbench {
1510
1164
  /** The existing source actor owns adoption and ambiguous-response recovery, including later native input. */
1511
1165
  async applyDocumentComponentPlan(plan: DocumentAuthoringActionPlan, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<{ answer: DocumentChangeAnswer, commitId?: string }> {
1512
1166
  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
1167
+ const source = this.production.source(expected), action = plan.action as DocumentComponentAction, scope = this.#documentScope
1514
1168
  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
1169
  this.#playback.stopPreviewOutputs()
1516
1170
  await this.pausePlayback()
1517
1171
  let receipt: AppliedDocumentAuthoringAction | undefined
1518
1172
  const remember = (answer: DocumentChangeAnswer) => {
1519
- if (this.#documentEditorBinding?.identity === expected.identity) this.#documentEditorCommands?.rememberComponentConfiguration(answer.content)
1173
+ this.editing.rememberComponent(answer.content, expected.identity)
1520
1174
  return { answer, ...receipt?.commit ? { commitId: receipt.commit.id } : {} }
1521
1175
  }
1522
1176
  try {
@@ -1536,7 +1190,7 @@ export class Workbench {
1536
1190
  && file?.version === current.version && current.version !== plan.source.version) {
1537
1191
  // Canonical acceptance is already known even when later native input has
1538
1192
  // deleted the target. Undoing that deletion must restore its accepted configuration.
1539
- if (this.#documentEditorBinding?.identity === expected.identity) this.#documentEditorCommands?.rememberComponentConfiguration(plan.content)
1193
+ this.editing.rememberComponent(plan.content, expected.identity)
1540
1194
  try {
1541
1195
  if (!applyDocumentComponentAction(current.content, action).effect.changed) return remember({ document: source.directory, content: plan.content,
1542
1196
  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 +1199,24 @@ export class Workbench {
1545
1199
  throw error
1546
1200
  }
1547
1201
  }
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
1202
  recordDocument(content: TeachingDocument): void { if (!isAgentChanging(this.#state)) this.#documentSession.record(content) }
1664
1203
  documentComposition(composing: boolean, owner = 'body', identity?: string): void { this.#documentSession.composition(composing, owner, identity) }
1665
1204
  retryDocument(): Promise<void> { return this.#documentSession.retry() }
1666
- discardDocument(): Promise<void> { return this.#documentSession.discard() }
1205
+ discardDocument(): Promise<void> { return this.#documentSession.discard().then(() => {}) }
1667
1206
  recoverDocumentDraft(value: DocumentDraftReference, identity: string): Promise<void> {
1668
- return this.#state.authoring?.identity === identity && !isAgentChanging(this.#state) ? this.#documentSession.recoverDraft(value) : Promise.resolve()
1207
+ return this.#state.authoring?.identity === identity && !isAgentChanging(this.#state) ? this.#documentSession.recoverDraft(value).then(() => {}) : Promise.resolve()
1669
1208
  }
1670
1209
  forgetDocumentDraft(value: DocumentDraftReference, identity: string): void {
1671
- if (this.#state.authoring?.identity === identity && !isAgentChanging(this.#state)) void this.#documentSession.forgetDraft(value)
1672
- }
1673
- 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
- }
1210
+ this.forgetDocumentDrafts([value], identity)
1711
1211
  }
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
- }
1212
+ forgetDocumentDrafts(values: readonly DocumentDraftReference[], identity: string): void {
1213
+ if (this.#state.authoring?.identity === identity && !isAgentChanging(this.#state)) void this.#documentSession.forgetDrafts(values)
1791
1214
  }
1215
+ documentError(error: Error): void { this.#set({ save: { kind: 'failed', message: error.message } }) }
1792
1216
  async flushPendingEdits(signal?: AbortSignal): Promise<void> {
1793
1217
  if (isAgentChanging(this.#state)) throw new Error('save-locked')
1794
1218
  await this.#documentSession.flush(signal)
1795
1219
  }
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
1220
  /** Points at a block or a passage (none: stops pointing): the preview outlines it and the conversation is told. */
1897
1221
  point(pointer: Pointer | undefined): void {
1898
1222
  const pointed = this.#state.pointer !== undefined || this.#state.focus.length > 0
@@ -1966,6 +1290,40 @@ export class Workbench {
1966
1290
  }
1967
1291
  }
1968
1292
 
1293
+ /**
1294
+ * Opens the conversation with a request, for the author to describe and send, to add an animation at `place` of the
1295
+ * open document; the document's focus points the AI at the place's block. Nothing is inserted or sent.
1296
+ */
1297
+ draftAnimation(place: DocumentInsertionPlace): boolean {
1298
+ const document = this.#state.document, content = this.#state.authoring?.content, drafter = [...this.#drafters][0]
1299
+ const section = content?.sections[place.sectionId]
1300
+ if (document === undefined || !content || !section || !drafter) return false
1301
+ const report = (block?: string): FocusReport => ({ id: 'insertion', from: this.#state.previewRenderer, section: place.sectionId, ...block ? { block } : {}, ...place.text ? { quote: place.text.slice(0, 2000) } : {} })
1302
+ const text = this.#messages.animationRequest(content.sectionOrder.indexOf(place.sectionId) + 1, section.title, place)
1303
+ const focus = [report(place.blocks[0])]
1304
+ void this.#focusFirst(document, [...place.blocks.map(block => [report(block)]), [report()], []])
1305
+ 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 })
1306
+ this.#set({ askFailure: undefined })
1307
+ void (async () => drafter({ text, focus }))().then(() => drafted({ 'presmium.outcome': 'drafted' }), (error: unknown) => {
1308
+ drafted({ 'presmium.outcome': 'failed', 'presmium.error': errorMessage(error) })
1309
+ if (this.#state.document === document) this.#set({ askFailure: errorMessage(error) })
1310
+ })
1311
+ return true
1312
+ }
1313
+
1314
+ /**
1315
+ * Sets the first of `choices` the service can locate as the document's focus. Its runtime snapshot is compiled from the
1316
+ * saved source, which may not have a block or page created moments ago yet; the last choice leaves no stale focus.
1317
+ */
1318
+ async #focusFirst(document: string, choices: FocusReport[][]): Promise<void> {
1319
+ for (const focus of choices) {
1320
+ this.setFocus(focus)
1321
+ const version = this.#focusVersion
1322
+ await this.#focusWriting
1323
+ if (version !== this.#focusVersion || this.#state.document !== document || !this.#state.focusFailure) return
1324
+ }
1325
+ }
1326
+
1969
1327
  /** A place as the author sees it: the section's title and the passage. */
1970
1328
  #describe(item: FocusReport & Partial<Focus>): AgentPlace {
1971
1329
  const doc = this.#state.ir?.doc
@@ -1989,7 +1347,7 @@ export class Workbench {
1989
1347
  /** Shows a section in the preview: from the navigation pane, the section to read or the slide to show. */
1990
1348
  goToSection(section: string): void {
1991
1349
  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
1350
+ this.#set({ position: { section, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: { section, request: randomUUID() } }); return
1993
1351
  }
1994
1352
  this.goToStep(section, this.#selectedSteps.get(`${this.#state.document}\0${section}`) ?? 0)
1995
1353
  }
@@ -2003,7 +1361,7 @@ export class Workbench {
2003
1361
  const visible = (index: number) => Boolean(section.stepOrder[index] && effectiveComponentParameters(document, blockId, section.stepOrder[index]).visual?.visible)
2004
1362
  const step = visible(current) ? current : Math.max(0, section.stepOrder.findIndex((_, index) => visible(index)))
2005
1363
  this.#set({ position: { section: sectionId, step, trail: [], view: 'document' }, documentPositionFailure: undefined,
2006
- documentNavigation: { section: sectionId, block: blockId, request: crypto.randomUUID() } })
1364
+ documentNavigation: { section: sectionId, block: blockId, request: randomUUID() } })
2007
1365
  }
2008
1366
 
2009
1367
  observeDocumentSection(section: string): void {
@@ -2035,7 +1393,7 @@ export class Workbench {
2035
1393
  const plan = this.#state.productionPlan, range = plan?.pages.find(page => page.sectionId === sectionId)?.steps.find(step => step.stepId === stepId)
2036
1394
  if (plan?.canPreview && this.#productionReady() && range?.startMs !== undefined) {
2037
1395
  this.stopAuditions()
2038
- if (this.#production.selecting(sectionId, stepId)) return
1396
+ if (this.#productionPlayback.selecting(sectionId, stepId)) return
2039
1397
  this.#selectedSteps.set(`${this.#state.document}\0${sectionId}`, step)
2040
1398
  this.#set({ position: { section: sectionId, step, trail: [], view: 'present' } })
2041
1399
  return this.controlProduction({ binding: plan.binding, action: 'step', sectionId, stepId }).catch(() => undefined)
@@ -2090,8 +1448,8 @@ export class Workbench {
2090
1448
  return true
2091
1449
  }
2092
1450
 
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') }
1451
+ undo(): Promise<boolean> { const result = this.editing.nativeHistory('undo'); return result === undefined ? this.#changeHistory('undo') : Promise.resolve(result) }
1452
+ redo(): Promise<boolean> { const result = this.editing.nativeHistory('redo'); return result === undefined ? this.#changeHistory('redo') : Promise.resolve(result) }
2095
1453
 
2096
1454
  async #changeHistory(action: 'undo' | 'redo' | 'revert', revision?: string): Promise<boolean> {
2097
1455
  if (this.#state.mode !== 'editing' || this.#state.isCreatingPage || this.#state.isEditingPage || this.#state.isHistoryBusy || this.#state.isHistoryPreparing) return false
@@ -2192,7 +1550,7 @@ export class Workbench {
2192
1550
  sink.send({ type: 'highlight', target: reveal ?? this.#state.pointer?.target ?? null })
2193
1551
  return () => {
2194
1552
  this.#previewSinks.delete(sink)
2195
- this.#production.detach(sink)
1553
+ this.#productionPlayback.detach(sink)
2196
1554
  this.#set({ previewConnection: this.#state.previewConnection + 1 })
2197
1555
  this.#playback.detach(sink)
2198
1556
  }
@@ -2209,7 +1567,7 @@ export class Workbench {
2209
1567
  if (report.type === 'page-create') { origin?.send({ type: 'page-created', section: report.section, request: report.request, error: unsupported }); return }
2210
1568
  if (document !== this.#state.document || renderer !== this.#state.previewRenderer) return
2211
1569
  this.#playback.report(document, report, origin)
2212
- this.#production.report(document, report, origin)
1570
+ this.#productionPlayback.report(document, report, origin)
2213
1571
  switch (report.type) {
2214
1572
  case 'ready':
2215
1573
  case 'updated':
@@ -2236,9 +1594,6 @@ export class Workbench {
2236
1594
  } else if (this.#state.pointer?.quote) this.point(undefined)
2237
1595
  break
2238
1596
  }
2239
- case 'flashed':
2240
- if (this.#trail) this.#set({ changeTrail: { id: this.#trail, rects: report.rects } })
2241
- break
2242
1597
  case 'rect':
2243
1598
  if (this.#state.pointer) this.#set({ pointer: { ...this.#state.pointer, rect: report.rect ?? undefined, obstacles: report.obstacles } })
2244
1599
  break
@@ -2247,7 +1602,7 @@ export class Workbench {
2247
1602
  if (snapshot && source && (source.dirty || source.loading || source.version !== snapshot.version || source.fingerprint !== snapshot.fingerprint)) break
2248
1603
  // An initial loader can report its old cursor while a newer stable selection is preparing.
2249
1604
  // Explicit native exits still reach the outer document workspace.
2250
- if (report.view !== 'document' && this.#production.selecting()) break
1605
+ if (report.view !== 'document' && this.#productionPlayback.selecting()) break
2251
1606
  // A fresh frame announces its document view before applying the queued
2252
1607
  // presentation command. Only the requested view completes that switch.
2253
1608
  if (renderer === 'web' && this.#awaitingView) {
@@ -2286,19 +1641,14 @@ export class Workbench {
2286
1641
 
2287
1642
  #stopSubscriptions(): void {
2288
1643
  this.#componentPropertyDrafts.stopAgentRead()
2289
- this.#saveDocumentReturnPoint(); this.#cancelOpeningDocument(); this.#stopDocumentReturnScroll?.()
2290
- this.#documentViewport?.stop(); this.#documentViewport = undefined; this.#documentEditorBinding = undefined
1644
+ this.editing.reset()
2291
1645
  this.#presentationPreparation++
2292
1646
  this.#presentationController?.abort(new Error('client-document-changed'))
2293
1647
  this.#voiceover.stop()
2294
- this.#production.reset()
1648
+ this.#productionPlayback.reset()
2295
1649
  this.#set({ isPreparingPresentation: false, presentationFailure: undefined, presentationSnapshot: undefined, productionPlan: undefined, productionFailure: undefined })
2296
- this.#removedCueTimings.clear(); this.#cueTimingScope = undefined
1650
+ this.production.reset()
2297
1651
  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
1652
  this.#playback.reset()
2303
1653
  this.#focusVersion++
2304
1654
  this.#pendingReveal = undefined
@@ -2321,8 +1671,9 @@ export class Workbench {
2321
1671
  this.#documentSession.dispose()
2322
1672
  this.#commentDrafts.close()
2323
1673
  this.#componentPropertyDrafts.close()
2324
- this.#captionTimingDrafts.close()
1674
+ this.production.dispose()
2325
1675
  disposeTranscriptionSessions(this.client)
2326
1676
  disposeDocumentRecordings(this)
1677
+ this.#clientControls.clear(); this.#navigationGuards.clear(); this.#clientControlListeners.clear()
2327
1678
  }
2328
1679
  }