@lincyaw/workbench 0.2.0-rc.47 → 0.2.0-rc.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workbench",
3
- "version": "0.2.0-rc.47",
3
+ "version": "0.2.0-rc.49",
4
4
  "description": "Presmium's workbench panels in React (the documents, a document edited on its rendered page with comments and version history) with the workspace service's client and the preview protocol's workbench side; @lincyaw/dsh places them in presmium studio (experimental)",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -55,8 +55,8 @@
55
55
  "@tiptap/pm": "3.32.0",
56
56
  "katex": "0.18.10",
57
57
  "react-resizable-panels": "4.14.5",
58
- "@lincyaw/kernel": "1.0.0-rc.47",
59
- "@lincyaw/design": "1.0.0-rc.47"
58
+ "@lincyaw/design": "1.0.0-rc.49",
59
+ "@lincyaw/kernel": "1.0.0-rc.49"
60
60
  },
61
61
  "peerDependencies": {
62
62
  "react": "^18.3.1",
@@ -67,6 +67,6 @@
67
67
  "@types/react-dom": "18.3.7",
68
68
  "react": "^18.3.1",
69
69
  "react-dom": "^18.3.1",
70
- "@lincyaw/compiler": "1.0.0-rc.47"
70
+ "@lincyaw/compiler": "1.0.0-rc.49"
71
71
  }
72
72
  }
@@ -1,4 +1,4 @@
1
- import { authoringClientResultFits, randomUUID } 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'
@@ -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,8 +104,8 @@ 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()
@@ -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,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
  }
@@ -2,7 +2,7 @@ import { isRecord, randomUUID, validateDocument } from '@lincyaw/kernel'
2
2
  import type { TeachingDocument } from '@lincyaw/kernel'
3
3
  import { DocumentDraftStore } from './document-draft-store.ts'
4
4
  import { sha256 as tokenOf } from './sha256.ts'
5
- import type { DraftStoreCommit } from './document-draft-store.ts'
5
+ import type { DraftStoreCommit, DraftStoreOperation } from './document-draft-store.ts'
6
6
 
7
7
  export interface DocumentDraftReference { id: string, revision: number, token: string }
