@lincyaw/workbench 0.2.0-rc.27 → 0.2.0-rc.29

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.27",
3
+ "version": "0.2.0-rc.29",
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/design": "1.0.0-rc.28",
59
- "@lincyaw/kernel": "1.0.0-rc.28"
58
+ "@lincyaw/design": "1.0.0-rc.29",
59
+ "@lincyaw/kernel": "1.0.0-rc.29"
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.28"
70
+ "@lincyaw/compiler": "1.0.0-rc.29"
71
71
  }
72
72
  }
@@ -93,6 +93,8 @@ export class DocumentDrafts {
93
93
  || typeof value.owner !== 'string' || !value.owner || value.owner.length > 200 || typeof value.updatedAt !== 'number' || !Number.isSafeInteger(value.updatedAt) || value.updatedAt < 0 || Number.isNaN(new Date(value.updatedAt).getTime())) throw new Error('document-draft-data')
94
94
  const draft = documentDraft(value, documentId)
95
95
  if (!draft) throw new Error('document-draft-document')
96
+ if (draft.baseHash.startsWith('json:')) draft.baseHash = await tokenOf(draft.baseHash.slice(5))
97
+ if (draft.pendingHash?.startsWith('json:')) draft.pendingHash = await tokenOf(draft.pendingHash.slice(5))
96
98
  const token = await tokenOf(raw), marker = settledKey(identity, { id: value.id, revision: value.revision, token })
97
99
  if (durable.get(marker) === token) continue
98
100
  if (source === 'rescue' && localStorage.getItem(marker) === token) continue
@@ -1,5 +1,6 @@
1
1
  import { useEffect, useMemo, useRef } from 'react'
2
2
  import type { Transaction } from '@tiptap/pm/state'
3
+ import { TextSelection } from '@tiptap/pm/state'
3
4
  import { closeHistory } from '@tiptap/pm/history'
4
5
  import { allocateDocumentPage, randomUUID } from '@lincyaw/kernel'
5
6
  import type { Member, TeachingDocument } from '@lincyaw/kernel'
@@ -12,8 +13,8 @@ import type { NativePageCreation } from './projection.ts'
12
13
  import { captureRichBaseline } from './rich-text.ts'
13
14
  import { captureTableIdentities, seedTableIdentities } from './table-identities.ts'
14
15
  import type { DocumentNodeViews, NativeDocumentEditor } from './schema.tsx'
15
- import { nativeEditingCursor } from './selection.ts'
16
- import type { NativeDocumentSelection } from './selection.ts'
16
+ import { nativeEditingCursor, nativeTextPoint, nativeTextPosition } from './selection.ts'
17
+ import type { NativeDocumentSelection, NativeTextPoint } from './selection.ts'
17
18
  import { documentInsertionPlace } from './insertion-place.ts'
18
19
  import type { DocumentInsertionPlace } from './insertion-place.ts'
19
20
 
@@ -88,6 +89,13 @@ export function DocumentEditor(props: DocumentEditorProps) {
88
89
  const focusFrame = useRef<number>()
89
90
  const binding = useRef(projection)
90
91
  const active = useRef(projection)
92
+ const editorIdentity = useRef(props.identity)
93
+ const retainedSelection = useRef<{ from: NativeTextPoint, to: NativeTextPoint }>()
94
+ const previous = editor.current
95
+ if (binding.current !== projection && editorIdentity.current === props.identity && previous?.isFocused() && !previous.prosemirrorView.composing) {
96
+ const from = nativeTextPoint(previous, previous.prosemirrorState.selection.anchor), to = nativeTextPoint(previous, previous.prosemirrorState.selection.head)
97
+ if (from && to) retainedSelection.current = { from, to }
98
+ }
91
99
  active.current = projection
92
100
  current.current = props
93
101
  const cancelFocus = () => { if (focusFrame.current !== undefined) cancelAnimationFrame(focusFrame.current); focusFrame.current = undefined }
@@ -166,7 +174,17 @@ export function DocumentEditor(props: DocumentEditorProps) {
166
174
  comments.restoreAnchors(value)
167
175
  binding.current = projection
168
176
  editor.current = value
177
+ editorIdentity.current = props.identity
169
178
  projectedDocument.current = value.prosemirrorState.doc
179
+ const selection = retainedSelection.current
180
+ retainedSelection.current = undefined
181
+ if (selection) {
182
+ const from = nativeTextPosition(value, selection.from), to = nativeTextPosition(value, selection.to)
183
+ if (from !== undefined && to !== undefined) {
184
+ value.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, from, to)).setMeta('addToHistory', false))
185
+ value.focus()
186
+ }
187
+ }
170
188
  const stopBefore = value.onBeforeChange(({ tr }) => { if (!comments.synchronizing && tr.docChanged) pendingTransaction.current = tr })
