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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workbench",
3
- "version": "0.2.0-rc.50",
3
+ "version": "0.2.0-rc.51",
4
4
  "description": "Presmium's workbench panels in React (the documents, a document edited on its rendered page with comments and version history) with the workspace service's client and the preview protocol's workbench side; @lincyaw/dsh places them in presmium studio (experimental)",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -55,8 +55,8 @@
55
55
  "@tiptap/pm": "3.32.0",
56
56
  "katex": "0.18.10",
57
57
  "react-resizable-panels": "4.14.5",
58
- "@lincyaw/design": "1.0.0-rc.50",
59
- "@lincyaw/kernel": "1.0.0-rc.50"
58
+ "@lincyaw/kernel": "1.0.0-rc.51",
59
+ "@lincyaw/design": "1.0.0-rc.51"
60
60
  },
61
61
  "peerDependencies": {
62
62
  "react": "^18.3.1",
@@ -67,6 +67,6 @@
67
67
  "@types/react-dom": "18.3.7",
68
68
  "react": "^18.3.1",
69
69
  "react-dom": "^18.3.1",
70
- "@lincyaw/compiler": "1.0.0-rc.50"
70
+ "@lincyaw/compiler": "1.0.0-rc.51"
71
71
  }
72
72
  }
@@ -0,0 +1,100 @@
1
+ import { randomUUID } from '@lincyaw/kernel'
2
+ import type { AuthoringWindowAcknowledgement, AuthoringWindowEvent, AuthoringWindowSnapshot } from '@lincyaw/kernel'
3
+ import type { Workbench } from './workbench.ts'
4
+
5
+ /** One root-lifetime reader on the existing socket, independent of document attachments. */
6
+ export function connectAuthoringWindow(workbench: Workbench): () => void {
7
+ const open = workbench.client.openAuthoringWindow
8
+ if (!open) return () => {}
9
+ const clientId = randomUUID(), epoch = randomUUID(), seen = new Set<string>()
10
+ let closed = false, connectionId: string | undefined, revision = 0, sequence = 0, signature: string | undefined
11
+ const compositions = new Set<EventTarget>()
12
+ let inputRevision = 0, lastInputRevision = 0
13
+ let content: object | undefined, drafts: string | undefined, playback: number | undefined, view: string | undefined
14
+ let active: { requestId: string, controller: AbortController, navigation: boolean } | undefined
15
+ let reports: Promise<void> = Promise.resolve(), pending: AuthoringWindowSnapshot | undefined, sending = false
16
+ const snapshot = () => {
17
+ for (const target of compositions) if (target instanceof Node && !target.isConnected) compositions.delete(target)
18
+ const value = workbench.authoringWindowSnapshot(0), state = workbench.state, bank = workbench.authoringDraftRevision()
19
+ if (compositions.size) value.actions = ['window.read']
20
+ const next = JSON.stringify(value)
21
+ if (next !== signature || content !== state.authoring?.content || bank !== drafts || playback !== state.productionNavigationVersion || view !== state.webView || inputRevision !== lastInputRevision) {
22
+ revision++; signature = next; content = state.authoring?.content; drafts = bank; playback = state.productionNavigationVersion; view = state.webView; lastInputRevision = inputRevision
23
+ }
24
+ return { ...value, revision }
25
+ }
26
+ const send = (connection: string, value: AuthoringWindowSnapshot, acknowledgement?: Omit<AuthoringWindowAcknowledgement, 'sequence' | 'snapshot'>, guard?: () => void) => {
27
+ const report = { sequence: ++sequence, snapshot: value, ...acknowledgement }
28
+ const next = reports.then(() => {
29
+ if (closed || connectionId !== connection) throw new Error('window-connection-changed')
30
+ guard?.()
31
+ return acknowledgement ? channel.acknowledge(connection, report as AuthoringWindowAcknowledgement) : channel.publish(connection, report)
32
+ })
33
+ reports = next.catch(() => {}); return next
34
+ }
35
+ const publish = (value: AuthoringWindowSnapshot) => {
36
+ pending = value
37
+ if (sending) return
38
+ sending = true
39
+ void (async () => {
40
+ try {
41
+ while (pending && connectionId) { pending = undefined; const connection = connectionId; await send(connection, snapshot()).catch(() => {}) }
42
+ } finally { sending = false }
43
+ })()
44
+ }
45
+ const received = async (event: AuthoringWindowEvent) => {
46
+ if (closed) return
47
+ if (event.type === 'connected') { active?.controller.abort(); active = undefined; connectionId = event.connectionId; publish(snapshot()); return }
48
+ if (event.type === 'cancel') { if (event.connectionId === connectionId && active?.requestId === event.requestId) active.controller.abort(new Error('window-request-cancelled')); return }
49
+ const connection = connectionId, request = event.request
50
+ if (!connection || request.clientId !== clientId || request.epoch !== epoch || request.connectionId !== connection || seen.has(request.requestId)) return
51
+ seen.add(request.requestId); if (seen.size > 64) seen.delete(seen.values().next().value!)
52
+ const initial = snapshot()
53
+ if (active || initial.revision !== request.revision || !initial.actions.includes(request.action.type) || Date.now() >= Date.parse(event.expiresAt)) {
54
+ await send(connection, initial, { requestId: request.requestId, state: 'refused', error: { code: 'window-state-changed' } }).catch(() => {}); return
55
+ }
56
+ const controller = new AbortController(), task = { requestId: request.requestId, controller, navigation: request.action.type !== 'window.read' }
57
+ active = task
58
+ const owned = () => { controller.signal.throwIfAborted(); if (closed || connectionId !== connection || active !== task || Date.now() >= Date.parse(event.expiresAt)) throw new Error('window-request-expired') }
59
+ const timeout = setTimeout(() => controller.abort(new Error('window-request-expired')), Math.max(0, Date.parse(event.expiresAt) - Date.now()))
60
+ try {
61
+ await send(connection, initial, { requestId: request.requestId, state: 'executing' }, () => { owned(); if (snapshot().revision !== request.revision) throw new Error('window-state-changed') })
62
+ owned()
63
+ if (snapshot().revision !== request.revision) throw new Error('window-state-changed')
64
+ const outcome = await workbench.executeAuthoringWindowAction(request, controller.signal)
65
+ owned()
66
+ const result = snapshot()
67
+ await send(connection, result, { requestId: request.requestId, state: 'done', outcome }, () => { owned(); if (snapshot().revision !== result.revision) throw new Error('window-state-changed') })
68
+ } catch (error) {
69
+ const code = error instanceof Error && /^window-[a-z-]{1,100}$/.test(error.message) ? error.message : 'window-action-not-verified'
70
+ if (!closed && connectionId === connection) await send(connection, snapshot(), { requestId: request.requestId, state: 'failed', error: { code } }).catch(() => {})
71
+ } finally { clearTimeout(timeout); if (active === task) active = undefined }
72
+ }
73
+ const channel = open({ clientId, epoch, snapshot: snapshot() }, event => { void received(event) }, () => { connectionId = undefined; pending = undefined; active?.controller.abort(); active = undefined })
74
+ const changed = () => { if (closed) return; const before = revision, value = snapshot(); if (before !== revision && connectionId) publish(value) }
75
+ const stop = workbench.subscribe(changed), stopDrafts = workbench.subscribeAuthoringDraftChanges(changed)
76
+ const interrupt = () => { if (active?.navigation) active.controller.abort(new Error('window-input-changed')) }
77
+ const input = () => { inputRevision++; interrupt(); changed() }
78
+ const escape = (event: KeyboardEvent) => { if (event.key === 'Escape') interrupt() }
79
+ const compositionStart = (event: CompositionEvent) => { if (event.target) compositions.add(event.target); input() }
80
+ const compositionEnd = (event: CompositionEvent) => { if (event.target) compositions.delete(event.target); input() }
81
+ // Only modal semantics matter. Text mutations and iframe animation frames never trigger publications.
82
+ const modal = typeof MutationObserver === 'undefined' ? undefined : new MutationObserver(records => {
83
+ const modalChange = records.some(record => record.type === 'attributes' || [...record.addedNodes, ...record.removedNodes].some(node => {
84
+ return node instanceof Element && (node.matches('[role="dialog"]') || node.querySelector('[role="dialog"]'))
85
+ }))
86
+ if (modalChange || compositions.size > 0 && records.some(record => record.removedNodes.length > 0)) changed()
87
+ })
88
+ if (typeof document !== 'undefined') {
89
+ modal?.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['aria-modal', 'hidden', 'inert'] })
90
+ document.addEventListener('input', input, true); document.addEventListener('compositionstart', compositionStart, true); document.addEventListener('compositionend', compositionEnd, true)
91
+ document.addEventListener('pointerdown', interrupt, true); document.addEventListener('keydown', escape, true)
92
+ }
93
+ return () => {
94
+ closed = true; stop(); stopDrafts(); modal?.disconnect(); active?.controller.abort(); channel.close(); pending = undefined; compositions.clear()
95
+ if (typeof document !== 'undefined') {
96
+ document.removeEventListener('input', input, true); document.removeEventListener('compositionstart', compositionStart, true); document.removeEventListener('compositionend', compositionEnd, true)
97
+ document.removeEventListener('pointerdown', interrupt, true); document.removeEventListener('keydown', escape, true)
98
+ }
99
+ }
100
+ }
@@ -1,5 +1,5 @@
1
1
  import { applyDocumentCaptionTiming, changeDocumentCaptionScale, DOCUMENT_AUDIO_MAX_BYTES, randomUUID, replaceStepNarrations, sameProductionBinding, validateDocument } from '@lincyaw/kernel'
