@lincyaw/workbench 0.2.0-rc.8 → 0.2.0-rc.80

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 (90) hide show
  1. package/package.json +5 -4
  2. package/src/MediaClipEditor.tsx +4 -3
  3. package/src/StepProductionEditor.tsx +13 -4
  4. package/src/approvals.tsx +6 -1
  5. package/src/audio-recording.ts +27 -5
  6. package/src/authoring-client.ts +10 -10
  7. package/src/authoring-draft-fragment.ts +3 -1
  8. package/src/authoring-window.ts +100 -0
  9. package/src/body-draft-actions.ts +60 -0
  10. package/src/caption-timing-drafts.ts +18 -1
  11. package/src/component-property-drafts.ts +5 -5
  12. package/src/components.tsx +22 -31
  13. package/src/context.tsx +5 -3
  14. package/src/diagnostics.ts +1 -1
  15. package/src/document-draft-store.ts +45 -18
  16. package/src/document-drafts.ts +28 -19
  17. package/src/document-editing.ts +484 -0
  18. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  19. package/src/document-editor/ComponentMaterials.tsx +3 -9
  20. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  21. package/src/document-editor/DocumentBlockPreview.tsx +4 -2
  22. package/src/document-editor/DocumentComments.tsx +85 -14
  23. package/src/document-editor/DocumentEditor.tsx +44 -7
  24. package/src/document-editor/DocumentStepNarration.tsx +33 -25
  25. package/src/document-editor/NarrationEditor.tsx +54 -20
  26. package/src/document-editor/NewCommentDrafts.tsx +114 -31
  27. package/src/document-editor/PlaceComment.tsx +228 -0
  28. package/src/document-editor/comment-draft-actions.ts +40 -20
  29. package/src/document-editor/comment-draft-inspection.ts +2 -2
  30. package/src/document-editor/comment-drafts.ts +73 -25
  31. package/src/document-editor/comments.ts +30 -10
  32. package/src/document-editor/component-label.ts +11 -0
  33. package/src/document-editor/file-input.ts +2 -2
  34. package/src/document-editor/focus.ts +0 -2
  35. package/src/document-editor/insertion-place.ts +60 -0
  36. package/src/document-editor/messages.ts +3 -3
  37. package/src/document-editor/narration-schema.tsx +12 -6
  38. package/src/document-editor/narration.ts +19 -3
  39. package/src/document-editor/page-body.ts +60 -0
  40. package/src/document-editor/projection.ts +2 -2
  41. package/src/document-editor/rich-text.ts +3 -2
  42. package/src/document-editor/selection.ts +13 -0
  43. package/src/document-editor/style.css +12 -1
  44. package/src/document-editor/table-identities.ts +2 -1
  45. package/src/document-production.ts +491 -0
  46. package/src/document-session.ts +202 -56
  47. package/src/document-timing-drafts.ts +22 -2
  48. package/src/history.ts +5 -5
  49. package/src/index.ts +6 -5
  50. package/src/jobs.ts +1 -1
  51. package/src/media-drafts.ts +43 -1
  52. package/src/messages.ts +31 -14
  53. package/src/panels/DocumentView.tsx +71 -28
  54. package/src/panels/DocumentVoiceDialog.tsx +25 -9
  55. package/src/panels/DocumentVoiceField.tsx +1 -1
  56. package/src/panels/ExportPanel.tsx +1 -6
  57. package/src/panels/HistoryPanel.tsx +32 -2
  58. package/src/panels/PageDeleteDialog.tsx +4 -4
  59. package/src/panels/PageRenameDialog.tsx +1 -1
  60. package/src/panels/PreviewPanel.tsx +1 -4
  61. package/src/panels/ProductionCaptionSize.tsx +20 -0
  62. package/src/panels/ProductionCaptionTiming.tsx +12 -9
  63. package/src/panels/ProductionMediaClips.tsx +23 -7
  64. package/src/panels/ProductionPanel.tsx +8 -4
  65. package/src/panels/ProductionRecording.tsx +86 -9
  66. package/src/panels/ProductionRecordingRange.tsx +21 -19
  67. package/src/panels/ProductionTimeline.tsx +6 -1
  68. package/src/panels/ProductionTranscription.tsx +5 -4
  69. package/src/panels/SourceDocumentPanel.tsx +16 -36
  70. package/src/panels/TranscriptionAdoption.tsx +40 -34
  71. package/src/panels/VoiceCloneDialog.tsx +2 -1
  72. package/src/panels/VoiceoverDialog.tsx +1 -1
  73. package/src/places.ts +1 -36
  74. package/src/preview-playback.ts +1 -1
  75. package/src/production-draft-actions.ts +37 -0
  76. package/src/production-messages.ts +6 -0
  77. package/src/production-playback.ts +1 -1
  78. package/src/production-voice-playback.ts +3 -2
  79. package/src/sha256.ts +9 -0
  80. package/src/styles.css +21 -43
  81. package/src/transcription-drafts.ts +124 -0
  82. package/src/use-recording-adoption.ts +2 -2
  83. package/src/voice-drafts.ts +32 -8
  84. package/src/voiceover-jobs.ts +1 -1
  85. package/src/workbench-state.ts +157 -0
  86. package/src/workbench.ts +258 -951
  87. package/src/workspace-client.ts +21 -11
  88. package/src/assistant-mascot.ts +0 -62
  89. package/src/mascot-preference.ts +0 -37
  90. package/src/panels/ChangeTrail.tsx +0 -79
@@ -4,7 +4,7 @@ import type { MediaClipDraft } from './MediaClipEditor.tsx'
4
4
  import type { WorkspaceClient } from './workspace-client.ts'
5
5
 
6
6
  export interface MediaDrafts { selectedClipId?: string, entries: Record<string, MediaClipDraft> }
7
- interface Entry { value: MediaDrafts, failed: boolean, volatile: boolean, unreadable?: string }
7
+ interface Entry { value: MediaDrafts, failed: boolean, volatile: boolean, unreadable?: string, raw?: string | null }
8
8
  const memory = new WeakMap<WorkspaceClient, Map<string, Entry>>()
9
9
  const prefix = 'presmium.media-drafts.v1:', limit = 64
10
10
  const keyOf = (identity: string, stepId: string) => prefix + JSON.stringify([identity, stepId])
