@agent-native/toolkit 0.6.0 → 0.8.0

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 (174) hide show
  1. package/README.md +17 -1
  2. package/agent-native.eject.json +411 -0
  3. package/dist/chat-history/ChatHistoryList.d.ts +103 -0
  4. package/dist/chat-history/ChatHistoryList.d.ts.map +1 -0
  5. package/dist/chat-history/ChatHistoryList.js +109 -0
  6. package/dist/chat-history/ChatHistoryList.js.map +1 -0
  7. package/dist/chat-history/ChatHistoryList.spec.d.ts +2 -0
  8. package/dist/chat-history/ChatHistoryList.spec.d.ts.map +1 -0
  9. package/dist/chat-history/ChatHistoryList.spec.js +283 -0
  10. package/dist/chat-history/ChatHistoryList.spec.js.map +1 -0
  11. package/dist/chat-history/index.d.ts +2 -0
  12. package/dist/chat-history/index.d.ts.map +1 -0
  13. package/dist/chat-history/index.js +2 -0
  14. package/dist/chat-history/index.js.map +1 -0
  15. package/dist/chat-history.css +314 -0
  16. package/package.json +20 -1
  17. package/src/app-shell/header-actions.tsx +84 -0
  18. package/src/app-shell/index.ts +1 -0
  19. package/src/chat-history/ChatHistoryList.spec.tsx +453 -0
  20. package/src/chat-history/ChatHistoryList.tsx +469 -0
  21. package/src/chat-history/index.ts +7 -0
  22. package/src/chat-history.css +314 -0
  23. package/src/collab-ui/AgentPresenceChip.tsx +69 -0
  24. package/src/collab-ui/LiveCursorOverlay.tsx +241 -0
  25. package/src/collab-ui/PresenceBar.tsx +346 -0
  26. package/src/collab-ui/RecentEditHighlights.tsx +225 -0
  27. package/src/collab-ui/RemoteSelectionRings.tsx +227 -0
  28. package/src/collab-ui/agent-identity.ts +16 -0
  29. package/src/collab-ui/index.ts +39 -0
  30. package/src/collab-ui/lead-client.ts +32 -0
  31. package/src/collab-ui/types.spec.ts +18 -0
  32. package/src/collab-ui/types.ts +96 -0
  33. package/src/composer/AgentComposerFrame.tsx +59 -0
  34. package/src/composer/ComposerPlusMenu.tsx +983 -0
  35. package/src/composer/MentionPopover.tsx +412 -0
  36. package/src/composer/PastedTextChip.tsx +150 -0
  37. package/src/composer/PromptComposer.spec.ts +73 -0
  38. package/src/composer/PromptComposer.tsx +718 -0
  39. package/src/composer/RealtimeVoiceMode.spec.tsx +771 -0
  40. package/src/composer/RealtimeVoiceMode.tsx +856 -0
  41. package/src/composer/TiptapComposer.spec.ts +390 -0
  42. package/src/composer/TiptapComposer.tsx +2936 -0
  43. package/src/composer/VoiceButton.spec.ts +33 -0
  44. package/src/composer/VoiceButton.tsx +255 -0
  45. package/src/composer/asset-picker-url.spec.ts +56 -0
  46. package/src/composer/asset-picker-url.ts +80 -0
  47. package/src/composer/attachment-accept.spec.ts +22 -0
  48. package/src/composer/attachment-accept.ts +71 -0
  49. package/src/composer/draft-key.spec.ts +19 -0
  50. package/src/composer/draft-key.ts +7 -0
  51. package/src/composer/extensions/FileReference.tsx +55 -0
  52. package/src/composer/extensions/MentionReference.tsx +93 -0
  53. package/src/composer/extensions/SkillReference.tsx +56 -0
  54. package/src/composer/index.ts +79 -0
  55. package/src/composer/pasted-text.spec.ts +162 -0
  56. package/src/composer/pasted-text.ts +160 -0
  57. package/src/composer/prompt-attachments.spec.ts +80 -0
  58. package/src/composer/prompt-attachments.ts +93 -0
  59. package/src/composer/realtime-voice-audio-level.spec.ts +32 -0
  60. package/src/composer/realtime-voice-audio-level.ts +64 -0
  61. package/src/composer/realtime-voice-transcript.spec.ts +95 -0
  62. package/src/composer/realtime-voice-transcript.ts +134 -0
  63. package/src/composer/runtime-adapters.tsx +343 -0
  64. package/src/composer/types.ts +66 -0
  65. package/src/composer/use-file-search.ts +64 -0
  66. package/src/composer/use-mention-search.ts +90 -0
  67. package/src/composer/use-skills.ts +45 -0
  68. package/src/composer/useRealtimeVoiceMode.spec.ts +818 -0
  69. package/src/composer/useRealtimeVoiceMode.tsx +2117 -0
  70. package/src/composer/useVoiceDictation.spec.ts +45 -0
  71. package/src/composer/useVoiceDictation.ts +1191 -0
  72. package/src/context-ui/ContextMeter.tsx +101 -0
  73. package/src/context-ui/ContextSegmentRow.tsx +184 -0
  74. package/src/context-ui/ContextTreemap.tsx +125 -0
  75. package/src/context-ui/ContextXRayPanel.tsx +377 -0
  76. package/src/context-ui/format.ts +42 -0
  77. package/src/context-ui/index.ts +15 -0
  78. package/src/context-ui/types.ts +43 -0
  79. package/src/design-tweaks/index.ts +1 -0
  80. package/src/design-tweaks/visual-style-controls.tsx +1084 -0
  81. package/src/editor/BubbleToolbar.tsx +253 -0
  82. package/src/editor/CodeBlockNode.tsx +254 -0
  83. package/src/editor/DragHandle.spec.ts +588 -0
  84. package/src/editor/DragHandle.ts +1437 -0
  85. package/src/editor/ImageExtension.roundtrip.spec.ts +117 -0
  86. package/src/editor/ImageExtension.ts +306 -0
  87. package/src/editor/RegistryBlockContext.tsx +107 -0
  88. package/src/editor/RegistryBlockNode.spec.ts +279 -0
  89. package/src/editor/RegistryBlockNode.tsx +652 -0
  90. package/src/editor/RichMarkdownEditor.collab.spec.ts +79 -0
  91. package/src/editor/RichMarkdownEditor.roundtrip.spec.ts +226 -0
  92. package/src/editor/RichMarkdownEditor.tsx +81 -0
  93. package/src/editor/RunId.ts +61 -0
  94. package/src/editor/SharedRichEditor.tsx +321 -0
  95. package/src/editor/SlashCommandMenu.tsx +310 -0
  96. package/src/editor/disableHistory.spec.ts +85 -0
  97. package/src/editor/extensions.ts +402 -0
  98. package/src/editor/gfmDoc.spec.ts +230 -0
  99. package/src/editor/gfmDoc.ts +92 -0
  100. package/src/editor/index.ts +93 -0
  101. package/src/editor/registrySlashCommands.ts +131 -0
  102. package/src/editor/structuralReorderUndo.spec.ts +144 -0
  103. package/src/editor/surgical-apply.spec.ts +279 -0
  104. package/src/editor/surgical-apply.ts +192 -0
  105. package/src/editor/useCollabReconcile.concurrent.spec.ts +422 -0
  106. package/src/editor/useCollabReconcile.idempotent.spec.ts +324 -0
  107. package/src/editor/useCollabReconcile.ts +589 -0
  108. package/src/editor.css +510 -0
  109. package/src/hooks/index.ts +2 -0
  110. package/src/hooks/use-mobile.tsx +21 -0
  111. package/src/hooks/use-toast.ts +188 -0
  112. package/src/index.ts +8 -0
  113. package/src/onboarding/index.ts +1 -0
  114. package/src/provider.tsx +47 -0
  115. package/src/sharing/VisibilityBadge.spec.ts +96 -0
  116. package/src/sharing/VisibilityBadge.tsx +37 -0
  117. package/src/sharing/index.ts +4 -0
  118. package/src/styles.css +21 -0
  119. package/src/ui/accordion.tsx +56 -0
  120. package/src/ui/alert-dialog.tsx +141 -0
  121. package/src/ui/alert.tsx +59 -0
  122. package/src/ui/aspect-ratio.tsx +5 -0
  123. package/src/ui/avatar.tsx +48 -0
  124. package/src/ui/badge.tsx +37 -0
  125. package/src/ui/breadcrumb.tsx +115 -0
  126. package/src/ui/button.tsx +78 -0
  127. package/src/ui/calendar.tsx +214 -0
  128. package/src/ui/card.tsx +86 -0
  129. package/src/ui/carousel.tsx +260 -0
  130. package/src/ui/chart.tsx +375 -0
  131. package/src/ui/checkbox.tsx +28 -0
  132. package/src/ui/collapsible.tsx +9 -0
  133. package/src/ui/command.spec.tsx +51 -0
  134. package/src/ui/command.tsx +174 -0
  135. package/src/ui/context-menu.tsx +202 -0
  136. package/src/ui/date-picker.tsx +64 -0
  137. package/src/ui/dialog.spec.tsx +43 -0
  138. package/src/ui/dialog.tsx +146 -0
  139. package/src/ui/drawer.tsx +126 -0
  140. package/src/ui/dropdown-menu.tsx +218 -0
  141. package/src/ui/form.tsx +177 -0
  142. package/src/ui/hover-card.tsx +27 -0
  143. package/src/ui/index.ts +52 -0
  144. package/src/ui/input-otp.tsx +69 -0
  145. package/src/ui/input.tsx +22 -0
  146. package/src/ui/label.tsx +24 -0
  147. package/src/ui/logo.tsx +36 -0
  148. package/src/ui/menubar.tsx +235 -0
  149. package/src/ui/navigation-menu.tsx +128 -0
  150. package/src/ui/pagination.tsx +121 -0
  151. package/src/ui/popover.tsx +44 -0
  152. package/src/ui/progress.tsx +26 -0
  153. package/src/ui/radio-group.tsx +42 -0
  154. package/src/ui/resizable.tsx +43 -0
  155. package/src/ui/scroll-area.tsx +46 -0
  156. package/src/ui/select.tsx +158 -0
  157. package/src/ui/separator.tsx +29 -0
  158. package/src/ui/sheet.tsx +160 -0
  159. package/src/ui/sidebar.tsx +777 -0
  160. package/src/ui/skeleton.tsx +18 -0
  161. package/src/ui/slider.tsx +26 -0
  162. package/src/ui/sonner.tsx +58 -0
  163. package/src/ui/spinner.tsx +17 -0
  164. package/src/ui/switch.tsx +27 -0
  165. package/src/ui/table.tsx +117 -0
  166. package/src/ui/tabs.tsx +53 -0
  167. package/src/ui/textarea.tsx +23 -0
  168. package/src/ui/toast.tsx +127 -0
  169. package/src/ui/toaster.tsx +33 -0
  170. package/src/ui/toggle-group.tsx +59 -0
  171. package/src/ui/toggle.tsx +43 -0
  172. package/src/ui/tooltip.tsx +53 -0
  173. package/src/ui/use-toast.ts +3 -0
  174. package/src/utils.ts +8 -0
