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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/package.json +5 -4
  2. package/src/MediaClipEditor.tsx +1 -1
  3. package/src/audio-recording.ts +27 -5
  4. package/src/authoring-client.ts +10 -10
  5. package/src/authoring-draft-fragment.ts +3 -1
  6. package/src/body-draft-actions.ts +60 -0
  7. package/src/component-property-drafts.ts +5 -5
  8. package/src/components.tsx +10 -28
  9. package/src/context.tsx +2 -1
  10. package/src/diagnostics.ts +1 -1
  11. package/src/document-draft-store.ts +45 -18
  12. package/src/document-drafts.ts +28 -19
  13. package/src/document-editing.ts +484 -0
  14. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  15. package/src/document-editor/ComponentMaterials.tsx +3 -9
  16. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  17. package/src/document-editor/DocumentBlockPreview.tsx +4 -2
  18. package/src/document-editor/DocumentComments.tsx +58 -9
  19. package/src/document-editor/DocumentEditor.tsx +44 -7
  20. package/src/document-editor/DocumentStepNarration.tsx +30 -25
  21. package/src/document-editor/NarrationEditor.tsx +54 -20
  22. package/src/document-editor/NewCommentDrafts.tsx +4 -3
  23. package/src/document-editor/PlaceComment.tsx +150 -0
  24. package/src/document-editor/comment-drafts.ts +16 -14
  25. package/src/document-editor/comments.ts +30 -10
  26. package/src/document-editor/component-label.ts +11 -0
  27. package/src/document-editor/file-input.ts +2 -2
  28. package/src/document-editor/focus.ts +0 -2
  29. package/src/document-editor/insertion-place.ts +60 -0
  30. package/src/document-editor/messages.ts +3 -3
  31. package/src/document-editor/narration-schema.tsx +12 -6
  32. package/src/document-editor/narration.ts +19 -3
  33. package/src/document-editor/page-body.ts +60 -0
  34. package/src/document-editor/projection.ts +2 -2
  35. package/src/document-editor/rich-text.ts +3 -2
  36. package/src/document-editor/selection.ts +13 -0
  37. package/src/document-editor/style.css +12 -1
  38. package/src/document-editor/table-identities.ts +2 -1
  39. package/src/document-production.ts +331 -0
  40. package/src/document-session.ts +190 -51
  41. package/src/history.ts +3 -3
  42. package/src/index.ts +5 -5
  43. package/src/jobs.ts +1 -1
  44. package/src/messages.ts +19 -4
  45. package/src/panels/DocumentView.tsx +66 -26
  46. package/src/panels/DocumentVoiceDialog.tsx +2 -2
  47. package/src/panels/DocumentVoiceField.tsx +1 -1
  48. package/src/panels/ExportPanel.tsx +1 -6
  49. package/src/panels/HistoryPanel.tsx +1 -1
  50. package/src/panels/PageDeleteDialog.tsx +4 -4
  51. package/src/panels/PageRenameDialog.tsx +1 -1
  52. package/src/panels/PreviewPanel.tsx +1 -4
  53. package/src/panels/ProductionCaptionSize.tsx +20 -0
  54. package/src/panels/ProductionCaptionTiming.tsx +7 -7
  55. package/src/panels/ProductionMediaClips.tsx +6 -5
  56. package/src/panels/ProductionPanel.tsx +8 -4
  57. package/src/panels/ProductionRecording.tsx +86 -9
  58. package/src/panels/ProductionRecordingRange.tsx +4 -4
  59. package/src/panels/ProductionTimeline.tsx +6 -1
  60. package/src/panels/ProductionTranscription.tsx +5 -4
  61. package/src/panels/SourceDocumentPanel.tsx +12 -15
  62. package/src/panels/TranscriptionAdoption.tsx +9 -8
  63. package/src/panels/VoiceCloneDialog.tsx +2 -1
  64. package/src/panels/VoiceoverDialog.tsx +1 -1
  65. package/src/places.ts +1 -36
  66. package/src/preview-playback.ts +1 -1
  67. package/src/production-messages.ts +6 -0
  68. package/src/production-playback.ts +1 -1
  69. package/src/production-voice-playback.ts +3 -2
  70. package/src/sha256.ts +9 -0
  71. package/src/styles.css +16 -41
  72. package/src/use-recording-adoption.ts +2 -2
  73. package/src/voiceover-jobs.ts +1 -1
  74. package/src/workbench-state.ts +157 -0
  75. package/src/workbench.ts +177 -943
  76. package/src/workspace-client.ts +6 -5
  77. package/src/assistant-mascot.ts +0 -62
  78. package/src/mascot-preference.ts +0 -37
  79. package/src/panels/ChangeTrail.tsx +0 -79
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workbench",
3
- "version": "0.2.0-rc.5",
3
+ "version": "0.2.0-rc.50",
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": {
@@ -39,6 +39,7 @@
39
39
  "@floating-ui/react": "0.27.20",
40
40
  "@mantine/core": "8.3.11",
41
41
  "@mantine/hooks": "8.3.11",
42
+ "@noble/hashes": "2.4.0",
42
43
  "@radix-ui/react-dialog": "^1.3.1",
43
44
  "@radix-ui/react-dropdown-menu": "^2.2.1",
44
45
  "@radix-ui/react-popover": "^1.1.15",
@@ -54,8 +55,8 @@
54
55
  "@tiptap/pm": "3.32.0",
55
56
  "katex": "0.18.10",
56
57
  "react-resizable-panels": "4.14.5",
57
- "@lincyaw/design": "1.0.0-rc.6",
58
- "@lincyaw/kernel": "1.0.0-rc.6"
58
+ "@lincyaw/design": "1.0.0-rc.50",
59
+ "@lincyaw/kernel": "1.0.0-rc.50"
59
60
  },