@@ -38,6 +38,7 @@ function load(client: WorkspaceClient, key: string): Entry {
38
38
  const entry: Entry = { value: { entries: {} }, failed: false, volatile: false }
39
39
  try {
40
40
  const raw = sessionStorage.getItem(key)
41
+ entry.raw = raw
41
42
  if (raw !== null) {
42
43
  entry.unreadable = raw
43
44
  if (raw.length > 131072) throw new Error('media-drafts-size')
@@ -68,6 +69,7 @@ export function keepMediaDrafts(client: WorkspaceClient, identity: string, stepI
68
69
  if (raw.length > 131072) throw new Error('media-drafts-size')
69
70
  if (entry.unreadable !== undefined) sessionStorage.setItem(`${key}:unreadable`, entry.unreadable)
70
71
  sessionStorage.setItem(key, raw)
72
+ entry.raw = raw
71
73
  const keys = Array.from({ length: sessionStorage.length }, (_, index) => sessionStorage.key(index)!).filter(name => name.startsWith(prefix) && !name.endsWith(':unreadable') && name !== key)
72
74
  let excess = keys.length - limit + 1
73
75
  for (const old of keys) {
@@ -81,3 +83,43 @@ export function keepMediaDrafts(client: WorkspaceClient, identity: string, stepI
81
83
  return true
82
84
  } catch { entry.failed = true; trim(known); return false }
83
85
  }
86
+
87
+ /** This is the same step/form bank used when the author reopens Media, including session-only input. */
88
+ export function mediaDraftSnapshot(client: WorkspaceClient, identity: string): { entries: { stepId: string, value: MediaDrafts, persisted: boolean }[], partial: boolean } {
89
+ const scoped = `${prefix}${JSON.stringify([identity]).slice(0, -1)},`
90
+ const keys = new Set([...store(client).keys()].filter(key => key.startsWith(scoped)))
91
+ let partial = false
92
+ try {
93
+ for (let index = 0; index < sessionStorage.length; index++) {
94
+ const key = sessionStorage.key(index)
95
+ if (key?.startsWith(scoped) && !key.endsWith(':unreadable')) keys.add(key)
96
+ }
97
+ } catch { partial = true }
98
+ const entries: { stepId: string, value: MediaDrafts, persisted: boolean }[] = []
99
+ for (const key of keys) {
100
+ let target: unknown
101
+ try { target = JSON.parse(key.slice(prefix.length)) } catch { partial = true; continue }
102
+ if (!Array.isArray(target) || target.length !== 2 || target[0] !== identity || typeof target[1] !== 'string') { partial = true; continue }
103
+ const entry = load(client, key)
104
+ let persisted = false
105
+ try { const raw = sessionStorage.getItem(key); persisted = !entry.failed && raw === entry.raw; if (raw !== entry.raw) partial = true } catch { partial = true }
106
+ if (entry.unreadable !== undefined || entry.raw === undefined) partial = true
107
+ if (Object.keys(entry.value.entries).length) entries.push({ stepId: target[1], value: structuredClone(entry.value), persisted })
108
+ }
109
+ return { entries, partial }
110
+ }
111
+
112
+ /** Retire one exact clip proposal, preserving sibling forms and any independently changed storage. */
113
+ export function discardMediaDraft(client: WorkspaceClient, identity: string, stepId: string, name: string, expected: MediaDrafts): boolean {
114
+ const key = keyOf(identity, stepId), entry = load(client, key)
115
+ if (!Object.hasOwn(expected.entries, name) || JSON.stringify(entry.value) !== JSON.stringify(expected)) return false
116
+ try {
117
+ if (entry.raw === undefined || entry.unreadable !== undefined || sessionStorage.getItem(key) !== entry.raw) return false
118
+ const next = structuredClone(entry.value)
119
+ delete next.entries[name]
120
+ const raw = JSON.stringify(next)
121
+ sessionStorage.setItem(key, raw)
122
+ entry.value = next; entry.raw = raw; entry.failed = false; entry.volatile = false
123
+ return true
124
+ } catch { entry.failed = true; return false }
125
+ }
package/src/messages.ts CHANGED
@@ -12,6 +12,11 @@ export interface AgentPlace {
12
12
 
13
13
  // A Latin word or a number set after Chinese text is spaced from it (docs/glossary.md 2).
14
14
  const spaced = (text: string) => (/^[A-Za-z0-9]/.test(text) ? ` ${text}` : text)
15
+ // The start of a passage, enough to recognize it.
16
+ const excerpt = (text: string, length: number) => [...text].length > length ? `${[...text].slice(0, length).join('').trimEnd()}…` : text
17
+
18
+ /** Where on a page the author asks for new content: after a passage (its text, '' for content without text), at the start (none) or at the end. */
19
+ interface AgentInsertion { after?: string, end: boolean }
15
20
 
16
21
  // Names of commands follow Microsoft Word's (撤消/Undo, 新建批注/New Comment, 版本历史/Version History…).
17
22
  const zh = {
@@ -106,14 +111,13 @@ const zh = {
106
111
  narrationAutosave: '自动保存;切换步骤会保留未完成的草稿。',
107
112
  narrationDiscard: '放弃草稿',
108
113
  narrationRecoveryUnavailable: '浏览器无法在本机保留草稿。草稿仍在本次会话中,请保存后再关闭窗口。',
109
- documentDraftFound: '发现本地草稿',
110
- documentDraftSelect: '恢复草稿',
111
- documentDraftChoose: '请选择草稿',
114
+ documentDrafts: '本地草稿',
115
+ documentDraftName: (index: number) => `草稿 ${index}`,
116
+ documentDraftDiscardAll: '全部放弃',
112
117
  documentDraftRestore: '恢复草稿',
113
- documentDraftChanged: '本地草稿已更新,请重新选择。',
118
+ documentDraftChanged: '本地草稿已更新,请查看最新列表。',
114
119
  documentDraftUnreadable: '部分本地草稿无法读取。',
115
120
  documentDraftBackingUp: '正在备份…',
116
- documentDraftOption: (index: number, date: string, source: 'durable' | 'rescue') => `${date} · ${source === 'rescue' ? '临时副本' : '草稿'} ${index}`,
117
121
  narrationCompositionInterrupted: '输入法组字未完成,草稿已保留。请检查文字后保存或继续编辑。',
118
122
  narrationRefresh: '讲稿已写入,但画面尚未完成更新。草稿已保留,请等待预览恢复后重试。',
119
123
  narrationDuring: '与动画同步',
@@ -241,6 +245,8 @@ const zh = {
241
245
  formattedEdit: '这一处带有格式或特殊内容,不能直接修改文字。要用 AI 改写吗?',
242
246
  rewriteEdit: '用 AI 改写',
243
247
  versionHistory: '版本历史',
248
+ historyWithDrafts: (count: number) => `版本历史(${count} 份本地草稿)`,
249
+ historySavedVersions: '已保存版本',
244
250
  historyNewer: '较新版本',
245
251
  historyOlder: '更早版本',
246
252
  exportPane: '导出',
@@ -325,11 +331,11 @@ const zh = {
325
331
  'history-result-no-longer-current': '之前的结果已不是当前版本,请查看最新的历史。',
326
332
  'authoring-review-required': '有修改等待你审阅,请先接受或放弃。',
327
333
  } as Record<string, string>,
328
- agentWorking: 'AI 正在修改文稿…',
329
334
  agentWaiting: (n: number) => `AI 修改了 ${n} 处内容,要接受这些修改吗?`,
330
335
  accept: '接受',
331
336
  reject: '拒绝',
332
- problems: (n: number) => `有 ${n} 处内容无法正确显示。`,
337
+ problems: (n: number) => `文稿有 ${n} 个问题需要处理。`,
338
+ problemsTitle: '文稿中的问题',
333
339
  fixWithAi: '用 AI 修复',
334
340
  fixing: '正在发送给 AI…',
335
341
  fixFailed: (reason: string) => `无法发送给 AI。${reason}`,
@@ -356,6 +362,11 @@ const zh = {
356
362
  place.quote ? `\n原文:“${place.quote}”` : '',
357
363
  ].join('')).filter(Boolean),
358
364
  ].join('\n\n'),
365
+ animationRequest: (page: number, title: string, place: AgentInsertion) => {
366
+ const at = `第 ${page} 页${title ? `“${title}”` : ''}`
367
+ return place.end ? `在${at}的末尾加一个动画:` : place.after === undefined ? `在${at}的开头加一个动画:`
368
+ : place.after ? `在${at}中“${excerpt(place.after, 16)}”这一段之后加一个动画:` : `在${at}的这个位置加一个动画:`
369
+ },
359
370
  commentsRequest: (comments: (AgentPlace & { text: string })[]) => [
360
371
  comments.length === 1 ? '我在文稿上写了一条批注:' : `我在文稿上写了 ${comments.length} 条批注:`,
361
372
  ...comments.map((comment, i) => [
@@ -470,14 +481,13 @@ const en: WorkbenchMessages = {
470
481
  narrationAutosave: 'Saved automatically. Switching steps keeps unfinished drafts.',
471
482
  narrationDiscard: 'Discard Draft',
472
483
  narrationRecoveryUnavailable: 'This browser can’t keep drafts on this device. Your draft stays in this session; save before closing the window.',
473
- documentDraftFound: 'Drafts found on this device',
474
- documentDraftSelect: 'Recover Draft',
475
- documentDraftChoose: 'Choose a draft',
484
+ documentDrafts: 'Local Drafts',
485
+ documentDraftName: (index: number) => `Draft ${index}`,
486
+ documentDraftDiscardAll: 'Discard All',
476
487
  documentDraftRestore: 'Recover Draft',
477
- documentDraftChanged: 'The draft on this device changed. Choose it again.',
488
+ documentDraftChanged: 'Drafts on this device changed. Check the updated list.',
478
489
  documentDraftUnreadable: 'Couldn’t read some drafts on this device.',
479
490
  documentDraftBackingUp: 'Backing up…',
480
- documentDraftOption: (index: number, date: string, source: 'durable' | 'rescue') => `${date} · ${source === 'rescue' ? 'Temporary copy' : 'Draft'} ${index}`,
481
491
  narrationCompositionInterrupted: 'Typing with the input method was interrupted. Your draft is kept; review it before saving, or keep editing.',
482
492
  narrationRefresh: 'The script was written, but the preview has not updated yet. Your draft is kept; retry after the preview recovers.',
483
493
  narrationDuring: 'During animation',
@@ -605,6 +615,8 @@ const en: WorkbenchMessages = {
605
615
  formattedEdit: 'This text has formatting or special content and can’t be edited directly. Rewrite it with AI?',
606
616
  rewriteEdit: 'Rewrite with AI',
607
617
  versionHistory: 'Version History',
618
+ historyWithDrafts: (count: number) => `Version History (${count} local ${count === 1 ? 'draft' : 'drafts'})`,
619
+ historySavedVersions: 'Saved Versions',
608
620
  historyNewer: 'Newer versions',
609
621
  historyOlder: 'Older versions',
610
622
  exportPane: 'Export',
@@ -689,11 +701,11 @@ const en: WorkbenchMessages = {
689
701
  'history-result-no-longer-current': 'The earlier result is no longer the current version. Review the latest history.',
690
702
  'authoring-review-required': 'Changes are waiting for your review. Accept or discard them first.',
691
703
  },
692
- agentWorking: 'The AI is editing the document…',
693
704
  agentWaiting: (n: number) => `The AI changed ${n} file${n === 1 ? '' : 's'}. Accept the changes?`,
694
705
  accept: 'Accept',
695
706
  reject: 'Reject',
696
- problems: (n: number) => `${n} item${n === 1 ? '' : 's'} can’t be displayed correctly.`,
707
+ problems: (n: number) => `The document has ${n} problem${n === 1 ? '' : 's'} to fix.`,
708
+ problemsTitle: 'Problems in the Document',
697
709
  fixWithAi: 'Fix with AI',
698
710
  fixing: 'Sending to the AI…',
699
711
  fixFailed: (reason: string) => `Couldn’t send to the AI. ${reason}`,
@@ -720,6 +732,11 @@ const en: WorkbenchMessages = {
720
732
  place.quote ? `\nText: “${place.quote}”` : '',
721
733
  ].join('')).filter(Boolean),
722
734
  ].join('\n\n'),
735
+ animationRequest: (page: number, title: string, place: AgentInsertion) => {
736
+ const at = `page ${page}${title ? `, “${title}”` : ''}`
737
+ return place.end ? `Add an animation at the end of ${at}: ` : place.after === undefined ? `Add an animation at the start of ${at}: `
738
+ : place.after ? `Add an animation on ${at}, after the paragraph “${excerpt(place.after, 40)}”: ` : `Add an animation at this point on ${at}: `
739
+ },
723
740
  commentsRequest: (comments: (AgentPlace & { text: string })[]) => [
724
741
  comments.length === 1 ? 'I left a comment on the document:' : `I left ${comments.length} comments on the document:`,
725
742
  ...comments.map((comment, i) => [
@@ -1,11 +1,11 @@
1
1
  import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
2
2
  import type { ReactNode, RefObject } from 'react'
3
- import { PmButton, PmIconButton, PmMascot, PmMenu, PmNotice, PmSkeleton, PmSortableList, PmToolbar, PmToolbarButton } from '../components.tsx'
3
+ import { PmBadge, PmButton, PmDialog, PmIcon, PmIconButton, PmMenu, PmNotice, PmSkeleton, PmSortableList, PmToolbar, PmToolbarButton } from '../components.tsx'
4
4
  import { useMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
5
5
  import { failureReason, timeAgo } from '../messages.ts'
6
6
  import { SHORTCUTS } from '../shortcuts.ts'
7
7
  import { DocumentOutline, DocumentWordCounter } from '../outline.ts'
8
- import { isAgentChanging } from '../workbench.ts'
8
+ import { isAgentChanging } from '../workbench-state.ts'
9
9
  import { ExportPanel } from './ExportPanel.tsx'
10
10
  import { HistoryPanel } from './HistoryPanel.tsx'
11
11
  import type { HistoryRevisionAction } from './HistoryPanel.tsx'
@@ -55,6 +55,7 @@ export function DocumentView({ active = true, framed = false, onBack, actions, h
55
55
  const [commentsPortal, setCommentsPortal] = useState<HTMLDivElement | null>(null)
56
56
  const t = useMessages()
57
57
  const document = useWorkbenchState(state => state.document)
58
+ const sourceIdentity = useWorkbenchState(state => state.authoring?.identity)
58
59
  const view = useWorkbenchState(state => state.webView)
59
60
  const previousView = useRef({ document, workspace, view, active })
60
61
  const currentScope = useRef({ document, active })
@@ -72,7 +73,7 @@ export function DocumentView({ active = true, framed = false, onBack, actions, h
72
73
  setNavigationDocument(document)
73
74
  if (navigation && typeof matchMedia === 'function' && !matchMedia(ROOMY).matches) setNavigation(false)
74
75
  }
75
- const compilePresentation = async (ready?: () => void, forReading = false): Promise<void> => {
76
+ const compilePresentation = async (ready?: () => void, forReading = false, signal?: AbortSignal, deadline?: number): Promise<void> => {
76
77
  if (preparing.current || workbench.getState().isPreparingPresentation) return
77
78
  preparing.current = true
78
79
  const generation = ++transition.current, identity = workbench.getState().authoring?.identity
@@ -80,34 +81,39 @@ export function DocumentView({ active = true, framed = false, onBack, actions, h
80
81
  setChangingView(true)
81
82
  const current = () => generation === transition.current && currentScope.current.active && currentScope.current.document === document && workbench.getState().authoring?.identity === identity
82
83
  try {
83
- const prepared = await workbench.preparePresentation()
84
+ const prepared = await workbench.preparePresentation(signal, deadline)
85
+ signal?.throwIfAborted()
84
86
  if (!current()) return
85
87
  if (prepared) ready?.()
86
88
  else setViewFailure(forReading ? t.readingFailed : workbench.getState().presentationFailure)
87
89
  } catch { if (current()) setViewFailure(forReading ? t.readingFailed : t.presentationCompileFailed) }
88
90
  finally { preparing.current = false; if (current()) setChangingView(false) }
89
91
  }
90
- const openProduction = async () => {
92
+ const openProduction = async (signal?: AbortSignal) => {
91
93
  if (changingView || workbench.client.capabilities?.production === false) return
92
94
  const generation = ++transition.current, identity = workbench.getState().authoring?.identity
93
95
  const current = () => generation === transition.current && currentScope.current.active && currentScope.current.document === document && workbench.getState().authoring?.identity === identity
94
96
  setChangingView(true); setViewFailure(undefined)
95
97
  try {
98
+ signal?.throwIfAborted()
96
99
  await workbench.pausePlayback()
97
- await workbench.flushPendingEdits()
100
+ await workbench.flushPendingEdits(signal)
101
+ signal?.throwIfAborted()
98
102
  if (current()) { workbench.setMode('editing'); setWorkspace('production') }
99
103
  } catch { if (current()) setViewFailure(t.presentationPending) }
100
104
  finally { if (current()) setChangingView(false) }
101
105
  }
102
- const exitPresent = (): Promise<void> => {
106
+ const exitPresent = (signal?: AbortSignal): Promise<void> => {
103
107
  if (exiting.current) return exiting.current
104
108
  const generation = ++transition.current, identity = workbench.getState().authoring?.identity
105
109
  setChangingView(true); setViewFailure(undefined)
106
110
  const current = () => generation === transition.current && currentScope.current.active && currentScope.current.document === document && workbench.getState().authoring?.identity === identity
107
111
  const work = Promise.resolve().then(async () => {
108
112
  try {
113
+ signal?.throwIfAborted()
109
114
  // The child flushes its latest position before acknowledging this pause.
110
115
  await workbench.pausePlayback()
116
+ signal?.throwIfAborted()
111
117
  if (!current()) return
112
118
  setWorkspace('document')
113
119
  workbench.setMode('editing')
@@ -120,6 +126,40 @@ export function DocumentView({ active = true, framed = false, onBack, actions, h
120
126
  exiting.current = work
121
127
  return work
122
128
  }
129
+ const controls = useRef({ workspace, changingView, viewFailure, generation: transition.current, compilePresentation, openProduction, exitPresent, setWorkspace })
130
+ controls.current = { workspace, changingView, viewFailure, generation: transition.current, compilePresentation, openProduction, exitPresent, setWorkspace }
131
+ useEffect(() => {
132
+ if (!active || !sourceIdentity) return
133
+ return workbench.registerAuthoringClientControls({ identity: sourceIdentity,
134
+ actions: () => {
135
+ const state = workbench.getState(), source = state.authoring
136
+ return currentScope.current.active && source?.identity === sourceIdentity && !controls.current.changingView
137
+ && !source.loading && !source.dirty && !source.saving && !source.composing && !source.restored && !source.error && !isAgentChanging(state)
138
+ && !state.isCreatingPage && !state.isEditingPage && !state.isHistoryBusy && !state.isHistoryPreparing ? ['view.set'] : []
139
+ },
140
+ snapshot: () => ({ mode: controls.current.workspace }),
141
+ execute: async (action, _source, signal, deadline) => {
142
+ if (action.type !== 'view.set') throw new Error('client-action-unavailable')
143
+ if (preparing.current || controls.current.changingView) throw new Error('client-action-unavailable')
144
+ if (action.view !== controls.current.workspace) {
145
+ if (action.view === 'document') await controls.current.exitPresent(signal)
146
+ else if (action.view === 'production') await controls.current.openProduction(signal)
147
+ else await controls.current.compilePresentation(() => {
148
+ workbench.setMode('viewing'); workbench.setWebView(action.view === 'presentation' ? 'present' : 'document')
149
+ controls.current.setWorkspace(action.view)
150
+ }, action.view === 'reading', signal, deadline)
151
+ }
152
+ const generation = transition.current
153
+ await workbench.waitForAuthoringClientState(() => {
154
+ if (!currentScope.current.active || workbench.getState().authoring?.identity !== sourceIdentity) throw new Error('client-document-changed')
155
+ if (generation !== transition.current) throw new Error('client-view-changed')
156
+ if (controls.current.generation === generation && controls.current.viewFailure && controls.current.workspace !== action.view) throw new Error('client-view-not-verified')
157
+ return controls.current.workspace === action.view && !controls.current.changingView
158
+ }, signal)
159
+ },
160
+ })
161
+ }, [workbench, active, sourceIdentity])
162
+ useEffect(() => workbench.refreshAuthoringClientControls(), [workbench, active, sourceIdentity, workspace, changingView])
123
163
  useEffect(() => {
124
164
  transition.current++; exiting.current = undefined
125
165
  setWorkspace('document')
@@ -198,7 +238,7 @@ export function DocumentView({ active = true, framed = false, onBack, actions, h
198
238
  <DocumentNotices />
199
239
  <div className="pmw-document__body" role="region" aria-label={producing ? PRODUCTION_MESSAGES[workbench.getState().locale].title : presenting ? t.presentationPreview : reading ? t.readDocument : t.documentEditor}>
200
240
  {!presenting && !producing && !reading && navigation && <NavigationPane onClose={() => setNavigation(false)} onSelect={() => { if (matchMedia('(max-width: 1279px)').matches) setNavigation(false) }} />}
201
- <div className="pmw-document__main"><div className="pmw-document__source" hidden={presenting || producing || reading}><SourceDocumentPanel commentsPortal={commentsPortal} onCommentDraftRestore={() => setAside(current => current === 'comments' ? null : current)} /></div>{producing && <ProductionPanel active={active} closing={changingView} onClose={() => void exitPresent()} />}{presenting && <PreviewPanel presentation active={active} onPresentationAction={action => { if (action === 'refresh') void compilePresentation(); else void exitPresent() }} />}{reading && <PreviewPanel active={active} />}</div>
241
+ <div className="pmw-document__main"><div className="pmw-document__source" hidden={presenting || producing || reading}><SourceDocumentPanel commentsPortal={commentsPortal} onCommentDraftRestore={() => setAside(current => current === 'comments' ? null : current)} onOpenComments={() => setAside('comments')} /></div>{producing && <ProductionPanel active={active} closing={changingView} onClose={() => void exitPresent()} />}{presenting && <PreviewPanel presentation active={active} onPresentationAction={action => { if (action === 'refresh') void compilePresentation(); else void exitPresent() }} />}{reading && <PreviewPanel active={active} />}</div>
202
242
  {!presenting && !producing && !reading && aside && (
203
243
  <aside className="pmw-document__aside pm-ui-block-editor" aria-label={{ narration: t.documentNarration, comments: t.comments, export: t.exportPane, history: t.versionHistory }[aside]}>
204
244
  {aside === 'comments' ? <section className="pmw-pane"><header className="pmw-pane__header"><h2 className="pmw-pane__title">{t.comments}</h2><PmIconButton small icon="close" label={t.close} onClick={() => setAside(null)} /></header><div ref={setCommentsPortal} /></section> : aside === 'narration' ? <DocumentNarrationPanel onClose={() => setAside(null)} /> : aside === 'export' ? <ExportPanel documentOnly onClose={() => setAside(null)} /> : <HistoryPanel onClose={() => setAside(null)} revisionAction={historyRevisionAction} />}
@@ -238,7 +278,7 @@ function NavigationPane({ onClose, onSelect }: { onClose(): void, onSelect(): vo
238
278
  const pages = editing || slides
239
279
  const top = Math.min(...items.map(item => Math.max(1, item.depth)))
240
280
  const pageActions = (item: typeof items[number], index: number) => {
241
- const capability = workbench.pageEditCapability(item.id), previousPeer = index > 0, nextPeer = index < items.length - 1
281
+ const capability = workbench.editing.pageCapability(item.id), previousPeer = index > 0, nextPeer = index < items.length - 1
242
282
  return <PmMenu label={t.pageMore(item.title)} description={capability.reason} triggerRef={node => { if (node) menuTriggers.current.set(item.id, node); else menuTriggers.current.delete(item.id) }} items={[
243
283
  { id: 'rename', label: t.rename, icon: 'edit', disabled: !capability.rename || !canCreate || pageBusy || creating },
244
284
  { id: 'copy', label: t.pageCopy, icon: 'copy', disabled: !canCreate || pageBusy || creating },
@@ -246,19 +286,19 @@ function NavigationPane({ onClose, onSelect }: { onClose(): void, onSelect(): vo
246
286
  { id: 'down', label: t.movePageDown, disabled: !capability.move || !canCreate || pageBusy || creating || !nextPeer },
247
287
  ...(canDelete ? [{ id: 'delete', label: t.pageDelete, icon: 'trash' as const, danger: true, separator: true, disabled: !canCreate || pageBusy || creating }] : []),
248
288
  ]} onSelect={id => {
249
- workbench.clearPageEditFailure()
289
+ workbench.editing.clearFailure()
250
290
  if (id === 'rename') setRenaming({ id: item.id, title: item.title, trigger: menuTriggers.current.get(item.id) })
251
- else if (id === 'copy') void workbench.duplicatePage(item.id)
291
+ else if (id === 'copy') void workbench.editing.duplicatePage(item.id)
252
292
  else if (id === 'delete') setDeleting({ id: item.id, title: item.title, trigger: menuTriggers.current.get(item.id) })
253
- else if (id === 'up' && index > 0) void workbench.movePage(item.id, items[index - 1]!.id)
254
- else if (id === 'down') void workbench.movePage(item.id, items[index + 2]?.id ?? null)
293
+ else if (id === 'up' && index > 0) void workbench.editing.movePage(item.id, items[index - 1]!.id)
294
+ else if (id === 'down') void workbench.editing.movePage(item.id, items[index + 2]?.id ?? null)
255
295
  }} />
256
296
  }
257
297
  return (
258
298
  <nav className="pmw-navigation" aria-label={t.navigation}>
259
299
  <header className="pmw-pane__header">
260
300
  <h2 className="pmw-pane__title">{editing ? t.pages : slides ? t.renderers.slides : t.navigation}</h2>
261
- {editing && <PmIconButton icon="plus" label={t.newPage} small loading={creating} disabled={!canCreate || pageBusy || !items.length} onClick={() => { if (workbench.createPage()) onSelect() }} />}
301
+ {editing && <PmIconButton icon="plus" label={t.newPage} small loading={creating} disabled={!canCreate || pageBusy || !items.length} onClick={() => { if (workbench.editing.createPage()) onSelect() }} />}
262
302
  <PmIconButton icon="close" label={t.closeNavigation} small onClick={onClose} />
263
303
  </header>
264
304
  {failure && !renaming && !deleting && <PmNotice tone="danger">{failure}</PmNotice>}
@@ -266,13 +306,13 @@ function NavigationPane({ onClose, onSelect }: { onClose(): void, onSelect(): vo
266
306
  : items.length === 0
267
307
  ? <p className="pmw-muted pmw-navigation__empty">{t.noSections}</p>
268
308
  : editing ? <PmSortableList label={t.pages} scopeKey={JSON.stringify([identity, documentId, document])} resetKey={reset} className="pmw-navigation__list" locale={locale}
269
- items={items.map((item, index) => ({ id: item.id, label: item.title, prefix: item.number, reorderDisabled: !workbench.pageEditCapability(item.id).move, actions: pageActions(item, index) }))}
309
+ items={items.map((item, index) => ({ id: item.id, label: item.title, prefix: item.number, reorderDisabled: !workbench.editing.pageCapability(item.id).move, actions: pageActions(item, index) }))}
270
310
  value={current} reorderDisabled={reorderDisabled} loading={pageBusy || creating}
271
311
  onSelect={id => { workbench.goToSection(id); onSelect() }}
272
312
  onMove={async (id, before) => {
273
313
  const state = workbench.getState()
274
314
  if (state.document !== document || state.authoring?.identity !== identity || state.authoring?.content?.id !== documentId) return
275
- if (!await workbench.movePage(id, before)) throw new Error('page-reorder-failed')
315
+ if (!await workbench.editing.movePage(id, before)) throw new Error('page-reorder-failed')
276
316
  }} /> : (
277
317
  <ol className="pmw-navigation__list" data-kind={pages ? 'slides' : 'headings'}>
278
318
  {items.map(item => (
@@ -291,8 +331,8 @@ function NavigationPane({ onClose, onSelect }: { onClose(): void, onSelect(): vo
291
331
  ))}
292
332
  </ol>
293
333
  )}
294
- {renaming && <PageRenameDialog section={renaming.id} title={renaming.title} trigger={renaming.trigger} onClose={() => { setRenaming(undefined); workbench.clearPageEditFailure() }} />}
295
- {deleting && <PageDeleteDialog section={deleting.id} title={deleting.title} trigger={deleting.trigger} onClose={() => { setDeleting(undefined); workbench.clearPageEditFailure() }} />}
334
+ {renaming && <PageRenameDialog section={renaming.id} title={renaming.title} trigger={renaming.trigger} onClose={() => { setRenaming(undefined); workbench.editing.clearFailure() }} />}
335
+ {deleting && <PageDeleteDialog section={deleting.id} title={deleting.title} trigger={deleting.trigger} onClose={() => { setDeleting(undefined); workbench.editing.clearFailure() }} />}
296
336
  </nav>
297
337
  )
298
338
  }
@@ -324,6 +364,8 @@ function DocumentToolbar({ presentButton, framed, onBack, actions, aside, naviga
324
364
  const history = useWorkbenchState(state => state.history)
325
365
  const editorHistory = useWorkbenchState(state => state.editorHistory)
326
366
  const dirty = useWorkbenchState(state => Boolean(state.authoring?.dirty))
367
+ const draftCount = useWorkbenchState(state => state.authoring?.recoveryDrafts?.length ?? 0)
368
+ const draftReadFailure = useWorkbenchState(state => Boolean(state.authoring?.recoveryReadFailure))
327
369
  const busy = useWorkbenchState(state => state.isHistoryBusy || state.isHistoryPreparing || Boolean(state.isCreatingPage) || Boolean(state.isEditingPage || state.authoring?.composing) || isAgentChanging(state))
328
370
  const timingDrafts = useWorkbenchState(state => state.hasDocumentTimingDrafts)
329
371
  const preparing = useWorkbenchState(state => Boolean(state.isPreparingPresentation))
@@ -336,6 +378,7 @@ function DocumentToolbar({ presentButton, framed, onBack, actions, aside, naviga
336
378
  const undoDisabled = Boolean(capabilities?.readOnly || !editorHistory?.undo && (editorHistory?.field || !history?.undo && !dirty) || busy)
337
379
  const redoDisabled = Boolean(capabilities?.readOnly || !editorHistory?.redo && (editorHistory?.field || dirty || !history?.redo) || busy)
338
380
  const commentsLabel = openComments ? `${t.comments} (${openComments})` : t.comments
381
+ const historyLabel = draftReadFailure ? `${t.versionHistory} · ${t.documentDraftUnreadable}` : draftCount ? t.historyWithDrafts(draftCount) : t.versionHistory
339
382
  return (
340
383
  <PmToolbar className={framed ? 'pmw-toolbar' : 'pmw-toolbar pmw-toolbar--document'} label={t.commands}>
341
384
  {!framed && <div className="pmw-toolbar__document">
@@ -354,7 +397,7 @@ function DocumentToolbar({ presentButton, framed, onBack, actions, aside, naviga
354
397
  {capabilities?.narration !== false && <PmToolbarButton asChild><PmIconButton small icon="captions" label={t.documentNarration} hint={t.documentNarrationHint} aria-pressed={aside === 'narration'} disabled={!hasStep} onClick={() => onAside('narration')} /></PmToolbarButton>}
355
398
  </>}
356
399
  {!compactCommands && <PmToolbarButton asChild><PmIconButton small icon="comment" label={commentsLabel} aria-pressed={aside === 'comments'} onClick={() => onAside('comments')} /></PmToolbarButton>}
357
- {!narrow && <PmToolbarButton asChild><PmIconButton small icon="versions" label={t.versionHistory} aria-pressed={aside === 'history'} onClick={() => onAside('history')} /></PmToolbarButton>}
400
+ {!narrow && <span className="pmw-toolbar__history"><PmToolbarButton asChild><PmIconButton small icon="versions" label={historyLabel} aria-pressed={aside === 'history'} onClick={() => onAside('history')} /></PmToolbarButton>{(draftCount > 0 || draftReadFailure) && <PmBadge tone={draftReadFailure ? 'warn' : 'neutral'}>{draftCount || <PmIcon name="warning" />}</PmBadge>}</span>}
358
401
  <span className="pmw-toolbar__divider" aria-hidden="true" />
359
402
  <PmToolbarButton asChild><PmIconButton small icon="eye" label={t.readDocument} disabled={blocked || changingView} onClick={onRead} /></PmToolbarButton>
360
403
  <PmToolbarButton asChild><PmIconButton ref={presentButton} small icon="slides" label={t.present} hint={preparing || changingView ? t.presentationPreparing : timingDrafts ? t.timingDraftPending : blocked ? t.presentationPending : t.presentHint} loading={preparing || changingView} disabled={blocked || changingView} onClick={onPresent} /></PmToolbarButton>
@@ -368,7 +411,7 @@ function DocumentToolbar({ presentButton, framed, onBack, actions, aside, naviga
368
411
  ] : [],
369
412
  ...capabilities?.production !== false ? [{ id: 'production', label: p.title, icon: 'arrange' as const, disabled: busy || !hasStep || changingView }] : [],
370
413
  ...capabilities?.narration !== false ? [{ id: 'narration', label: t.documentNarration, icon: 'captions' as const, disabled: !hasStep }] : [],
371
- { id: 'history', label: t.versionHistory, icon: 'versions' },
414
+ { id: 'history', label: historyLabel, icon: 'versions' },
372
415
  ]} onSelect={id => { if (id === 'undo') void workbench.undo(); else if (id === 'redo') void workbench.redo(); else if (id === 'production') onProduction(); else onAside(id as DocumentAside) }} />}
373
416
  </PmToolbar>
374
417
  )
@@ -409,10 +452,8 @@ function DocumentNotices() {
409
452
  const askFailure = useWorkbenchState(state => (state.pointer ? undefined : state.askFailure))
410
453
  return (
411
454
  <div className="pmw-notices">
412
- {review?.running && <PmNotice tone="accent"><PmMascot size="small" action={review.changes.length > 0 ? 'write' : 'read'} />{t.agentWorking}</PmNotice>}
413
455
  {review && !review.running && review.changes.length > 0 && (
414
456
  <PmNotice tone="accent">
415
- <PmMascot size="small" action="ask" />
416
457
  <span>{t.agentWaiting(review.changes.length)}</span>
417
458
  <span className="pmw-notice__actions">
418
459
  <PmButton small onClick={() => void workbench.rejectReview()}>{t.reject}</PmButton>
@@ -431,7 +472,7 @@ function DocumentNotices() {
431
472
  )
432
473
  }
433
474
 
434
- /** Content that did not display, said plainly, with the AI to fix it and the details for whoever wants them. */
475
+ /** The document's problems in one line above the page, with the AI to fix them; the list itself opens in a dialog. */
435
476
  function ProblemsNotice() {
436
477
  const t = useMessages()
437
478
  const workbench = useWorkbench()
@@ -440,23 +481,25 @@ function ProblemsNotice() {
440
481
  const canRepair = useWorkbenchState(state => state.canRepairDiagnostics)
441
482
  const repairing = useWorkbenchState(state => state.isRepairingDiagnostics)
442
483
  const repairFailure = useWorkbenchState(state => state.diagnosticsRepairFailure)
484
+ const [open, setOpen] = useState(false)
443
485
  if (workbench.client.capabilities?.diagnostics === 'none') return null
444
486
  const problems = (snapshot?.diagnostics ?? []).filter(diagnostic => diagnostic.severity === 'error' && !diagnostic.checkId.startsWith('presmium.workbench.'))
445
487
  if (unavailable) return <PmNotice tone="warn"><span>{t.diagnosticsUnavailable}</span><PmButton small onClick={() => workbench.retryDiagnostics()}>{t.retry}</PmButton></PmNotice>
446
488
  if (problems.length === 0) return repairFailure ? <PmNotice tone="danger">{t.fixFailed(failureReason(t, repairFailure))}</PmNotice> : null
489
+ const repair = canRepair && <PmButton small variant="accent" icon="sparkle" disabled={repairing} onClick={() => void workbench.requestRepairDiagnostics()}>{repairing ? t.fixing : t.fixWithAi}</PmButton>
447
490
  return (
448
491
  <PmNotice tone="warn">
449
492
  <div className="pmw-problems">
450
493
  <div className="pmw-problems__summary">
451
494
  <span>{t.problems(problems.length)}</span>
452
- {canRepair && <PmButton small variant="accent" icon="sparkle" disabled={repairing} onClick={() => void workbench.requestRepairDiagnostics()}>{repairing ? t.fixing : t.fixWithAi}</PmButton>}
495
+ <PmButton small variant="ghost" onClick={() => setOpen(true)}>{t.details}</PmButton>
496
+ {repair}
453
497
  </div>
454
498
  {repairFailure && <p className="pmw-problems__failure">{t.fixFailed(failureReason(t, repairFailure))}</p>}
455
- <details className="pmw-problems__details">
456
- <summary>{t.details}</summary>
457
- <ul>{problems.map(problem => <li key={problem.id}>{problem.message}</li>)}</ul>
458
- </details>
459
499
  </div>
500
+ <PmDialog open={open} label={t.problemsTitle} closeLabel={t.close} actions={repair || undefined} onClose={() => setOpen(false)}>
501
+ <ul className="pmw-problems__list">{problems.map(problem => <li key={problem.id}><p>{problem.message}</p>{problem.hint && <p className="pmw-problems__hint">{problem.hint}</p>}</li>)}</ul>
502
+ </PmDialog>
460
503
  </PmNotice>
461
504
  )
462
505
  }
@@ -4,14 +4,14 @@ import { PmButton, PmDialog, PmField, PmInput, PmNotice, PmSearchList, PmSegment
4
4
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
5
5
  import { documentVoiceStepIds, previewDocumentVoiceChange, resolveDocumentStepVoice } from '../document-voices.ts'
6
6
  import type { DocumentVoiceImpact } from '../document-voices.ts'
7
- import { clearVoiceDraft, keepVoiceDraft, readVoiceDraft, voiceDraftStorageStatus } from '../voice-drafts.ts'
7
+ import { readVoiceDraft, voiceDraftStorageStatus } from '../voice-drafts.ts'
8
8
  import type { VoiceDraft } from '../voice-drafts.ts'
9
9
  import { PRODUCTION_MESSAGES } from '../production-messages.ts'
10
10
  import { VOICE_CLONE_MESSAGES } from '../voice-clone-messages.ts'
11
11
  import { VOICE_MESSAGES, voiceFailure } from '../voice-messages.ts'
12
12
  import { prepareVoiceSnapshot, voiceSnapshotCurrent } from '../voice-snapshot.ts'
13
13
  import type { VoiceSnapshot } from '../voice-snapshot.ts'
14
- import { isAgentChanging } from '../workbench.ts'
14
+ import { isAgentChanging } from '../workbench-state.ts'
15
15
  import { VoiceCloneDialog } from './VoiceCloneDialog.tsx'
16
16
  import { VoicePreviewDialog } from './VoicePreviewDialog.tsx'
17
17
  import { VoiceScopeField } from './VoiceScopeField.tsx'
@@ -26,13 +26,14 @@ export function DocumentVoiceDialog({ stepId, onClose }: { stepId: string, onClo
26
26
  const t = VOICE_MESSAGES[locale], p = PRODUCTION_MESSAGES[locale], c = VOICE_CLONE_MESSAGES[locale]
27
27
  const serviceVersion = useWorkbenchState(state => state.voiceServiceVersion)
28
28
  const identity = useRef(actor!.identity!).current, directory = useRef(actor!.directory).current
29
- const [restored] = useState(() => readVoiceDraft(workbench.client, identity, stepId))
29
+ const [restored, setRestored] = useState(() => readVoiceDraft(workbench.client, identity, stepId))
30
30
  const [draft, setDraft] = useState<VoiceDraft>(() => restored ?? { version: actor!.version!, scope: { kind: 'step', stepId }, source: resolveDocumentStepVoice(actor!.content!, stepId).value ?? null, replaceOverrides: false })
31
31
  const [storageFailed, setStorageFailed] = useState(() => voiceDraftStorageStatus(workbench.client, identity, stepId) !== 'available')
32
32
  const [engineFilter, setEngineFilter] = useState(draft.source?.type === 'tts' ? draft.source.voice.engine : undefined)
33
33
  const [language, setLanguage] = useState(''), [query, setQuery] = useState(''), [catalog, setCatalog] = useState<VoiceCatalogAnswer>()
34
34
  const [catalogBusy, setCatalogBusy] = useState(true), [catalogFailure, setCatalogFailure] = useState<string>(), [reload, setReload] = useState(0)
35
- const [busy, setBusy] = useState(false), [failure, setFailure] = useState<string>(), [review, setReview] = useState<Review>()
35
+ const pending = useRef(false), composing = useRef(false)
36
+ const [busy, renderBusy] = useState(false), [failure, setFailure] = useState<string>(), [review, setReview] = useState<Review>()
36
37
  const [preview, setPreview] = useState<{ quote: VoicePreviewQuote, snapshot: VoiceSnapshot }>(), [cloning, setCloning] = useState(false)
37
38
  const owner = useRef({ active: true, generation: 0 }), request = useRef<AbortController>()
38
39
  useEffect(() => () => { owner.current.active = false; owner.current.generation++; request.current?.abort() }, [])
@@ -57,10 +58,25 @@ export function DocumentVoiceDialog({ stepId, onClose }: { stepId: string, onClo
57
58
  const rateInvalid = draft.rateInput !== undefined && normalizedRate !== undefined && normalizedRate.length > 0 && (!rateRange || !/^\d+(?:\.\d+)?$/.test(normalizedRate) || !Number.isFinite(rate) || rate! < rateRange.min || rate! > rateRange.max)
58
59
  const sourceType = draft.source === null ? 'inherit' : draft.source.type
59
60
  const current = () => owner.current.active && workbench.getState().authoring?.identity === identity
61
+ const unavailable = useRef(false)
62
+ unavailable.current = blocked || cloning || Boolean(preview)
63
+ const setBusy = (value: boolean) => { pending.current = value; renderBusy(value); workbench.refreshAuthoringClientControls() }
64
+ useEffect(() => workbench.production.registerDraftView({ identity, kind: 'voice', has: key => current() && key === stepId,
65
+ blocked: () => composing.current || pending.current || unavailable.current,
66
+ clear: () => {
67
+ const actual = workbench.getState().authoring, content = workbench.getDocument(identity)
68
+ if (!actual?.version || !content) return
69
+ owner.current.generation++; request.current?.abort(); request.current = undefined
70
+ const value: VoiceDraft = { version: actual.version, scope: { kind: 'step', stepId }, source: resolveDocumentStepVoice(content, stepId).value ?? null, replaceOverrides: false }
71
+ setDraft(value); setRestored(undefined); setStorageFailed(false); setReview(undefined); setFailure(undefined)
72
+ setEngineFilter(value.source?.type === 'tts' ? value.source.voice.engine : undefined); setLanguage(''); setQuery('')
73
+ } }), [workbench, identity, stepId])
74
+ useEffect(() => workbench.registerNavigationGuard(() => current() && (composing.current || pending.current || unavailable.current)), [workbench, identity])
75
+ useEffect(() => { workbench.refreshAuthoringClientControls() }, [workbench, blocked, busy, preview, cloning])
60
76
  const edit = (value: VoiceDraft) => {
61
77
  request.current?.abort(); owner.current.generation++
62
78
  setBusy(false); setFailure(undefined); setReview(undefined); setPreview(undefined); workbench.stopAuditions()
63
- setDraft(value); setStorageFailed(!keepVoiceDraft(workbench.client, identity, stepId, value))
79
+ setDraft(value); setStorageFailed(!workbench.production.keepVoiceDraft(identity, stepId, value))
64
80
  }
65
81
  const checkedDraft = (value: VoiceDraft): VoiceDraft => ({ ...value, version: workbench.getState().authoring!.version! })
66
82
  const checkScope = async (value = draft) => {
@@ -73,7 +89,7 @@ export function DocumentVoiceDialog({ stepId, onClose }: { stepId: string, onClo
73
89
  const source = workbench.getState().authoring, latest = workbench.getDocument(identity)
74
90
  if (!source?.version || !source.fingerprint || !latest || source.dirty || source.saving || source.error || source.restored || source.composing) throw new Error('voice-context-changed')
75
91
  const proposal = checkedDraft(value), impact = previewDocumentVoiceChange(latest, proposal.scope, proposal.source, { replaceOverrides: proposal.replaceOverrides })
76
- setDraft(proposal); setStorageFailed(!keepVoiceDraft(workbench.client, identity, stepId, proposal))
92
+ setDraft(proposal); setStorageFailed(!workbench.production.keepVoiceDraft(identity, stepId, proposal))
77
93
  const targets = documentVoiceStepIds(latest, proposal.scope).map(id => { const step = latest.steps[id]!, page = latest.sections[step.sectionId]!; return `${page.title} · ${t.step(latest.sectionOrder.indexOf(page.id) + 1, page.stepOrder.indexOf(id) + 1)}` })
78
94
  setReview({ draft: proposal, impact, scopeLabel: t.scopes[proposal.scope.kind], targets, expected: { identity, version: source.version, fingerprint: source.fingerprint } })
79
95
  } catch (error) { if (current() && generation === owner.current.generation) setFailure(voiceFailure(error, locale)) }
@@ -84,10 +100,10 @@ export function DocumentVoiceDialog({ stepId, onClose }: { stepId: string, onClo
84
100
  const confirmation = review, generation = ++owner.current.generation
85
101
  setBusy(true); setFailure(undefined)
86
102
  try {
87
- const saved = await workbench.applyDocumentVoice(confirmation.draft.scope, confirmation.draft.source, { replaceOverrides: confirmation.draft.replaceOverrides }, confirmation.expected)
103
+ const saved = await workbench.production.applyVoice(confirmation.draft.scope, confirmation.draft.source, { replaceOverrides: confirmation.draft.replaceOverrides }, confirmation.expected)
88
104
  if (!current() || generation !== owner.current.generation) return
89
105
  if (!saved) throw new Error('voice-context-changed')
90
- if (!clearVoiceDraft(workbench.client, identity, stepId, confirmation.draft)) { setStorageFailed(true); setReview(undefined); return }
106
+ if (!workbench.production.clearVoiceDraft(identity, stepId, confirmation.draft)) { setStorageFailed(true); setReview(undefined); return }
91
107
  onClose()
92
108
  } catch (error) { if (current() && generation === owner.current.generation) { setReview(undefined); setFailure(voiceFailure(error, locale)) } }
93
109
  finally { if (current() && generation === owner.current.generation) setBusy(false) }
@@ -109,7 +125,7 @@ export function DocumentVoiceDialog({ stepId, onClose }: { stepId: string, onClo
109
125
  if (!document || !validTarget) return <PmDialog open label={t.settings} closeLabel={t.close} onClose={onClose}><PmNotice tone="warn">{p.draftChanged}</PmNotice></PmDialog>
110
126
  return <>
111
127
  <PmDialog open label={t.settings} closeLabel={t.close} onClose={onClose} footer={<><PmButton onClick={onClose}>{t.close}</PmButton><PmButton loading={busy} disabled={blocked || rateInvalid || draft.source?.type === 'tts' && !draft.source.voice.voice.trim() || draft.scope.kind === 'steps' && !draft.scope.stepIds.length} variant="primary" onClick={() => void checkScope()}>{t.check}</PmButton></>}>
112
- <div className="pmw-voice__form">
128
+ <div className="pmw-voice__form" onCompositionStartCapture={() => { composing.current = true; workbench.refreshAuthoringClientControls() }} onCompositionEndCapture={() => { composing.current = false; workbench.refreshAuthoringClientControls() }}>
113
129
  {restored && <PmNotice tone="accent">{t.draftRecovered}</PmNotice>}
114
130
  {storageFailed && <PmNotice tone="warn">{t.recoveryFailed}</PmNotice>}
115
131
  {failure && <PmNotice tone="danger">{failure}</PmNotice>}
@@ -3,7 +3,7 @@ import { PmButton, PmField } from '../components.tsx'
3
3
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
4
4
  import { resolveDocumentStepVoice } from '../document-voices.ts'
5
5
  import { PRODUCTION_MESSAGES } from '../production-messages.ts'
6
- import { isAgentChanging } from '../workbench.ts'
6
+ import { isAgentChanging } from '../workbench-state.ts'
7
7
  import { DocumentVoiceDialog } from './DocumentVoiceDialog.tsx'
8
8
 
9
9
  /** One current voice and selector, shared by document captions and production. */
@@ -1,8 +1,7 @@
1
1
  import { useEffect, useState } from 'react'
2
- import type { CSSProperties } from 'react'
3
2
  import type { CompileJob, OutputTarget } from '@lincyaw/kernel'
4
3
  import type { IconName } from '@lincyaw/design'
5
- import { PmBadge, PmButton, PmDialog, PmEmpty, PmIcon, PmIconButton, PmMascot, PmNotice } from '../components.tsx'
4
+ import { PmBadge, PmButton, PmDialog, PmEmpty, PmIcon, PmIconButton, PmNotice } from '../components.tsx'
6
5
  import { useMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
7
6
  import { failureReason, timeAgo } from '../messages.ts'
8
7
 
@@ -105,10 +104,6 @@ function JobItem({ job, label, current, onPlay }: { job: CompileJob, label: stri
105
104
  </p>
106
105
  {job.state === 'running' && progress && (
107
106
  <div className="pmw-job__progress">
108
- {/* the kitten runs along the bar to how far the job has come; with no total yet it walks at the start */}
109
- <span className="pmw-job__runner" style={{ '--pmw-job-done': progress.total ? Math.min(1, (progress.done ?? 0) / progress.total) : 0 } as CSSProperties}>
110
- <PmMascot size="small" action={progress.total ? 'run' : 'walk'} />
111
- </span>
112
107
  <progress max={progress.total ?? 1} value={progress.total ? progress.done ?? 0 : undefined} aria-label={label} />
113
108
  <span>{t.jobProgress(t.jobPhases[progress.phase] ?? t.outputLabels[progress.phase] ?? progress.phase, progress.done, progress.total)}</span>
114
109
  </div>