@lincyaw/workbench 0.2.0-rc.52 → 0.2.0-rc.53

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.52",
3
+ "version": "0.2.0-rc.53",
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/kernel": "1.0.0-rc.52",
59
- "@lincyaw/design": "1.0.0-rc.52"
58
+ "@lincyaw/design": "1.0.0-rc.53",
59
+ "@lincyaw/kernel": "1.0.0-rc.53"
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.52"
70
+ "@lincyaw/compiler": "1.0.0-rc.53"
71
71
  }
72
72
  }
@@ -40,16 +40,21 @@ interface DurationFieldProps {
40
40
  onDraft?(draft: StepDurationDraft | undefined): void
41
41
  onChange(value: number | null): void
42
42
  onComposition?(composing: boolean): void
43
+ controlKey?: string
44
+ registerControl?(control: StepDraftControl): () => void
43
45
  }
46
+ export interface StepDraftControl { composing(): boolean, clear(): void }
44
47
 
45
48
  /** Short author intent, never an estimated timestamp or a second playback clock. */
46
- function DurationField({ label, value, source, locale, readOnly, draft, onDraft, onChange, onComposition }: DurationFieldProps) {
47
- const t = MESSAGES[locale], current = useRef({ onComposition, onChange, onDraft, value })
48
- current.current = { onComposition, onChange, onDraft, value }
49
+ function DurationField({ label, value, source, locale, readOnly, draft, onDraft, onChange, onComposition, controlKey, registerControl }: DurationFieldProps) {
50
+ const t = MESSAGES[locale], current = useRef({ onComposition, onChange, onDraft, value, registerControl })
51
+ current.current = { onComposition, onChange, onDraft, value, registerControl }
49
52
  const [text, setText] = useState(draft?.text ?? (value === undefined ? '' : String(value))), [error, setError] = useState(draft?.error ?? false)
50
53
  const focused = useRef(false), composing = useRef(false)
51
54
  useEffect(() => { if (!focused.current) { setText(draft?.text ?? (value === undefined ? '' : String(value))); setError(draft?.error ?? false) } }, [value, source, draft?.text, draft?.error, draft?.review])
52
55
  useEffect(() => () => { if (composing.current) current.current.onComposition?.(false) }, [])
56
+ useEffect(() => current.current.registerControl?.({ composing: () => composing.current,
57
+ clear: () => { setText(current.current.value === undefined ? '' : String(current.current.value)); setError(false) } }), [controlKey])
53
58
  const commit = (input: string): boolean => {
54
59
  const normalized = input.normalize('NFKC').trim()
55
60
  if (!normalized) { setError(false); current.current.onDraft?.(undefined); current.current.onChange(null); return true }
@@ -92,10 +97,12 @@ export interface StepProductionEditorProps {
92
97
  draftStorageFailure?: boolean
93
98
  onDraft?(key: StepDurationKey, draft: StepDurationDraft | undefined): void
94
99
  onComposition?(key: StepDurationKey, composing: boolean): void
100
+ draftControlKey?: string
101
+ registerDraftControl?(key: StepDurationKey, control: StepDraftControl): () => void
95
102
  }
96
103
 
97
104
  /** A reusable view of the canonical step production, including inherited and migrated settings. */
98
- export function StepProductionEditor({ document, stepId, locale, readOnly, advanced = true, onPause, onInteraction, onChange, drafts, onDraft, draftStorageFailure, onComposition }: StepProductionEditorProps) {
105
+ export function StepProductionEditor({ document, stepId, locale, readOnly, advanced = true, onPause, onInteraction, onChange, drafts, onDraft, draftStorageFailure, onComposition, draftControlKey, registerDraftControl }: StepProductionEditorProps) {
99
106
  const t = MESSAGES[locale], [unifying, setUnifying] = useState(false)
100
107
  const start = stepTimingValue(document, stepId, 'narrationStart'), minimum = stepTimingValue(document, stepId, 'minimumHoldMs'), trailing = stepTimingValue(document, stepId, 'trailingPauseMs')
101
108
  const narrations = stepNarrationStarts(document, stepId), hasOverrides = narrations.some(value => value.overridden)
@@ -120,8 +127,10 @@ export function StepProductionEditor({ document, stepId, locale, readOnly, advan
120
127
  </PmField>
121
128
  <div className="pm-ui-step-production__durations">
122
129
  <DurationField label={t.minimum} value={minimum.value} source={minimum.source} locale={locale} readOnly={readOnly} draft={drafts?.minimumHoldMs} onDraft={draft => onDraft?.('minimumHoldMs', draft)}
130
+ controlKey={draftControlKey} registerControl={registerDraftControl && (control => registerDraftControl('minimumHoldMs', control))}
123
131
  onChange={value => apply({ minimumHoldMs: value })} onComposition={composing => onComposition?.('minimumHoldMs', composing)} />
124
132
  <DurationField label={t.trailing} value={trailing.value} source={trailing.source} locale={locale} readOnly={readOnly} draft={drafts?.trailingPauseMs} onDraft={draft => onDraft?.('trailingPauseMs', draft)}
133
+ controlKey={draftControlKey} registerControl={registerDraftControl && (control => registerDraftControl('trailingPauseMs', control))}
125
134
  onChange={value => apply({ trailingPauseMs: value })} onComposition={composing => onComposition?.('trailingPauseMs', composing)} />
126
135
  </div></>}
127
136
  {!advanced && (drafts?.minimumHoldMs || drafts?.trailingPauseMs || draftStorageFailure) ? <span className="pm-ui-field__error" role="alert">{t.advancedDraft}</span>
@@ -3,7 +3,7 @@ import type { CaptionTimingSource, TeachingDocument } from '@lincyaw/kernel'
3
3
  export interface CaptionTimingRow { id: string, from: number, to: number, start: string, end: string }
4
4
  export interface CaptionTimingDraft { version: string, text: string, basis: CaptionTimingSource, rows: CaptionTimingRow[] }
5
5
  type Scope = { identity: string, memberId: string }
6
- interface Entry { values: Map<string, CaptionTimingDraft>, failed: boolean, unreadable: boolean }
6
+ interface Entry { raw?: string | null, values: Map<string, CaptionTimingDraft>, failed: boolean, unreadable: boolean }
7
7
  const MAX_CHARS = 1 << 20
8
8
  const MAX_TARGETS = 512
9
9
  const valid = (value: unknown): value is CaptionTimingDraft => {
@@ -32,6 +32,7 @@ export class CaptionTimingDrafts {
32
32
  const result: Entry = { values: new Map(), failed: false, unreadable: false }; this.#entries.set(key, result)
33
33
  try {
34
34
  const raw = sessionStorage.getItem(key)
35
+ result.raw = raw
35
36
  if (raw === null) return result
36
37
  if (raw.length > MAX_CHARS) throw new Error('caption-draft-limit')
37
38
  const data: unknown = JSON.parse(raw)
@@ -44,6 +45,21 @@ export class CaptionTimingDrafts {
44
45
  return result
45
46
  }
46
47
  get(scope: Scope, stepId: string): CaptionTimingDraft | undefined { return this.#entry(scope).values.get(stepId) }
48
+ entries(scope: Scope): readonly (readonly [string, CaptionTimingDraft])[] { return [...this.#entry(scope).values] }
49
+ partial(scope: Scope): boolean { const entry = this.#entry(scope); try { return entry.unreadable || sessionStorage.getItem(this.#key(scope)) !== entry.raw } catch { return true } }
50
+ discard(scope: Scope, stepId: string): boolean {
51
+ const entry = this.#entry(scope)
52
+ if (entry.unreadable || !entry.values.has(stepId)) return false
53
+ try {
54
+ const next = [...entry.values].filter(([target]) => target !== stepId), key = this.#key(scope)
55
+ if (sessionStorage.getItem(key) !== entry.raw) { entry.failed = true; return false }
56
+ if (next.length) sessionStorage.setItem(key, JSON.stringify(next))
57
+ else sessionStorage.removeItem(key)
58
+ entry.raw = next.length ? JSON.stringify(next) : null
59
+ entry.values.delete(stepId); entry.failed = false
60
+ return true
61
+ } catch { entry.failed = true; return false }
62
+ }
47
63
  steps(scope: Scope, document: TeachingDocument): string[] { return [...this.#entry(scope).values.keys()].filter(id => Object.hasOwn(document.steps, id)) }
48
64
  failed(scope: Scope): boolean { return this.#entry(scope).failed }
49
65
  set(scope: Scope, stepId: string, value: CaptionTimingDraft | undefined): void {
@@ -54,6 +70,7 @@ export class CaptionTimingDrafts {
54
70
  const key = this.#key(scope), raw = JSON.stringify([...entry.values])
55
71
  if (raw.length > MAX_CHARS || entry.values.size > MAX_TARGETS || [...entry.values.values()].some(draft => !valid(draft))) throw new Error('caption-draft-limit')
56
72
  if (entry.values.size) sessionStorage.setItem(key, raw); else sessionStorage.removeItem(key)
73
+ entry.raw = entry.values.size ? raw : null
57
74
  entry.failed = false
58
75
  } catch { entry.failed = true }
59
76
  }
@@ -92,6 +92,9 @@ export function DocumentStepNarration({ blockId, sectionId, stepId, expanded, ad
92
92
  drafts={{ minimumHoldMs: workbench.production.timingDraft(stepId, 'minimumHoldMs', source.identity, source.reset), trailingPauseMs: workbench.production.timingDraft(stepId, 'trailingPauseMs', source.identity, source.reset) }}
93
93
  draftStorageFailure={timingStorageFailure}
94
94
  onDraft={(key, draft) => workbench.production.setTimingDraft(stepId, key, draft, source.identity!, source.reset)}
95
+ draftControlKey={JSON.stringify([source.identity, source.reset, stepId])}
96
+ registerDraftControl={(key, control) => workbench.production.registerDraftView({ identity: source.identity!, kind: 'step-timing',
97
+ has: target => target === JSON.stringify([stepId, key]), blocked: () => control.composing(), clear: () => control.clear() })}
95
98
  onComposition={(key, composing) => workbench.documentComposition(composing, `production:${source.identity}:${source.reset}:${blockId}:${stepId}:${key}`, source.identity)} />
96
99
  </div>}
97
100
  </section>
@@ -16,6 +16,7 @@ import type { StepDurationDraft, StepDurationKey, StepTimingPatch } from './step
16
16
  import { DocumentTimingDrafts } from './document-timing-drafts.ts'
17
17
  import { CaptionTimingDrafts } from './caption-timing-drafts.ts'
18
18
  import type { CaptionTimingDraft } from './caption-timing-drafts.ts'
19
+ import type { ClientProductionDraftMetadata } from '@lincyaw/kernel'
19
20
 
20
21
  interface ProductionOptions {
21
22
  store: WorkbenchStore
@@ -30,6 +31,19 @@ interface ProductionOptions {
30
31
  sourceCurrent(binding: ProductionBinding): boolean
31
32
  }
32
33
  export interface RecordingRangeDraft { version: string, voice: Extract<VoiceSource, { type: 'recording' }>, range?: TimeRange, startText?: string, endText?: string }
34
+ export interface ProductionDraftView {
35
+ identity: string
36
+ kind: ClientProductionDraftMetadata['kind']
37
+ has(key: string): boolean
38
+ blocked(): boolean
39
+ clear(key: string): void
40
+ }
41
+ export interface ProductionDraftSnapshot {
42
+ stamp: string
43
+ coverage: 'tab-state' | 'partial'
44
+ candidates: { key: string, metadata: Omit<ClientProductionDraftMetadata, 'draft'>, value: unknown, discard(): void }[]
45
+ guard(): void
46
+ }
33
47
 
34
48
  /** Source-bound media transactions, timing drafts and narration edits share the document actor. */
35
49
  export class DocumentProduction {
@@ -38,6 +52,11 @@ export class DocumentProduction {
38
52
  readonly #documentTimingDrafts = new DocumentTimingDrafts()
39
53
  readonly #captionTimingDrafts = new CaptionTimingDrafts()
40
54
  readonly #recordingRangeDrafts = new Map<string, Map<string, RecordingRangeDraft>>()
55
+ readonly #draftViews = new Set<ProductionDraftView>()
56
+ readonly #draftSalt = randomUUID()
57
+ #draftRevision = 0
58
+ #unknownDraftViews = 0
59
+ #closed = false
41
60
  readonly #removedCueTimings = new Map<string, { pauseMs: number }>()
42
61
  readonly #removedNarrations = new Map<string, { narration: Narration, override?: { narrationStart: 'with-animation' | 'after-animation' } }>()
43
62
  #cueTimingScope?: string
@@ -54,13 +73,92 @@ export class DocumentProduction {
54
73
  }
55
74
  }
56
75
  reset(): void { this.#removedCueTimings.clear(); this.#removedNarrations.clear(); this.#cueTimingScope = undefined }
57
- dispose(): void { this.reset(); this.#captionTimingDrafts.close(); this.#recordingRangeDrafts.clear() }
76
+ dispose(): void { this.#closed = true; this.reset(); this.#captionTimingDrafts.close(); this.#recordingRangeDrafts.clear(); this.#draftViews.clear() }
77
+ get draftRevision(): number { return this.#draftRevision }
78
+ get productionDraftsBlocked(): boolean {
79
+ const identity = this.#options.store.state.authoring?.identity
80
+ return this.#closed || Boolean(this.#unknownDraftViews) || this.#options.session.hasPendingAssetWrite()
81
+ || [...this.#draftViews].some(view => view.identity === identity && view.blocked())
82
+ }
83
+ #draftChanged(): void {
84
+ if (this.#closed) return
85
+ this.#draftRevision++
86
+ const source = this.#options.store.state.authoring
87
+ if (source) this.#options.store.set({ authoring: { ...source }, ...this.draftState(source) })
88
+ }
89
+ registerDraftView(view: ProductionDraftView): () => void {
90
+ if (this.#closed) return () => {}
91
+ let closed = false
92
+ if (this.#draftViews.size >= 128) {
93
+ this.#unknownDraftViews++; this.#draftChanged()
94
+ return () => { if (closed) return; closed = true; this.#unknownDraftViews--; this.#draftChanged() }
95
+ }
96
+ this.#draftViews.add(view); this.#draftChanged()
97
+ return () => { if (closed) return; closed = true; this.#draftViews.delete(view); this.#draftChanged() }
98
+ }
58
99
  /** Native pending range input survives mode and document changes within this workbench. */
59
- recordingRangeDrafts(identity: string): Map<string, RecordingRangeDraft> {
100
+ recordingRangeDrafts(identity: string): ReadonlyMap<string, RecordingRangeDraft> {
60
101
  let values = this.#recordingRangeDrafts.get(identity)
61
102
  if (!values) { values = new Map(); this.#recordingRangeDrafts.set(identity, values) }
62
103
  return values
63
104
  }
105
+ setRecordingRangeDraft(identity: string, key: string, value: RecordingRangeDraft | undefined): void {
106
+ this.recordingRangeDrafts(identity)
107
+ const values = this.#recordingRangeDrafts.get(identity)!
108
+ if (value) values.set(key, value); else values.delete(key)
109
+ this.#draftChanged()
110
+ }
111
+
112
+ /** Native banks remain the sole content owners. A snapshot exposes metadata until an explicit read. */
113
+ productionDraftSnapshot(): ProductionDraftSnapshot {
114
+ const state = this.#options.store.state, source = state.authoring, identity = source?.identity, memberId = source?.member?.id, content = source?.content
115
+ if (this.#closed || !source || !identity || !memberId || !content || !source.version || !source.fingerprint || source.loading) throw new Error('client-production-drafts-unavailable')
116
+ const revision = this.#draftRevision, version = source.version, reset = source.reset
117
+ const views = [...this.#draftViews].filter(view => view.identity === identity)
118
+ const viewState = () => JSON.stringify(views.map(view => view.blocked()))
119
+ const blocked = viewState()
120
+ const clean = () => {
121
+ const value = this.#options.store.state, current = value.authoring
122
+ return Boolean(this.#options.client.capabilities?.readOnly !== true && current && !current.loading && !current.dirty && !current.saving && !current.composing && !current.restored && !current.recovering && !current.error
123
+ && !isAgentChanging(value) && !value.isCreatingPage && !value.isEditingPage && !value.isHistoryBusy && !value.isHistoryPreparing && !this.productionDraftsBlocked)
124
+ }
125
+ const guard = () => {
126
+ const current = this.#options.store.state.authoring
127
+ if (!current || current.identity !== identity || current.member?.id !== memberId || current.content !== content || current.version !== version || current.reset !== reset
128
+ || current.loading || revision !== this.#draftRevision || viewState() !== blocked) throw new Error('client-production-drafts-changed')
129
+ }
130
+ const candidates: ProductionDraftSnapshot['candidates'] = []
131
+ const add = (kind: ClientProductionDraftMetadata['kind'], key: string, stepId: string, value: unknown, requiresReview: boolean, storage: 'tab' | 'memory', remove: () => boolean, extra: { field?: StepDurationKey, assetId?: string } = {}, readable = true) => {
132
+ const matches = views.filter(view => view.kind === kind && view.has(key))
133
+ const discardable = readable && clean() && !this.#unknownDraftViews && !matches.some(view => view.blocked())
134
+ candidates.push({ key: JSON.stringify([kind, key]), metadata: { kind, stepId, ...extra, targetAvailable: Object.hasOwn(content.steps, stepId), requiresReview, storage, discardable }, value,
135
+ discard: () => {
136
+ guard()
137
+ const activeViews = views.filter(view => view.kind === kind && view.has(key))
138
+ if (!discardable || !clean() || activeViews.some(view => view.blocked())) throw new Error('client-production-draft-needs-human')
139
+ if (!remove()) { this.#draftChanged(); throw new Error('client-production-draft-storage-unavailable') }
140
+ for (const view of activeViews) view.clear(key)
141
+ this.#draftChanged()
142
+ } })
143
+ }
144
+ const timingPartial = this.#documentTimingDrafts.partial(identity), scope = { identity, memberId }
145
+ for (const [key, value] of this.#documentTimingDrafts.entries(identity)) {
146
+ const [stepId, field] = JSON.parse(key) as [string, StepDurationKey]
147
+ add('step-timing', key, stepId, value, !Object.hasOwn(content.steps, stepId) || (this.#documentTimingDrafts.get(identity, content, stepId, field)?.review ?? true), this.#documentTimingDrafts.failed || timingPartial ? 'memory' : 'tab', () => this.#documentTimingDrafts.discard(identity, key), { field }, !timingPartial)
148
+ }
149
+ const captionPartial = this.#captionTimingDrafts.partial(scope)
150
+ for (const [stepId, value] of this.#captionTimingDrafts.entries(scope)) {
151
+ const basis = state.productionPlan?.pages.flatMap(page => page.steps).find(step => step.stepId === stepId)?.captionTiming
152
+ add('caption-timing', stepId, stepId, value, value.version !== version || !basis || JSON.stringify(basis) !== JSON.stringify(value.basis), this.#captionTimingDrafts.failed(scope) || captionPartial ? 'memory' : 'tab', () => this.#captionTimingDrafts.discard(scope, stepId), {}, !captionPartial)
153
+ }
154
+ for (const [key, value] of this.#recordingRangeDrafts.get(identity) ?? []) {
155
+ const [stepId] = JSON.parse(key) as [string]
156
+ add('recording-range', key, stepId, value, value.version !== version, 'memory', () => this.#recordingRangeDrafts.get(identity)!.delete(key), { assetId: value.voice.assetId })
157
+ }
158
+ candidates.sort((a, b) => a.key.localeCompare(b.key))
159
+ guard()
160
+ return { stamp: JSON.stringify([this.#draftSalt, identity, memberId, version, reset, revision]), coverage: timingPartial || captionPartial ? 'partial' : 'tab-state', candidates, guard }
161
+ }
64
162
 
65
163
  source(expected: { identity: string, version: string }): DocumentSessionState {
66
164
  const source = this.#options.store.state.authoring
@@ -280,6 +378,7 @@ export class DocumentProduction {
280
378
  const source = this.#options.store.state.authoring, document = this.#options.document(identity)
281
379
  if (!document?.steps[stepId] || source?.reset !== reset || isAgentChanging(this.#options.store.state)) return
282
380
  if (!this.#documentTimingDrafts.set(identity, document, stepId, key, draft)) return
381
+ this.#draftRevision++
283
382
  this.#options.store.set({ authoring: { ...source }, hasDocumentTimingDrafts: this.#documentTimingDrafts.has(identity, document), documentTimingDraftStorageFailure: this.#documentTimingDrafts.failed })
284
383
  }
285
384
  captionTimingDraft(stepId: string, identity: string): CaptionTimingDraft | undefined {
@@ -291,8 +390,16 @@ export class DocumentProduction {
291
390
  if (!document?.steps[stepId] || source?.identity !== identity || !source.member?.id) return
292
391
  const scope = { identity, memberId: source.member.id }
293
392
  this.#captionTimingDrafts.set(scope, stepId, draft)
393
+ this.#draftRevision++
294
394
  this.#options.store.set({ captionTimingDraftSteps: this.#captionTimingDrafts.steps(scope, document), captionTimingDraftStorageFailure: this.#captionTimingDrafts.failed(scope) })
295
395
  }
396
+ discardCaptionTimingDraft(stepId: string, identity: string): boolean {
397
+ const source = this.#options.store.state.authoring
398
+ if (source?.identity !== identity || !source.member?.id) return false
399
+ const discarded = this.#captionTimingDrafts.discard({ identity, memberId: source.member.id }, stepId)
400
+ this.#draftChanged()
401
+ return discarded
402
+ }
296
403
  copyNarrationCueTiming(from: string, to: string, identity: string): void {
297
404
  const document = this.#options.document(identity)
298
405
  if (!document || isAgentChanging(this.#options.store.state)) return
@@ -8,6 +8,8 @@ const KEYS = ['minimumHoldMs', 'trailingPauseMs'] as const
8
8
  /** Only unaccepted form strings live here. Accepted timing remains in the document actor. */
9
9
  export class DocumentTimingDrafts {
10
10
  readonly #documents = new Map<string, Map<string, StoredDraft>>()
11
+ readonly #stored = new Map<string, string | null>()
12
+ readonly #unreadable = new Set<string>()
11
13
  failed = false
12
14
  #storage(identity: string): string { return `presmium.document-timing.v1:${identity}` }
13
15
  #load(identity: string): Map<string, StoredDraft> {
@@ -18,6 +20,7 @@ export class DocumentTimingDrafts {
18
20
  let raw: string | null = null
19
21
  try {
20
22
  raw = sessionStorage.getItem(this.#storage(identity))
23
+ this.#stored.set(identity, raw)
21
24
  const entries: unknown = JSON.parse(raw ?? '[]')
22
25
  if (!Array.isArray(entries) || entries.length > 512) throw new Error('document-timing-draft-data')
23
26
  for (const entry of entries) {
@@ -27,12 +30,12 @@ export class DocumentTimingDrafts {
27
30
  values.set(entry[0], { text: value.text, error: true, review: true, baseValue: value.baseValue, baseSource: value.baseSource })
28
31
  }
29
32
  } catch {
30
- this.failed = true
33
+ this.failed = true; this.#unreadable.add(identity)
31
34
  if (raw !== null) try { sessionStorage.setItem(`${this.#storage(identity)}:unreadable`, raw) } catch { /* Keep the original slot untouched when storage is unavailable. */ }
32
35
  }
33
36
  if (!this.failed) for (const key of this.#documents.keys()) {
34
37
  if (this.#documents.size <= 8) break
35
- if (key !== identity) this.#documents.delete(key)
38
+ if (key !== identity) { this.#documents.delete(key); this.#stored.delete(key) }
36
39
  }
37
40
  return values
38
41
  }
@@ -45,6 +48,22 @@ export class DocumentTimingDrafts {
45
48
  has(identity: string, document: TeachingDocument): boolean {
46
49
  return [...this.#load(identity).keys()].some(target => Object.hasOwn(document.steps, JSON.parse(target)[0]))
47
50
  }
51
+ partial(identity: string): boolean { this.#load(identity); try { return this.#unreadable.has(identity) || sessionStorage.getItem(this.#storage(identity)) !== this.#stored.get(identity) } catch { return true } }
52
+ entries(identity: string): readonly (readonly [string, StoredDraft])[] { return [...this.#load(identity)] }
53
+ /** Retire only after the original session slot accepted the removal. */
54
+ discard(identity: string, key: string): boolean {
55
+ const values = this.#load(identity)
56
+ if (this.#unreadable.has(identity) || !values.has(key)) return false
57
+ try {
58
+ if (sessionStorage.getItem(this.#storage(identity)) !== this.#stored.get(identity)) { this.failed = true; return false }
59
+ const next = [...values].filter(([target]) => target !== key)
60
+ if (next.length) sessionStorage.setItem(this.#storage(identity), JSON.stringify(next))
61
+ else sessionStorage.removeItem(this.#storage(identity))
62
+ this.#stored.set(identity, next.length ? JSON.stringify(next) : null)
63
+ values.delete(key); this.failed = false
64
+ return true
65
+ } catch { this.failed = true; return false }
66
+ }
48
67
  set(identity: string, document: TeachingDocument, stepId: string, key: StepDurationKey, draft: StepDurationDraft | undefined): boolean {
49
68
  const values = this.#load(identity), target = JSON.stringify([stepId, key]), previous = values.get(target), actual = stepTimingValue(document, stepId, key)
50
69
  if (draft && draft.text.length > 256 || draft && !previous && values.size >= 512) { this.failed = true; return true }
@@ -54,6 +73,7 @@ export class DocumentTimingDrafts {
54
73
  try {
55
74
  if (values.size) sessionStorage.setItem(this.#storage(identity), JSON.stringify([...values]))
56
75
  else sessionStorage.removeItem(this.#storage(identity))
76
+ this.#stored.set(identity, values.size ? JSON.stringify([...values]) : null)
57
77
  this.failed = false
58
78
  } catch { this.failed = true }
59
79
  return true
@@ -43,6 +43,9 @@ export function ProductionCaptionTiming({ identity, stepId, plan, current, loadi
43
43
  const pendingSteps = useWorkbenchState(state => state.captionTimingDraftSteps), storageFailure = useWorkbenchState(state => state.captionTimingDraftStorageFailure)
44
44
  const [open, setOpen] = useState(false), [busy, setBusy] = useState(false), [failure, setFailure] = useState<string>(), [saved, setSaved] = useState(false), [, render] = useState(0)
45
45
  const drafts = useRef(new Map<string, Draft>()), alive = useRef(true), request = useRef<AbortController>(), needsRefresh = useRef(false), openRef = useRef(false), composing = useRef(false)
46
+ useEffect(() => workbench.production.registerDraftView({ identity, kind: 'caption-timing', has: target => drafts.current.has(target),
47
+ blocked: () => composing.current || Boolean(request.current), clear: target => { drafts.current.delete(target); setSaved(false); setFailure(undefined); render(n => n + 1) } }), [workbench, identity])
48
+ useEffect(() => workbench.refreshAuthoringClientControls(), [workbench, open, busy, stepId, disabled])
46
49
  const latest = useRef({ stepId, onChanged }); latest.current = { stepId, onChanged }
47
50
  if (!drafts.current.has(stepId)) { const savedDraft = workbench.production.captionTimingDraft(stepId, identity); if (savedDraft) drafts.current.set(stepId, savedDraft) }
48
51
  const draft = drafts.current.get(stepId), value = draft && valueOf(draft), canonical = document?.production.captionTimings?.[stepId], hasDraft = Boolean(pendingSteps?.includes(stepId))
@@ -61,7 +64,7 @@ export function ProductionCaptionTiming({ identity, stepId, plan, current, loadi
61
64
  // A plan may arrive after opening. Step/close effects fence the original opening;
62
65
  // an existing target draft always wins over this passive initialization.
63
66
  if (open && openRef.current && !saved && current && basis && source?.identity === identity && !drafts.current.has(stepId)) initialize()
64
- }, [open, saved, current, basis, source?.identity, source?.version, identity, stepId])
67
+ }, [open, saved, current, basis, source?.identity, source?.version, identity, stepId, hasDraft])
65
68
  const close = () => {
66
69
  request.current?.abort(); setBusy(false); openRef.current = false; setOpen(false)
67
70
  if (needsRefresh.current) { needsRefresh.current = false; latest.current.onChanged() }
@@ -94,7 +97,7 @@ export function ProductionCaptionTiming({ identity, stepId, plan, current, loadi
94
97
  <PmButton small onClick={close}>{saved ? t.done : t.cancel}</PmButton>
95
98
  <PmButton small variant="primary" loading={busy} disabled={!writable || !current || !value || Boolean(changed) || same(value, canonical)} onClick={() => void apply()}>{t.apply}</PmButton>
96
99
  </>}>
97
- <div className="pmw-caption-times" onCompositionStart={() => { composing.current = true }} onCompositionEnd={() => { composing.current = false }}>
100
+ <div className="pmw-caption-times" onCompositionStart={() => { composing.current = true; workbench.refreshAuthoringClientControls() }} onCompositionEnd={() => { composing.current = false; workbench.refreshAuthoringClientControls() }}>
98
101
  <span>{t.step}</span>
99
102
  {!saved && basis?.available === false && <PmNotice tone="warn">{t.unavailable}</PmNotice>}
100
103
  {!saved && !basis && <PmNotice>{loading ? t.loading : t.prepare}</PmNotice>}
@@ -111,7 +114,7 @@ export function ProductionCaptionTiming({ identity, stepId, plan, current, loadi
111
114
  <div className="pmw-caption-times__actions">
112
115
  <PmButton small disabled={!basis?.available || busy || !writable} onClick={() => { if (document && basis && source?.version) pending({ version: source.version, text: stepCaptionText(document, stepId), basis: structuredClone(basis), rows: lineRows(stepCaptionText(document, stepId)) }) }}>{t.split}</PmButton>
113
116
  <PmButton small disabled={!canonical || busy || !writable} onClick={() => void apply(true)}>{t.automatic}</PmButton>
114
- {hasDraft && <PmButton small disabled={busy} onClick={() => { workbench.production.setCaptionTimingDraft(stepId, undefined, identity); drafts.current.delete(stepId); initialize() }}>{t.discard}</PmButton>}
117
+ {hasDraft && <PmButton small disabled={busy} onClick={() => { if (workbench.production.discardCaptionTimingDraft(stepId, identity)) { drafts.current.delete(stepId); initialize() } }}>{t.discard}</PmButton>}
115
118
  </div>
116
119
  {storageFailure && <PmNotice tone="warn">{t.storageFailed}</PmNotice>}
117
120
  {saved && <PmNotice tone="ok">{t.saved}</PmNotice>}
@@ -47,8 +47,8 @@ export function ProductionRecordingRange({ identity, sectionId, stepId, active,
47
47
  if (!value || !actual?.version || saved?.type !== 'recording' || saved.assetId !== value.request.assetId || !same(saved.sourceRange, value.request.sourceRange)
48
48
  || actual.content?.assets[saved.assetId]?.fingerprint !== `sha256:${value.request.sha256}`) return false
49
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) })
50
+ if (pending === value.draft) workbench.production.setRecordingRangeDraft(identity, value.key, undefined)
51
+ else if (pending?.version === value.draft.version && same(pending.voice, value.draft.voice)) workbench.production.setRecordingRangeDraft(identity, value.key, { ...pending, version: actual.version, voice: structuredClone(saved) })
52
52
  if (current()) { workbench.refreshAuthoringClientControls(); setFailure(undefined); render(value => value + 1) }
53
53
  if (latest.current.key === value.key && latest.current.active && !latest.current.disabled && reported.current !== value.request.id) {
54
54
  reported.current = value.request.id; latest.current.onChanged()
@@ -56,6 +56,8 @@ export function ProductionRecordingRange({ identity, sectionId, stepId, active,
56
56
  return true
57
57
  }
58
58
  useEffect(() => workbench.registerNavigationGuard(() => current() && (composing.current || Boolean(request.current))), [workbench, identity])
59
+ useEffect(() => workbench.production.registerDraftView({ identity, kind: 'recording-range', has: target => current() && target === latest.current.key,
60
+ blocked: () => composing.current || Boolean(request.current), clear: () => { setFailure(undefined); render(value => value + 1) } }), [workbench, identity])
59
61
  useEffect(() => { workbench.refreshAuthoringClientControls() }, [workbench, busy, key, active])
60
62
  useEffect(() => () => { mounted.current = false; request.current?.abort() }, [])
61
63
  useEffect(() => { request.current?.abort(); request.current = undefined; setBusy(false); setFailure(undefined) }, [key, active])
@@ -72,7 +74,7 @@ export function ProductionRecordingRange({ identity, sectionId, stepId, active,
72
74
  useEffect(() => { settle() }, [source?.version, source?.content, source?.loading, source?.dirty, source?.saving, source?.composing, source?.restored, source?.error, active, disabled, key])
73
75
  const edit = (patch: Partial<RangeDraft>) => {
74
76
  if (!draft) return
75
- drafts.set(key, { ...draft, ...range ? { range: { ...range } } : {}, ...patch }); workbench.refreshAuthoringClientControls(); setFailure(undefined); render(value => value + 1)
77
+ workbench.production.setRecordingRangeDraft(identity, key, { ...draft, ...range ? { range: { ...range } } : {}, ...patch }); workbench.refreshAuthoringClientControls(); setFailure(undefined); render(value => value + 1)
76
78
  }
77
79
  const apply = async () => {
78
80
  if (!voice || !draft || !inspected || !valid || !changed || busy || disabled || !active || composing.current || !current()) return
@@ -83,7 +85,7 @@ export function ProductionRecordingRange({ identity, sectionId, stepId, active,
83
85
  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
86
  ? previous : { id: randomUUID(), source: { documentId: source.content.id, version: source.version, fingerprint: source.fingerprint }, stepId, assetId: voice.assetId, sha256: inspected.sha256, sourceRange: proposed }
85
87
  const stored = drafts.get(key) ?? draft
86
- drafts.set(key, stored); sent.current = { key, draft: stored, request: change }; request.current = controller
88
+ workbench.production.setRecordingRangeDraft(identity, key, stored); sent.current = { key, draft: stored, request: change }; request.current = controller
87
89
  setBusy(true); setFailure(undefined)
88
90
  try { await workbench.production.adoptRecording(change, { identity, version: source.version }, controller.signal); if (current()) settle() }
89
91
  catch (error) { if (current() && request.current === controller && !settle() && !controller.signal.aborted) setFailure(failureText(error)) }
@@ -0,0 +1,37 @@
1
+ import type { AuthoringClientAction, AuthoringClientActionResult } from '@lincyaw/kernel'
2
+ import { authoringDraftFragment, draftContentHash } from './authoring-draft-fragment.ts'
3
+ import type { DocumentProduction } from './document-production.ts'
4
+
5
+ /** Explicit reads use the native pending values; discard never submits production changes. */
6
+ export async function executeProductionDraftAction(owner: DocumentProduction, action: Extract<AuthoringClientAction, { type: `production-drafts.${string}` }>, signal: AbortSignal, owned: () => void, fits: (value: AuthoringClientActionResult) => boolean): Promise<AuthoringClientActionResult> {
7
+ const snapshot = owner.productionDraftSnapshot()
8
+ const guard = () => { signal.throwIfAborted(); owned(); snapshot.guard() }
9
+ const values = await Promise.all(snapshot.candidates.map(async candidate => ({ candidate, metadata: { ...candidate.metadata, draft: await draftContentHash(JSON.stringify([snapshot.stamp, candidate.key])) } })))
10
+ guard()
11
+ if (action.type === 'production-drafts.inspect') {
12
+ const token = await draftContentHash(JSON.stringify([snapshot.coverage, values.map(value => value.metadata)]))
13
+ guard()
14
+ if (action.cursor && action.cursor.token !== token) throw new Error('client-production-drafts-changed')
15
+ const start = action.cursor ? values.findIndex(value => value.metadata.draft === action.cursor!.after) + 1 : 0
16
+ if (action.cursor && !start) throw new Error('client-production-drafts-changed')
17
+ const result: Extract<AuthoringClientActionResult, { type: 'production-drafts.inspect' }> = { type: action.type, family: 'production', coverage: snapshot.coverage, token, drafts: [] }
18
+ for (const value of values.slice(start, start + (action.limit ?? 10))) {
19
+ const next = { ...result, drafts: [...result.drafts, value.metadata], ...start + result.drafts.length + 1 < values.length ? { next: { after: value.metadata.draft, token } } : {} }
20
+ if (!fits(next)) break
21
+ result.drafts.push(value.metadata)
22
+ }
23
+ if (start < values.length && !result.drafts.length) throw new Error('client-production-metadata-too-large')
24
+ if (start + result.drafts.length < values.length) result.next = { after: result.drafts.at(-1)!.draft, token }
25
+ if (!fits(result)) throw new Error('client-production-metadata-too-large')
26
+ guard(); return result
27
+ }
28
+ const selected = values.filter(value => value.metadata.draft === action.draft)
29
+ if (selected.length !== 1) throw new Error('client-production-drafts-changed')
30
+ const candidate = selected[0]!.candidate
31
+ if (action.type === 'production-drafts.read') return authoringDraftFragment({ text: JSON.stringify({ kind: candidate.metadata.kind, stepId: candidate.metadata.stepId, ...candidate.metadata.field ? { field: candidate.metadata.field } : {}, value: candidate.value }),
32
+ base: { type: action.type, family: 'production', draft: action.draft, format: 'presmium-production-draft-json-v1' }, offset: action.offset, maxChars: action.maxChars }, guard, fits)
33
+ const result: AuthoringClientActionResult = { type: action.type, family: 'production', draft: action.draft, discarded: true }
34
+ if (!fits(result)) throw new Error('client-production-result-too-large')
35
+ guard(); candidate.discard(); signal.throwIfAborted(); owned()
36
+ return result
37
+ }
package/src/workbench.ts CHANGED
@@ -13,6 +13,7 @@ import type { DocumentAuthoringActionPlan, DocumentComponentAction, AppliedDocum
13
13
  import { inspectCommentDrafts } from './document-editor/comment-draft-inspection.ts'
14
14
  import { mutateCommentDrafts } from './document-editor/comment-draft-actions.ts'
15
15
  import { executeBodyDraftAction } from './body-draft-actions.ts'
16
+ import { executeProductionDraftAction } from './production-draft-actions.ts'
16
17
  import { inspectComponentDrafts } from './component-draft-inspection.ts'
17
18
  import { mutateComponentDrafts } from './component-draft-actions.ts'
18
19
  import { DocumentSession } from './document-session.ts'
@@ -292,7 +293,7 @@ export class Workbench {
292
293
  /** Only counters enter passive client state; no new form payload is exposed to MCP. */
293
294
  authoringDraftRevision(): string {
294
295
  const source = this.#state.authoring
295
- return JSON.stringify([this.#documentSession.bodyDraftRevision(), this.authoringCommentDraftRevision(), source?.identity && source.member?.id ? this.#componentPropertyDrafts.revision(source.identity, source.member.id) : 0, this.#clientControlRevision])
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])
296
297
  }
297
298
  subscribeAuthoringDraftChanges(listener: () => void): () => void {
298
299
  const comments = this.#commentDrafts.subscribe(listener), properties = this.#componentPropertyDrafts.subscribe(listener)
@@ -864,6 +865,7 @@ export class Workbench {
864
865
  ...safe && state.mode === 'editing' && state.editorHistory?.undo ? ['native-history.undo' as const] : [],
865
866
  ...safe && state.mode === 'editing' && state.editorHistory?.redo ? ['native-history.redo' as const] : [],
866
867
  ...unique,
868
+ ...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] : []] : [],
867
869
  ...bodyDrafts.read ? ['body-drafts.inspect' as const, 'body-drafts.read' as const] : [],
868
870
  ...bodyDrafts.mutate && !locked && !state.isCreatingPage && !state.isEditingPage && !state.isHistoryBusy && !state.isHistoryPreparing && !state.hasDocumentTimingDrafts
869
871
  ? ['body-drafts.restore' as const, 'body-drafts.discard' as const, ...bodyDrafts.current ? ['body-drafts.retry' as const] : []] : [],
@@ -905,6 +907,10 @@ export class Workbench {
905
907
  }
906
908
  return executeBodyDraftAction(this.#documentSession, () => this.#state.authoring, action, { signal, guard, source: expected, ...action.type !== 'body-drafts.retry' ? { localDraft: true as const } : {} }, fits)
907
909
  }
910
+ if (action.type === 'production-drafts.inspect' || action.type === 'production-drafts.read' || action.type === 'production-drafts.discard') {
911
+ if (!identity || !this.#state.authoring?.member?.id || !fits) throw new Error('client-production-drafts-unavailable')
912
+ return executeProductionDraftAction(this.production, action, signal, () => { owned(); current() }, fits)
913
+ }
908
914
  if (action.type === 'comment-drafts.inspect' || action.type === 'comment-drafts.read') {
909
915
  const drafts = identity ? this.documentCommentDrafts(identity) : undefined
910
916
  if (!drafts?.readable || !fits) throw new Error('client-comment-drafts-unavailable')