60
61
  "peerDependencies": {
61
62
  "react": "^18.3.1",
@@ -66,6 +67,6 @@
66
67
  "@types/react-dom": "18.3.7",
67
68
  "react": "^18.3.1",
68
69
  "react-dom": "^18.3.1",
69
- "@lincyaw/compiler": "1.0.0-rc.6"
70
+ "@lincyaw/compiler": "1.0.0-rc.50"
70
71
  }
71
72
  }
@@ -101,7 +101,7 @@ export function MediaClipEditor(props: MediaClipEditorProps) {
101
101
  {rangeError && <span id={rangeErrorId} className="pm-ui-field__error" role="alert">{rangeError}</span>}
102
102
  <PmInput label={t.offset} density={density} width="number" inputMode="decimal" maxLength={32} value={draft.offsetText ?? (clip.attachment.offsetMs / 1000).toFixed(3)}
103
103
  readOnly={disabled || !inspected} error={offsetMs === undefined ? t.invalidOffset : undefined} onChange={event => change({ offsetText: event.target.value })} {...composition('offset')} />
104
- <PmField label={t.volume} density={density} group><div className="pm-ui-media-clip-editor__volume">
104
+ <PmField label={t.volume} density={density} group><div className="pm-ui-range-row">
105
105
  <PmRange label={t.volume} density={density} value={clip.volume * 100} max={100} disabled={disabled || !inspected} valueText={value => `${Math.round(value)}%`} onPreviewChange={setVolumePreview}
106
106
  onValueCommit={value => change({ clip: { ...clip, volume: value / 100 } })} />
107
107
  <output>{Math.round(volumePreview ?? clip.volume * 100)}%</output><PmButton density={density} aria-pressed={Boolean(clip.muted)} disabled={disabled || !inspected} onClick={() => change({ clip: { ...clip, muted: !clip.muted } })}>{clip.muted ? t.unmute : t.mute}</PmButton>
@@ -10,6 +10,21 @@ const MAX_BYTES = 16 << 20
10
10
  const MAX_DURATION_MS = 10 * 60_000
11
11
  const MIME_TYPES = ['audio/webm;codecs=opus', 'audio/ogg;codecs=opus', 'audio/mp4']
12
12
 
13
+ /** getUserMedia has no AbortSignal; late permission grants must release their stream. */
14
+ function recordingWait<T>(work: Promise<T>, signal: AbortSignal | undefined, releaseLate: (value: T) => void): Promise<T> {
15
+ if (!signal) return work
16
+ return new Promise((resolve, reject) => {
17
+ const abort = () => { signal.removeEventListener('abort', abort); reject(signal.reason ?? new Error('recording-cancelled')) }
18
+ signal.addEventListener('abort', abort, { once: true })
19
+ work.then(value => {
20
+ signal.removeEventListener('abort', abort)
21
+ if (signal.aborted) { releaseLate(value); return }
22
+ resolve(value)
23
+ }, error => { signal.removeEventListener('abort', abort); reject(error) })
24
+ if (signal.aborted) abort()
25
+ })
26
+ }
27
+
13
28
  export function recordingUnavailable(): string | undefined {
14
29
  if (!globalThis.isSecureContext || !navigator.mediaDevices?.getUserMedia) return 'recording-context'
15
30
  if (typeof MediaRecorder === 'undefined' || !MIME_TYPES.some(type => MediaRecorder.isTypeSupported(type))) return 'recording-unsupported'
@@ -36,6 +51,7 @@ export class AudioRecording {
36
51
  #generation = 0
37
52
  #disposed = false
38
53
  #take?: Take
54
+ #request?: AbortController
39
55
  #release?: () => void
40
56
  #warning = false
41
57
  readonly #beforeUnload = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = '' }
@@ -57,19 +73,24 @@ export class AudioRecording {
57
73
  this.#set({ phase: error ? 'failed' : this.#state.candidate ? 'ready' : 'idle', candidate: this.#state.candidate, elapsedMs: this.#state.candidate?.elapsedMs ?? 0, ...error ? { error } : {} })
58
74
  }
59
75
 
60
- async start(prepare: () => Promise<() => void>): Promise<void> {
76
+ async start(prepare: (signal: AbortSignal) => Promise<() => void>, signal?: AbortSignal): Promise<void> {
77
+ if (signal?.aborted) return
61
78
  if (this.#disposed || this.#take || this.#state.phase === 'requesting') return
62
79
  const unavailable = recordingUnavailable()
63
80
  if (unavailable) { this.#settle(unavailable); return }
64
81
  const generation = ++this.#generation
82
+ const request = this.#request = new AbortController()
83
+ const pendingSignal = signal ? AbortSignal.any([signal, request.signal]) : request.signal
84
+ const abort = () => { if (generation === this.#generation) this.cancelTake() }
85
+ signal?.addEventListener('abort', abort, { once: true })
65
86
  this.#set({ ...this.#state, phase: 'requesting', error: undefined })
66
87
  let stream: MediaStream | undefined
67
88
  let release: (() => void) | undefined
68
89
  try {
69
- release = await prepare()
90
+ release = await recordingWait(prepare(pendingSignal), pendingSignal, release => release())
70
91
  if (generation !== this.#generation) { release(); return }
71
92
  this.#release = release
72
- stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: { ideal: 1 } }, video: false })
93
+ stream = await recordingWait(navigator.mediaDevices.getUserMedia({ audio: { channelCount: { ideal: 1 } }, video: false }), pendingSignal, stream => stream.getTracks().forEach(track => track.stop()))
73
94
  if (generation !== this.#generation) { stream.getTracks().forEach(track => track.stop()); return }
74
95
  const mimeType = MIME_TYPES.find(type => MediaRecorder.isTypeSupported(type))!
75
96
  const recorder = new MediaRecorder(stream, { mimeType, audioBitsPerSecond: 128_000 })
@@ -102,13 +123,13 @@ export class AudioRecording {
102
123
  this.#take = undefined
103
124
  const name = error instanceof DOMException ? error.name : ''
104
125
  this.#settle(name === 'NotAllowedError' || name === 'SecurityError' ? 'recording-permission' : name === 'NotFoundError' ? 'recording-device' : name === 'NotReadableError' ? 'recording-device-busy' : name === 'NotSupportedError' ? 'recording-device-unsupported' : 'recording-failed')
105
- }
126
+ } finally { signal?.removeEventListener('abort', abort); if (this.#request === request) this.#request = undefined }
106
127
  }
107
128
 
108
129
  stop(error?: string): void {
109
130
  const take = this.#take
110
131
  if (!take) {
111
- if (this.#state.phase === 'requesting') { this.#generation++; this.#release?.(); this.#release = undefined; this.#settle(error) }
132
+ if (this.#state.phase === 'requesting') { this.#generation++; this.#request?.abort(new Error('recording-cancelled')); this.#request = undefined; this.#release?.(); this.#release = undefined; this.#settle(error) }
112
133
  return
113
134
  }
114
135
  if (error) take.error ??= error
@@ -159,6 +180,7 @@ export class AudioRecording {
159
180
  if (this.#disposed) return
160
181
  this.#disposed = true
161
182
  this.#generation++
183
+ this.#request?.abort(new Error('recording-cancelled')); this.#request = undefined
162
184
  const take = this.#take
163
185
  if (take) { take.discard = true; this.stop(); this.#finish(take) }
164
186
  this.#release?.(); this.#release = undefined
@@ -1,11 +1,11 @@
1
- import { authoringClientResultFits } from '@lincyaw/kernel'
1
+ import { authoringClientActionMutatesDraft, authoringClientResultFits, randomUUID } from '@lincyaw/kernel'
2
2
  import type { AuthoringClientActionResult, AuthoringClientEvent, AuthoringClientSnapshot, CanonicalSource } from '@lincyaw/kernel'
3
3
  import type { Workbench } from './workbench.ts'
4
4
  import type { AuthoringClientChannel } from './workspace-client.ts'
5
5
 
6
6
  const sameSource = (a: CanonicalSource, b: CanonicalSource) => a.documentId === b.documentId && a.version === b.version && a.fingerprint === b.fingerprint
7
7
  // Clock samples are observations, not user input revisions. Never push at animation-frame frequency.
8
- const signature = (value: AuthoringClientSnapshot) => JSON.stringify({ ...value, revision: 0, playback: value.playback && { ...value.playback,
8
+ const signature = (value: AuthoringClientSnapshot) => JSON.stringify({ ...value, revision: 0, recording: value.recording && { ...value.recording, elapsedMs: 0 }, playback: value.playback && { ...value.playback,
9
9
  position: value.playback.position && { ...value.playback.position, timeMs: 0, stepTimeMs: 0 } } })
10
10
  type Attachment = { directory: string, identity: string, epoch: string, channel: AuthoringClientChannel, connectionId?: string }
11
11
 
@@ -13,7 +13,7 @@ type Attachment = { directory: string, identity: string, epoch: string, channel:
13
13
  export function connectAuthoringClient(workbench: Workbench): () => void {
14
14
  const open = workbench.client.openAuthoringClient
15
15
  if (!open) return () => {}
16
- const clientId = crypto.randomUUID()
16
+ const clientId = randomUUID()
17
17
  let closed = false, revision = 0, sequence = 0
18
18
  let attached: Attachment | undefined
19
19
  let lastSignature: string | undefined, lastContent: object | undefined
@@ -71,7 +71,7 @@ export function connectAuthoringClient(workbench: Workbench): () => void {
71
71
  if (value) publishState(owner, event.connectionId, value)
72
72
  return
73
73
  }
74
- if (event.type === 'cancel') { if (event.connectionId === owner.connectionId && event.requestId === active?.requestId) active.controller.abort(); return }
74
+ if (event.type === 'cancel') { if (event.connectionId === owner.connectionId && event.requestId === active?.requestId) active.controller.abort(new Error('client-request-cancelled')); return }
75
75
  const request = event.request, connectionId = owner.connectionId
76
76
  if (!connectionId || request.clientId !== clientId || request.epoch !== owner.epoch || request.expectedClientState.connectionId !== connectionId || seen.has(request.requestId)) return
77
77
  seen.add(request.requestId)
@@ -83,7 +83,7 @@ export function connectAuthoringClient(workbench: Workbench): () => void {
83
83
  controller.signal.throwIfAborted()
84
84
  if (closed || attached !== owner || owner.connectionId !== connectionId || active !== task || Date.now() >= Date.parse(event.expiresAt)) throw new Error('client-request-expired')
85
85
  }
86
- if (active || value.revision !== request.expectedClientState.revision || !sameSource(value.source, request.source) || !value.actions.includes(request.action.type) || Date.now() >= Date.parse(event.expiresAt)) {
86
+ if (active || value.revision !== request.expectedClientState.revision || (request.action.type === 'body-drafts.retry' ? value.source.documentId !== request.source.documentId : !sameSource(value.source, request.source)) || !value.actions.includes(request.action.type) || Date.now() >= Date.parse(event.expiresAt)) {
87
87
  await send(owner, connectionId, value, { requestId: request.requestId, state: 'refused', error: { code: 'client-state-changed' } }).catch(() => {})
88
88
  return
89
89
  }
@@ -95,7 +95,7 @@ export function connectAuthoringClient(workbench: Workbench): () => void {
95
95
  await send(owner, connectionId, value, { requestId: request.requestId, state: 'executing' })
96
96
  owned()
97
97
  const latest = snapshot()
98
- if (!latest || latest.revision !== request.expectedClientState.revision || !sameSource(latest.source, request.source)) throw new Error('client-state-changed')
98
+ if (!latest || latest.revision !== request.expectedClientState.revision || (request.action.type === 'body-drafts.retry' ? latest.source.documentId !== request.source.documentId : !sameSource(latest.source, request.source))) throw new Error('client-state-changed')
99
99
  const fits = (result: AuthoringClientActionResult) => authoringClientResultFits({ request, connection: { clientId, epoch: owner.epoch, connectionId }, document: owner.directory, snapshot: snapshot() ?? value }, result)
100
100
  const actionResult = await workbench.executeAuthoringClientAction(request.action, request.source, controller.signal, expiresAt, fits)
101
101
  owned()
@@ -104,13 +104,13 @@ export function connectAuthoringClient(workbench: Workbench): () => void {
104
104
  await send(owner, connectionId, result, { requestId: request.requestId, state: 'done', ...actionResult ? { result: actionResult } : {} }, actionResult ? () => {
105
105
  owned()
106
106
  const latest = snapshot()
107
- if (!latest || latest.revision !== result.revision || !['component-drafts.restore', 'component-drafts.discard', 'comment-drafts.restore', 'comment-drafts.discard'].includes(actionResult.type) && latest.revision !== request.expectedClientState.revision) throw new Error(actionResult.family === 'component' ? 'client-component-drafts-changed' : 'client-comment-drafts-changed')
108
- if (!fits(actionResult)) throw new Error(actionResult.family === 'component' ? 'client-component-result-too-large' : 'client-comment-result-too-large')
107
+ if (!latest || latest.revision !== result.revision || !authoringClientActionMutatesDraft(actionResult.type) && latest.revision !== request.expectedClientState.revision) throw new Error(`client-${actionResult.family}-drafts-changed`)
108
+ if (!fits(actionResult)) throw new Error(`client-${actionResult.family}-result-too-large`)
109
109
  } : undefined)
110
110
  } catch (error) {
111
111
  const result = snapshot()
112
112
  const code = error instanceof Error && /^(client|production)-[a-z-]{1,100}$/.test(error.message) ? error.message : 'client-action-not-verified'
113
- if (!controller.signal.aborted && attached === owner && owner.connectionId === connectionId && result) await send(owner, connectionId, result, { requestId: request.requestId, state: 'failed', error: { code } }).catch(() => {})
113
+ if (attached === owner && owner.connectionId === connectionId && result) await send(owner, connectionId, result, { requestId: request.requestId, state: 'failed', error: { code } }).catch(() => {})
114
114
  } finally { clearTimeout(timeout); if (active === task) active = undefined }
115
115
  }
116
116
  const changed = () => {
@@ -120,7 +120,7 @@ export function connectAuthoringClient(workbench: Workbench): () => void {
120
120
  if (!value) { detach(); return }
121
121
  if (attached && (attached.directory !== state.document || attached.identity !== source.identity)) detach()
122
122
  if (!attached) {
123
- const epoch = crypto.randomUUID()
123
+ const epoch = randomUUID()
124
124
  // Callbacks run after the channel has been installed; the socket implementation is asynchronous.
125
125
  const owner = { directory: state.document, identity: source.identity, epoch } as Attachment
126
126
  owner.channel = open(state.document, { clientId, epoch, snapshot: value }, event => { void received(owner, event) }, () => {
@@ -1,9 +1,11 @@
1
1
  import type { AuthoringClientActionResult } from '@lincyaw/kernel'
2
+ import { sha256 as draftContentHash } from './sha256.ts'
3
+
4
+ export { draftContentHash }
2
5
 
3
6
  type Fragment = Extract<AuthoringClientActionResult, { jsonText: string }>
4
7
  type Fields = 'offset' | 'endOffset' | 'totalUtf16' | 'totalUtf8' | 'sha256' | 'jsonText'
5
8
  type FragmentBase = Fragment extends infer Value ? Value extends Fragment ? Omit<Value, Fields> : never : never
6
- export const draftContentHash = async (text: string): Promise<string> => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))].map(value => value.toString(16).padStart(2, '0')).join('')
7
9
  const boundary = (text: string, offset: number) => !(offset > 0 && offset < text.length && /[\uD800-\uDBFF]/.test(text[offset - 1]!) && /[\uDC00-\uDFFF]/.test(text[offset]!))
8
10
 
9
11
  /** Budget the complete client receipt and WS frame, preserving exact JSON text and Unicode progress. */
@@ -0,0 +1,60 @@
1
+ import type { AuthoringClientAction, AuthoringClientActionResult, ClientBodyDraftMetadata } from '@lincyaw/kernel'
2
+ import { authoringDraftFragment, draftContentHash } from './authoring-draft-fragment.ts'
3
+ import type { BodyDraftCandidate, DocumentDraftOperation, DocumentSession, DocumentSessionState } from './document-session.ts'
4
+
5
+ type BodyAction = Extract<AuthoringClientAction, { type: `body-drafts.${string}` }>
6
+ /** Explicit draft inspection never sends owner IDs, base hashes or body text in metadata. */
7
+ const metadata = (value: BodyDraftCandidate, version: string): ClientBodyDraftMetadata => ({
8
+ draft: value.draft.token, current: value.draft.current, storage: value.storage, updatedAt: value.updatedAt, baseVersion: value.baseVersion, baseObserved: value.baseVersion === version,
9
+ composing: value.composing, pendingSubmission: value.pendingSubmission,
10
+ })
11
+ export async function executeBodyDraftAction(session: DocumentSession, state: () => DocumentSessionState | undefined, action: BodyAction, operation: DocumentDraftOperation, fits: (result: AuthoringClientActionResult) => boolean): Promise<AuthoringClientActionResult> {
12
+ const read = await session.readBodyDrafts(operation.signal, 'draft' in action ? action.draft : undefined)
13
+ const guard = () => { operation.guard(); read.guard() }
14
+ guard()
15
+ if (action.type === 'body-drafts.inspect') {
16
+ const values = read.candidates.map(value => metadata(value, operation.source.version)), token = await draftContentHash(JSON.stringify({ values, coverage: read.coverage }))
17
+ guard()
18
+ if (action.cursor && action.cursor.token !== token) throw new Error('client-body-drafts-changed')
19
+ const start = action.cursor ? values.findIndex(value => value.draft === action.cursor!.after) + 1 : 0
20
+ if (action.cursor && start === 0) throw new Error('client-body-drafts-changed')
21
+ const result: Extract<AuthoringClientActionResult, { type: 'body-drafts.inspect' }> = { type: action.type, family: 'body', coverage: read.coverage, token, drafts: [] }
22
+ for (const value of values.slice(start, start + (action.limit ?? 10))) {
23
+ const next = { ...result, drafts: [...result.drafts, value], ...start + result.drafts.length + 1 < values.length ? { next: { after: value.draft, token } } : {} }
24
+ if (!fits(next)) break
25
+ result.drafts.push(value)
26
+ }
27
+ if (start < values.length && !result.drafts.length) throw new Error('client-body-metadata-too-large')
28
+ if (start + result.drafts.length < values.length) result.next = { after: result.drafts.at(-1)!.draft, token }
29
+ if (!fits(result)) throw new Error('client-body-metadata-too-large')
30
+ guard(); return result
31
+ }
32
+ const value = read.candidates[0]!
33
+ if (action.type === 'body-drafts.read') return authoringDraftFragment({ text: JSON.stringify(value.content), base: { type: action.type, family: 'body', draft: value.draft.token, storage: value.storage, format: 'presmium-document-json-v1' }, offset: action.offset, maxChars: action.maxChars }, guard, fits)
34
+ if (!session.bodyDraftCapabilities().mutate || value.composing || value.pendingSubmission || action.type === 'body-drafts.restore' && value.draft.current || action.type === 'body-drafts.retry' && !value.draft.current) throw new Error('client-body-draft-needs-human')
35
+ const result = (outcome: Extract<AuthoringClientActionResult, { family: 'body', outcome: string }>['outcome']): Extract<AuthoringClientActionResult, { family: 'body', outcome: string }> => {
36
+ const now = state()
37
+ return { type: action.type, family: 'body', draft: value.draft.token, outcome, dirty: Boolean(now?.dirty), conflicted: Boolean(now?.error), ...now?.backupPending ? { backupPending: true as const } : {}, ...now?.storageFailure ? { backupRetained: true as const } : {} }
38
+ }
39
+ if (!fits({ ...result(action.type === 'body-drafts.restore' ? 'restored' : action.type === 'body-drafts.retry' ? 'saved' : value.draft.current ? 'source-restored' : 'backup-discarded'), backupPending: true, backupRetained: true })) throw new Error('client-body-result-too-large')
40
+ guard()
41
+ let outcome: 'restored' | 'already-saved' | 'source-restored' | 'backup-discarded' | 'saved'
42
+ if (action.type === 'body-drafts.restore') {
43
+ const restored = await session.recoverDraft(value.draft, operation)
44
+ if (!restored) throw new Error('client-body-drafts-changed')
45
+ outcome = restored
46
+ } else if (action.type === 'body-drafts.discard') {
47
+ const done = value.draft.current ? await session.discard(operation) : await session.forgetDraft(value.draft, operation)
48
+ if (!done) throw new Error('client-body-drafts-changed')
49
+ outcome = value.draft.current ? 'source-restored' : 'backup-discarded'
50
+ } else {
51
+ await session.retry(operation)
52
+ if (state()?.error || state()?.saving || state()?.restored) throw new Error('client-body-save-unverified')
53
+ outcome = 'saved'
54
+ }
55
+ operation.signal.throwIfAborted()
56
+ // A successful retry may finish at a new canonical version. The transport checks that saved source.
57
+ const answer = result(outcome)
58
+ if (!fits(answer)) throw new Error('client-body-result-too-large')
59
+ return answer
60
+ }
@@ -1,6 +1,7 @@
1
- import { isRecord } from '@lincyaw/kernel'
1
+ import { isRecord, randomUUID } from '@lincyaw/kernel'
2
2
  import type { CanonicalSource, ClientComponentDraftReference, JsonObject } from '@lincyaw/kernel'
3
3
  import { DocumentDraftStore } from './document-draft-store.ts'
4
+ import { sha256 as tokenOf } from './sha256.ts'
4
5
  import type { DraftStoreCommit } from './document-draft-store.ts'
5
6
 
6
7
  export interface ComponentPropertyTarget { identity: string, memberId: string, blockId: string, stepId?: string }
@@ -32,7 +33,6 @@ const scopedPrefix = (kind: string, identity: string, memberId: string) => `${ki
32
33
  const markerOf = (target: ComponentPropertyTarget, reference: { id: string, revision: number, token: string }) => `${markerPrefix(target)}${JSON.stringify([reference.id, reference.revision, reference.token])}`
33
34
  const marker = (backup: ComponentPropertyBackup) => markerOf(backup.record.target, { id: backup.record.id, revision: backup.record.revision, token: backup.token })
34
35
  const keyOf = (record: ComponentPropertyDraft) => `${prefix(record.target)}${record.id}`
35
- const tokenOf = async (raw: string) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw)))].map(byte => byte.toString(16).padStart(2, '0')).join('')
36
36
 
37
37
  function valid(value: unknown, target: ComponentPropertyTarget): value is ComponentPropertyDraft {
38
38
  return isRecord(value) && value.format === 1 && typeof value.id === 'string' && value.id.length > 0
@@ -50,7 +50,7 @@ export class ComponentPropertyDrafts {
50
50
  readonly #revisions = new Map<string, number>()
51
51
  readonly #settling = new Map<string, number>()
52
52
  #agentReader?: { identity: string, memberId: string, store: DocumentDraftStore }
53
- readonly #writerOwner = crypto.randomUUID()
53
+ readonly #writerOwner = randomUUID()
54
54
  #revision = 0
55
55
  #closed = false
56
56
  readonly #leave = (event: BeforeUnloadEvent) => {
@@ -149,7 +149,7 @@ export class ComponentPropertyDrafts {
149
149
  if (this.#closed) throw new Error('component-draft-closed')
150
150
  const key = targetKey(target), previous = this.#entries.get(key)
151
151
  if (!previous && this.#entries.size >= 512) throw new Error('component-draft-limit')
152
- const record: ComponentPropertyDraft = { format: 1, id: previous?.record.id ?? crypto.randomUUID(), revision: (previous?.record.revision ?? 0) + 1,
152
+ const record: ComponentPropertyDraft = { format: 1, id: previous?.record.id ?? randomUUID(), revision: (previous?.record.revision ?? 0) + 1,
153
153
  target: structuredClone(target), source: structuredClone(value.source), definitionId: value.definitionId, baseline: structuredClone(value.baseline), value: structuredClone(value.value),
154
154
  reset: Boolean(value.reset), composing: Boolean(value.composing), updatedAt: new Date().toISOString() }
155
155
  const entry: Entry = previous ?? { record, store: new DocumentDraftStore(scope(target), undefined, { owner: this.#writerOwner, family: 'component' }), failed: false, origins: [] }
@@ -213,7 +213,7 @@ export class ComponentPropertyDrafts {
213
213
  try { value = JSON.parse(raw) } catch { return false }
214
214
  if (!valid(value, target) || backup.key !== keyOf(value)) return false
215
215
  guard?.()
216
- const record: ComponentPropertyDraft = { ...structuredClone(value), id: crypto.randomUUID(), revision: 1, composing: false, updatedAt: new Date().toISOString() }
216
+ const record: ComponentPropertyDraft = { ...structuredClone(value), id: randomUUID(), revision: 1, composing: false, updatedAt: new Date().toISOString() }
217
217
  const fork = JSON.stringify(record)
218
218
  if (fork.length > MAX_CHARS) return false
219
219
  const operation = store.put(keyOf(record), fork)
@@ -1,6 +1,4 @@
1
1
  import type { IconName } from '@lincyaw/design'
2
- import { mountMascot } from '@lincyaw/design/mascot'
3
- import type { MascotAction } from '@lincyaw/design/mascot'
4
2
  import * as Dialog from '@radix-ui/react-dialog'
5
3
  import * as DropdownMenu from '@radix-ui/react-dropdown-menu'
6
4
  import * as Popover from '@radix-ui/react-popover'
@@ -11,7 +9,6 @@ import { forwardRef, useEffect, useId, useMemo, useRef, useState } from 'react'
11
9
  import type { ComponentProps, CSSProperties, InputHTMLAttributes, ReactNode, Ref, SelectHTMLAttributes, TextareaHTMLAttributes } from 'react'
12
10
  import { Group as ResizableGroup, Panel as ResizablePanel, Separator as ResizableSeparator } from 'react-resizable-panels'
13
11
  import { PmButton, PmIcon, PmIconButton, PmTooltip } from './base-controls.tsx'
14
- import { useMascotEnabled } from './mascot-preference.ts'
15
12
  import type { ControlDensity } from './base-controls.tsx'
16
13
  export { PmButton, PmIcon, PmIconButton, PmTooltip } from './base-controls.tsx'
17
14
  export type { ButtonVariant, ControlDensity } from './base-controls.tsx'
@@ -413,26 +410,6 @@ export function PmNotice({ tone = 'neutral', children }: { tone?: 'neutral' | 'a
413
410
  return <div className={cls('pm-ui-notice', tone !== 'neutral' && `pm-ui-notice--${tone}`)} role={tone === 'danger' ? 'alert' : 'status'}>{children}</div>
414
411
  }
415
412
 
416
- /** The Presmium kitten acting out what the assistant or a long task is doing. It is decoration: the text beside it
417
- * says the same thing for everyone, so it is hidden from assistive technology. Nothing shows when the author turned
418
- * the kitten off in Settings. */
419
- export function PmMascot(props: { action: MascotAction, size?: 'small' | 'regular' }) {
420
- return useMascotEnabled() ? <MascotPlayer {...props} /> : null
421
- }
422
-
423
- function MascotPlayer({ action, size = 'regular' }: { action: MascotAction, size?: 'small' | 'regular' }) {
424
- const ref = useRef<HTMLSpanElement>(null)
425
- const player = useRef<ReturnType<typeof mountMascot>>(undefined)
426
- const first = useRef(action)
427
- useEffect(() => {
428
- const mounted = mountMascot(ref.current!, first.current)
429
- player.current = mounted
430
- return () => mounted.stop()
431
- }, [])
432
- useEffect(() => { player.current?.set(action) }, [action])
433
- return <span ref={ref} className={cls('pm-ui-mascot', size === 'small' && 'pm-ui-mascot--sm')} data-pm-mascot={action} aria-hidden="true" />
434
- }
435
-
436
413
  export interface RangeProps {
437
414
  label: string
438
415
  value: number
@@ -526,6 +503,10 @@ export interface TimelineProps {
526
503
  showSteps?: boolean
527
504
  /** A flush docked editor, with status and zoom in the same tool row. */
528
505
  variant?: 'default' | 'editor'
506
+ /** The page has no place on this timeline (the lecture leaves it out): its status and notice say so, with no tracks to seek. */
507
+ excluded?: { status: string, notice: string }
508
+ /** A note about the selected step, under the tracks. */
509
+ notice?: string
529
510
  }
530
511
 
531
512
  const timelineTime = (ms: number) => `${String(Math.floor(ms / 60000)).padStart(2, '0')}:${(ms % 60000 / 1000).toFixed(3).padStart(6, '0')}`
@@ -540,11 +521,11 @@ function waveformPath(samples: readonly number[] | undefined): string | undefine
540
521
  }
541
522
 
542
523
  /** Data-only timeline; source, playback, seeking authority and all labels remain with its caller. */
543
- export function PmTimeline({ label, tracks, labels, durationMs, durationStatus, currentTimeMs, selectedStepId, zoom, onZoomChange, onSelectStep, onSelectSegment, segmentPicker, onSeek, seekDisabled, disabled, loading, seeking, density = 'compact', showSteps = true, variant = 'default' }: TimelineProps) {
524
+ export function PmTimeline({ label, tracks, labels, durationMs, durationStatus, currentTimeMs, selectedStepId, zoom, onZoomChange, onSelectStep, onSelectSegment, segmentPicker, onSeek, seekDisabled, disabled, loading, seeking, density = 'compact', showSteps = true, variant = 'default', excluded, notice }: TimelineProps) {
544
525
  const hintId = useId()
545
526
  const viewport = useRef<HTMLDivElement>(null), tick = useRef<HTMLSpanElement>(null), composing = useRef(false)
546
527
  const [width, setWidth] = useState(0), [tickWidth, setTickWidth] = useState(1), [localZoom, setLocalZoom] = useState(1), [raw, setRaw] = useState<string>(), [previewTime, setPreviewTime] = useState<number>()
547
- const span = Number.isFinite(durationMs) && durationMs! >= 0 ? durationMs : undefined
528
+ const span = !excluded && Number.isFinite(durationMs) && durationMs! >= 0 ? durationMs : undefined
548
529
  const timing = durationStatus ?? (span === undefined ? 'unknown' : 'confirmed')
549
530
  const timed = span !== undefined && span > 0 && timing !== 'unknown'
550
531
  const blocked = Boolean(disabled || loading), cannotSeek = Boolean(blocked || seeking || seekDisabled || !timed || timing !== 'confirmed')
@@ -585,10 +566,10 @@ export function PmTimeline({ label, tracks, labels, durationMs, durationStatus,
585
566
  const marks = Array.from({ length: Math.min(200, Math.floor(span / unit) + 1) }, (_, index) => index * unit)
586
567
  return [0, ...marks.filter(time => time > 0 && time < span && Math.min(time, span - time) / span * width * scale >= tickWidth), span]
587
568
  }, [span, timed, width, scale, tickWidth])
588
- const status = <div className="pm-ui-timeline__status" role="status">{loading ? labels.loading : timing === 'unknown' || span === undefined ? labels.unknown : `${timing === 'estimated' ? `${labels.estimated} · ` : ''}${timelineTime(span)}`}</div>
569
+ const status = <div className="pm-ui-timeline__status" role="status">{loading ? labels.loading : excluded ? excluded.status : timing === 'unknown' || span === undefined ? labels.unknown : `${timing === 'estimated' ? `${labels.estimated} · ` : ''}${timelineTime(span)}`}</div>
589
570
  return <section className="pm-ui-timeline" data-variant={variant} data-density={density} data-disabled={blocked || undefined} data-segment-picker={segmentPicker?.track} aria-label={label} aria-busy={loading || seeking || undefined}>
590
571
  <div className="pm-ui-timeline__tools">
591
- <PmInput label={`${labels.position} (${labels.seconds})`} labelHidden={variant === 'editor'} width="time" density={density} inputMode="decimal" maxLength={32} value={raw ?? (position === undefined ? '' : (position / 1000).toFixed(3))} placeholder={labels.unknown} error={invalid ? labels.invalidPosition : undefined} disabled={cannotSeek}
572
+ <PmInput label={`${labels.position} (${labels.seconds})`} labelHidden={variant === 'editor'} width="time" density={density} inputMode="decimal" maxLength={32} value={raw ?? (position === undefined ? '' : (position / 1000).toFixed(3))} placeholder={excluded ? undefined : labels.unknown} error={invalid ? labels.invalidPosition : undefined} disabled={cannotSeek}
592
573
  onChange={event => setRaw(event.target.value)} onBlur={commitPosition}
593
574
  onCompositionStart={() => { composing.current = true }} onCompositionEnd={() => { composing.current = false }}
594
575
  onKeyDown={event => { if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) return; if (event.key === 'Enter') { event.preventDefault(); commitPosition() } else if (event.key === 'Escape') setRaw(undefined) }} />
@@ -625,7 +606,8 @@ export function PmTimeline({ label, tracks, labels, durationMs, durationStatus,
625
606
  <option value="">{segmentPicker.placeholder}</option>{pickerSegments.map(segment => <option key={segment.id} value={segment.id} disabled={segment.disabled}>{timelineTime(segment.startMs!)} · {segment.label}</option>)}
626
607
  </PmSelect></div>}
627
608
  {showSteps && <div className="pm-ui-timeline__steps">{steps.map(segment => <PmButton key={segment.stepId} density={density} disabled={blocked || segment.disabled} aria-pressed={segment.stepId === selectedStepId} variant={segment.stepId === selectedStepId ? 'accent' : 'default'} onClick={() => onSelectStep(segment.stepId!)}>{segment.label}</PmButton>)}</div>}
628
- {!tracks.some(track => track.segments.length) && <PmNotice>{labels.empty}</PmNotice>}
609
+ {(excluded || !tracks.some(track => track.segments.length)) && <PmNotice>{excluded?.notice ?? labels.empty}</PmNotice>}
610
+ {notice && <PmNotice>{notice}</PmNotice>}
629
611
  <p id={hintId} className="pm-ui-sr-only">{labels.seekHint}</p>
630
612
  </section>
631
613
  }
package/src/context.tsx CHANGED
@@ -2,7 +2,8 @@ import { createContext, useContext, useSyncExternalStore } from 'react'
2
2
  import type { ReactNode } from 'react'
3
3
  import { MESSAGES } from './messages.ts'
4
4
  import type { WorkbenchMessages } from './messages.ts'
5
- import type { Workbench, WorkbenchState } from './workbench.ts'
5
+ import type { Workbench } from './workbench.ts'
6
+ import type { WorkbenchState } from './workbench-state.ts'
6
7
 
7
8
  const WORKBENCH = createContext<Workbench | undefined>(undefined)
8
9
 
@@ -1,6 +1,6 @@
1
1
  import { errorMessage } from '@lincyaw/kernel'
2
2
  import type { Diagnostic, DiagnosticSnapshot, PreviewDiagnostics } from '@lincyaw/kernel'
3
- import type { WorkbenchStore } from './workbench.ts'
3
+ import type { WorkbenchStore } from './workbench-state.ts'
4
4
  import type { WorkspaceClient } from './workspace-client.ts'
5
5
 
6
6
  type Repairer = (diagnostics: readonly Diagnostic[]) => void | Promise<void>
@@ -1,3 +1,14 @@
1
+ export interface DraftStoreOperation { signal?: AbortSignal, guard?(): void }
2
+ export async function waitForDraft<T>(work: Promise<T>, signal?: AbortSignal): Promise<T> {
3
+ signal?.throwIfAborted()
4
+ if (!signal) return work
5
+ return new Promise<T>((resolve, reject) => {
6
+ const abort = () => { signal.removeEventListener('abort', abort); reject(signal.reason) }
7
+ signal.addEventListener('abort', abort, { once: true })
8
+ work.then(value => { signal.removeEventListener('abort', abort); signal.aborted ? reject(signal.reason) : resolve(value) }, error => { signal.removeEventListener('abort', abort); reject(error) })
9
+ })
10
+ }
11
+
1
12
  export type DraftStoreResult = 'committed' | 'superseded' | 'failed'
2
13
  export interface DraftStoreCommit { generation: number, done: Promise<DraftStoreResult> }
3
14
  interface Operation extends DraftStoreCommit {
@@ -98,31 +109,47 @@ export class DocumentDraftStore {
98
109
 
99
110
  #notify(): void { if (!this.#closing) this.#channel?.postMessage({ scope: this.#scope, ...this.#writerOwner ? { owner: this.#writerOwner } : {}, ...this.#family ? { family: this.#family } : {} }) }
100
111
 
101
- async #commit(key: string | undefined, raw: string | undefined, markers: readonly [string, string][]): Promise<{ committed: boolean, foreign: boolean }> {
112
+ async #commit(key: string | undefined, raw: string | undefined, markers: readonly [string, string][], operation?: DraftStoreOperation): Promise<{ committed: boolean, foreign: boolean }> {
102
113
  try {
103
- const db = await this.#db()
104
- return await new Promise(resolve => {
114
+ operation?.signal?.throwIfAborted(); operation?.guard?.()
115
+ const db = await waitForDraft(this.#db(), operation?.signal)
116
+ operation?.signal?.throwIfAborted(); operation?.guard?.()
117
+ return await new Promise((resolve, reject) => {
105
118
  const tx = db.transaction(ENTRIES, 'readwrite', { durability: 'strict' }), store = tx.objectStore(ENTRIES)
106
- let foreign = false
107
- tx.oncomplete = () => resolve({ committed: true, foreign })
108
- tx.onabort = () => resolve({ committed: false, foreign })
119
+ let foreign = false, failure: unknown
120
+ const abort = () => { try { tx.abort() } catch {} }
121
+ const stop = () => operation?.signal?.removeEventListener('abort', abort)
122
+ operation?.signal?.addEventListener('abort', abort, { once: true })
123
+ tx.oncomplete = () => { stop(); resolve({ committed: true, foreign }) }
124
+ tx.onabort = () => { stop(); failure || operation?.signal?.aborted ? reject(failure ?? operation?.signal?.reason) : resolve({ committed: false, foreign }) }
109
125
  tx.onerror = () => { /* The abort event delivers the terminal transaction result. */ }
110
126
  if (tx.durability !== 'strict') { tx.abort(); return }
127
+ const check = () => { operation?.signal?.throwIfAborted(); operation?.guard?.() }
111
128
  const apply = () => {
129
+ check()
112
130
  for (const [marker, value] of markers) store.put(value, marker)
113
131
  }
114
- if (key === undefined) { apply(); return }
132
+ if (key === undefined) {
133
+ if (operation) {
134
+ const gate = store.get(markers[0]?.[0] ?? 'presmium-draft-guard')
135
+ gate.onsuccess = () => { try { apply() } catch (error) { failure = error; abort() } }
136
+ } else { try { apply() } catch (error) { failure = error; abort() } }
137
+ return
138
+ }
115
139
  const request = store.get(key), expected = this.#confirmed.get(key)
116
140
  request.onsuccess = () => {
117
- foreign = request.result !== expected
118
- if (raw !== undefined) {
119
- if (foreign) { tx.abort(); return }
120
- store.put(raw, key)
121
- } else if (!foreign) store.delete(key)
122
- apply()
141
+ try {
142
+ check()
143
+ foreign = request.result !== expected
144
+ if (raw !== undefined) {
145
+ if (foreign) { tx.abort(); return }
146
+ store.put(raw, key)
147
+ } else if (!foreign) store.delete(key)
148
+ apply()
149
+ } catch (error) { failure = error; abort() }
123
150
  }
124
151
  })
125
- } catch { return { committed: false, foreign: false } }
152
+ } catch (error) { if (operation) throw error; return { committed: false, foreign: false } }
126
153
  }
127
154
 
128
155
  #stage(key: string, raw: string | undefined, markers: readonly [string, string][]): DraftStoreCommit | undefined {
@@ -157,16 +184,16 @@ export class DocumentDraftStore {
157
184
  }
158
185
 
159
186
  /** A candidate copy must be strictly committed before the actor switches to it. */
160
- async create(key: string, raw: string): Promise<boolean> {
187
+ async create(key: string, raw: string, operation?: DraftStoreOperation): Promise<boolean> {
161
188
  if (this.#closing) return false
162
- const result = await this.#commit(key, raw, [])
189
+ const result = await this.#commit(key, raw, [], operation)
163
190
  if (result.committed) { this.#confirmed.set(key, raw); this.#notify() }
164
191
  return result.committed
165
192
  }
166
193
 
167
- async mark(markers: readonly [string, string][]): Promise<boolean> {
194
+ async mark(markers: readonly [string, string][], operation?: DraftStoreOperation): Promise<boolean> {
168
195
  if (this.#closing) return false
169
- const result = await this.#commit(undefined, undefined, markers)
196
+ const result = await this.#commit(undefined, undefined, markers, operation)
170
197
  if (result.committed) this.#notify()
171
198
  return result.committed
172
199
  }