2
- import type { DocumentAudioImportAnswer, DocumentAudioInspectionAnswer, DocumentCaptionTimingAction, DocumentChangeAnswer, DocumentRecordingAdoption, DocumentTranscriptionRequest, MediaClip, Narration, ProductionBinding, TeachingDocument, TranscriptionAdoptionAnswer, TranscriptionAdoptionApply, TranscriptionAdoptionDraft, TranscriptionAdoptionPlan, TranscriptionTask, VerifiedDocumentRecordingAdoption, VoiceSource } from '@lincyaw/kernel'
2
+ import type { DocumentAudioImportAnswer, DocumentAudioInspectionAnswer, DocumentCaptionTimingAction, DocumentChangeAnswer, DocumentRecordingAdoption, DocumentTranscriptionRequest, MediaClip, Narration, ProductionBinding, TeachingDocument, TimeRange, TranscriptionAdoptionAnswer, TranscriptionAdoptionApply, TranscriptionAdoptionDraft, TranscriptionAdoptionPlan, TranscriptionTask, VerifiedDocumentRecordingAdoption, VoiceSource } from '@lincyaw/kernel'
3
3
  import { isAgentChanging } from './workbench-state.ts'
4
4
  import type { WorkbenchStore } from './workbench-state.ts'
5
5
  import type { DocumentSession, DocumentSessionState } from './document-session.ts'