8
8
  export interface DocumentDraft {
@@ -54,24 +54,28 @@ export class DocumentDrafts {
54
54
  #store?: DocumentDraftStore
55
55
  #identity?: string
56
56
  #closed = false
57
+ #revision = 0
58
+ get revision(): number { return this.#revision }
59
+ #touch(): void { if (!this.#closed) { this.#revision++; this.#changed?.() } }
57
60
  readonly #changed?: () => void
58
61
  constructor(changed?: () => void) { this.#changed = changed }
59
62
 
60
63
  #storage(identity: string): DocumentDraftStore | undefined {
61
64
  if (this.#closed || this.#identity !== undefined && this.#identity !== identity) return
62
65
  this.#identity = identity
63
- return this.#store ??= new DocumentDraftStore(identity, this.#changed)
66
+ return this.#store ??= new DocumentDraftStore(identity, () => this.#touch())
64
67
  }
65
68
  matches(identity: string, key: string | null): boolean { return key === null || key.startsWith(prefix(identity)) || key.startsWith(markerPrefix(identity)) }
66
69
 
67
- async read(identity: string, documentId: string): Promise<{ records: RecoverableDocumentDraft[], failed: boolean }> {
70
+ async read(identity: string, documentId: string, signal?: AbortSignal): Promise<{ records: RecoverableDocumentDraft[], failed: boolean }> {
71
+ signal?.throwIfAborted()
68
72
  const store = this.#storage(identity), values: { key: string, raw: unknown, source: 'durable' | 'rescue' }[] = []
69
73
  let failed = false, durable = new Map<string, unknown>()
70
74
  if (!store) return { records: [], failed: true }
71
75
  try {
72
- durable = await store.read([prefix(identity), markerPrefix(identity)])
76
+ durable = await store.read([prefix(identity), markerPrefix(identity)], signal, signal ? 2048 : undefined)
73
77
  for (const [key, raw] of durable) if (key.startsWith(prefix(identity))) values.push({ key, raw, source: 'durable' })
74
- } catch { failed = true }
78
+ } catch { signal?.throwIfAborted(); failed = true }
75
79
  // Existing localStorage input is never removed or silently treated as a strict commit.
76
80
  try {
77
81
  const keys: string[] = []
@@ -83,9 +87,10 @@ export class DocumentDrafts {
83
87
  const raw = localStorage.getItem(key)
84
88
  if (raw !== null) values.push({ key, raw, source: 'rescue' })
85
89
  }
86
- } catch { failed = true }
90
+ } catch { signal?.throwIfAborted(); failed = true }
87
91
  const records = new Map<string, RecoverableDocumentDraft>()
88
92
  for (const { key, raw, source } of values) {
93
+ signal?.throwIfAborted()
89
94
  try {
90
95
  if (typeof raw !== 'string' || raw.length > MAX_CHARS) throw new Error('document-draft-size')
91
96
  const value: unknown = JSON.parse(raw)
@@ -101,8 +106,9 @@ export class DocumentDrafts {
101
106
  const id = JSON.stringify([value.id, value.revision, token])
102
107
  if (!records.has(id)) records.set(id, { ...draft, format: 2, identity, id: value.id, owner: value.owner, revision: value.revision, updatedAt: value.updatedAt, token, source,
103
108
  owned: source === 'durable' && value.owner === this.#owner && (this.#owned.get(value.id)?.raw === raw || store.owns(key, raw)) })
104
- } catch { failed = true }
109
+ } catch { signal?.throwIfAborted(); failed = true }
105
110
  }
111
+ signal?.throwIfAborted()
106
112
  return { records: [...records.values()], failed }
107
113
  }
108
114
 
@@ -125,21 +131,25 @@ export class DocumentDrafts {
125
131
  const commit = this.#store!.put(keyOf(identity, next.record.id), next.raw)
126
132
  if (!commit) return
127
133
  this.#owned.set(next.record.id, { identity, revision: next.record.revision, raw: next.raw })
134
+ void commit.done.then(() => this.#touch())
128
135
  if (previous && previous.id !== next.record.id) this.archive(previous)
129
136
  return { ...commit, record: next.record, clearing: false }
130
137
  }
131
138
 
132
- async fork(identity: string, draft: DocumentDraft): Promise<StoredDocumentDraft | undefined> {
139
+ async fork(identity: string, draft: DocumentDraft, operation?: DraftStoreOperation): Promise<StoredDocumentDraft | undefined> {
133
140
  const next = this.#record(identity, draft)
134
- if (!next || !await this.#store!.create(keyOf(identity, next.record.id), next.raw)) return
141
+ if (!next || !await this.#store!.create(keyOf(identity, next.record.id), next.raw, operation)) return
135
142
  this.#owned.set(next.record.id, { identity, revision: next.record.revision, raw: next.raw })
143
+ this.#touch()
136
144
  return next.record
137
145
  }
138
146
 
139
147
  /** Immutable, revision-specific markers never delete another tab's newer record. */
140
- async settle(identity: string, values: readonly DocumentDraftReference[]): Promise<boolean> {
148
+ async settle(identity: string, values: readonly DocumentDraftReference[], operation?: DraftStoreOperation): Promise<boolean> {
141
149
  const store = this.#storage(identity)
142
- return Boolean(store && await store.mark(values.map(value => [settledKey(identity, value), value.token])))
150
+ const done = Boolean(store && await store.mark(values.map(value => [settledKey(identity, value), value.token]), operation))
151
+ if (done) this.#touch()
152
+ return done
143
153
  }
144
154
 
145
155
  remove(identity: string, record: StoredDocumentDraft, origins: readonly DocumentDraftReference[]): DocumentDraftCommit | undefined {
@@ -147,7 +157,7 @@ export class DocumentDrafts {
147
157
  if (!store || !owned || owned.identity !== identity || record.owner !== this.#owner || owned.revision !== record.revision) return
148
158
  const commit = store.remove(keyOf(identity, record.id), origins.map(value => [settledKey(identity, value), value.token]))
149
159
  if (!commit) return
150
- void commit.done.then(result => { if (result === 'committed' && this.#owned.get(record.id)?.revision === record.revision) this.#owned.delete(record.id) })
160
+ void commit.done.then(result => { if (result === 'committed' && this.#owned.get(record.id)?.revision === record.revision) this.#owned.delete(record.id); this.#touch() })
151
161
  return { ...commit, record, clearing: true }
152
162
  }
153
163
 
@@ -1,7 +1,8 @@
1
1
  import { hasRole, isRecord, randomUUID, validateDocument } from '@lincyaw/kernel'
2
- import type { DocumentAnswer, DocumentChangeAnswer, DocumentImageImportAnswer, DocumentIssue, Member, TeachingDocument } from '@lincyaw/kernel'
2
+ import type { CanonicalSource, ClientBodyDraftReference, DocumentAnswer, DocumentChangeAnswer, DocumentImageImportAnswer, DocumentIssue, Member, TeachingDocument } from '@lincyaw/kernel'
3
3
  import { WorkspaceServerError } from './workspace-client.ts'
4
4
  import type { WorkspaceClient } from './workspace-client.ts'
5
+ import { waitForDraft } from './document-draft-store.ts'
5
6
  import { DocumentDrafts } from './document-drafts.ts'
6
7
  import { sha256 } from './sha256.ts'
7
8
  import type { DocumentDraftChoice, DocumentDraftCommit, DocumentDraftReference, StoredDocumentDraft } from './document-drafts.ts'
@@ -29,7 +30,10 @@ export interface DocumentSessionState {
29
30
  recoveryDrafts?: DocumentDraftChoice[]
30
31
  recoveryChanged?: boolean
31
32
  }
33
+ export interface DocumentDraftOperation { signal: AbortSignal, guard(): void, source: CanonicalSource, localDraft?: true }
34
+ export interface BodyDraftCandidate { draft: DocumentDraftReference & { current: boolean }, content: TeachingDocument, storage: 'durable' | 'rescue' | 'session', updatedAt: number, baseVersion: string, composing: boolean, pendingSubmission: boolean }
32
35
  interface Slot {
36
+ observedSource?: CanonicalSource
33
37
  state: DocumentSessionState
34
38
  read: number
35
39
  compositions: Set<string>
@@ -56,6 +60,7 @@ interface Slot {
56
60
  }
57
61
 
58
62
  const serialize = (value: unknown) => JSON.stringify(value, (_, entry) => entry && typeof entry === 'object' && !Array.isArray(entry) ? Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a.localeCompare(b))) : entry)
63
+ const sameSource = (a: CanonicalSource | undefined, b: CanonicalSource) => a?.documentId === b.documentId && a.version === b.version && a.fingerprint === b.fingerprint
59
64
  /** Non-body authoring changes keep native selection, comment drafts and body history. */
60
65
  function keepsEditorContent(before: TeachingDocument, after: TeachingDocument): boolean {
61
66
  const editing = ({ assets: _assets, production: _production, comments: _comments, definitions: _definitions, ...document }: TeachingDocument) => {
@@ -155,7 +160,7 @@ export class DocumentSession {
155
160
  const baseHash = await digest(answer.content)
156
161
  if (this.#disposed || this.#active !== directory || opening !== this.#opening) return
157
162
  const drafts = new DocumentDrafts(() => { if (slot && !this.#disposed) void this.#readDrafts(slot) })
158
- slot = { input: 0, read: 0, compositions: new Set(), drafts, baseHash, baseContent: structuredClone(answer.content), storage: `presmium.document.v1:${JSON.stringify([info.root, answer.content.id])}`, state: { directory, member: info.member, identity: JSON.stringify([info.root, answer.content.id]), content: answer.content, version: answer.version, fingerprint: answer.fingerprint, loading: true, dirty: false, saving: false, restored: false, composing: false, storageFailure: false, reset: 0, issues: answer.issues } }
163
+ slot = { observedSource: this.#source(answer), input: 0, read: 0, compositions: new Set(), drafts, baseHash, baseContent: structuredClone(answer.content), storage: `presmium.document.v1:${JSON.stringify([info.root, answer.content.id])}`, state: { directory, member: info.member, identity: JSON.stringify([info.root, answer.content.id]), content: answer.content, version: answer.version, fingerprint: answer.fingerprint, loading: true, dirty: false, saving: false, restored: false, composing: false, storageFailure: false, reset: 0, issues: answer.issues } }
159
164
  this.#slots.set(directory, slot)
160
165
  await this.#restore(slot, answer)
161
166
  } else {
@@ -206,23 +211,76 @@ export class DocumentSession {
206
211
  for (const changed of slot.saveWaiters ?? []) changed()
207
212
  if (this.#active === slot.state.directory && this.#slots.get(slot.state.directory) === slot) this.#changed({ ...slot.state })
208
213
  }
214
+ bodyDraftRevision(): number { const slot = this.#active === undefined ? undefined : this.#slots.get(this.#active); return slot?.drafts.revision ?? 0 }
215
+ bodyDraftCapabilities(): { read: boolean, mutate: boolean, current: boolean } {
216
+ const slot = this.#active === undefined ? undefined : this.#slots.get(this.#active)
217
+ const read = Boolean(slot?.state.identity && slot.state.content && slot.state.version && !slot.state.loading && !this.#disposed)
218
+ return { read, mutate: Boolean(read && slot && !this.#readOnly(slot) && !slot.state.composing && !slot.flight && !slot.assetFlight && !slot.state.recovering),
219
+ current: Boolean(slot && (slot.state.dirty || slot.state.restored || slot.state.composing || slot.state.error)) }
220
+ }
221
+ async readBodyDrafts(signal: AbortSignal, selected?: ClientBodyDraftReference): Promise<{ candidates: BodyDraftCandidate[], coverage: 'stored-and-session' | 'partial', guard(): void }> {
222
+ const slot = this.#active === undefined ? undefined : this.#slots.get(this.#active)
223
+ if (!slot || !this.bodyDraftCapabilities().read || !slot.state.identity || !slot.state.content || !slot.state.version) throw new Error('client-body-drafts-unavailable')
224
+ const identity = slot.state.identity, documentId = slot.state.content.id, input = slot.input, read = slot.read, content = slot.state.content, version = slot.state.version,
225
+ revision = slot.drafts.revision, composing = slot.state.composing, source = JSON.stringify(slot.observedSource), own = slot.draft, flight = slot.flight, assetFlight = slot.assetFlight
226
+ const guard = () => {
227
+ signal.throwIfAborted()
228
+ if (this.#disposed || this.#active !== slot.state.directory || this.#slots.get(slot.state.directory) !== slot || slot.state.identity !== identity
229
+ || slot.input !== input || slot.read !== read || slot.state.content !== content || slot.state.version !== version || slot.state.composing !== composing
230
+ || JSON.stringify(slot.observedSource) !== source || slot.draft !== own || slot.flight !== flight || slot.assetFlight !== assetFlight || slot.drafts.revision !== revision) throw new Error('client-body-drafts-changed')
231
+ }
232
+ guard()
233
+ const stored = await slot.drafts.read(identity, documentId, signal)
234
+ guard()
235
+ let candidates: BodyDraftCandidate[] = stored.records.filter(record => !(record.owned && record.id === slot.draft?.id)).map(record => ({
236
+ draft: { id: record.id, revision: record.revision, token: record.token, current: false }, content: record.content, storage: record.source,
237
+ updatedAt: record.updatedAt, baseVersion: record.baseVersion, composing: Boolean(record.composing), pendingSubmission: false,
238
+ }))
239
+ if (this.bodyDraftCapabilities().current) {
240
+ const token = await sha256(JSON.stringify({ domain: 'body-current', identity, id: slot.draft?.id ?? 'current', content, version, input, composing, pendingHash: slot.pendingHash }))
241
+ guard()
242
+ candidates.push({ draft: { id: slot.draft?.id ?? 'current', revision: input + 1, token, current: true }, content: structuredClone(content),
243
+ storage: stored.records.some(record => record.source === 'durable' && record.owned && record.id === slot.draft?.id && record.revision === slot.draft.revision && record.baseVersion === version && Boolean(record.composing) === composing && JSON.stringify(record.content) === JSON.stringify(content)) ? 'durable' : 'session', updatedAt: slot.draft?.updatedAt ?? 0,
244
+ baseVersion: version, composing, pendingSubmission: Boolean(flight || assetFlight) })
245
+ }
246
+ candidates.sort((a, b) => a.draft.token.localeCompare(b.draft.token))
247
+ if (selected) {
248
+ candidates = candidates.filter(value => value.draft.token === selected)
249
+ if (candidates.length !== 1) throw new Error('client-body-drafts-changed')
250
+ }
251
+ guard()
252
+ return { candidates, coverage: stored.failed ? 'partial' : 'stored-and-session', guard }
253
+ }
254
+
255
+ #source(answer: DocumentAnswer): CanonicalSource { return { documentId: answer.content.id, version: answer.version, fingerprint: answer.fingerprint } }
256
+ canonicalSource(): CanonicalSource | undefined { const slot = this.#active === undefined ? undefined : this.#slots.get(this.#active); return slot?.observedSource && { ...slot.observedSource } }
257
+ #checkOperation(operation?: DocumentDraftOperation, answer?: DocumentAnswer): void {
258
+ operation?.signal.throwIfAborted(); operation?.guard()
259
+ if (operation && !operation.localDraft && answer && !sameSource(this.#source(answer), operation.source)) throw new Error('client-source-changed')
260
+ }
209
261
  #error(error: unknown): string { return error instanceof WorkspaceServerError ? error.answer.error ?? 'document-request-failed' : 'document-disconnected' }
210
262
  #readOnly(slot: Slot): boolean { return this.#client.capabilities?.readOnly === true || Boolean(slot.state.member && !hasRole(slot.state.member, 'editor')) }
211
263
  #issues(error: unknown): DocumentIssue[] { const value = error instanceof WorkspaceServerError ? (error.answer as { issues?: DocumentIssue[] }).issues : undefined; return Array.isArray(value) ? value : [] }
212
264
 
213
- async refresh(directory = this.#active): Promise<void> {
265
+ async refresh(directory = this.#active, operation?: DocumentDraftOperation): Promise<void> {
214
266
  if (directory === undefined) return
215
267
  const slot = this.#slots.get(directory)
216
268
  if (!slot) { if (directory === this.#active) await this.open(directory); return }
217
- if (slot.flight || slot.assetFlight) { slot.refreshed = true; return }
218
- const read = ++slot.read, current = () => slot.read === read && this.#slots.get(directory) === slot
269
+ if (slot.flight || slot.assetFlight) { slot.refreshed = true; if (operation) throw new Error('client-body-drafts-changed'); return }
270
+ const read = ++slot.read, current = () => {
271
+ const matches = slot.read === read && this.#slots.get(directory) === slot
272
+ if (operation && !matches) throw new Error('client-body-drafts-changed')
273
+ return matches
274
+ }
219
275
  try {
220
- const answer = await this.#client.readDocument(directory)
276
+ const answer = await this.#client.readDocument(directory, operation?.signal)
221
277
  if (!current()) return
222
- if (slot.flight || slot.assetFlight) { slot.refreshed = true; return }
223
- await this.#adopt(slot, answer, current)
278
+ if (slot.flight || slot.assetFlight) { slot.refreshed = true; if (operation) throw new Error('client-body-drafts-changed'); return }
279
+ this.#checkOperation(operation, answer)
280
+ await this.#adopt(slot, answer, () => { this.#checkOperation(operation); return current() })
224
281
  if (current()) { this.#persist(slot); this.#emit(slot); void this.#readDrafts(slot) }
225
282
  } catch (error) {
283
+ if (operation) throw error
226
284
  if (current()) { slot.state = { ...slot.state, error: this.#error(error), issues: this.#issues(error) }; this.#emit(slot) }
227
285
  }
228
286
  }
@@ -230,6 +288,7 @@ export class DocumentSession {
230
288
  async #adopt(slot: Slot, answer: DocumentAnswer, current = () => true): Promise<void> {
231
289
  if (!current()) return
232
290
  if (answer.content.id !== slot.state.content?.id) { slot.state = { ...slot.state, error: 'document-identity-changed' }; return }
291
+ slot.observedSource = this.#source(answer)
233
292
  if (answer.version === slot.state.version) {
234
293
  if (answer.fingerprint !== slot.state.fingerprint) slot.state = { ...slot.state, fingerprint: answer.fingerprint, issues: answer.issues }
235
294
  return
@@ -261,6 +320,7 @@ export class DocumentSession {
261
320
  const reset = slot.state.reset + (keepsEditorContent(slot.state.content!, answer.content) ? 0 : 1)
262
321
  slot.baseHash = remoteHash
263
322
  slot.baseContent = structuredClone(answer.content)
323
+ slot.observedSource = this.#source(answer)
264
324
  slot.state = { ...slot.state, version: answer.version, fingerprint: answer.fingerprint, content: answer.content, reset, error: undefined, issues: answer.issues }
265
325
  }
266
326
 
@@ -304,37 +364,49 @@ export class DocumentSession {
304
364
  this.#persist(slot); this.#emit(slot)
305
365
  }
306
366
 
307
- async #save(slot: Slot, immediate = false): Promise<void> {
367
+ async #save(slot: Slot, immediate = false, operation?: DocumentDraftOperation): Promise<void> {
308
368
  if (immediate) { clearTimeout(slot.timer); slot.timer = undefined }
309
369
  else if (slot.timer !== undefined) return
310
370
  if (this.#readOnly(slot) || slot.flight || slot.assetFlight || !slot.state.dirty || slot.state.composing || slot.state.restored || slot.state.error || !slot.state.content || !slot.state.version) return
371
+ const check = () => {
372
+ this.#checkOperation(operation)
373
+ if (operation && (slot.state.version !== operation.source.version || !sameSource(slot.observedSource, operation.source))) throw new Error('client-source-changed')
374
+ }
375
+ check()
311
376
  slot.read++
312
377
  const flight = { id: randomUUID(), input: slot.input, content: structuredClone(slot.state.content), baseVersion: slot.state.version, hash: undefined as string | undefined }
313
378
  slot.flight = flight
379
+ let completed = false
314
380
  slot.state = { ...slot.state, saving: true }; this.#emit(slot)
315
381
  try {
316
382
  flight.hash = await digest(flight.content)
383
+ check()
384
+ if (operation && (slot.input !== flight.input || slot.state.composing)) throw new Error('client-body-drafts-changed')
317
385
  slot.pendingHash = flight.hash
318
386
  this.#persist(slot)
319
- const answer = await this.#client.changeDocument(slot.state.directory, { id: flight.id, baseDocumentVersion: flight.baseVersion, replacement: flight.content })
387
+ const answer = await this.#client.changeDocument(slot.state.directory, { id: flight.id, baseDocumentVersion: flight.baseVersion, replacement: flight.content }, operation?.signal)
320
388
  if (answer.changeId !== flight.id || answer.document !== slot.state.directory || answer.content.id !== flight.content.id) throw new Error('document-confirmation')
321
389
  this.#ack(slot, flight, answer)
390
+ completed = true
322
391
  } catch (error) {
323
- if (this.#error(error) === 'document-version-changed' && !slot.state.composing) {
392
+ if (!operation && this.#error(error) === 'document-version-changed' && !slot.state.composing) {
324
393
  try {
325
394
  await this.#adopt(slot, await this.#client.readDocument(slot.state.directory))
326
395
  slot.state = { ...slot.state, saving: false }
327
396
  } catch (refreshError) { slot.state = { ...slot.state, saving: false, error: this.#error(refreshError), issues: this.#issues(refreshError) } }
328
397
  } else slot.state = { ...slot.state, saving: false, error: this.#error(error), issues: this.#issues(error) }
398
+ if (operation) { slot.state = { ...slot.state, restored: true }; throw error }
329
399
  } finally {
330
400
  if (slot.flight === flight) slot.flight = undefined
331
401
  this.#persist(slot); this.#emit(slot)
332
402
  void this.#readDrafts(slot)
333
- if (slot.refreshed) { slot.refreshed = false; await this.refresh(slot.state.directory) }
334
- if (!slot.state.error) void this.#save(slot)
403
+ if (slot.refreshed && (!operation || completed)) { slot.refreshed = false; await this.refresh(slot.state.directory) }
404
+ if (!operation && !slot.state.error) void this.#save(slot)
405
+ else if (operation && completed && slot.input !== flight.input && !slot.state.error) this.#schedule(slot)
335
406
  }
336
407
  }
337
408
  #ack(slot: Slot, flight: NonNullable<Slot['flight']>, answer: DocumentChangeAnswer): void {
409
+ slot.observedSource = this.#source(answer)
338
410
  slot.baseHash = flight.hash!
339
411
  slot.baseContent = structuredClone(answer.content)
340
412
  slot.pendingHash = undefined
@@ -356,6 +428,7 @@ export class DocumentSession {
356
428
  if (!same) for (const [id, asset] of added) content.assets[id] = structuredClone(asset)
357
429
  slot.baseHash = baseHash
358
430
  slot.baseContent = structuredClone(answer.content)
431
+ slot.observedSource = this.#source(answer)
359
432
  slot.state = { ...slot.state, content, version: answer.version, fingerprint: answer.fingerprint, dirty: !same, error: undefined, issues: answer.issues }
360
433
  return true
361
434
  }
@@ -372,6 +445,7 @@ export class DocumentSession {
372
445
  slot.baseHash = baseHash
373
446
  slot.baseContent = structuredClone(answer.content)
374
447
  slot.pendingHash = undefined
448
+ slot.observedSource = this.#source(answer)
375
449
  slot.state = { ...slot.state, content: structuredClone(checked.document), version: answer.version, fingerprint: answer.fingerprint,
376
450
  dirty: slot.input !== input || slot.state.composing || serialize(content) !== serialize(answer.content), error: undefined, issues: answer.issues }
377
451
  return true
@@ -472,39 +546,58 @@ export class DocumentSession {
472
546
  }
473
547
  }
474
548
 
475
- async retry(): Promise<void> {
549
+ async retry(operation?: DocumentDraftOperation): Promise<void> {
476
550
  if (this.#disposed || this.#active === undefined) return
477
551
  const slot = this.#slots.get(this.#active)
478
552
  if (!slot) { await this.open(this.#active); return }
479
553
  if (slot.flight || slot.assetFlight || slot.state.composing) return
480
- const previousError = slot.state.error
481
- slot.state = { ...slot.state, restored: false, error: undefined }
482
- await this.refresh(slot.state.directory)
483
- if (slot.state.error) { if (!previousError) this.#emit(slot); return }
484
- await this.#save(slot, true)
554
+ this.#checkOperation(operation)
555
+ const previousError = slot.state.error, restored = slot.state.restored, input = slot.input
556
+ if (!operation) slot.state = { ...slot.state, restored: false, error: undefined }
557
+ try {
558
+ await this.refresh(slot.state.directory, operation)
559
+ this.#checkOperation(operation)
560
+ if (operation && slot.input !== input) throw new Error('client-body-drafts-changed')
561
+ if (operation) slot.state = { ...slot.state, restored: false, error: undefined }
562
+ if (slot.state.error) { if (!previousError) this.#emit(slot); return }
563
+ await this.#save(slot, true, operation)
564
+ } catch (error) {
565
+ if (operation && slot.input === input && this.#slots.get(slot.state.directory) === slot) { slot.state = { ...slot.state, restored: restored || slot.state.restored, error: slot.state.error ?? previousError }; this.#emit(slot) }
566
+ throw error
567
+ }
485
568
  }
486
- async discard(): Promise<void> {
569
+ async discard(operation?: DocumentDraftOperation): Promise<boolean | void> {
487
570
  const slot = this.#active === undefined ? undefined : this.#slots.get(this.#active)
488
571
  if (!slot || slot.flight || slot.assetFlight || slot.state.composing) return
572
+ const pendingSave = slot.timer !== undefined
573
+ clearTimeout(slot.timer); slot.timer = undefined
574
+ let discarded = false
489
575
  const directory = slot.state.directory, identity = slot.state.identity, documentId = slot.state.content?.id, input = slot.input, read = ++slot.read
490
- const current = () => !this.#disposed && this.#slots.get(directory) === slot && slot.read === read && slot.input === input
491
- && slot.state.identity === identity && !slot.state.composing && !slot.flight && !slot.assetFlight
576
+ const current = () => { this.#checkOperation(operation); return !this.#disposed && this.#slots.get(directory) === slot && slot.read === read && slot.input === input
577
+ && slot.state.identity === identity && !slot.state.composing && !slot.flight && !slot.assetFlight }
492
578
  try {
493
- const answer = await this.#client.readDocument(directory)
579
+ const answer = await this.#client.readDocument(directory, operation?.signal)
494
580
  if (!current()) return
495
581
  if (answer.document !== directory || answer.content.id !== documentId) {
496
582
  slot.state = { ...slot.state, error: 'document-identity-changed' }; this.#emit(slot)
497
583
  return
498
584
  }
585
+ this.#checkOperation(operation, answer)
499
586
  const baseHash = await digest(answer.content)
587
+ this.#checkOperation(operation)
500
588
  if (!current()) return
589
+ slot.observedSource = this.#source(answer)
590
+ discarded = true
501
591
  slot.input++; slot.baseHash = baseHash
502
592
  slot.pendingHash = undefined
503
593
  slot.compositions.clear()
504
594
  slot.state = { ...slot.state, content: answer.content, version: answer.version, fingerprint: answer.fingerprint, dirty: false, restored: false, composing: false, reset: slot.state.reset + 1, error: undefined, issues: answer.issues }
505
595
  this.#persist(slot); this.#emit(slot)
596
+ if (operation && slot.backup) await waitForDraft(slot.backup.done, operation.signal)
506
597
  void this.#readDrafts(slot)
507
- } catch (error) { if (current()) { slot.state = { ...slot.state, error: this.#error(error) }; this.#emit(slot) } }
598
+ return true
599
+ } catch (error) { if (operation) throw error; if (current()) { slot.state = { ...slot.state, error: this.#error(error) }; this.#emit(slot) } }
600
+ finally { if (!discarded && pendingSave && this.#slots.get(directory) === slot && slot.input === input && slot.timer === undefined) this.#schedule(slot) }
508
601
  }
509
602
  async flush(signal?: AbortSignal): Promise<void> {
510
603
  signal?.throwIfAborted()
@@ -613,7 +706,7 @@ export class DocumentSession {
613
706
  }
614
707
 
615
708
  /** Selecting a candidate never writes the source or replaces this tab's only snapshot. */
616
- async recoverDraft(value: DocumentDraftReference): Promise<void> {
709
+ async recoverDraft(value: DocumentDraftReference, request?: DocumentDraftOperation): Promise<'restored' | 'already-saved' | void> {
617
710
  const slot = this.#active === undefined ? undefined : this.#slots.get(this.#active)
618
711
  if (slot && this.#readOnly(slot)) return
619
712
  if (!slot?.state.identity || !slot.state.content || slot.state.loading || slot.flight || slot.assetFlight || slot.state.composing || this.#disposed) return
@@ -623,21 +716,25 @@ export class DocumentSession {
623
716
  clearTimeout(slot.timer); slot.timer = undefined
624
717
  let adopted = false
625
718
  let protectedRecord: { id?: string, revision?: number } | undefined
626
- const current = () => !this.#disposed && this.#active === slot.state.directory && this.#slots.get(slot.state.directory) === slot && slot.state.identity === identity && slot.read === read && slot.input === input && slot.recoveryOperation === operation
627
- && !slot.state.composing && !slot.flight && !slot.assetFlight && (!protectedRecord || slot.draft?.id === protectedRecord.id && slot.draft?.revision === protectedRecord.revision)
719
+ const current = () => { this.#checkOperation(request); return !this.#disposed && this.#active === slot.state.directory && this.#slots.get(slot.state.directory) === slot && slot.state.identity === identity && slot.read === read && slot.input === input && slot.recoveryOperation === operation
720
+ && !slot.state.composing && !slot.flight && !slot.assetFlight && (!protectedRecord || slot.draft?.id === protectedRecord.id && slot.draft?.revision === protectedRecord.revision) }
628
721
  slot.state = { ...slot.state, recovering: true, recoveryChanged: false }; this.#emit(slot)
629
722
  try {
723
+ this.#checkOperation(request)
630
724
  if (!this.#persist(slot)) { this.#emit(slot); return }
631
725
  const backup = slot.backup
632
- if (backup && await backup.done !== 'committed') return
726
+ if (backup && await waitForDraft(backup.done, request?.signal) !== 'committed') return
633
727
  if (!current()) return
634
728
  protectedRecord = { id: slot.draft?.id, revision: slot.draft?.revision }
635
- const candidate = (await slot.drafts.read(identity, documentId)).records.find(record => record.id === value.id && record.revision === value.revision && record.token === value.token)
729
+ const candidate = (await slot.drafts.read(identity, documentId, request?.signal)).records.find(record => record.id === value.id && record.revision === value.revision && record.token === value.token)
636
730
  if (!current()) return
731
+ this.#checkOperation(request)
637
732
  if (!candidate) { slot.state = { ...slot.state, recoveryChanged: true }; return }
638
- const answer = await this.#client.readDocument(slot.state.directory)
733
+ const answer = await this.#client.readDocument(slot.state.directory, request?.signal)
639
734
  if (!current()) return
640
735
  if (answer.document !== slot.state.directory || answer.content.id !== documentId) { slot.state = { ...slot.state, error: 'document-identity-changed' }; return }
736
+ this.#checkOperation(request, answer)
737
+ slot.observedSource = this.#source(answer)
641
738
  // Older LAN HTTP drafts stored canonical JSON in place of a SHA-256 fingerprint.
642
739
  const [localHash, remoteHash, candidateBaseHash, pendingHash] = await Promise.all([
643
740
  digest(candidate.content), digest(answer.content),
@@ -645,21 +742,24 @@ export class DocumentSession {
645
742
  candidate.pendingHash?.startsWith('json:') ? sha256(candidate.pendingHash.slice(5)) : candidate.pendingHash,
646
743
  ])
647
744
  if (!current()) return
745
+ this.#checkOperation(request)
648
746
  const origins = [...new Map([...(candidate.origins ?? []), { id: candidate.id, revision: candidate.revision, token: candidate.token }].map(value => [JSON.stringify([value.id, value.revision, value.token]), value])).values()]
649
747
  if (localHash === remoteHash && !candidate.composing) {
650
- const settled = await slot.drafts.settle(identity, origins)
748
+ const settled = await slot.drafts.settle(identity, origins, request && { ...request, guard: () => { if (!current()) throw new Error('client-body-drafts-changed') } })
651
749
  if (!current()) return
652
750
  slot.persistFailure = !settled
653
- return
751
+ if (!settled) return
752
+ return 'already-saved'
654
753
  }
655
754
  const conflict = answer.version !== candidate.baseVersion && remoteHash !== candidateBaseHash && remoteHash !== pendingHash
656
755
  const version = remoteHash === pendingHash || remoteHash === candidateBaseHash ? answer.version : candidate.baseVersion
657
756
  const baseHash = remoteHash === pendingHash ? remoteHash : candidateBaseHash
658
757
  const record = await slot.drafts.fork(identity, { content: candidate.content, baseVersion: version, baseHash, input: input + 1,
659
- pendingHash, composing: Boolean(candidate.composing), origins })
758
+ pendingHash, composing: Boolean(candidate.composing), origins }, request && { ...request, guard: () => { if (!current()) throw new Error('client-body-drafts-changed') } })
660
759
  if (!current()) { if (record) slot.drafts.archive(record); return }
661
760
  if (!record) { slot.persistFailure = true; slot.state = { ...slot.state, storageFailure: true }; return }
662
761
  clearTimeout(slot.timer); slot.timer = undefined
762
+ this.#checkOperation(request)
663
763
  if (slot.draft) slot.drafts.archive(slot.draft)
664
764
  slot.input = input + 1; slot.baseHash = baseHash; slot.pendingHash = pendingHash; slot.draft = record; slot.draftOrigins = origins
665
765
  slot.backup = undefined; slot.persistFailure = false
@@ -668,7 +768,9 @@ export class DocumentSession {
668
768
  slot.state = { ...slot.state, content: candidate.content, version, fingerprint: answer.fingerprint, dirty: true, restored: true, composing: false,
669
769
  backupPending: false, storageFailure: slot.legacyFailure === 'write', reset: slot.state.reset + 1,
670
770
  error: conflict ? 'document-version-changed' : candidate.composing ? 'document-composition-interrupted' : undefined, issues: answer.issues }
771
+ return 'restored'
671
772
  } catch (error) {
773
+ if (request) throw error
672
774
  if (current()) slot.state = { ...slot.state, error: this.#error(error), issues: this.#issues(error) }
673
775
  } finally {
674
776
  if (!this.#disposed && this.#slots.get(slot.state.directory) === slot && slot.state.identity === identity && slot.recoveryOperation === operation) {
@@ -678,25 +780,28 @@ export class DocumentSession {
678
780
  }
679
781
  }
680
782
 
681
- async forgetDraft(value: DocumentDraftReference): Promise<void> {
783
+ async forgetDraft(value: DocumentDraftReference, request?: DocumentDraftOperation): Promise<boolean | void> {
682
784
  const slot = this.#active === undefined ? undefined : this.#slots.get(this.#active)
683
785
  if (!slot?.state.identity || !slot.state.content || slot.state.recovering || slot.flight || slot.assetFlight || slot.state.composing || this.#disposed) return
684
786
  const identity = slot.state.identity, documentId = slot.state.content.id, input = slot.input, read = slot.read
685
787
  const operation = slot.recoveryOperation = (slot.recoveryOperation ?? 0) + 1
686
- const current = () => !this.#disposed && this.#active === slot.state.directory && this.#slots.get(slot.state.directory) === slot && slot.state.identity === identity && slot.input === input && slot.read === read && slot.recoveryOperation === operation && !slot.state.composing && !slot.flight && !slot.assetFlight
788
+ const current = () => { this.#checkOperation(request); return !this.#disposed && this.#active === slot.state.directory && this.#slots.get(slot.state.directory) === slot && slot.state.identity === identity && slot.input === input && slot.read === read && slot.recoveryOperation === operation && !slot.state.composing && !slot.flight && !slot.assetFlight }
687
789
  slot.state = { ...slot.state, recovering: true }; this.#emit(slot)
688
790
  try {
689
- const candidate = (await slot.drafts.read(identity, documentId)).records.find(record => record.id === value.id && record.revision === value.revision && record.token === value.token)
791
+ this.#checkOperation(request)
792
+ const candidate = (await slot.drafts.read(identity, documentId, request?.signal)).records.find(record => record.id === value.id && record.revision === value.revision && record.token === value.token)
690
793
  if (!current()) return
794
+ this.#checkOperation(request)
691
795
  if (candidate?.owned && candidate.id === slot.draft?.id) return
692
796
  if (!candidate) slot.state = { ...slot.state, recoveryChanged: true }
693
797
  else {
694
- const settled = await slot.drafts.settle(identity, [value])
798
+ const settled = await slot.drafts.settle(identity, [value], request && { ...request, guard: () => { if (!current()) throw new Error('client-body-drafts-changed') } })
695
799
  if (!current()) return
696
800
  slot.persistFailure = !settled
697
801
  slot.state = { ...slot.state, recoveryChanged: false, storageFailure: Boolean(slot.persistFailure || slot.legacyFailure === 'write') }
802
+ return settled
698
803
  }
699
- } catch { if (current()) { slot.persistFailure = true; slot.state = { ...slot.state, storageFailure: true } } }
804
+ } catch (error) { if (request) throw error; if (current()) { slot.persistFailure = true; slot.state = { ...slot.state, storageFailure: true } } }
700
805
  finally {
701
806
  if (!this.#disposed && this.#slots.get(slot.state.directory) === slot && slot.state.identity === identity && slot.recoveryOperation === operation) {
702
807
  slot.state = { ...slot.state, recovering: false }; this.#emit(slot); void this.#readDrafts(slot)
package/src/workbench.ts CHANGED
@@ -12,6 +12,7 @@ import { applyDocumentComponentAction, documentComponentSection, effectiveCompon
12
12
  import type { DocumentAuthoringActionPlan, DocumentComponentAction, AppliedDocumentAuthoringAction } from '@lincyaw/kernel'
13
13
  import { inspectCommentDrafts } from './document-editor/comment-draft-inspection.ts'
14
14
  import { mutateCommentDrafts } from './document-editor/comment-draft-actions.ts'
15
+ import { executeBodyDraftAction } from './body-draft-actions.ts'
15
16
  import { inspectComponentDrafts } from './component-draft-inspection.ts'
16
17
  import { mutateComponentDrafts } from './component-draft-actions.ts'
17
18
  import { DocumentSession } from './document-session.ts'
@@ -290,7 +291,7 @@ export class Workbench {
290
291
  /** Only counters enter passive client state; no new form payload is exposed to MCP. */
291
292
  authoringDraftRevision(): string {
292
293
  const source = this.#state.authoring
293
- return JSON.stringify([this.authoringCommentDraftRevision(), source?.identity && source.member?.id ? this.#componentPropertyDrafts.revision(source.identity, source.member.id) : 0, this.#clientControlRevision])
294
+ return JSON.stringify([this.#documentSession.bodyDraftRevision(), this.authoringCommentDraftRevision(), source?.identity && source.member?.id ? this.#componentPropertyDrafts.revision(source.identity, source.member.id) : 0, this.#clientControlRevision])
294
295
  }
295
296
  subscribeAuthoringDraftChanges(listener: () => void): () => void {
296
297
  const comments = this.#commentDrafts.subscribe(listener), properties = this.#componentPropertyDrafts.subscribe(listener)
@@ -779,15 +780,16 @@ export class Workbench {
779
780
  const plan = state.productionPlan, playback = state.productionPlayback
780
781
  const ready = clean && plan?.canPreview && this.#productionReady() && playback?.status === 'ready' && sameProductionBinding(plan.binding, playback.binding)
781
782
  const position = state.position, page = position && content.sections[position.section]
783
+ const bodyDrafts = this.#documentSession.bodyDraftCapabilities()
782
784
  const commentDrafts = source.member?.id ? this.#commentDrafts.peek(source.identity, source.member.id) : undefined
783
- const prepared = state.presentationSnapshot, actual = { documentId: content.id, version: source.version, fingerprint: source.fingerprint }
785
+ const prepared = state.presentationSnapshot, actual = this.#documentSession.canonicalSource() ?? { documentId: content.id, version: source.version, fingerprint: source.fingerprint }
784
786
  const preparedCurrent = clean && prepared && prepared.version === source.version && prepared.fingerprint === source.fingerprint && prepared.project === (source.projectRevision ?? 0)
785
787
  && state.ir?.revision === prepared.revision && state.ir.doc.source?.version === source.version && state.ir.doc.source.fingerprint === source.fingerprint
786
788
  const controls = [...this.#clientControls].filter(owner => owner.identity === source.identity)
787
789
  const advertised = controls.flatMap(owner => owner.actions()), unique = advertised.filter((type, index) => advertised.indexOf(type) === index && advertised.lastIndexOf(type) === index)
788
790
  const reported = controls.map(owner => owner.snapshot?.()).filter(value => value !== undefined)
789
791
  const mode = reported.find(value => value.mode)?.mode, recording = reported.find(value => value.recording)?.recording
790
- return { revision, source: { documentId: content.id, version: source.version, fingerprint: source.fingerprint }, view: state.webView, editing,
792
+ return { revision, source: actual, view: state.webView, editing,
791
793
  ...mode ? { mode } : {}, ...recording ? { recording } : {},
792
794
  interaction: state.documentPositionToken,
793
795
  ...page && position ? { position: { sectionId: page.id, ...page.stepOrder[position.step] ? { stepId: page.stepOrder[position.step] } : {} } } : {},
@@ -798,6 +800,9 @@ export class Workbench {
798
800
  ...safe && state.mode === 'editing' && state.editorHistory?.undo ? ['native-history.undo' as const] : [],
799
801
  ...safe && state.mode === 'editing' && state.editorHistory?.redo ? ['native-history.redo' as const] : [],
800
802
  ...unique,
803
+ ...bodyDrafts.read ? ['body-drafts.inspect' as const, 'body-drafts.read' as const] : [],
804
+ ...bodyDrafts.mutate && !locked && !state.isCreatingPage && !state.isEditingPage && !state.isHistoryBusy && !state.isHistoryPreparing && !state.hasDocumentTimingDrafts
805
+ ? ['body-drafts.restore' as const, 'body-drafts.discard' as const, ...bodyDrafts.current ? ['body-drafts.retry' as const] : []] : [],
801
806
  ...commentDrafts?.readable ? ['comment-drafts.inspect' as const, 'comment-drafts.read' as const] : [],
802
807
  ...clean && !state.isHistoryBusy && !state.isHistoryPreparing && commentDrafts?.readable && commentDrafts.ownersKnown ? ['comment-drafts.discard' as const, ...state.webView === 'document' && commentDrafts.hasRestoreComposer() ? ['comment-drafts.restore' as const] : []] : [],
803
808
  ...source.member?.id && this.#componentPropertyDrafts.readable(source.identity, source.member.id) ? ['component-drafts.inspect' as const, 'component-drafts.read' as const] : [],
@@ -811,7 +816,7 @@ export class Workbench {
811
816
  async executeAuthoringClientAction(action: AuthoringClientAction, expected: CanonicalSource, signal: AbortSignal, deadline?: number, fits?: (result: AuthoringClientActionResult) => boolean): Promise<void | AuthoringClientActionResult> {
812
817
  const scope = this.#documentScope, identity = this.#state.authoring?.identity, document = this.#state.document, interaction = this.#state.documentPositionToken
813
818
  const owned = () => { signal.throwIfAborted(); if (scope !== this.#documentScope || identity !== this.#state.authoring?.identity || document !== this.#state.document) throw new Error('client-document-changed') }
814
- const current = () => { owned(); const state = this.authoringClientSnapshot(0); if (!state || !sameSource(state.source, expected) || !state.actions.includes(action.type)) throw new Error('client-action-unavailable'); return state }
819
+ const current = () => { owned(); const state = this.authoringClientSnapshot(0); if (!state || (action.type === 'body-drafts.retry' ? state.source.documentId !== expected.documentId : !sameSource(state.source, expected)) || !state.actions.includes(action.type)) throw new Error('client-action-unavailable'); return state }
815
820
  current()
816
821
  if (action.type === 'state.read') return
817
822
  if (action.type === 'native-history.undo' || action.type === 'native-history.redo') {
@@ -827,6 +832,15 @@ export class Workbench {
827
832
  if (!this.#clientControls.has(control)) throw new Error('client-action-unavailable')
828
833
  return
829
834
  }
835
+ if (action.type === 'body-drafts.inspect' || action.type === 'body-drafts.read' || action.type === 'body-drafts.restore' || action.type === 'body-drafts.discard' || action.type === 'body-drafts.retry') {
836
+ if (!identity || !fits) throw new Error('client-body-drafts-unavailable')
837
+ const guard = () => {
838
+ owned()
839
+ const actual = this.#documentSession.canonicalSource()
840
+ if (!actual || actual.documentId !== expected.documentId || action.type !== 'body-drafts.inspect' && action.type !== 'body-drafts.read' && isAgentChanging(this.#state)) throw new Error('client-source-changed')
841
+ }
842
+ return executeBodyDraftAction(this.#documentSession, () => this.#state.authoring, action, { signal, guard, source: expected, ...action.type !== 'body-drafts.retry' ? { localDraft: true as const } : {} }, fits)
843
+ }
830
844
  if (action.type === 'comment-drafts.inspect' || action.type === 'comment-drafts.read') {
831
845
  const drafts = identity ? this.documentCommentDrafts(identity) : undefined
832
846
  if (!drafts?.readable || !fits) throw new Error('client-comment-drafts-unavailable')
@@ -1074,9 +1088,9 @@ export class Workbench {
1074
1088
  recordDocument(content: TeachingDocument): void { if (!isAgentChanging(this.#state)) this.#documentSession.record(content) }
1075
1089
  documentComposition(composing: boolean, owner = 'body', identity?: string): void { this.#documentSession.composition(composing, owner, identity) }
1076
1090
  retryDocument(): Promise<void> { return this.#documentSession.retry() }
1077
- discardDocument(): Promise<void> { return this.#documentSession.discard() }
1091
+ discardDocument(): Promise<void> { return this.#documentSession.discard().then(() => {}) }
1078
1092
  recoverDocumentDraft(value: DocumentDraftReference, identity: string): Promise<void> {
1079
- return this.#state.authoring?.identity === identity && !isAgentChanging(this.#state) ? this.#documentSession.recoverDraft(value) : Promise.resolve()
1093
+ return this.#state.authoring?.identity === identity && !isAgentChanging(this.#state) ? this.#documentSession.recoverDraft(value).then(() => {}) : Promise.resolve()
1080
1094
  }
1081
1095
  forgetDocumentDraft(value: DocumentDraftReference, identity: string): void {
1082
1096
  if (this.#state.authoring?.identity === identity && !isAgentChanging(this.#state)) void this.#documentSession.forgetDraft(value)
@@ -81,14 +81,14 @@ export interface WorkspaceClient {
81
81
  /** Saves a small set of files in one document with one version and rollback boundary. */
82
82
  saveSourceTransaction(document: string, changes: SourceTransactionChange[], message?: string): Promise<SourceTransactionAnswer>
83
83
  readIr(document: string): Promise<IrAnswer>
84
- readDocument(document: string): Promise<DocumentAnswer>
84
+ readDocument(document: string, signal?: AbortSignal): Promise<DocumentAnswer>
85
85
  readAuthoringCapabilities(document: string, signal?: AbortSignal): Promise<AuthoringCapabilities>
86
86
  planDocumentAction(document: string, request: DocumentAuthoringActionRequest, signal?: AbortSignal): Promise<DocumentAuthoringActionPlan>
87
87
  readDocumentActionPlan(document: string, reference: DocumentAuthoringActionRead, signal?: AbortSignal): Promise<DocumentAuthoringActionInspection>
88
88
  applyDocumentAction(document: string, reference: DocumentAuthoringActionReference, signal?: AbortSignal): Promise<AppliedDocumentAuthoringAction>
89
89
  /** A same-origin display URL; the canonical asset location remains untouched. */
90
90
  documentAssetURL(document: string, assetId: string): string
91
- changeDocument(document: string, change: DocumentChange): Promise<DocumentChangeAnswer>
91
+ changeDocument(document: string, change: DocumentChange, signal?: AbortSignal): Promise<DocumentChangeAnswer>
92
92
  importDocumentImage(document: string, file: File, change: DocumentImageImport, signal?: AbortSignal): Promise<DocumentImageImportAnswer>
93
93
  readDocumentAudio(document: string, assetId: string, baseDocumentVersion: string, signal?: AbortSignal): Promise<DocumentAudioInspectionAnswer>
94
94
  importDocumentAudio(document: string, file: File, change: DocumentAudioImport, signal?: AbortSignal): Promise<DocumentAudioImportAnswer>
@@ -359,13 +359,13 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
359
359
  saveSource: (document, path, content, base, message) => post(url('source', document), { path, content, base, ...message ? { message } : {} }),
360
360
  saveSourceTransaction: (document, changes, message) => post(url('source/transaction', document), { changes, ...message ? { message } : {} }),
361
361
  readIr,
362
- readDocument: document => call(url('document', document)),
362
+ readDocument: (document, signal) => call(url('document', document), { signal }),
363
363
  readAuthoringCapabilities: (document, signal) => call(url('document/capabilities', document), { signal }),
364
364
  planDocumentAction: (document, request, signal) => post(url('document/action/plan', document), request, signal),
365
365
  readDocumentActionPlan: (document, reference, signal) => call(url('document/action/plan', document, { planId: reference.planId, digest: reference.digest }), { signal }),
366
366
  applyDocumentAction: (document, reference, signal) => post(url('document/action/apply', document), reference, signal),
367
367
  documentAssetURL: (document, asset) => url('document/asset', document, { asset }),
368
- changeDocument: (document, change) => post(url('document/change', document), change),
368
+ changeDocument: (document, change, signal) => post(url('document/change', document), change, signal),
369
369
  importDocumentImage: (document, file, change, signal) => {
370
370
  const body = new FormData()
371
371
  body.set('change', JSON.stringify(change)); body.set('file', file)