@@ -0,0 +1,589 @@
1
+ import { isChangeOrigin } from "@tiptap/extension-collaboration";
2
+ import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
3
+ import type { Transaction } from "@tiptap/pm/state";
4
+ import type { Editor } from "@tiptap/react";
5
+ import { useEffect, useRef, useState, type MutableRefObject } from "react";
6
+ import type { Awareness } from "y-protocols/awareness";
7
+ import type { Doc as YDoc } from "yjs";
8
+
9
+ import { AGENT_CLIENT_ID, isReconcileLeadClient } from "../collab-ui/index.js";
10
+ import {
11
+ RICH_MARKDOWN_PROGRAMMATIC_TRANSACTION,
12
+ applyDocSurgically,
13
+ defaultParseValue,
14
+ } from "./surgical-apply.js";
15
+
16
+ export { RICH_MARKDOWN_PROGRAMMATIC_TRANSACTION };
17
+
18
+ /** Reads the current markdown out of the tiptap-markdown storage. */
19
+ export function getEditorMarkdown(editor: Editor): string {
20
+ const markdownStorage = editor.storage as unknown as {
21
+ markdown?: { getMarkdown?: () => string };
22
+ };
23
+ return markdownStorage.markdown?.getMarkdown?.() ?? "";
24
+ }
25
+
26
+ /**
27
+ * Push a value onto the bounded ring of recently-emitted markdown (most recent
28
+ * last, deduped, capped). The reconcile uses this to recognize a stale-but-recent
29
+ * echo of OUR OWN edits: a debounced autosave can persist a PARTIAL burst, and
30
+ * the next poll re-supplies that partial value with a newer timestamp — applying
31
+ * it would clobber the freshly-typed tail. An external change (agent/peer) never
32
+ * byte-matches one of our own recent emissions, and if it somehow did the content
33
+ * is identical, so skipping it is safe by construction.
34
+ */
35
+ const EMITTED_RING_MAX = 16;
36
+ function pushEmittedRing(ring: string[], value: string): void {
37
+ if (!value) return;
38
+ if (ring[ring.length - 1] === value) return;
39
+ const dupe = ring.indexOf(value);
40
+ if (dupe !== -1) ring.splice(dupe, 1);
41
+ ring.push(value);
42
+ if (ring.length > EMITTED_RING_MAX) ring.shift();
43
+ }
44
+
45
+ export interface UseCollabReconcileOptions {
46
+ /** The live editor, or null until it mounts. */
47
+ editor: Editor | null;
48
+ /** Shared Y.Doc when collaborating; null disables all collab paths. */
49
+ ydoc?: YDoc | null;
50
+ /** True after the collab provider has loaded the persisted initial Y.Doc state. */
51
+ collabSynced?: boolean;
52
+ /** Shared awareness; null keeps the sole-client lead path. */
53
+ awareness?: Awareness | null;
54
+ /** Authoritative markdown value (SQL source of truth). */
55
+ value: string;
56
+ /** Timestamp of the authoritative value; gates newer-than reconcile. */
57
+ contentUpdatedAt?: string | null;
58
+ /** Whether the editor accepts edits. Reconcile/seed only run for the live editor. */
59
+ editable: boolean;
60
+ /**
61
+ * Reads the current markdown from the editor. Injected so a dialect could
62
+ * swap serializers; defaults to the tiptap-markdown storage reader. For an app
63
+ * with a custom serializer (e.g. Content's `docToNfm(editor.getJSON())`), pass
64
+ * it here so the seed/reconcile equality checks compare like-for-like.
65
+ */
66
+ getMarkdown?: (editor: Editor) => string;
67
+ /**
68
+ * Applies the authoritative `value` into the editor. Defaults to passing the
69
+ * raw markdown string to `editor.commands.setContent`. Apps whose serializer
70
+ * is NOT tiptap-markdown (Content parses `nfmToDoc(value)` into a PM doc)
71
+ * override this so seed + reconcile write the correct content shape. The
72
+ * supplied `options` carry the history/whitespace flags the default path uses;
73
+ * a custom implementation should forward them when relevant.
74
+ */
75
+ setContent?: (
76
+ editor: Editor,
77
+ value: string,
78
+ options: { emitUpdate?: boolean; addToHistory?: boolean },
79
+ ) => void;
80
+ /**
81
+ * Parses the authoritative `value` into a full ProseMirror document for the
82
+ * SURGICAL reconcile path: instead of a whole-document `setContent` (which
83
+ * under Collaboration rewrites the entire Y.XmlFragment and tears down every
84
+ * block NodeView), the reconcile diffs the parsed doc against the live doc
85
+ * and replaces only the changed top-level run. Return null to skip the
86
+ * surgical path for a given value (falls back to `setContent`).
87
+ *
88
+ * Defaults to a best-effort tiptap-markdown parse; apps with their own
89
+ * serializers (Content's NFM, Plan's blocks[] doc) should supply the exact
90
+ * doc their `setContent` would write. Pass `false` to disable surgical
91
+ * application entirely.
92
+ */
93
+ parseValue?:
94
+ | ((editor: Editor, value: string) => ProseMirrorNode | null)
95
+ | false;
96
+ /**
97
+ * Normalizes the authoritative `value` to the canonical markdown the editor
98
+ * would emit, so the "already in sync / our own echo" equality checks match a
99
+ * serializer that re-canonicalizes (Content's `canonicalizeNfm`). Defaults to
100
+ * identity (GFM already round-trips byte-stably).
101
+ */
102
+ normalizeValue?: (value: string) => string;
103
+ /**
104
+ * Decides whether the empty-doc seed should run for the current shared
105
+ * fragment. Defaults to "fragment has no nodes, or the editor holds no
106
+ * semantic markdown". Apps with sentinel-empty content (Content's
107
+ * `<empty-block/>` filler) override this. Receives the live fragment length
108
+ * and the editor's current markdown.
109
+ */
110
+ shouldSeed?: (info: {
111
+ value: string;
112
+ currentMarkdown: string;
113
+ fragmentLength: number;
114
+ }) => boolean;
115
+ /**
116
+ * The initial "applied" watermark. Default mirrors `contentUpdatedAt`, so a
117
+ * fresh mount whose Y.Doc already matches SQL doesn't re-apply. Pass `null`
118
+ * to force the first reconcile pass to adopt authoritative SQL even at the
119
+ * same timestamp — Content does this so a stale persisted Y.Doc (an agent that
120
+ * edited the CLOSED doc) is corrected on open. The editor is keyed per
121
+ * document upstream, so this only affects the first mount of each doc.
122
+ */
123
+ initialAppliedUpdatedAt?: string | null;
124
+ }
125
+
126
+ export interface UseCollabReconcileResult {
127
+ /** True when a Y.Doc is bound (collaborative editing active). */
128
+ collab: boolean;
129
+ /**
130
+ * Set true around any programmatic `setContent` so the editor's `onUpdate`
131
+ * can ignore the resulting transaction (it isn't a user edit).
132
+ */
133
+ isSettingContentRef: MutableRefObject<boolean>;
134
+ /**
135
+ * Call from `onUpdate` BEFORE serializing. Returns true when the update must
136
+ * be ignored: editor not editable, mid-programmatic-setContent, or (in collab
137
+ * mode) a remote-origin transaction. Also records the local typing time.
138
+ */
139
+ shouldIgnoreUpdate: (transaction: Transaction) => boolean;
140
+ /**
141
+ * Call from `onUpdate` AFTER computing the markdown to emit. Returns false
142
+ * when the value must NOT be persisted yet (an empty collab doc before the
143
+ * seed has run); records it as the last-emitted value otherwise.
144
+ */
145
+ registerEmitted: (markdown: string) => boolean;
146
+ }
147
+
148
+ /**
149
+ * The subtle seed / reconcile / lead-client logic for the shared markdown
150
+ * editor, extracted once so it can never be duplicated across embedders.
151
+ *
152
+ * Responsibilities (reproducing the Plan editor's behavior exactly):
153
+ * - Track whether THIS client is the reconcile lead (sole client always leads;
154
+ * otherwise elected via {@link isReconcileLeadClient}) and how many other
155
+ * visible human peers are present.
156
+ * - Seed an empty shared Y.Doc once from `value` — lead client only — so two
157
+ * clients opening a brand-new block don't both insert the content.
158
+ * - Reconcile authoritative external markdown (agent edit, source patch, peer
159
+ * edit mirrored to SQL) into the editor: in collab mode only the lead client
160
+ * applies it through `setContent` and Yjs propagates; in non-collab mode this
161
+ * is the original controlled-value reconcile.
162
+ * - Provide the `onUpdate` guards (`shouldIgnoreUpdate`, `registerEmitted`) so
163
+ * the component never persists remote-origin or pre-seed empty content.
164
+ */
165
+ /** Default seed predicate: seed only when the shared doc is genuinely empty. */
166
+ function defaultShouldSeed({
167
+ currentMarkdown,
168
+ fragmentLength,
169
+ }: {
170
+ value: string;
171
+ currentMarkdown: string;
172
+ fragmentLength: number;
173
+ }): boolean {
174
+ return fragmentLength === 0 || !currentMarkdown.trim();
175
+ }
176
+
177
+ /**
178
+ * Default content writer: hand the raw markdown string to `setContent`, which
179
+ * tiptap-markdown overrides to parse the markdown into a ProseMirror doc.
180
+ *
181
+ * IMPORTANT: do NOT pass `parseOptions: { preserveWhitespace: "full" }` here.
182
+ * In tiptap v3 the core `setContent` command routes `preserveWhitespace: "full"`
183
+ * through `insertContentAt`, which tiptap-markdown ALSO overrides to re-run its
184
+ * markdown parser. That double-parse stringifies the already-parsed PM doc and
185
+ * re-parses it as HTML, so a clean heading/list/code block comes back as the
186
+ * escaped, non-idempotent `&lt;h1&gt;…` — which then escalates every reconcile
187
+ * cycle (`<p>` → `&lt;p&gt;` → `&amp;lt;p&amp;gt;` …). Letting the markdown
188
+ * override parse the string directly (no `parseOptions`) round-trips byte-stably
189
+ * for the GFM corpus, including code-block and empty-line whitespace. Content's
190
+ * NFM path supplies its own `setContent` (it passes a pre-parsed PM doc) and is
191
+ * unaffected by this default.
192
+ */
193
+ function defaultSetContent(
194
+ editor: Editor,
195
+ value: string,
196
+ options: { emitUpdate?: boolean; addToHistory?: boolean },
197
+ ): void {
198
+ if (options.addToHistory === false) {
199
+ editor
200
+ .chain()
201
+ .command(({ tr }) => {
202
+ // addToHistory:false so cmd+z (or Yjs undo) doesn't erase
203
+ // externally-loaded content.
204
+ tr.setMeta("addToHistory", false);
205
+ return true;
206
+ })
207
+ .setContent(value, { emitUpdate: options.emitUpdate })
208
+ .run();
209
+ return;
210
+ }
211
+ editor.commands.setContent(value);
212
+ }
213
+
214
+ export function useCollabReconcile({
215
+ editor,
216
+ ydoc = null,
217
+ collabSynced = true,
218
+ awareness = null,
219
+ value,
220
+ contentUpdatedAt,
221
+ editable,
222
+ getMarkdown = getEditorMarkdown,
223
+ setContent = defaultSetContent,
224
+ parseValue,
225
+ normalizeValue = (v) => v,
226
+ shouldSeed = defaultShouldSeed,
227
+ initialAppliedUpdatedAt,
228
+ }: UseCollabReconcileOptions): UseCollabReconcileResult {
229
+ const collab = !!ydoc;
230
+ const isSettingContentRef = useRef(false);
231
+ const lastEmittedRef = useRef("");
232
+ // Ring of recent local emissions (see pushEmittedRing). Lets the reconcile
233
+ // recognize a stale-but-recent echo of our OWN (possibly partial, debounced)
234
+ // save so a lagging poll never clobbers freshly-typed text.
235
+ const recentEmittedRef = useRef<string[]>([]);
236
+ const lastTypedAtRef = useRef(0);
237
+ // The raw authoritative `value` string the reconcile last applied. When the
238
+ // SAME raw string is re-fetched (a lagging poll, or a source-sync that keeps
239
+ // re-supplying the same stored markdown), applying it again would only
240
+ // reproduce the doc we already hold — and if `value` is NON-idempotent
241
+ // (serialize(parse(value)) !== value) re-applying compounds the divergence
242
+ // every cycle (`<p>` → `&lt;p&gt;` → `&amp;lt;p&amp;gt;` …). Tracked so the
243
+ // identical re-fetch is recognized and skipped.
244
+ const lastAppliedValueRef = useRef<string | null>(null);
245
+ // The editor's SERIALIZED output captured right AFTER the last reconcile/seed
246
+ // apply (`getMarkdown(editor)` once the content settled). For non-idempotent
247
+ // input this is what autosave actually persists, so the NEXT poll hands it
248
+ // back as the new `value`. Comparing the incoming value against this lets the
249
+ // reconcile recognize its own echo even when the raw string changed once, so
250
+ // it never re-parses content the editor already represents. This is the
251
+ // doc-equivalence guard that breaks the escalation loop.
252
+ const lastAppliedSerializedRef = useRef<string | null>(null);
253
+ const lastAppliedUpdatedAtRef = useRef<string | null>(
254
+ initialAppliedUpdatedAt !== undefined
255
+ ? initialAppliedUpdatedAt
256
+ : (contentUpdatedAt ?? null),
257
+ );
258
+
259
+ // Whether THIS client is the one that seeds the empty shared doc / applies an
260
+ // authoritative external snapshot into it. Exactly one client does, so the
261
+ // content isn't inserted once per open editor. A sole client always leads.
262
+ const [isLeadClient, setIsLeadClient] = useState(true);
263
+ // Count of OTHER visible human collaborators. When >0, a peer's edit also
264
+ // arrives via Yjs, so external markdown reconcile must defer (avoid applying
265
+ // the same change through both Yjs and setContent).
266
+ const peerCountRef = useRef(0);
267
+ useEffect(() => {
268
+ if (!collab || !awareness || !ydoc) {
269
+ setIsLeadClient(true);
270
+ peerCountRef.current = 0;
271
+ return;
272
+ }
273
+ const update = () => {
274
+ setIsLeadClient(isReconcileLeadClient(awareness, ydoc.clientID));
275
+ let peers = 0;
276
+ awareness.getStates().forEach((state, clientId) => {
277
+ if (clientId === ydoc.clientID) return; // self
278
+ if (clientId === AGENT_CLIENT_ID) return; // agent isn't a Yjs editor
279
+ const s = state as { user?: unknown; visible?: boolean };
280
+ if (s && s.user && s.visible !== false) peers += 1;
281
+ });
282
+ peerCountRef.current = peers;
283
+ };
284
+ update();
285
+ awareness.on("change", update);
286
+ document.addEventListener("visibilitychange", update);
287
+ return () => {
288
+ awareness.off("change", update);
289
+ document.removeEventListener("visibilitychange", update);
290
+ };
291
+ }, [collab, awareness, ydoc]);
292
+
293
+ // Collab seed: populate an empty shared Y.Doc from the markdown `value` once.
294
+ // The Collaboration extension does NOT auto-seed; only the lead client does,
295
+ // so two clients opening a brand-new block at once don't both seed (which
296
+ // would duplicate the content via concurrent inserts at the same position).
297
+ const seededRef = useRef(false);
298
+ useEffect(() => {
299
+ if (!collab || !editor || editor.isDestroyed || !ydoc) return;
300
+ if (seededRef.current) return;
301
+ if (!collabSynced) return;
302
+ if (!isLeadClient) return;
303
+ if (!value.trim()) return;
304
+ const fragment = ydoc.getXmlFragment("default");
305
+ const currentMarkdown = getMarkdown(editor);
306
+ // Seed only when the shared doc is genuinely empty — either the fragment has
307
+ // no nodes yet, or it holds no semantic markdown (an empty paragraph, or an
308
+ // app's sentinel-empty filler via a custom `shouldSeed`).
309
+ if (
310
+ !shouldSeed({ value, currentMarkdown, fragmentLength: fragment.length })
311
+ ) {
312
+ seededRef.current = true;
313
+ return;
314
+ }
315
+
316
+ let cancelled = false;
317
+ // Defer via a timer task (NOT a microtask — microtasks can still run
318
+ // inside React's commit and trigger flushSync-from-lifecycle warnings).
319
+ const seedTimer = setTimeout(() => {
320
+ if (cancelled || editor.isDestroyed) return;
321
+ isSettingContentRef.current = true;
322
+ try {
323
+ setContent(editor, value, {});
324
+ } finally {
325
+ isSettingContentRef.current = false;
326
+ }
327
+ const serialized = getMarkdown(editor);
328
+ lastEmittedRef.current = serialized;
329
+ pushEmittedRing(recentEmittedRef.current, serialized);
330
+ lastAppliedValueRef.current = value;
331
+ lastAppliedSerializedRef.current = serialized;
332
+ if (contentUpdatedAt) lastAppliedUpdatedAtRef.current = contentUpdatedAt;
333
+ seededRef.current = true;
334
+ }, 0);
335
+ return () => {
336
+ cancelled = true;
337
+ clearTimeout(seedTimer);
338
+ };
339
+ }, [
340
+ collab,
341
+ collabSynced,
342
+ editor,
343
+ ydoc,
344
+ value,
345
+ isLeadClient,
346
+ contentUpdatedAt,
347
+ getMarkdown,
348
+ setContent,
349
+ shouldSeed,
350
+ ]);
351
+
352
+ // Reconcile authoritative external markdown (agent edit, source patch, or a
353
+ // peer edit mirrored to SQL) into the live editor. In collab mode only the
354
+ // lead client applies it through setContent; Yjs propagates the result to
355
+ // every other client. In non-collab mode this is the original controlled-value
356
+ // reconcile, unchanged.
357
+ useEffect(() => {
358
+ if (!editor || editor.isDestroyed) return;
359
+
360
+ let cancelled = false;
361
+ let retry: ReturnType<typeof setTimeout> | null = null;
362
+ // With peers present, a peer's edit also arrives via Yjs. Defer one poll
363
+ // cycle (+margin) and re-check before applying via setContent so the same
364
+ // change isn't inserted twice (Yjs + setContent → duplicated region).
365
+ const PEER_SETTLE_MS = 2500;
366
+
367
+ const apply = (deferred = false) => {
368
+ if (cancelled || editor.isDestroyed) return;
369
+ // In collab mode, defer all reconcile until the shared doc is seeded so we
370
+ // never setContent over an unseeded fragment.
371
+ if (collab && (!collabSynced || !seededRef.current)) {
372
+ retry = setTimeout(() => apply(deferred), 300);
373
+ return;
374
+ }
375
+ const currentMarkdown = getMarkdown(editor);
376
+ // Compare against the canonical form the editor would emit so a serializer
377
+ // that re-normalizes (Content's NFM) still recognizes "already in sync".
378
+ const normalizedValue = normalizeValue(value);
379
+ // Whether the editor still holds exactly what THIS hook last applied (the
380
+ // user hasn't edited since). Only then are the round-trip echo guards
381
+ // below safe: if the user has since edited away from the applied content,
382
+ // an external snapshot equal to a previously-applied value is a real
383
+ // revert and must NOT be swallowed as an echo.
384
+ const editorUnchangedSinceApply =
385
+ lastAppliedSerializedRef.current !== null &&
386
+ currentMarkdown === lastAppliedSerializedRef.current;
387
+ const typingRecently =
388
+ editor.isFocused && Date.now() - lastTypedAtRef.current < 1500;
389
+
390
+ // Doc-equivalence skip. Never re-apply content the editor already
391
+ // represents — comparing by DOC EQUIVALENCE, not raw strings/timestamps:
392
+ // 1. `currentMarkdown === normalizedValue` — the editor's CURRENT
393
+ // serialized doc already equals the (normalized) incoming value.
394
+ // 2. `value === lastEmittedRef.current` — the incoming value is our own
395
+ // just-emitted markdown echoing back.
396
+ // 3. `value === lastAppliedValueRef.current` — the SAME raw value we
397
+ // already applied is being re-supplied (a lagging poll or a
398
+ // source-sync re-handing the same stored markdown). Applying it again
399
+ // would only reproduce the doc we hold; for NON-idempotent input it
400
+ // would compound divergence. Guarded by `editorUnchangedSinceApply`
401
+ // so a deliberate revert-to-previous after a local edit still lands.
402
+ // 4. `normalizedValue === lastAppliedSerializedRef.current` — the
403
+ // incoming value round-trips to the serialized output we last
404
+ // produced (our own autosaved echo coming back from SQL). For
405
+ // non-idempotent input the raw string differs from what we were
406
+ // handed, but it is doc-equivalent to what the editor already shows,
407
+ // so re-parsing it must be skipped. This is the guard that stops the
408
+ // `<p>` → `&lt;p&gt;` → `&amp;lt;p&amp;gt;` escalation.
409
+ if (
410
+ currentMarkdown === normalizedValue ||
411
+ (typingRecently &&
412
+ // A stale echo of our own (possibly partial) save while the user is
413
+ // actively typing would clobber the fresh tail. Outside active
414
+ // typing, the same bytes can be a deliberate newer external revert
415
+ // (history restore / provider conflict choice) and must be allowed
416
+ // through even if mount-time normalization emitted them.
417
+ (value === lastEmittedRef.current ||
418
+ recentEmittedRef.current.includes(value) ||
419
+ recentEmittedRef.current.includes(normalizedValue))) ||
420
+ (editorUnchangedSinceApply &&
421
+ (value === lastAppliedValueRef.current ||
422
+ normalizedValue === lastAppliedSerializedRef.current))
423
+ ) {
424
+ if (contentUpdatedAt) {
425
+ lastAppliedUpdatedAtRef.current = contentUpdatedAt;
426
+ }
427
+ return;
428
+ }
429
+
430
+ const externalNewer =
431
+ !lastAppliedUpdatedAtRef.current ||
432
+ !contentUpdatedAt ||
433
+ contentUpdatedAt > lastAppliedUpdatedAtRef.current;
434
+
435
+ // Only the lead client applies an authoritative snapshot into the shared
436
+ // Y.Doc; peers receive it through Yjs sync.
437
+ if (collab && !isLeadClient) {
438
+ if (contentUpdatedAt && !externalNewer) {
439
+ lastAppliedUpdatedAtRef.current = contentUpdatedAt;
440
+ }
441
+ return;
442
+ }
443
+
444
+ // Never clobber an in-progress edit. While the user is actively typing
445
+ // (focused and a keystroke landed within the window) defer and re-check —
446
+ // applying external content now would yank text out from under them and,
447
+ // for non-idempotent input, fight every keystroke. Newer external content
448
+ // retries so it still lands once they pause; older-or-equal content is a
449
+ // stale poll and is dropped outright while focused.
450
+ if (typingRecently) {
451
+ if (externalNewer) {
452
+ retry = setTimeout(() => apply(deferred), 700);
453
+ }
454
+ return;
455
+ }
456
+ // Older-or-equal content is a stale poll / lagging echo. Drop it while
457
+ // focused (a peer/agent edit would be NEWER and retries above). In
458
+ // NON-COLLAB mode there is no peer, so older-or-equal external content is
459
+ // ALWAYS stale — dropping it regardless of focus stops a lagging
460
+ // `get-visual-plan` poll from reverting a just-applied local structural
461
+ // change (drag-to-columns) while the editor is blurred (the drag grips the
462
+ // handle, not the prose, so `isFocused` is false at drop time). Gated on
463
+ // `lastAppliedSerializedRef` so the very first seed (nothing applied yet,
464
+ // also not-newer) still lands.
465
+ const seeded = lastAppliedSerializedRef.current !== null;
466
+ if (!externalNewer && (editor.isFocused || (!collab && seeded))) return;
467
+
468
+ // Race guard: with peers present, let Yjs deliver a peer's edit first.
469
+ // Defer once and re-check — a peer edit makes the equality check above
470
+ // no-op next pass; an agent/source edit still differs and applies.
471
+ if (collab && externalNewer && !deferred && peerCountRef.current > 0) {
472
+ retry = setTimeout(() => apply(true), PEER_SETTLE_MS);
473
+ return;
474
+ }
475
+
476
+ const applyTimer = setTimeout(() => {
477
+ if (cancelled || editor.isDestroyed) return;
478
+ // Re-check doc-equivalence at apply time. Between the decision above and
479
+ // this task a peer/Yjs edit (or our own prior apply) may have made
480
+ // the editor already represent this value — re-applying would be a
481
+ // wasted setContent that, for non-idempotent input, re-triggers the
482
+ // loop. Skip when the editor's current serialization already matches the
483
+ // normalized value, or the value round-trips to what we last produced.
484
+ const beforeMarkdown = getMarkdown(editor);
485
+ const normalized = normalizeValue(value);
486
+ const unchangedSinceApply =
487
+ lastAppliedSerializedRef.current !== null &&
488
+ beforeMarkdown === lastAppliedSerializedRef.current;
489
+ if (
490
+ beforeMarkdown === normalized ||
491
+ (unchangedSinceApply &&
492
+ normalized === lastAppliedSerializedRef.current)
493
+ ) {
494
+ lastAppliedValueRef.current = value;
495
+ if (contentUpdatedAt) {
496
+ lastAppliedUpdatedAtRef.current = contentUpdatedAt;
497
+ }
498
+ return;
499
+ }
500
+ isSettingContentRef.current = true;
501
+ // Surgical path first: replace only the changed top-level run so
502
+ // unchanged block NodeViews are never torn down and (under
503
+ // Collaboration) Yjs sees a minimal edit instead of a full-fragment
504
+ // rewrite. Falls back to the classic whole-document setContent when no
505
+ // parser is available or the targeted transaction cannot be applied.
506
+ let appliedSurgically = false;
507
+ if (parseValue !== false) {
508
+ const parse = parseValue ?? defaultParseValue;
509
+ const parsedDoc = parse(editor, value);
510
+ if (parsedDoc) {
511
+ const result = applyDocSurgically(editor, parsedDoc);
512
+ appliedSurgically = result === "applied" || result === "noop";
513
+ }
514
+ }
515
+ if (!appliedSurgically) {
516
+ setContent(editor, value, { emitUpdate: false, addToHistory: false });
517
+ }
518
+ isSettingContentRef.current = false;
519
+ // Capture the SERIALIZED result, not the raw value. For non-idempotent
520
+ // input these differ; recording the serialized output is what lets the
521
+ // next poll (which returns this serialized form) be recognized as our
522
+ // own echo and skipped — stabilizing the doc after exactly one apply.
523
+ const serialized = getMarkdown(editor);
524
+ lastEmittedRef.current = serialized;
525
+ pushEmittedRing(recentEmittedRef.current, serialized);
526
+ lastAppliedValueRef.current = value;
527
+ lastAppliedSerializedRef.current = serialized;
528
+ if (contentUpdatedAt) {
529
+ lastAppliedUpdatedAtRef.current = contentUpdatedAt;
530
+ }
531
+ }, 0);
532
+ retry = applyTimer;
533
+ };
534
+
535
+ apply();
536
+ return () => {
537
+ cancelled = true;
538
+ if (retry) clearTimeout(retry);
539
+ };
540
+ }, [
541
+ contentUpdatedAt,
542
+ editor,
543
+ value,
544
+ collab,
545
+ collabSynced,
546
+ isLeadClient,
547
+ getMarkdown,
548
+ setContent,
549
+ parseValue,
550
+ normalizeValue,
551
+ ]);
552
+
553
+ const shouldIgnoreUpdate = (transaction: Transaction): boolean => {
554
+ if (!editable || isSettingContentRef.current) return true;
555
+ // Collaboration can emit schema/default-paragraph transactions while the
556
+ // persisted Y.Doc is still loading and before the authoritative value has
557
+ // seeded/reconciled. Never let those transient pre-seed updates reach an
558
+ // app's local mirror or autosave path (Content serializes an empty paragraph
559
+ // as `<empty-block/>`, which is non-empty text and bypasses the generic
560
+ // registerEmitted empty-string guard).
561
+ if (collab && !seededRef.current) return true;
562
+ if (transaction.getMeta(RICH_MARKDOWN_PROGRAMMATIC_TRANSACTION)) {
563
+ return true;
564
+ }
565
+ // In collab mode, never persist remote-originated changes (the initial Yjs
566
+ // state load or a peer's edit arriving via sync). Each client saves only its
567
+ // OWN local edits; a peer's edit is saved by that peer. Without this, a
568
+ // lagging Y.Doc load would write stale markdown over newer SQL.
569
+ if (collab && transaction && isChangeOrigin(transaction)) return true;
570
+ lastTypedAtRef.current = Date.now();
571
+ return false;
572
+ };
573
+
574
+ const registerEmitted = (markdown: string): boolean => {
575
+ // Don't persist an empty doc before Collaboration has seeded — that would
576
+ // clobber the saved block content with an empty string.
577
+ if (collab && !markdown.trim()) return false;
578
+ lastEmittedRef.current = markdown;
579
+ pushEmittedRing(recentEmittedRef.current, markdown);
580
+ return true;
581
+ };
582
+
583
+ return {
584
+ collab,
585
+ isSettingContentRef,
586
+ shouldIgnoreUpdate,
587
+ registerEmitted,
588
+ };
589
+ }