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

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.
@@ -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,11 +865,12 @@ 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] : []] : [],
870
872
  ...commentDrafts?.readable ? ['comment-drafts.inspect' as const, 'comment-drafts.read' as const] : [],
871
- ...clean && !state.isHistoryBusy && !state.isHistoryPreparing && commentDrafts?.readable && commentDrafts.ownersKnown ? ['comment-drafts.discard' as const, ...state.webView === 'document' && commentDrafts.hasRestoreComposer() ? ['comment-drafts.restore' as const] : []] : [],
873
+ ...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] : []] : [],
872
874
  ...source.member?.id && this.#componentPropertyDrafts.readable(source.identity, source.member.id) ? ['component-drafts.inspect' as const, 'component-drafts.read' as const] : [],
873
875
  ...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] : [],
874
876
  ...this.#canPreparePresentation() ? ['preview.prepare' 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')
@@ -918,7 +924,7 @@ export class Workbench {
918
924
  const guard = () => {
919
925
  owned()
920
926
  const state = this.#state, source = state.authoring
921
- if (!source?.content || source.member?.id !== memberId || !source.version || !source.fingerprint
927
+ if (this.client.capabilities?.readOnly === true || !source?.content || source.member?.id !== memberId || !source.version || !source.fingerprint
922
928
  || !sameSource({ documentId: source.content.id, version: source.version, fingerprint: source.fingerprint }, expected)
923
929
  || source.loading || source.dirty || source.saving || source.composing || source.restored || source.recovering || source.error || isAgentChanging(state)
924
930
  || state.isCreatingPage || state.isEditingPage || state.isHistoryBusy || state.isHistoryPreparing || state.hasDocumentTimingDrafts