171
189
  const stopComments = comments.subscribe(emit)
172
190
  const stopSelection = value.onSelectionChange(() => { cancelFocus(); reportPosition() })
@@ -1,4 +1,4 @@
1
- import { hasRole, randomUUID, validateDocument } from '@lincyaw/kernel'
1
+ import { hasRole, isRecord, randomUUID, validateDocument } from '@lincyaw/kernel'
2
2
  import type { 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'
@@ -35,6 +35,7 @@ interface Slot {
35
35
  compositions: Set<string>
36
36
  input: number
37
37
  baseHash: string
38
+ baseContent: TeachingDocument
38
39
  storage: string
39
40
  drafts: DocumentDrafts
40
41
  backup?: DocumentDraftCommit
@@ -92,6 +93,20 @@ async function digest(value: TeachingDocument): Promise<string> {
92
93
  return sha256(serialize(value))
93
94
  }
94
95
 
96
+ /** Replay pending author input on a newer saved document; an overlapping value belongs to the author. */
97
+ function rebaseDocument(base: TeachingDocument, local: TeachingDocument, remote: TeachingDocument): TeachingDocument {
98
+ const merge = (before: unknown, author: unknown, saved: unknown): unknown => {
99
+ if (serialize(author) === serialize(before)) return structuredClone(saved)
100
+ if (serialize(saved) === serialize(before) || serialize(author) === serialize(saved)) return structuredClone(author)
101
+ if (isRecord(before) && isRecord(author) && isRecord(saved)) return Object.fromEntries([...new Set([...Object.keys(before), ...Object.keys(author), ...Object.keys(saved)])]
102
+ .map(key => [key, merge(before[key], author[key], saved[key])] as const).filter(([, value]) => value !== undefined))
103
+ return structuredClone(author)
104
+ }
105
+ const merged = validateDocument(merge(base, local, remote))
106
+ // A structural conflict is one document operation: preserve the author's valid complete document.
107
+ return merged.document && !merged.issues.some(issue => issue.severity === 'error') ? merged.document : structuredClone(local)
108
+ }
109
+
95
110
  /** One source actor per document. Runtime compilation and iframe lifecycle never own its input. */
96
111
  export class DocumentSession {
97
112
  readonly #client: WorkspaceClient
@@ -140,7 +155,7 @@ export class DocumentSession {
140
155
  const baseHash = await digest(answer.content)
141
156
  if (this.#disposed || this.#active !== directory || opening !== this.#opening) return
142
157
  const drafts = new DocumentDrafts(() => { if (slot && !this.#disposed) void this.#readDrafts(slot) })
143
- slot = { input: 0, read: 0, compositions: new Set(), drafts, baseHash, 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 } }
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 } }
144
159
  this.#slots.set(directory, slot)
145
160
  await this.#restore(slot, answer)
146
161
  } else {
@@ -233,11 +248,19 @@ export class DocumentSession {
233
248
  slot.baseHash = remoteHash; slot.pendingHash = undefined
234
249
  slot.state = { ...slot.state, version: answer.version, fingerprint: answer.fingerprint, error: undefined, issues: answer.issues }
235
250
  } else if (remoteHash === slot.baseHash) slot.state = { ...slot.state, version: answer.version, fingerprint: answer.fingerprint, issues: answer.issues }
236
- else slot.state = { ...slot.state, error: 'document-version-changed', issues: answer.issues }
251
+ else if (!slot.state.composing) {
252
+ const content = rebaseDocument(slot.baseContent, slot.state.content!, answer.content)
253
+ const reset = slot.state.reset + (keepsEditorContent(slot.state.content!, content) ? 0 : 1)
254
+ slot.baseHash = remoteHash
255
+ slot.pendingHash = undefined
256
+ slot.state = { ...slot.state, content, reset, version: answer.version, fingerprint: answer.fingerprint, error: undefined, dirty: true, issues: answer.issues }
257
+ }
258
+ if (slot.state.version === answer.version) slot.baseContent = structuredClone(answer.content)
237
259
  return
238
260
  }
239
261
  const reset = slot.state.reset + (keepsEditorContent(slot.state.content!, answer.content) ? 0 : 1)
240
262
  slot.baseHash = remoteHash
263
+ slot.baseContent = structuredClone(answer.content)
241
264
  slot.state = { ...slot.state, version: answer.version, fingerprint: answer.fingerprint, content: answer.content, reset, error: undefined, issues: answer.issues }
242
265
  }
243
266
 
@@ -297,7 +320,12 @@ export class DocumentSession {
297
320
  if (answer.changeId !== flight.id || answer.document !== slot.state.directory || answer.content.id !== flight.content.id) throw new Error('document-confirmation')
298
321
  this.#ack(slot, flight, answer)
299
322
  } catch (error) {
300
- slot.state = { ...slot.state, saving: false, error: this.#error(error), issues: this.#issues(error) }
323
+ if (this.#error(error) === 'document-version-changed' && !slot.state.composing) {
324
+ try {
325
+ await this.#adopt(slot, await this.#client.readDocument(slot.state.directory))
326
+ slot.state = { ...slot.state, saving: false }
327
+ } catch (refreshError) { slot.state = { ...slot.state, saving: false, error: this.#error(refreshError), issues: this.#issues(refreshError) } }
328
+ } else slot.state = { ...slot.state, saving: false, error: this.#error(error), issues: this.#issues(error) }
301
329
  } finally {
302
330
  if (slot.flight === flight) slot.flight = undefined
303
331
  this.#persist(slot); this.#emit(slot)
@@ -308,6 +336,7 @@ export class DocumentSession {
308
336
  }
309
337
  #ack(slot: Slot, flight: NonNullable<Slot['flight']>, answer: DocumentChangeAnswer): void {
310
338
  slot.baseHash = flight.hash!
339
+ slot.baseContent = structuredClone(answer.content)
311
340
  slot.pendingHash = undefined
312
341
  const same = slot.input === flight.input
313
342
  slot.state = { ...slot.state, version: answer.version, fingerprint: answer.fingerprint, ...(same ? { content: answer.content } : {}), dirty: !same, saving: false, error: undefined, issues: answer.issues }
@@ -326,6 +355,7 @@ export class DocumentSession {
326
355
  const same = slot.input === input, content = same ? answer.content : structuredClone(current)
327
356
  if (!same) for (const [id, asset] of added) content.assets[id] = structuredClone(asset)
328
357
  slot.baseHash = baseHash
358
+ slot.baseContent = structuredClone(answer.content)
329
359
  slot.state = { ...slot.state, content, version: answer.version, fingerprint: answer.fingerprint, dirty: !same, error: undefined, issues: answer.issues }
330
360
  return true
331
361
  }
@@ -340,6 +370,7 @@ export class DocumentSession {
340
370
  const checked = validateDocument(content)
341
371
  if (!checked.document || checked.issues.some(issue => issue.severity === 'error')) return false
342
372
  slot.baseHash = baseHash
373
+ slot.baseContent = structuredClone(answer.content)
343
374
  slot.pendingHash = undefined
344
375
  slot.state = { ...slot.state, content: structuredClone(checked.document), version: answer.version, fingerprint: answer.fingerprint,
345
376
  dirty: slot.input !== input || slot.state.composing || serialize(content) !== serialize(answer.content), error: undefined, issues: answer.issues }
package/src/workbench.ts CHANGED
@@ -217,7 +217,7 @@ export function selectedDocument(state: WorkbenchState): string | null {
217
217
 
218
218
  /** Whether the AI is changing the workspace now, or its change waits for the author. */
219
219
  export function isAgentChanging(state: WorkbenchState): boolean {
220
- return Boolean(state.review && (state.review.running || state.review.changes.length > 0))
220
+ return Boolean(state.review?.engine === 'git' && (state.review.running || state.review.changes.length > 0))
221
221
  }
222
222
 
223
223
  /** Whether the document has a slides form (no renderers listed: every form). */