@@ -29,6 +29,7 @@ interface ProductionOptions {
29
29
  stopPreviewOutputs(): void
30
30
  sourceCurrent(binding: ProductionBinding): boolean
31
31
  }
32
+ export interface RecordingRangeDraft { version: string, voice: Extract<VoiceSource, { type: 'recording' }>, range?: TimeRange, startText?: string, endText?: string }
32
33
 
33
34
  /** Source-bound media transactions, timing drafts and narration edits share the document actor. */
34
35
  export class DocumentProduction {
@@ -36,6 +37,7 @@ export class DocumentProduction {
36
37
  readonly #audioFingerprints = new WeakMap<File, Promise<string>>()
37
38
  readonly #documentTimingDrafts = new DocumentTimingDrafts()
38
39
  readonly #captionTimingDrafts = new CaptionTimingDrafts()
40
+ readonly #recordingRangeDrafts = new Map<string, Map<string, RecordingRangeDraft>>()
39
41
  readonly #removedCueTimings = new Map<string, { pauseMs: number }>()
40
42
  readonly #removedNarrations = new Map<string, { narration: Narration, override?: { narrationStart: 'with-animation' | 'after-animation' } }>()
41
43
  #cueTimingScope?: string
@@ -52,7 +54,13 @@ export class DocumentProduction {
52
54
  }
53
55
  }
54
56
  reset(): void { this.#removedCueTimings.clear(); this.#removedNarrations.clear(); this.#cueTimingScope = undefined }
55
- dispose(): void { this.reset(); this.#captionTimingDrafts.close() }
57
+ dispose(): void { this.reset(); this.#captionTimingDrafts.close(); this.#recordingRangeDrafts.clear() }
58
+ /** Native pending range input survives mode and document changes within this workbench. */
59
+ recordingRangeDrafts(identity: string): Map<string, RecordingRangeDraft> {
60
+ let values = this.#recordingRangeDrafts.get(identity)
61
+ if (!values) { values = new Map(); this.#recordingRangeDrafts.set(identity, values) }
62
+ return values
63
+ }
56
64
 
57
65
  source(expected: { identity: string, version: string }): DocumentSessionState {
58
66
  const source = this.#options.store.state.authoring
@@ -143,7 +143,7 @@ export class DocumentSession {
143
143
  this.#leaveTarget = target
144
144
  }
145
145
 
146
- async open(directory: string, expectedIdentity?: string): Promise<'identity-changed' | void> {
146
+ async open(directory: string, expectedIdentity?: string, signal?: AbortSignal): Promise<'identity-changed' | void> {
147
147
  if (this.#active !== directory) this.interrupt()
148
148
  const opening = ++this.#opening
149
149
  this.#active = directory
@@ -152,7 +152,7 @@ export class DocumentSession {
152
152
  if (cached) { cached.read++; cached.state = { ...cached.state, loading: true } }
153
153
  this.#changed(cached ? { ...cached.state } : { directory, loading: true, dirty: false, saving: false, restored: false, composing: false, storageFailure: false, reset: 0, issues: [] })
154
154
  try {
155
- const [info, answer] = await Promise.all([this.#client.readWorkbenchInfo(), this.#client.readDocument(directory)])
155
+ const [info, answer] = await waitForDraft(Promise.all([this.#client.readWorkbenchInfo(), this.#client.readDocument(directory, signal)]), signal)
156
156
  if (this.#active !== directory || opening !== this.#opening) return
157
157
  if (expectedIdentity !== undefined && JSON.stringify([info.root, answer.content.id]) !== expectedIdentity) return 'identity-changed'
158
158
  let slot = this.#slots.get(directory)
@@ -212,6 +212,7 @@ export class DocumentSession {
212
212
  if (this.#active === slot.state.directory && this.#slots.get(slot.state.directory) === slot) this.#changed({ ...slot.state })
213
213
  }
214
214
  bodyDraftRevision(): number { const slot = this.#active === undefined ? undefined : this.#slots.get(this.#active); return slot?.drafts.revision ?? 0 }
215
+ hasPendingAssetWrite(): boolean { return Boolean(this.#active !== undefined && this.#slots.get(this.#active)?.assetFlight) }
215
216
  bodyDraftCapabilities(): { read: boolean, mutate: boolean, current: boolean } {
216
217
  const slot = this.#active === undefined ? undefined : this.#slots.get(this.#active)
217
218
  const read = Boolean(slot?.state.identity && slot.state.content && slot.state.version && !slot.state.loading && !this.#disposed)
package/src/history.ts CHANGED
@@ -42,13 +42,13 @@ export class DocumentHistory {
42
42
  this.#review = undefined
43
43
  }
44
44
 
45
- async read(dir: string): Promise<void> {
45
+ async read(dir: string, signal?: AbortSignal): Promise<void> {
46
46
  this.#offsets = [0]
47
47
  this.#page = 0
48
48
  const read = ++this.#reads, scope = this.#scope
49
49
  const current = () => this.#store.state.document === dir && read === this.#reads && scope === this.#scope
50
50
  try {
51
- const [history, { files }] = await Promise.all([this.#client.readRevisions(dir), this.#client.readChanges(dir)])
51
+ const [history, { files }] = await Promise.all([this.#client.readRevisions(dir, undefined, signal), this.#client.readChanges(dir, signal)])
52
52
  if (current()) {
53
53
  const historyFailure = this.#store.state.historyFailure
54
54
  this.#store.set({ history, outside: files, ...this.#readFailure === historyFailure ? { historyFailure: undefined } : {} })
package/src/index.ts CHANGED
@@ -33,4 +33,5 @@ export { PreviewPanel } from './panels/PreviewPanel.tsx'
33
33
  export { SpeechSettingsPanel } from './panels/SpeechSettingsPanel.tsx'
34
34
  export { SPEECH_SETTINGS_MESSAGES } from './speech-settings-messages.ts'
35
35
  export { connectAuthoringClient } from './authoring-client.ts'
36
+ export { connectAuthoringWindow } from './authoring-window.ts'
36
37
  export { SHORTCUTS } from './shortcuts.ts'
@@ -1,15 +1,13 @@
1
1
  import { useEffect, useId, useRef, useState } from 'react'
2
2
  import { randomUUID, recordingSourceRange } from '@lincyaw/kernel'
3
- import type { DocumentRecordingAdoption, ProductionAssetInspection, TimeRange, VoiceSource } from '@lincyaw/kernel'
3
+ import type { DocumentRecordingAdoption, ProductionAssetInspection } from '@lincyaw/kernel'
4
4
  import { PmButton, PmInput, PmNotice } from '../components.tsx'
5
5
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
6
6
  import { AUDIO_RECORDING_MESSAGES } from '../audio-recording-messages.ts'
7
7
  import { MEDIA_MESSAGES, mediaFailure } from '../media-messages.ts'
8
8
  import { mediaTime, mediaTimeValue } from '../media-time.ts'
9
9
  import { PRODUCTION_MESSAGES } from '../production-messages.ts'
10
-
11
- type RecordingSource = Extract<VoiceSource, { type: 'recording' }>
12
- interface RangeDraft { version: string, voice: RecordingSource, range?: TimeRange, startText?: string, endText?: string }
10
+ import type { RecordingRangeDraft as RangeDraft } from '../document-production.ts'
13
11
  const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
14
12
 
15
13
  /** Video-only pending input; the existing recording transaction and source actor own every write. */
@@ -21,7 +19,7 @@ export function ProductionRecordingRange({ identity, sectionId, stepId, active,
21
19
  const document = source?.identity === identity ? source.content : undefined
22
20
  const effective = document?.production.stepOverrides[stepId]?.voiceSource ?? document?.production.sectionOverrides?.[sectionId]?.voiceSource ?? document?.production.defaults.voiceSource
23
21
  const voice = effective?.type === 'recording' ? effective : undefined, key = JSON.stringify([stepId, voice?.assetId])
24
- const drafts = useRef(new Map<string, RangeDraft>()), mounted = useRef(true), request = useRef<AbortController>()
22
+ const drafts = workbench.production.recordingRangeDrafts(identity), mounted = useRef(true), request = useRef<AbortController>()
25
23
  const [inspection, setInspection] = useState<{ version: string, value: ProductionAssetInspection }>(), [loading, setLoading] = useState(false)
26
24
  const [busy, setBusy] = useState(false), [failure, setFailure] = useState<string>(), [reload, setReload] = useState(0), [, render] = useState(0)
27
25
  const rangeErrorId = useId()
@@ -34,7 +32,7 @@ export function ProductionRecordingRange({ identity, sectionId, stepId, active,
34
32
  const latest = useRef({ key, active, disabled, onChanged }); latest.current = { key, active, disabled, onChanged }
35
33
  const current = () => mounted.current && workbench.getState().authoring?.identity === identity
36
34
  const inspected = inspection && inspection.version === source?.version && inspection.value.assetId === voice?.assetId ? inspection.value : undefined
37
- const draft = drafts.current.get(key) ?? (voice ? { version: source?.version ?? '', voice } : undefined)
35
+ const draft = drafts.get(key) ?? (voice ? { version: source?.version ?? '', voice } : undefined)
38
36
  const range = draft?.range ?? (draft && inspected ? recordingSourceRange(draft.voice, inspected.durationMs) : undefined)
39
37
  const start = draft ? mediaTimeValue(draft.startText, range?.startMs ?? draft.voice.sourceRange?.startMs ?? 0) : undefined
40
38
  const end = draft ? mediaTimeValue(draft.endText, range?.endMs ?? draft.voice.sourceRange?.endMs ?? 0) : undefined
@@ -48,15 +46,17 @@ export function ProductionRecordingRange({ identity, sectionId, stepId, active,
48
46
  const saved = step && (actual!.content!.production.stepOverrides[step.id]?.voiceSource ?? actual!.content!.production.sectionOverrides?.[step.sectionId]?.voiceSource ?? actual!.content!.production.defaults.voiceSource)
49
47
  if (!value || !actual?.version || saved?.type !== 'recording' || saved.assetId !== value.request.assetId || !same(saved.sourceRange, value.request.sourceRange)
50
48
  || actual.content?.assets[saved.assetId]?.fingerprint !== `sha256:${value.request.sha256}`) return false
51
- const pending = drafts.current.get(value.key)
52
- if (pending === value.draft) drafts.current.delete(value.key)
53
- else if (pending?.version === value.draft.version && same(pending.voice, value.draft.voice)) drafts.current.set(value.key, { ...pending, version: actual.version, voice: structuredClone(saved) })
54
- if (current()) { setFailure(undefined); render(value => value + 1) }
49
+ const pending = drafts.get(value.key)
50
+ if (pending === value.draft) drafts.delete(value.key)
51
+ else if (pending?.version === value.draft.version && same(pending.voice, value.draft.voice)) drafts.set(value.key, { ...pending, version: actual.version, voice: structuredClone(saved) })
52
+ if (current()) { workbench.refreshAuthoringClientControls(); setFailure(undefined); render(value => value + 1) }
55
53
  if (latest.current.key === value.key && latest.current.active && !latest.current.disabled && reported.current !== value.request.id) {
56
54
  reported.current = value.request.id; latest.current.onChanged()
57
55
  }
58
56
  return true
59
57
  }
58
+ useEffect(() => workbench.registerNavigationGuard(() => current() && (composing.current || Boolean(request.current))), [workbench, identity])
59
+ useEffect(() => { workbench.refreshAuthoringClientControls() }, [workbench, busy, key, active])
60
60
  useEffect(() => () => { mounted.current = false; request.current?.abort() }, [])
61
61
  useEffect(() => { request.current?.abort(); request.current = undefined; setBusy(false); setFailure(undefined) }, [key, active])
62
62
  useEffect(() => {
@@ -72,7 +72,7 @@ export function ProductionRecordingRange({ identity, sectionId, stepId, active,
72
72
  useEffect(() => { settle() }, [source?.version, source?.content, source?.loading, source?.dirty, source?.saving, source?.composing, source?.restored, source?.error, active, disabled, key])
73
73
  const edit = (patch: Partial<RangeDraft>) => {
74
74
  if (!draft) return
75
- drafts.current.set(key, { ...draft, ...range ? { range: { ...range } } : {}, ...patch }); setFailure(undefined); render(value => value + 1)
75
+ drafts.set(key, { ...draft, ...range ? { range: { ...range } } : {}, ...patch }); workbench.refreshAuthoringClientControls(); setFailure(undefined); render(value => value + 1)
76
76
  }
77
77
  const apply = async () => {
78
78
  if (!voice || !draft || !inspected || !valid || !changed || busy || disabled || !active || composing.current || !current()) return
@@ -82,8 +82,8 @@ export function ProductionRecordingRange({ identity, sectionId, stepId, active,
82
82
  const previous = sent.current?.request
83
83
  const change: DocumentRecordingAdoption = previous && previous.source.version === source.version && previous.stepId === stepId && previous.assetId === voice.assetId && previous.sha256 === inspected.sha256 && same(previous.sourceRange, proposed)
84
84
  ? previous : { id: randomUUID(), source: { documentId: source.content.id, version: source.version, fingerprint: source.fingerprint }, stepId, assetId: voice.assetId, sha256: inspected.sha256, sourceRange: proposed }
85
- const stored = drafts.current.get(key) ?? draft
86
- drafts.current.set(key, stored); sent.current = { key, draft: stored, request: change }; request.current = controller
85
+ const stored = drafts.get(key) ?? draft
86
+ drafts.set(key, stored); sent.current = { key, draft: stored, request: change }; request.current = controller
87
87
  setBusy(true); setFailure(undefined)
88
88
  try { await workbench.production.adoptRecording(change, { identity, version: source.version }, controller.signal); if (current()) settle() }
89
89
  catch (error) { if (current() && request.current === controller && !settle() && !controller.signal.aborted) setFailure(failureText(error)) }
@@ -95,7 +95,7 @@ export function ProductionRecordingRange({ identity, sectionId, stepId, active,
95
95
  const trimmed = Boolean(canonicalRange && inspected && (canonicalRange.startMs > 0 || canonicalRange.endMs < inspected.durationMs))
96
96
  const hasCaptions = document?.steps[stepId]?.narrationIds.some(id => document.narrations[id]?.content.some(node => node.type !== 'cue' && (node.type === 'text' ? node.text : node.display).trim()))
97
97
  return <section className="pm-ui-media-clip-editor" aria-label={r.trim} onFocusCapture={() => { if (!disabled) void workbench.pausePlayback() }}
98
- onCompositionStart={() => { composing.current = true }} onCompositionEnd={() => { composing.current = false }}
98
+ onCompositionStart={() => { composing.current = true; workbench.refreshAuthoringClientControls() }} onCompositionEnd={() => { composing.current = false; workbench.refreshAuthoringClientControls() }}
99
99
  onKeyDown={event => { event.stopPropagation(); if (event.key === 'Enter' && event.target instanceof HTMLInputElement && !event.nativeEvent.isComposing && !composing.current) { event.preventDefault(); void apply() } }}>
100
100
  <strong>{r.trim}</strong>
101
101
  <span>{document?.assets[voice.assetId]?.title || r.title}</span>
@@ -113,6 +113,6 @@ export function ProductionRecordingRange({ identity, sectionId, stepId, active,
113
113
  {review && <PmNotice tone="warn">{t.review}<PmButton small disabled={disabled || !inspected || busy} onClick={() => edit({ version: source!.version!, voice: structuredClone(voice) })}>{t.check}</PmButton></PmNotice>}
114
114
  {trimmed && hasCaptions && <PmNotice tone="warn">{r.captionReview}</PmNotice>}
115
115
  {failure && <PmNotice tone="danger">{failure}<PmButton small disabled={disabled || busy} onClick={() => { setInspection(undefined); setFailure(undefined); setReload(value => value + 1) }}>{t.retry}</PmButton></PmNotice>}
116
- {drafts.current.has(key) && <span className="pm-ui-field__hint" role="status">{t.pending}</span>}
116
+ {drafts.has(key) && <span className="pm-ui-field__hint" role="status">{t.pending}</span>}
117
117
  </section>
118
118
  }
package/src/workbench.ts CHANGED
@@ -3,7 +3,7 @@ import { DocumentEditing } from './document-editing.ts'
3
3
  import { isAgentChanging } from './workbench-state.ts'
4
4
  import type { AgentAnswer, AgentDraft, AgentRequest, PlaybackKey, Pointer, PreviewSink, WebView, WorkbenchMode, WorkbenchState, WorkbenchStore } from './workbench-state.ts'
5
5
  import { enableDocumentProduction, randomUUID } from '@lincyaw/kernel'
6
- import type { ProjectOperation, ProjectPlan } 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'
@@ -118,6 +118,7 @@ export class Workbench {
118
118
  #state: WorkbenchState
119
119
  readonly #listeners = new Set<Listener>()
120
120
  readonly #clientControls = new Set<AuthoringClientControls>()
121
+ readonly #navigationGuards = new Set<() => boolean>()
121
122
  readonly #clientControlListeners = new Set<Listener>()
122
123
  #clientControlRevision = 0
123
124
  readonly #commentDrafts = new CommentDraftBank()
@@ -307,6 +308,11 @@ export class Workbench {
307
308
  this.#clientControlRevision++
308
309
  for (const listener of this.#clientControlListeners) listener()
309
310
  }
311
+ /** A mounted native form owns any input/transaction that cannot safely leave its view. */
312
+ registerNavigationGuard(blocked: () => boolean): () => void {
313
+ this.#navigationGuards.add(blocked); this.refreshAuthoringClientControls()
314
+ return () => { this.#navigationGuards.delete(blocked); this.refreshAuthoringClientControls() }
315
+ }
310
316
  waitForAuthoringClientState(ready: () => boolean, signal: AbortSignal): Promise<void> {
311
317
  return new Promise((resolve, reject) => {
312
318
  const finish = (error?: unknown) => { stop(); stopControls(); signal.removeEventListener('abort', aborted); error ? reject(error) : resolve() }
@@ -437,7 +443,7 @@ export class Workbench {
437
443
  await this.operateDocument({ op: 'retitle', dir, title })
438
444
  }
439
445
 
440
- async openDocument(dir: string, options: { focus?: 'body', expectedIdentity?: string, fallbackReturnPoint?: DocumentReturnPoint } = {}): Promise<void> {
446
+ async openDocument(dir: string, options: { focus?: 'body', expectedIdentity?: string, fallbackReturnPoint?: DocumentReturnPoint, signal?: AbortSignal } = {}): Promise<void> {
441
447
  if (this.#state.document === dir) {
442
448
  if (options.focus) { this.editing.beginOpening(dir, options.focus); this.editing.finishOpening() }
443
449
  return
@@ -452,9 +458,9 @@ export class Workbench {
452
458
  this.#record('document.open')
453
459
  this.#diagnostics.subscribe(dir)
454
460
  // Authoring is ready from source JSON; compilation and preview are independent.
455
- const [opened] = await Promise.all([this.#documentSession.open(dir, options.expectedIdentity), this.#readFocus(dir), this.#history.read(dir)])
461
+ const [opened] = await Promise.all([this.#documentSession.open(dir, options.expectedIdentity, options.signal), this.#readFocus(dir, options.signal), this.#history.read(dir, options.signal)])
456
462
  if (opened === 'identity-changed' && scope === this.#documentScope && this.#state.document === dir) { this.closeDocument(); return }
457
- this.editing.finishOpening()
463
+ if (scope === this.#documentScope && this.#state.document === dir) this.editing.finishOpening()
458
464
  }
459
465
 
460
466
  closeDocument(): void {
@@ -467,10 +473,10 @@ export class Workbench {
467
473
  void this.loadDocuments()
468
474
  }
469
475
 
470
- async #readFocus(dir: string): Promise<void> {
476
+ async #readFocus(dir: string, signal?: AbortSignal): Promise<void> {
471
477
  const version = this.#focusVersion
472
478
  try {
473
- const answer = await this.client.readFocus(dir)
479
+ const answer = await this.client.readFocus(dir, signal)
474
480
  if (this.#state.document === dir && version === this.#focusVersion) this.#set({ focus: answer.focus ?? [] })
475
481
  } catch {
476
482
  }
@@ -769,6 +775,64 @@ export class Workbench {
769
775
  && !state.hasDocumentTimingDrafts && !state.documentTimingDraftStorageFailure)
770
776
  }
771
777
 
778
+ /** Home is distinct from the root document, whose directory is the empty string. */
779
+ authoringWindowSnapshot(revision: number): AuthoringWindowSnapshot {
780
+ const state = this.#state, source = state.authoring
781
+ const recording = this.authoringClientSnapshot(0)?.recording
782
+ const guarded = !isAgentChanging(state) && !source?.composing && !source?.recovering && !state.isCreatingPage && !state.isEditingPage
783
+ && !state.isHistoryBusy && !state.isHistoryPreparing && !state.isPreparingPresentation && !state.hasDocumentTimingDrafts
784
+ && !this.#documentSession.hasPendingAssetWrite() && ![...this.#navigationGuards].some(blocked => blocked())
785
+ && !this.#previewModalOpen() && !(recording && (['requesting', 'recording', 'stopping'].includes(recording.phase) || recording.candidate && !recording.candidate.assetId))
786
+ return { revision, location: state.document === undefined ? { type: 'home' } : { type: 'document', document: state.document,
787
+ ...source?.directory === state.document && source.content ? { documentId: source.content.id } : {},
788
+ status: source?.directory !== state.document || source.loading ? 'loading' : source.content ? 'ready' : 'failed' },
789
+ actions: ['window.read', ...guarded ? ['document.open' as const, 'document.close' as const] : []] }
790
+ }
791
+
792
+ /** Uses the same native navigation and retained document actors; it never implicitly saves or discards. */
793
+ async executeAuthoringWindowAction(request: AuthoringWindowRequest, signal: AbortSignal): Promise<AuthoringWindowRequestResult['outcome']> {
794
+ const action = request.action
795
+ signal.throwIfAborted()
796
+ if (action.type === 'window.read') return 'observed'
797
+ const scope = this.#documentScope, content = this.#state.authoring?.content, identity = this.#state.authoring?.identity,
798
+ drafts = this.authoringDraftRevision(), view = this.#state.webView, playback = this.#state.productionNavigationVersion
799
+ const guard = () => {
800
+ signal.throwIfAborted()
801
+ if (scope !== this.#documentScope || identity !== this.#state.authoring?.identity || content !== this.#state.authoring?.content || drafts !== this.authoringDraftRevision()
802
+ || view !== this.#state.webView || playback !== this.#state.productionNavigationVersion || !this.authoringWindowSnapshot(0).actions.includes(action.type)) throw new Error('window-state-changed')
803
+ }
804
+ guard()
805
+ await waitForPreviewRequest(this.pausePlayback(), signal)
806
+ guard(); this.stopAuditions()
807
+ if (action.type === 'document.close') {
808
+ if (this.#state.document === undefined) return 'unchanged'
809
+ this.closeDocument(); return 'closed'
810
+ }
811
+ const target = request.target
812
+ if (!target || target.document !== action.document) throw new Error('window-target-changed')
813
+ const [answer, info] = await waitForPreviewRequest(Promise.all([this.client.readDocument(target.document, signal), this.client.readWorkbenchInfo()]), signal)
814
+ guard()
815
+ if (answer.document !== target.document || answer.content.id !== target.documentId || !info.root) throw new Error('window-target-changed')
816
+ if (this.#state.document === target.document && this.#state.authoring?.content?.id === target.documentId) return 'unchanged'
817
+ let navigationScope: number | undefined
818
+ const cancel = () => {
819
+ // A later human navigation owns its own scope. Never roll that view back.
820
+ if (navigationScope !== undefined && navigationScope === this.#documentScope && this.#state.document === target.document
821
+ && (this.#state.authoring?.loading || !this.#state.authoring?.content)) this.closeDocument()
822
+ }
823
+ signal.addEventListener('abort', cancel, { once: true })
824
+ try {
825
+ const opening = this.openDocument(target.document, { expectedIdentity: JSON.stringify([info.root, target.documentId]), signal })
826
+ navigationScope = this.#documentScope
827
+ await waitForPreviewRequest(opening, signal)
828
+ signal.throwIfAborted()
829
+ const location = this.authoringWindowSnapshot(0).location
830
+ if (navigationScope !== this.#documentScope || location.type !== 'document' || location.document !== target.document || location.documentId !== target.documentId
831
+ || location.status !== 'ready' || this.#state.authoring?.error) throw new Error('window-target-not-verified')
832
+ return 'opened'
833
+ } finally { signal.removeEventListener('abort', cancel) }
834
+ }
835
+
772
836
  /** Bounded observations, without reading or publishing any unsubmitted editor content. */
773
837
  authoringClientSnapshot(revision: number): AuthoringClientSnapshot | undefined {
774
838
  const state = this.#state, source = state.authoring, content = source?.content
@@ -1557,6 +1621,6 @@ export class Workbench {
1557
1621
  this.production.dispose()
1558
1622
  disposeTranscriptionSessions(this.client)
1559
1623
  disposeDocumentRecordings(this)
1560
- this.#clientControls.clear(); this.#clientControlListeners.clear()
1624
+ this.#clientControls.clear(); this.#navigationGuards.clear(); this.#clientControlListeners.clear()
1561
1625
  }
1562
1626
  }
@@ -71,6 +71,7 @@ export interface WorkspaceClient {
71
71
  capabilities?: Readonly<WorkspaceCapabilities>
72
72
  subscribePreviewEvents?: PreviewEventSubscription
73
73
  openAuthoringClient?: AuthoringClientSubscription
74
+ openAuthoringWindow?: AuthoringWindowSubscription
74
75
  subscribeRequests?(listener: (event: WorkspaceRequestEvent) => void): () => void
75
76
  readDocuments(document?: string): Promise<DocumentsAnswer>
76
77
  planProjectChange(request: ProjectPlanRequest): Promise<ProjectPlan>
@@ -130,16 +131,16 @@ export interface WorkspaceClient {
130
131
  prefetchPreview(document: string, renderer: PreviewRenderer): Promise<PreviewAnswer>
131
132
  /** The MCP address and the workspace root, read once. */
132
133
  readWorkbenchInfo(): Promise<WorkbenchAnswer>
133
- readFocus(document: string): Promise<FocusAnswer>
134
+ readFocus(document: string, signal?: AbortSignal): Promise<FocusAnswer>
134
135
  writeFocus(document: string, focus: FocusReport[]): Promise<FocusAnswer>
135
136
  subscribeReview(document: string, update: (event: ReviewUpdate) => void): () => void
136
137
  acceptReview(document: string, body: { reject?: string[], message?: string }): Promise<{ ended: ReviewEnd }>
137
138
  rejectReview(document: string, paths?: string[]): Promise<ReviewUpdate>
138
139
  restoreReview(document: string, step: string): Promise<{ review: ReviewSnapshot }>
139
- readChanges(document: string): Promise<{ files: UncommittedFile[] }>
140
+ readChanges(document: string, signal?: AbortSignal): Promise<{ files: UncommittedFile[] }>
140
141
  commitChanges(document: string, message: string, paths?: string[]): Promise<unknown>
141
142
  discardChanges(document: string, paths?: string[]): Promise<unknown>
142
- readRevisions(document: string, query?: import('@lincyaw/kernel').DocumentHistoryQuery): Promise<RevisionsAnswer>
143
+ readRevisions(document: string, query?: import('@lincyaw/kernel').DocumentHistoryQuery, signal?: AbortSignal): Promise<RevisionsAnswer>
143
144
  readHistoryFile(document: string, query: import('@lincyaw/kernel').DocumentHistoryRead): Promise<import('@lincyaw/kernel').DocumentHistoryFile>
144
145
  revertRevision(document: string, request: import('@lincyaw/kernel').DocumentHistoryChange): Promise<import('@lincyaw/kernel').DocumentHistoryChanged>
145
146
  /** Takes back the document's latest change; `expect` is the `undo` of the history read, refused when it is not the latest any more. */
@@ -170,9 +171,16 @@ export interface AuthoringClientChannel {
170
171
  close(): void
171
172
  }
172
173
  export type AuthoringClientSubscription = (document: string, open: import('@lincyaw/kernel').AuthoringClientOpen, received: (event: import('@lincyaw/kernel').AuthoringClientEvent) => void, failed: () => void) => AuthoringClientChannel
174
+ export interface AuthoringWindowChannel {
175
+ publish(connectionId: string, report: import('@lincyaw/kernel').AuthoringWindowReport): Promise<void>
176
+ acknowledge(connectionId: string, report: import('@lincyaw/kernel').AuthoringWindowAcknowledgement): Promise<void>
177
+ close(): void
178
+ }
179
+ export type AuthoringWindowSubscription = (open: import('@lincyaw/kernel').AuthoringWindowOpen, received: (event: import('@lincyaw/kernel').AuthoringWindowEvent) => void, failed: () => void) => AuthoringWindowChannel
173
180
  export interface WorkspaceSubscription {
174
181
  (address: string, event: string, received: (data: string, event?: string) => void, failed?: () => void, ready?: () => void): () => void
175
182
  openAuthoringClient?: AuthoringClientSubscription
183
+ openAuthoringWindow?: AuthoringWindowSubscription
176
184
  }
177
185
 
178
186
  /** A remote host may add its CSRF header without replacing the page's global fetch. */
@@ -330,6 +338,7 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
330
338
  const projectIntents = new Map<string, { id: string, plan?: ProjectPlan }>()
331
339
  return client = {
332
340
  ...subscription?.openAuthoringClient ? { openAuthoringClient: subscription.openAuthoringClient } : {},
341
+ ...subscription?.openAuthoringWindow ? { openAuthoringWindow: subscription.openAuthoringWindow } : {},
333
342
  ...subscription ? { subscribePreviewEvents: ((target, received) => {
334
343
  const address = new URL(base, globalThis.document.baseURI)
335
344
  for (const [key, value] of Object.entries(target)) if (key !== 'topic') address.searchParams.set(key, value)
@@ -434,20 +443,20 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
434
443
  })
435
444
  return workbenchInfo
436
445
  },
437
- readFocus: document => call(url('focus', document)),
446
+ readFocus: (document, signal) => call(url('focus', document), { signal }),
438
447
  writeFocus: (document, focus) => post(url('focus'), { document, focus }),
439
448
  subscribeReview: (document, update) => subscribe(url('review', document), 'review', update),
440
449
  acceptReview: (document, body) => post(url('review/accept', document), body),
441
450
  rejectReview: (document, paths) => post(url('review/reject', document), paths ? { paths } : {}),
442
451
  restoreReview: (document, step) => post(url('review/restore', document), { step }),
443
- readChanges: document => call(url('changes', document)),
452
+ readChanges: (document, signal) => call(url('changes', document), { signal }),
444
453
  commitChanges: (document, message, paths) => post(url('changes/commit', document), { message, ...paths ? { paths } : {} }),
445
454
  discardChanges: (document, paths) => post(url('changes/discard', document), paths ? { paths } : {}),
446
455
  readJobs: document => call(url('jobs', document)),
447
456
  startJob: (document, target, source) => post(url('jobs', document), { target, source } satisfies StartJobRequest),
448
457
  cancelJob: (document, id) => post(url('jobs/cancel', document), { id }),
449
458
  subscribeJobs: (document, changed, failed, ready) => subscribe(url('jobs/events', document), 'job', changed, failed, ready),
450
- readRevisions: (document, query = {}) => call(url('revisions', document, { query: JSON.stringify(query) })),
459
+ readRevisions: (document, query = {}, signal) => call(url('revisions', document, { query: JSON.stringify(query) }), { signal }),
451
460
  readHistoryFile: (document, query) => call(url('history/file', document, { query: JSON.stringify(query) })),
452
461
  revertRevision: (document, request) => post(url('revisions/revert', document), request),
453
462
  undo: (document, request) => post(url('history/undo', document), request),