@agent-native/core 0.39.1 → 0.40.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 (208) hide show
  1. package/README.md +1 -1
  2. package/dist/action.js +12 -0
  3. package/dist/action.js.map +1 -1
  4. package/dist/cli/create.d.ts.map +1 -1
  5. package/dist/cli/create.js +5 -1
  6. package/dist/cli/create.js.map +1 -1
  7. package/dist/cli/index.js +1 -1
  8. package/dist/cli/index.js.map +1 -1
  9. package/dist/cli/skills.d.ts +6 -6
  10. package/dist/cli/skills.d.ts.map +1 -1
  11. package/dist/cli/skills.js +936 -1167
  12. package/dist/cli/skills.js.map +1 -1
  13. package/dist/client/MultiTabAssistantChat.d.ts.map +1 -1
  14. package/dist/client/MultiTabAssistantChat.js +2 -5
  15. package/dist/client/MultiTabAssistantChat.js.map +1 -1
  16. package/dist/client/NewWorkspaceAppFlow.js +1 -1
  17. package/dist/client/NewWorkspaceAppFlow.js.map +1 -1
  18. package/dist/client/blocks/AiEditableField.d.ts +8 -0
  19. package/dist/client/blocks/AiEditableField.d.ts.map +1 -0
  20. package/dist/client/blocks/AiEditableField.js +10 -0
  21. package/dist/client/blocks/AiEditableField.js.map +1 -0
  22. package/dist/client/blocks/BlockView.d.ts +3 -3
  23. package/dist/client/blocks/BlockView.d.ts.map +1 -1
  24. package/dist/client/blocks/BlockView.js +15 -3
  25. package/dist/client/blocks/BlockView.js.map +1 -1
  26. package/dist/client/blocks/SchemaBlockEditor.js +2 -2
  27. package/dist/client/blocks/SchemaBlockEditor.js.map +1 -1
  28. package/dist/client/blocks/index.d.ts +5 -2
  29. package/dist/client/blocks/index.d.ts.map +1 -1
  30. package/dist/client/blocks/index.js +6 -3
  31. package/dist/client/blocks/index.js.map +1 -1
  32. package/dist/client/blocks/library/ApiEndpointBlock.d.ts.map +1 -1
  33. package/dist/client/blocks/library/ApiEndpointBlock.js +20 -6
  34. package/dist/client/blocks/library/ApiEndpointBlock.js.map +1 -1
  35. package/dist/client/blocks/library/DiffBlock.d.ts +29 -0
  36. package/dist/client/blocks/library/DiffBlock.d.ts.map +1 -1
  37. package/dist/client/blocks/library/DiffBlock.js +190 -30
  38. package/dist/client/blocks/library/DiffBlock.js.map +1 -1
  39. package/dist/client/blocks/library/FileTreeBlock.d.ts.map +1 -1
  40. package/dist/client/blocks/library/FileTreeBlock.js +46 -7
  41. package/dist/client/blocks/library/FileTreeBlock.js.map +1 -1
  42. package/dist/client/blocks/library/HighlightedCode.d.ts +10 -0
  43. package/dist/client/blocks/library/HighlightedCode.d.ts.map +1 -0
  44. package/dist/client/blocks/library/HighlightedCode.js +92 -0
  45. package/dist/client/blocks/library/HighlightedCode.js.map +1 -0
  46. package/dist/client/blocks/library/JsonExplorerBlock.d.ts +9 -4
  47. package/dist/client/blocks/library/JsonExplorerBlock.d.ts.map +1 -1
  48. package/dist/client/blocks/library/JsonExplorerBlock.js +66 -30
  49. package/dist/client/blocks/library/JsonExplorerBlock.js.map +1 -1
  50. package/dist/client/blocks/library/MermaidBlock.d.ts.map +1 -1
  51. package/dist/client/blocks/library/MermaidBlock.js +73 -44
  52. package/dist/client/blocks/library/MermaidBlock.js.map +1 -1
  53. package/dist/client/blocks/library/OpenApiSpecBlock.d.ts.map +1 -1
  54. package/dist/client/blocks/library/OpenApiSpecBlock.js +3 -2
  55. package/dist/client/blocks/library/OpenApiSpecBlock.js.map +1 -1
  56. package/dist/client/blocks/library/checklist.d.ts.map +1 -1
  57. package/dist/client/blocks/library/checklist.js +1 -0
  58. package/dist/client/blocks/library/checklist.js.map +1 -1
  59. package/dist/client/blocks/library/code-tabs.d.ts.map +1 -1
  60. package/dist/client/blocks/library/code-tabs.js +183 -102
  61. package/dist/client/blocks/library/code-tabs.js.map +1 -1
  62. package/dist/client/blocks/library/columns.config.d.ts +60 -0
  63. package/dist/client/blocks/library/columns.config.d.ts.map +1 -0
  64. package/dist/client/blocks/library/columns.config.js +37 -0
  65. package/dist/client/blocks/library/columns.config.js.map +1 -0
  66. package/dist/client/blocks/library/columns.d.ts +25 -0
  67. package/dist/client/blocks/library/columns.d.ts.map +1 -0
  68. package/dist/client/blocks/library/columns.js +199 -0
  69. package/dist/client/blocks/library/columns.js.map +1 -0
  70. package/dist/client/blocks/library/dev-doc-ui.d.ts +2 -1
  71. package/dist/client/blocks/library/dev-doc-ui.d.ts.map +1 -1
  72. package/dist/client/blocks/library/dev-doc-ui.js +2 -1
  73. package/dist/client/blocks/library/dev-doc-ui.js.map +1 -1
  74. package/dist/client/blocks/library/html.d.ts +1 -1
  75. package/dist/client/blocks/library/html.d.ts.map +1 -1
  76. package/dist/client/blocks/library/html.js +34 -4
  77. package/dist/client/blocks/library/html.js.map +1 -1
  78. package/dist/client/blocks/library/json-explorer.config.d.ts +3 -1
  79. package/dist/client/blocks/library/json-explorer.config.d.ts.map +1 -1
  80. package/dist/client/blocks/library/json-explorer.config.js +30 -1
  81. package/dist/client/blocks/library/json-explorer.config.js.map +1 -1
  82. package/dist/client/blocks/library/server-specs.d.ts.map +1 -1
  83. package/dist/client/blocks/library/server-specs.js +13 -3
  84. package/dist/client/blocks/library/server-specs.js.map +1 -1
  85. package/dist/client/blocks/library/specs.d.ts +4 -4
  86. package/dist/client/blocks/library/specs.d.ts.map +1 -1
  87. package/dist/client/blocks/library/specs.js +21 -16
  88. package/dist/client/blocks/library/specs.js.map +1 -1
  89. package/dist/client/blocks/library/table.config.d.ts +3 -0
  90. package/dist/client/blocks/library/table.config.d.ts.map +1 -1
  91. package/dist/client/blocks/library/table.config.js +13 -1
  92. package/dist/client/blocks/library/table.config.js.map +1 -1
  93. package/dist/client/blocks/library/table.d.ts.map +1 -1
  94. package/dist/client/blocks/library/table.js +90 -9
  95. package/dist/client/blocks/library/table.js.map +1 -1
  96. package/dist/client/blocks/library/tabs.config.d.ts +16 -8
  97. package/dist/client/blocks/library/tabs.config.d.ts.map +1 -1
  98. package/dist/client/blocks/library/tabs.config.js +10 -4
  99. package/dist/client/blocks/library/tabs.config.js.map +1 -1
  100. package/dist/client/blocks/library/tabs.d.ts.map +1 -1
  101. package/dist/client/blocks/library/tabs.js +146 -21
  102. package/dist/client/blocks/library/tabs.js.map +1 -1
  103. package/dist/client/blocks/server.d.ts +2 -1
  104. package/dist/client/blocks/server.d.ts.map +1 -1
  105. package/dist/client/blocks/server.js +1 -0
  106. package/dist/client/blocks/server.js.map +1 -1
  107. package/dist/client/blocks/types.d.ts +99 -9
  108. package/dist/client/blocks/types.d.ts.map +1 -1
  109. package/dist/client/blocks/types.js.map +1 -1
  110. package/dist/client/index.d.ts +1 -1
  111. package/dist/client/index.d.ts.map +1 -1
  112. package/dist/client/index.js +2 -2
  113. package/dist/client/index.js.map +1 -1
  114. package/dist/client/rich-markdown-editor/BubbleToolbar.d.ts.map +1 -1
  115. package/dist/client/rich-markdown-editor/BubbleToolbar.js +13 -3
  116. package/dist/client/rich-markdown-editor/BubbleToolbar.js.map +1 -1
  117. package/dist/client/rich-markdown-editor/DragHandle.d.ts +49 -4
  118. package/dist/client/rich-markdown-editor/DragHandle.d.ts.map +1 -1
  119. package/dist/client/rich-markdown-editor/DragHandle.js +656 -88
  120. package/dist/client/rich-markdown-editor/DragHandle.js.map +1 -1
  121. package/dist/client/rich-markdown-editor/RegistryBlockNode.d.ts +10 -1
  122. package/dist/client/rich-markdown-editor/RegistryBlockNode.d.ts.map +1 -1
  123. package/dist/client/rich-markdown-editor/RegistryBlockNode.js +180 -15
  124. package/dist/client/rich-markdown-editor/RegistryBlockNode.js.map +1 -1
  125. package/dist/client/rich-markdown-editor/SharedRichEditor.d.ts +2 -1
  126. package/dist/client/rich-markdown-editor/SharedRichEditor.d.ts.map +1 -1
  127. package/dist/client/rich-markdown-editor/SharedRichEditor.js +3 -1
  128. package/dist/client/rich-markdown-editor/SharedRichEditor.js.map +1 -1
  129. package/dist/client/rich-markdown-editor/SlashCommandMenu.d.ts +5 -0
  130. package/dist/client/rich-markdown-editor/SlashCommandMenu.d.ts.map +1 -1
  131. package/dist/client/rich-markdown-editor/SlashCommandMenu.js +33 -5
  132. package/dist/client/rich-markdown-editor/SlashCommandMenu.js.map +1 -1
  133. package/dist/client/rich-markdown-editor/index.d.ts +3 -3
  134. package/dist/client/rich-markdown-editor/index.d.ts.map +1 -1
  135. package/dist/client/rich-markdown-editor/index.js +2 -2
  136. package/dist/client/rich-markdown-editor/index.js.map +1 -1
  137. package/dist/client/rich-markdown-editor/registrySlashCommands.d.ts +14 -0
  138. package/dist/client/rich-markdown-editor/registrySlashCommands.d.ts.map +1 -1
  139. package/dist/client/rich-markdown-editor/registrySlashCommands.js +38 -0
  140. package/dist/client/rich-markdown-editor/registrySlashCommands.js.map +1 -1
  141. package/dist/client/rich-markdown-editor/useCollabReconcile.d.ts +1 -0
  142. package/dist/client/rich-markdown-editor/useCollabReconcile.d.ts.map +1 -1
  143. package/dist/client/rich-markdown-editor/useCollabReconcile.js +4 -0
  144. package/dist/client/rich-markdown-editor/useCollabReconcile.js.map +1 -1
  145. package/dist/client/settings/SettingsPanel.d.ts.map +1 -1
  146. package/dist/client/settings/SettingsPanel.js +11 -19
  147. package/dist/client/settings/SettingsPanel.js.map +1 -1
  148. package/dist/client/use-chat-models.d.ts.map +1 -1
  149. package/dist/client/use-chat-models.js +2 -5
  150. package/dist/client/use-chat-models.js.map +1 -1
  151. package/dist/db/client.d.ts.map +1 -1
  152. package/dist/db/client.js +17 -1
  153. package/dist/db/client.js.map +1 -1
  154. package/dist/deploy/build.d.ts.map +1 -1
  155. package/dist/deploy/build.js +2 -1
  156. package/dist/deploy/build.js.map +1 -1
  157. package/dist/deploy/route-discovery.d.ts +29 -0
  158. package/dist/deploy/route-discovery.d.ts.map +1 -1
  159. package/dist/deploy/route-discovery.js +158 -11
  160. package/dist/deploy/route-discovery.js.map +1 -1
  161. package/dist/server/auth.d.ts +2 -0
  162. package/dist/server/auth.d.ts.map +1 -1
  163. package/dist/server/auth.js +9 -0
  164. package/dist/server/auth.js.map +1 -1
  165. package/dist/sharing/access.d.ts +4 -2
  166. package/dist/sharing/access.d.ts.map +1 -1
  167. package/dist/sharing/access.js +8 -3
  168. package/dist/sharing/access.js.map +1 -1
  169. package/dist/sharing/actions/set-resource-visibility.d.ts.map +1 -1
  170. package/dist/sharing/actions/set-resource-visibility.js +2 -3
  171. package/dist/sharing/actions/set-resource-visibility.js.map +1 -1
  172. package/dist/sharing/registry.d.ts +13 -0
  173. package/dist/sharing/registry.d.ts.map +1 -1
  174. package/dist/sharing/registry.js.map +1 -1
  175. package/dist/styles/rich-markdown-editor.css +15 -0
  176. package/dist/templates/default/.agents/skills/actions/SKILL.md +96 -11
  177. package/dist/templates/default/.agents/skills/adding-a-feature/SKILL.md +126 -26
  178. package/dist/templates/default/.agents/skills/capture-learnings/SKILL.md +56 -30
  179. package/dist/templates/default/.agents/skills/create-skill/SKILL.md +28 -0
  180. package/dist/templates/default/.agents/skills/delegate-to-agent/SKILL.md +75 -5
  181. package/dist/templates/default/.agents/skills/frontend-design/SKILL.md +17 -0
  182. package/dist/templates/default/.agents/skills/real-time-collab/SKILL.md +99 -124
  183. package/dist/templates/default/.agents/skills/real-time-sync/SKILL.md +43 -10
  184. package/dist/templates/default/.agents/skills/security/SKILL.md +162 -144
  185. package/dist/templates/default/.agents/skills/self-modifying-code/SKILL.md +5 -3
  186. package/dist/templates/default/.agents/skills/shadcn-ui/SKILL.md +15 -0
  187. package/dist/templates/default/.agents/skills/storing-data/SKILL.md +116 -83
  188. package/dist/templates/default/DEVELOPING.md +10 -13
  189. package/dist/templates/workspace-core/.agents/skills/client-methods/references/legacy-client-fetch-audit-2026-06-03.md +9 -0
  190. package/dist/templates/workspace-core/.agents/skills/writing-agent-instructions/SKILL.md +27 -0
  191. package/docs/content/template-plan.md +5 -3
  192. package/docs/content/visual-plans.md +5 -2
  193. package/package.json +16 -1
  194. package/src/templates/default/.agents/skills/actions/SKILL.md +96 -11
  195. package/src/templates/default/.agents/skills/adding-a-feature/SKILL.md +126 -26
  196. package/src/templates/default/.agents/skills/capture-learnings/SKILL.md +56 -30
  197. package/src/templates/default/.agents/skills/create-skill/SKILL.md +28 -0
  198. package/src/templates/default/.agents/skills/delegate-to-agent/SKILL.md +75 -5
  199. package/src/templates/default/.agents/skills/frontend-design/SKILL.md +17 -0
  200. package/src/templates/default/.agents/skills/real-time-collab/SKILL.md +99 -124
  201. package/src/templates/default/.agents/skills/real-time-sync/SKILL.md +43 -10
  202. package/src/templates/default/.agents/skills/security/SKILL.md +162 -144
  203. package/src/templates/default/.agents/skills/self-modifying-code/SKILL.md +5 -3
  204. package/src/templates/default/.agents/skills/shadcn-ui/SKILL.md +15 -0
  205. package/src/templates/default/.agents/skills/storing-data/SKILL.md +116 -83
  206. package/src/templates/default/DEVELOPING.md +10 -13
  207. package/src/templates/workspace-core/.agents/skills/client-methods/references/legacy-client-fetch-audit-2026-06-03.md +9 -0
  208. package/src/templates/workspace-core/.agents/skills/writing-agent-instructions/SKILL.md +27 -0
@@ -1,3 +1,40 @@
1
+ const COMPACT_REGISTRY_BLOCK_DESCRIPTIONS = {
2
+ callout: "Emphasized note",
3
+ diagram: "Inline diagram",
4
+ wireframe: "Screen mockup",
5
+ "question-form": "Interactive questions",
6
+ checklist: "Checklist items",
7
+ table: "Editable grid",
8
+ "table-block": "Editable grid",
9
+ "code-tabs": "Tabbed code snippets",
10
+ "custom-html": "Sandboxed HTML",
11
+ tabs: "Tabbed block group",
12
+ columns: "Side-by-side columns",
13
+ mermaid: "Mermaid diagram",
14
+ "api-endpoint": "API reference",
15
+ "openapi-spec": "OpenAPI document",
16
+ "data-model": "ERD schema",
17
+ diff: "Code diff",
18
+ "file-tree": "File/change tree",
19
+ "json-explorer": "JSON tree",
20
+ "annotated-code": "Code walkthrough",
21
+ };
22
+ /**
23
+ * Compact, user-facing slash-menu copy for structured registry blocks. The full
24
+ * registry description remains available through search text, but the visible
25
+ * row should scan like a command palette, not a block reference page.
26
+ */
27
+ export function getRegistryBlockSlashDescription(spec) {
28
+ return (COMPACT_REGISTRY_BLOCK_DESCRIPTIONS[spec.type] ??
29
+ spec.description.trim().replace(/\s+/g, " "));
30
+ }
31
+ /** Searchable text for registry block slash items, including raw type keywords. */
32
+ export function getRegistryBlockSlashSearchText(spec) {
33
+ return [spec.label, spec.description, spec.type]
34
+ .filter(Boolean)
35
+ .join(" ")
36
+ .toLowerCase();
37
+ }
1
38
  /**
2
39
  * Build the registry-derived block slash items, shared by plan and content. Each
3
40
  * app prepends its own prose/base commands and wraps the result in its own item
@@ -7,6 +44,7 @@ export function buildRegistryBlockSlashItems(registry, options) {
7
44
  const isCompatible = options.isNotionCompatible ?? ((spec) => Boolean(spec.notionCompatible));
8
45
  return registry
9
46
  .list("block")
47
+ .filter((spec) => options.includeSpec?.(spec) ?? true)
10
48
  .filter((spec) => !options.notionCompatibleOnly || isCompatible(spec))
11
49
  .map((spec) => options.toItem(spec, (editor) => options.insertBlock(editor, spec)));
12
50
  }
@@ -1 +1 @@
1
- {"version":3,"file":"registrySlashCommands.js","sourceRoot":"","sources":["../../../src/client/rich-markdown-editor/registrySlashCommands.ts"],"names":[],"mappings":"AAyCA;;;;GAIG;AACH,MAAM,UAAU,4BAA4B,CAC1C,QAAuB,EACvB,OAA4D;IAE5D,MAAM,YAAY,GAChB,OAAO,CAAC,kBAAkB,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC;IAC3E,OAAO,QAAQ;SACZ,IAAI,CAAC,OAAO,CAAC;SACb,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,oBAAoB,IAAI,YAAY,CAAC,IAAI,CAAC,CAAC;SACrE,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACZ,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CACpE,CAAC;AACN,CAAC","sourcesContent":["import type { BlockRegistry, BlockSpec } from \"../blocks/index.js\";\n\n/**\n * Shared builder for the registry-derived block slash commands both the plan and\n * content editors offer. Both apps take every `BlockSpec` whose `placement`\n * includes `\"block\"`, gate it by Notion-compatibility when the open document is\n * linked to a Notion page, and emit one slash item per surviving spec that\n * inserts that block's atom node. The only legitimate per-app differences are:\n *\n * - the ITEM SHAPE (plan uses a text-glyph `icon`, content a React component),\n * - the Notion-compat PREDICATE (plan unions in prose-only NFM analogs, content\n * reads the registry `notionCompatible` flag directly), and\n * - the INSERT behavior (plan inserts a `planBlock` node, content a\n * `registryBlock` node seeded with inline `__raw`).\n *\n * Those three are injected; everything else (the `list(\"block\")` source, the\n * Notion filter wiring, the one-item-per-spec mapping) lives here so adding a\n * new library block only touches the registry, never the slash builders.\n */\nexport interface BuildRegistryBlockSlashItemsOptions<TItem, TEditor> {\n /**\n * When `true`, only specs the predicate accepts are offered (the open document\n * is linked to a Notion page, so blocks that can't round-trip to NFM are\n * hidden). When unset/false, every block-placed spec is offered.\n */\n notionCompatibleOnly?: boolean;\n /**\n * Decide whether a spec round-trips to Notion. Defaults to the spec's own\n * `notionCompatible` flag (content's rule). Plan passes a predicate that unions\n * in prose-only NFM analogs not carried as registry flags.\n */\n isNotionCompatible?: (spec: BlockSpec) => boolean;\n /** Build one app-shaped slash item from a surviving block spec. */\n toItem: (spec: BlockSpec, insert: (editor: TEditor) => void) => TItem;\n /**\n * Insert this spec's block atom into the editor. Plan inserts a `planBlock`\n * node; content inserts a `registryBlock` node seeded with inline `__raw`.\n */\n insertBlock: (editor: TEditor, spec: BlockSpec) => void;\n}\n\n/**\n * Build the registry-derived block slash items, shared by plan and content. Each\n * app prepends its own prose/base commands and wraps the result in its own item\n * type via {@link BuildRegistryBlockSlashItemsOptions.toItem}.\n */\nexport function buildRegistryBlockSlashItems<TItem, TEditor>(\n registry: BlockRegistry,\n options: BuildRegistryBlockSlashItemsOptions<TItem, TEditor>,\n): TItem[] {\n const isCompatible =\n options.isNotionCompatible ?? ((spec) => Boolean(spec.notionCompatible));\n return registry\n .list(\"block\")\n .filter((spec) => !options.notionCompatibleOnly || isCompatible(spec))\n .map((spec) =>\n options.toItem(spec, (editor) => options.insertBlock(editor, spec)),\n );\n}\n"]}
1
+ {"version":3,"file":"registrySlashCommands.js","sourceRoot":"","sources":["../../../src/client/rich-markdown-editor/registrySlashCommands.ts"],"names":[],"mappings":"AAEA,MAAM,mCAAmC,GAA2B;IAClE,OAAO,EAAE,iBAAiB;IAC1B,OAAO,EAAE,gBAAgB;IACzB,SAAS,EAAE,eAAe;IAC1B,eAAe,EAAE,uBAAuB;IACxC,SAAS,EAAE,iBAAiB;IAC5B,KAAK,EAAE,eAAe;IACtB,aAAa,EAAE,eAAe;IAC9B,WAAW,EAAE,sBAAsB;IACnC,aAAa,EAAE,gBAAgB;IAC/B,IAAI,EAAE,oBAAoB;IAC1B,OAAO,EAAE,sBAAsB;IAC/B,OAAO,EAAE,iBAAiB;IAC1B,cAAc,EAAE,eAAe;IAC/B,cAAc,EAAE,kBAAkB;IAClC,YAAY,EAAE,YAAY;IAC1B,IAAI,EAAE,WAAW;IACjB,WAAW,EAAE,kBAAkB;IAC/B,eAAe,EAAE,WAAW;IAC5B,gBAAgB,EAAE,kBAAkB;CACrC,CAAC;AAEF;;;;GAIG;AACH,MAAM,UAAU,gCAAgC,CAC9C,IAA6C;IAE7C,OAAO,CACL,mCAAmC,CAAC,IAAI,CAAC,IAAI,CAAC;QAC9C,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAC7C,CAAC;AACJ,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU,+BAA+B,CAC7C,IAAuD;IAEvD,OAAO,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC;SAC7C,MAAM,CAAC,OAAO,CAAC;SACf,IAAI,CAAC,GAAG,CAAC;SACT,WAAW,EAAE,CAAC;AACnB,CAAC;AA+CD;;;;GAIG;AACH,MAAM,UAAU,4BAA4B,CAC1C,QAAuB,EACvB,OAA4D;IAE5D,MAAM,YAAY,GAChB,OAAO,CAAC,kBAAkB,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC;IAC3E,OAAO,QAAQ;SACZ,IAAI,CAAC,OAAO,CAAC;SACb,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC;SACrD,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,oBAAoB,IAAI,YAAY,CAAC,IAAI,CAAC,CAAC;SACrE,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACZ,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CACpE,CAAC;AACN,CAAC","sourcesContent":["import type { BlockRegistry, BlockSpec } from \"../blocks/index.js\";\n\nconst COMPACT_REGISTRY_BLOCK_DESCRIPTIONS: Record<string, string> = {\n callout: \"Emphasized note\",\n diagram: \"Inline diagram\",\n wireframe: \"Screen mockup\",\n \"question-form\": \"Interactive questions\",\n checklist: \"Checklist items\",\n table: \"Editable grid\",\n \"table-block\": \"Editable grid\",\n \"code-tabs\": \"Tabbed code snippets\",\n \"custom-html\": \"Sandboxed HTML\",\n tabs: \"Tabbed block group\",\n columns: \"Side-by-side columns\",\n mermaid: \"Mermaid diagram\",\n \"api-endpoint\": \"API reference\",\n \"openapi-spec\": \"OpenAPI document\",\n \"data-model\": \"ERD schema\",\n diff: \"Code diff\",\n \"file-tree\": \"File/change tree\",\n \"json-explorer\": \"JSON tree\",\n \"annotated-code\": \"Code walkthrough\",\n};\n\n/**\n * Compact, user-facing slash-menu copy for structured registry blocks. The full\n * registry description remains available through search text, but the visible\n * row should scan like a command palette, not a block reference page.\n */\nexport function getRegistryBlockSlashDescription(\n spec: Pick<BlockSpec, \"type\" | \"description\">,\n): string {\n return (\n COMPACT_REGISTRY_BLOCK_DESCRIPTIONS[spec.type] ??\n spec.description.trim().replace(/\\s+/g, \" \")\n );\n}\n\n/** Searchable text for registry block slash items, including raw type keywords. */\nexport function getRegistryBlockSlashSearchText(\n spec: Pick<BlockSpec, \"type\" | \"label\" | \"description\">,\n): string {\n return [spec.label, spec.description, spec.type]\n .filter(Boolean)\n .join(\" \")\n .toLowerCase();\n}\n\n/**\n * Shared builder for the registry-derived block slash commands both the plan and\n * content editors offer. Both apps take every `BlockSpec` whose `placement`\n * includes `\"block\"`, gate it by Notion-compatibility when the open document is\n * linked to a Notion page, and emit one slash item per surviving spec that\n * inserts that block's atom node. The only legitimate per-app differences are:\n *\n * - the ITEM SHAPE (plan uses a text-glyph `icon`, content a React component),\n * - the Notion-compat PREDICATE (plan unions in prose-only NFM analogs, content\n * reads the registry `notionCompatible` flag directly), and\n * - the INSERT behavior (plan inserts a `planBlock` node, content a\n * `registryBlock` node seeded with inline `__raw`).\n *\n * Those three are injected; everything else (the `list(\"block\")` source, the\n * Notion filter wiring, the one-item-per-spec mapping) lives here so adding a\n * new library block only touches the registry, never the slash builders.\n */\nexport interface BuildRegistryBlockSlashItemsOptions<TItem, TEditor> {\n /**\n * When `true`, only specs the predicate accepts are offered (the open document\n * is linked to a Notion page, so blocks that can't round-trip to NFM are\n * hidden). When unset/false, every block-placed spec is offered.\n */\n notionCompatibleOnly?: boolean;\n /**\n * Decide whether a spec round-trips to Notion. Defaults to the spec's own\n * `notionCompatible` flag (content's rule). Plan passes a predicate that unions\n * in prose-only NFM analogs not carried as registry flags.\n */\n isNotionCompatible?: (spec: BlockSpec) => boolean;\n /** Build one app-shaped slash item from a surviving block spec. */\n toItem: (spec: BlockSpec, insert: (editor: TEditor) => void) => TItem;\n /**\n * Optional app-level capability gate. Use this for blocks whose schema is\n * registered for parse/render compatibility but whose authoring experience is\n * not available in this editor yet.\n */\n includeSpec?: (spec: BlockSpec) => boolean;\n /**\n * Insert this spec's block atom into the editor. Plan inserts a `planBlock`\n * node; content inserts a `registryBlock` node seeded with inline `__raw`.\n */\n insertBlock: (editor: TEditor, spec: BlockSpec) => void;\n}\n\n/**\n * Build the registry-derived block slash items, shared by plan and content. Each\n * app prepends its own prose/base commands and wraps the result in its own item\n * type via {@link BuildRegistryBlockSlashItemsOptions.toItem}.\n */\nexport function buildRegistryBlockSlashItems<TItem, TEditor>(\n registry: BlockRegistry,\n options: BuildRegistryBlockSlashItemsOptions<TItem, TEditor>,\n): TItem[] {\n const isCompatible =\n options.isNotionCompatible ?? ((spec) => Boolean(spec.notionCompatible));\n return registry\n .list(\"block\")\n .filter((spec) => options.includeSpec?.(spec) ?? true)\n .filter((spec) => !options.notionCompatibleOnly || isCompatible(spec))\n .map((spec) =>\n options.toItem(spec, (editor) => options.insertBlock(editor, spec)),\n );\n}\n"]}
@@ -3,6 +3,7 @@ import type { Editor } from "@tiptap/react";
3
3
  import type { Transaction } from "@tiptap/pm/state";
4
4
  import type { Doc as YDoc } from "yjs";
5
5
  import type { Awareness } from "y-protocols/awareness";
6
+ export declare const RICH_MARKDOWN_PROGRAMMATIC_TRANSACTION = "an-rich-md-programmatic-transaction";
6
7
  /** Reads the current markdown out of the tiptap-markdown storage. */
7
8
  export declare function getEditorMarkdown(editor: Editor): string;
8
9
  export interface UseCollabReconcileOptions {
@@ -1 +1 @@
1
- {"version":3,"file":"useCollabReconcile.d.ts","sourceRoot":"","sources":["../../../src/client/rich-markdown-editor/useCollabReconcile.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+B,KAAK,gBAAgB,EAAE,MAAM,OAAO,CAAC;AAC3E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBA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;IACjE,MAAM,EAAE,OAAO,CAAC;IAChB;;;OAGG;IACH,mBAAmB,EAAE,gBAAgB,CAAC,OAAO,CAAC,CAAC;IAC/C;;;;OAIG;IACH,kBAAkB,EAAE,CAAC,WAAW,EAAE,WAAW,KAAK,OAAO,CAAC;IAC1D;;;;OAIG;IACH,eAAe,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC;CAChD;AAoED,wBAAgB,kBAAkB,CAAC,EACjC,MAAM,EACN,IAAW,EACX,SAAgB,EAChB,KAAK,EACL,gBAAgB,EAChB,QAAQ,EACR,WAA+B,EAC/B,UAA8B,EAC9B,cAAyB,EACzB,UAA8B,EAC9B,uBAAuB,GACxB,EAAE,yBAAyB,GAAG,wBAAwB,CA4StD"}
1
+ {"version":3,"file":"useCollabReconcile.d.ts","sourceRoot":"","sources":["../../../src/client/rich-markdown-editor/useCollabReconcile.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+B,KAAK,gBAAgB,EAAE,MAAM,OAAO,CAAC;AAC3E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAEpD,OAAO,KAAK,EAAE,GAAG,IAAI,IAAI,EAAE,MAAM,KAAK,CAAC;AACvC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAIvD,eAAO,MAAM,sCAAsC,wCACZ,CAAC;AAExC,qEAAqE;AACrE,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAKxD;AAqBD,MAAM,WAAW,yBAAyB;IACxC,gDAAgD;IAChD,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,uEAAuE;IACvE,IAAI,CAAC,EAAE,IAAI,GAAG,IAAI,CAAC;IACnB,8DAA8D;IAC9D,SAAS,CAAC,EAAE,SAAS,GAAG,IAAI,CAAC;IAC7B,0DAA0D;IAC1D,KAAK,EA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BAAwB,CA+StD"}
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";
2
2
  import { isChangeOrigin } from "@tiptap/extension-collaboration";
3
3
  import { isReconcileLeadClient } from "../../collab/client.js";
4
4
  import { AGENT_CLIENT_ID } from "../../collab/agent-identity.js";
5
+ export const RICH_MARKDOWN_PROGRAMMATIC_TRANSACTION = "an-rich-md-programmatic-transaction";
5
6
  /** Reads the current markdown out of the tiptap-markdown storage. */
6
7
  export function getEditorMarkdown(editor) {
7
8
  const markdownStorage = editor.storage;
@@ -347,6 +348,9 @@ export function useCollabReconcile({ editor, ydoc = null, awareness = null, valu
347
348
  const shouldIgnoreUpdate = (transaction) => {
348
349
  if (!editable || isSettingContentRef.current)
349
350
  return true;
351
+ if (transaction.getMeta(RICH_MARKDOWN_PROGRAMMATIC_TRANSACTION)) {
352
+ return true;
353
+ }
350
354
  // In collab mode, never persist remote-originated changes (the initial Yjs
351
355
  // state load or a peer's edit arriving via sync). Each client saves only its
352
356
  // OWN local edits; a peer's edit is saved by that peer. Without this, a
@@ -1 +1 @@
1
- {"version":3,"file":"useCollabReconcile.js","sourceRoot":"","sources":["../../../src/client/rich-markdown-editor/useCollabReconcile.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAyB,MAAM,OAAO,CAAC;AAG3E,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAGjE,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAEjE,qEAAqE;AACrE,MAAM,UAAU,iBAAiB,CAAC,MAAc;IAC9C,MAAM,eAAe,GAAG,MAAM,CAAC,OAE9B,CAAC;IACF,OAAO,eAAe,CAAC,QAAQ,EAAE,WAAW,EAAE,EAAE,IAAI,EAAE,CAAC;AACzD,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,gBAAgB,GAAG,EAAE,CA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DAAwD;QACxD,IAAI,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE;YAAE,OAAO,KAAK,CAAC;QAC7C,cAAc,CAAC,OAAO,GAAG,QAAQ,CAAC;QAClC,eAAe,CAAC,gBAAgB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACpD,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;IAEF,OAAO;QACL,MAAM;QACN,mBAAmB;QACnB,kBAAkB;QAClB,eAAe;KAChB,CAAC;AACJ,CAAC","sourcesContent":["import { useEffect, useRef, useState, type MutableRefObject } from \"react\";\nimport type { Editor } from \"@tiptap/react\";\nimport type { Transaction } from \"@tiptap/pm/state\";\nimport { isChangeOrigin } from \"@tiptap/extension-collaboration\";\nimport type { Doc as YDoc } from \"yjs\";\nimport type { Awareness } from \"y-protocols/awareness\";\nimport { isReconcileLeadClient } from \"../../collab/client.js\";\nimport { AGENT_CLIENT_ID } from \"../../collab/agent-identity.js\";\n\n/** Reads the current markdown out of the tiptap-markdown storage. */\nexport function getEditorMarkdown(editor: Editor): string {\n const markdownStorage = editor.storage as unknown as {\n markdown?: { getMarkdown?: () => string };\n };\n return markdownStorage.markdown?.getMarkdown?.() ?? \"\";\n}\n\n/**\n * Push a value onto the bounded ring of recently-emitted markdown (most recent\n * last, deduped, capped). The reconcile uses this to recognize a stale-but-recent\n * echo of OUR OWN edits: a debounced autosave can persist a PARTIAL burst, and\n * the next poll re-supplies that partial value with a newer timestamp — applying\n * it would clobber the freshly-typed tail. An external change (agent/peer) never\n * byte-matches one of our own recent emissions, and if it somehow did the content\n * is identical, so skipping it is safe by construction.\n */\nconst EMITTED_RING_MAX = 16;\nfunction pushEmittedRing(ring: string[], value: string): void {\n if (!value) return;\n if (ring[ring.length - 1] === value) return;\n const dupe = ring.indexOf(value);\n if (dupe !== -1) ring.splice(dupe, 1);\n ring.push(value);\n if (ring.length > EMITTED_RING_MAX) ring.shift();\n}\n\nexport interface UseCollabReconcileOptions {\n /** The live editor, or null until it mounts. */\n editor: Editor | null;\n /** Shared Y.Doc when collaborating; null disables all collab paths. */\n ydoc?: YDoc | null;\n /** Shared awareness; null keeps the sole-client lead path. */\n awareness?: Awareness | null;\n /** Authoritative markdown value (SQL source of truth). */\n value: string;\n /** Timestamp of the authoritative value; gates newer-than reconcile. */\n contentUpdatedAt?: string | null;\n /** Whether the editor accepts edits. Reconcile/seed only run for the live editor. */\n editable: boolean;\n /**\n * Reads the current markdown from the editor. Injected so a dialect could\n * swap serializers; defaults to the tiptap-markdown storage reader. For an app\n * with a custom serializer (e.g. Content's `docToNfm(editor.getJSON())`), pass\n * it here so the seed/reconcile equality checks compare like-for-like.\n */\n getMarkdown?: (editor: Editor) => string;\n /**\n * Applies the authoritative `value` into the editor. Defaults to passing the\n * raw markdown string to `editor.commands.setContent`. Apps whose serializer\n * is NOT tiptap-markdown (Content parses `nfmToDoc(value)` into a PM doc)\n * override this so seed + reconcile write the correct content shape. The\n * supplied `options` carry the history/whitespace flags the default path uses;\n * a custom implementation should forward them when relevant.\n */\n setContent?: (\n editor: Editor,\n value: string,\n options: { emitUpdate?: boolean; addToHistory?: boolean },\n ) => void;\n /**\n * Normalizes the authoritative `value` to the canonical markdown the editor\n * would emit, so the \"already in sync / our own echo\" equality checks match a\n * serializer that re-canonicalizes (Content's `canonicalizeNfm`). Defaults to\n * identity (GFM already round-trips byte-stably).\n */\n normalizeValue?: (value: string) => string;\n /**\n * Decides whether the empty-doc seed should run for the current shared\n * fragment. Defaults to \"fragment has no nodes, or the editor holds no\n * semantic markdown\". Apps with sentinel-empty content (Content's\n * `<empty-block/>` filler) override this. Receives the live fragment length\n * and the editor's current markdown.\n */\n shouldSeed?: (info: {\n value: string;\n currentMarkdown: string;\n fragmentLength: number;\n }) => boolean;\n /**\n * The initial \"applied\" watermark. Default mirrors `contentUpdatedAt`, so a\n * fresh mount whose Y.Doc already matches SQL doesn't re-apply. Pass `null`\n * to force the first reconcile pass to adopt authoritative SQL even at the\n * same timestamp — Content does this so a stale persisted Y.Doc (an agent that\n * edited the CLOSED doc) is corrected on open. The editor is keyed per\n * document upstream, so this only affects the first mount of each doc.\n */\n initialAppliedUpdatedAt?: string | null;\n}\n\nexport interface UseCollabReconcileResult {\n /** True when a Y.Doc is bound (collaborative editing active). */\n collab: boolean;\n /**\n * Set true around any programmatic `setContent` so the editor's `onUpdate`\n * can ignore the resulting transaction (it isn't a user edit).\n */\n isSettingContentRef: MutableRefObject<boolean>;\n /**\n * Call from `onUpdate` BEFORE serializing. Returns true when the update must\n * be ignored: editor not editable, mid-programmatic-setContent, or (in collab\n * mode) a remote-origin transaction. Also records the local typing time.\n */\n shouldIgnoreUpdate: (transaction: Transaction) => boolean;\n /**\n * Call from `onUpdate` AFTER computing the markdown to emit. Returns false\n * when the value must NOT be persisted yet (an empty collab doc before the\n * seed has run); records it as the last-emitted value otherwise.\n */\n registerEmitted: (markdown: string) => boolean;\n}\n\n/**\n * The subtle seed / reconcile / lead-client logic for the shared markdown\n * editor, extracted once so it can never be duplicated across embedders.\n *\n * Responsibilities (reproducing the Plan editor's behavior exactly):\n * - Track whether THIS client is the reconcile lead (sole client always leads;\n * otherwise elected via {@link isReconcileLeadClient}) and how many other\n * visible human peers are present.\n * - Seed an empty shared Y.Doc once from `value` — lead client only — so two\n * clients opening a brand-new block don't both insert the content.\n * - Reconcile authoritative external markdown (agent edit, source patch, peer\n * edit mirrored to SQL) into the editor: in collab mode only the lead client\n * applies it through `setContent` and Yjs propagates; in non-collab mode this\n * is the original controlled-value reconcile.\n * - Provide the `onUpdate` guards (`shouldIgnoreUpdate`, `registerEmitted`) so\n * the component never persists remote-origin or pre-seed empty content.\n */\n/** Default seed predicate: seed only when the shared doc is genuinely empty. */\nfunction defaultShouldSeed({\n currentMarkdown,\n fragmentLength,\n}: {\n value: string;\n currentMarkdown: string;\n fragmentLength: number;\n}): boolean {\n return fragmentLength === 0 || !currentMarkdown.trim();\n}\n\n/**\n * Default content writer: hand the raw markdown string to `setContent`, which\n * tiptap-markdown overrides to parse the markdown into a ProseMirror doc.\n *\n * IMPORTANT: do NOT pass `parseOptions: { preserveWhitespace: \"full\" }` here.\n * In tiptap v3 the core `setContent` command routes `preserveWhitespace: \"full\"`\n * through `insertContentAt`, which tiptap-markdown ALSO overrides to re-run its\n * markdown parser. That double-parse stringifies the already-parsed PM doc and\n * re-parses it as HTML, so a clean heading/list/code block comes back as the\n * escaped, non-idempotent `&lt;h1&gt;…` — which then escalates every reconcile\n * cycle (`<p>` → `&lt;p&gt;` → `&amp;lt;p&amp;gt;` …). Letting the markdown\n * override parse the string directly (no `parseOptions`) round-trips byte-stably\n * for the GFM corpus, including code-block and empty-line whitespace. Content's\n * NFM path supplies its own `setContent` (it passes a pre-parsed PM doc) and is\n * unaffected by this default.\n */\nfunction defaultSetContent(\n editor: Editor,\n value: string,\n options: { emitUpdate?: boolean; addToHistory?: boolean },\n): void {\n if (options.addToHistory === false) {\n editor\n .chain()\n .command(({ tr }) => {\n // addToHistory:false so cmd+z (or Yjs undo) doesn't erase\n // externally-loaded content.\n tr.setMeta(\"addToHistory\", false);\n return true;\n })\n .setContent(value, { emitUpdate: options.emitUpdate })\n .run();\n return;\n }\n editor.commands.setContent(value);\n}\n\nexport function useCollabReconcile({\n editor,\n ydoc = null,\n awareness = null,\n value,\n contentUpdatedAt,\n editable,\n getMarkdown = getEditorMarkdown,\n setContent = defaultSetContent,\n normalizeValue = (v) => v,\n shouldSeed = defaultShouldSeed,\n initialAppliedUpdatedAt,\n}: UseCollabReconcileOptions): UseCollabReconcileResult {\n const collab = !!ydoc;\n const isSettingContentRef = useRef(false);\n const lastEmittedRef = useRef(\"\");\n // Ring of recent local emissions (see pushEmittedRing). Lets the reconcile\n // recognize a stale-but-recent echo of our OWN (possibly partial, debounced)\n // save so a lagging poll never clobbers freshly-typed text.\n const recentEmittedRef = useRef<string[]>([]);\n const lastTypedAtRef = useRef(0);\n // The raw authoritative `value` string the reconcile last applied. When the\n // SAME raw string is re-fetched (a lagging poll, or a source-sync that keeps\n // re-supplying the same stored markdown), applying it again would only\n // reproduce the doc we already hold — and if `value` is NON-idempotent\n // (serialize(parse(value)) !== value) re-applying compounds the divergence\n // every cycle (`<p>` → `&lt;p&gt;` → `&amp;lt;p&amp;gt;` …). Tracked so the\n // identical re-fetch is recognized and skipped.\n const lastAppliedValueRef = useRef<string | null>(null);\n // The editor's SERIALIZED output captured right AFTER the last reconcile/seed\n // apply (`getMarkdown(editor)` once the content settled). For non-idempotent\n // input this is what autosave actually persists, so the NEXT poll hands it\n // back as the new `value`. Comparing the incoming value against this lets the\n // reconcile recognize its own echo even when the raw string changed once, so\n // it never re-parses content the editor already represents. This is the\n // doc-equivalence guard that breaks the escalation loop.\n const lastAppliedSerializedRef = useRef<string | null>(null);\n const lastAppliedUpdatedAtRef = useRef<string | null>(\n initialAppliedUpdatedAt !== undefined\n ? initialAppliedUpdatedAt\n : (contentUpdatedAt ?? null),\n );\n\n // Whether THIS client is the one that seeds the empty shared doc / applies an\n // authoritative external snapshot into it. Exactly one client does, so the\n // content isn't inserted once per open editor. A sole client always leads.\n const [isLeadClient, setIsLeadClient] = useState(true);\n // Count of OTHER visible human collaborators. When >0, a peer's edit also\n // arrives via Yjs, so external markdown reconcile must defer (avoid applying\n // the same change through both Yjs and setContent).\n const peerCountRef = useRef(0);\n useEffect(() => {\n if (!collab || !awareness || !ydoc) {\n setIsLeadClient(true);\n peerCountRef.current = 0;\n return;\n }\n const update = () => {\n setIsLeadClient(isReconcileLeadClient(awareness, ydoc.clientID));\n let peers = 0;\n awareness.getStates().forEach((state, clientId) => {\n if (clientId === ydoc.clientID) return; // self\n if (clientId === AGENT_CLIENT_ID) return; // agent isn't a Yjs editor\n const s = state as { user?: unknown; visible?: boolean };\n if (s && s.user && s.visible !== false) peers += 1;\n });\n peerCountRef.current = peers;\n };\n update();\n awareness.on(\"change\", update);\n document.addEventListener(\"visibilitychange\", update);\n return () => {\n awareness.off(\"change\", update);\n document.removeEventListener(\"visibilitychange\", update);\n };\n }, [collab, awareness, ydoc]);\n\n // Collab seed: populate an empty shared Y.Doc from the markdown `value` once.\n // The Collaboration extension does NOT auto-seed; only the lead client does,\n // so two clients opening a brand-new block at once don't both seed (which\n // would duplicate the content via concurrent inserts at the same position).\n const seededRef = useRef(false);\n useEffect(() => {\n if (!collab || !editor || editor.isDestroyed || !ydoc) return;\n if (seededRef.current) return;\n if (!isLeadClient) return;\n if (!value.trim()) return;\n const fragment = ydoc.getXmlFragment(\"default\");\n const currentMarkdown = getMarkdown(editor);\n // Seed only when the shared doc is genuinely empty — either the fragment has\n // no nodes yet, or it holds no semantic markdown (an empty paragraph, or an\n // app's sentinel-empty filler via a custom `shouldSeed`).\n if (\n shouldSeed({ value, currentMarkdown, fragmentLength: fragment.length })\n ) {\n isSettingContentRef.current = true;\n setContent(editor, value, {});\n isSettingContentRef.current = false;\n const serialized = getMarkdown(editor);\n lastEmittedRef.current = serialized;\n pushEmittedRing(recentEmittedRef.current, serialized);\n lastAppliedValueRef.current = value;\n lastAppliedSerializedRef.current = serialized;\n if (contentUpdatedAt) lastAppliedUpdatedAtRef.current = contentUpdatedAt;\n }\n seededRef.current = true;\n }, [\n collab,\n editor,\n ydoc,\n value,\n isLeadClient,\n contentUpdatedAt,\n getMarkdown,\n setContent,\n shouldSeed,\n ]);\n\n // Reconcile authoritative external markdown (agent edit, source patch, or a\n // peer edit mirrored to SQL) into the live editor. In collab mode only the\n // lead client applies it through setContent; Yjs propagates the result to\n // every other client. In non-collab mode this is the original controlled-value\n // reconcile, unchanged.\n useEffect(() => {\n if (!editor || editor.isDestroyed) return;\n\n let cancelled = false;\n let retry: ReturnType<typeof setTimeout> | null = null;\n // With peers present, a peer's edit also arrives via Yjs. Defer one poll\n // cycle (+margin) and re-check before applying via setContent so the same\n // change isn't inserted twice (Yjs + setContent → duplicated region).\n const PEER_SETTLE_MS = 2500;\n\n const apply = (deferred = false) => {\n if (cancelled || editor.isDestroyed) return;\n // In collab mode, defer all reconcile until the shared doc is seeded so we\n // never setContent over an unseeded fragment.\n if (collab && !seededRef.current) {\n retry = setTimeout(() => apply(deferred), 300);\n return;\n }\n const currentMarkdown = getMarkdown(editor);\n // Compare against the canonical form the editor would emit so a serializer\n // that re-normalizes (Content's NFM) still recognizes \"already in sync\".\n const normalizedValue = normalizeValue(value);\n // Whether the editor still holds exactly what THIS hook last applied (the\n // user hasn't edited since). Only then are the round-trip echo guards\n // below safe: if the user has since edited away from the applied content,\n // an external snapshot equal to a previously-applied value is a real\n // revert and must NOT be swallowed as an echo.\n const editorUnchangedSinceApply =\n lastAppliedSerializedRef.current !== null &&\n currentMarkdown === lastAppliedSerializedRef.current;\n\n // Doc-equivalence skip. Never re-apply content the editor already\n // represents — comparing by DOC EQUIVALENCE, not raw strings/timestamps:\n // 1. `currentMarkdown === normalizedValue` — the editor's CURRENT\n // serialized doc already equals the (normalized) incoming value.\n // 2. `value === lastEmittedRef.current` — the incoming value is our own\n // just-emitted markdown echoing back.\n // 3. `value === lastAppliedValueRef.current` — the SAME raw value we\n // already applied is being re-supplied (a lagging poll or a\n // source-sync re-handing the same stored markdown). Applying it again\n // would only reproduce the doc we hold; for NON-idempotent input it\n // would compound divergence. Guarded by `editorUnchangedSinceApply`\n // so a deliberate revert-to-previous after a local edit still lands.\n // 4. `normalizedValue === lastAppliedSerializedRef.current` — the\n // incoming value round-trips to the serialized output we last\n // produced (our own autosaved echo coming back from SQL). For\n // non-idempotent input the raw string differs from what we were\n // handed, but it is doc-equivalent to what the editor already shows,\n // so re-parsing it must be skipped. This is the guard that stops the\n // `<p>` → `&lt;p&gt;` → `&amp;lt;p&amp;gt;` escalation.\n if (\n currentMarkdown === normalizedValue ||\n value === lastEmittedRef.current ||\n // A stale-but-recent echo of our own (possibly partial) save — applying\n // it would clobber the freshly-typed tail. External edits never match.\n recentEmittedRef.current.includes(value) ||\n recentEmittedRef.current.includes(normalizedValue) ||\n (editorUnchangedSinceApply &&\n (value === lastAppliedValueRef.current ||\n normalizedValue === lastAppliedSerializedRef.current))\n ) {\n if (contentUpdatedAt) {\n lastAppliedUpdatedAtRef.current = contentUpdatedAt;\n }\n return;\n }\n\n const externalNewer =\n !lastAppliedUpdatedAtRef.current ||\n !contentUpdatedAt ||\n contentUpdatedAt > lastAppliedUpdatedAtRef.current;\n\n // Only the lead client applies an authoritative snapshot into the shared\n // Y.Doc; peers receive it through Yjs sync.\n if (collab && !isLeadClient) {\n if (contentUpdatedAt && !externalNewer) {\n lastAppliedUpdatedAtRef.current = contentUpdatedAt;\n }\n return;\n }\n\n // Never clobber an in-progress edit. While the user is actively typing\n // (focused and a keystroke landed within the window) defer and re-check —\n // applying external content now would yank text out from under them and,\n // for non-idempotent input, fight every keystroke. Newer external content\n // retries so it still lands once they pause; older-or-equal content is a\n // stale poll and is dropped outright while focused.\n const typingRecently =\n editor.isFocused && Date.now() - lastTypedAtRef.current < 1500;\n if (typingRecently) {\n if (externalNewer) {\n retry = setTimeout(() => apply(deferred), 700);\n }\n return;\n }\n if (!externalNewer && editor.isFocused) return;\n\n // Race guard: with peers present, let Yjs deliver a peer's edit first.\n // Defer once and re-check — a peer edit makes the equality check above\n // no-op next pass; an agent/source edit still differs and applies.\n if (collab && externalNewer && !deferred && peerCountRef.current > 0) {\n retry = setTimeout(() => apply(true), PEER_SETTLE_MS);\n return;\n }\n\n queueMicrotask(() => {\n if (cancelled || editor.isDestroyed) return;\n // Re-check doc-equivalence at apply time. Between the decision above and\n // this microtask a peer/Yjs edit (or our own prior apply) may have made\n // the editor already represent this value — re-applying would be a\n // wasted setContent that, for non-idempotent input, re-triggers the\n // loop. Skip when the editor's current serialization already matches the\n // normalized value, or the value round-trips to what we last produced.\n const beforeMarkdown = getMarkdown(editor);\n const normalized = normalizeValue(value);\n const unchangedSinceApply =\n lastAppliedSerializedRef.current !== null &&\n beforeMarkdown === lastAppliedSerializedRef.current;\n if (\n beforeMarkdown === normalized ||\n (unchangedSinceApply &&\n normalized === lastAppliedSerializedRef.current)\n ) {\n lastAppliedValueRef.current = value;\n if (contentUpdatedAt) {\n lastAppliedUpdatedAtRef.current = contentUpdatedAt;\n }\n return;\n }\n isSettingContentRef.current = true;\n setContent(editor, value, { emitUpdate: false, addToHistory: false });\n isSettingContentRef.current = false;\n // Capture the SERIALIZED result, not the raw value. For non-idempotent\n // input these differ; recording the serialized output is what lets the\n // next poll (which returns this serialized form) be recognized as our\n // own echo and skipped — stabilizing the doc after exactly one apply.\n const serialized = getMarkdown(editor);\n lastEmittedRef.current = serialized;\n pushEmittedRing(recentEmittedRef.current, serialized);\n lastAppliedValueRef.current = value;\n lastAppliedSerializedRef.current = serialized;\n if (contentUpdatedAt) {\n lastAppliedUpdatedAtRef.current = contentUpdatedAt;\n }\n });\n };\n\n apply();\n return () => {\n cancelled = true;\n if (retry) clearTimeout(retry);\n };\n }, [\n contentUpdatedAt,\n editor,\n value,\n collab,\n isLeadClient,\n getMarkdown,\n setContent,\n normalizeValue,\n ]);\n\n const shouldIgnoreUpdate = (transaction: Transaction): boolean => {\n if (!editable || isSettingContentRef.current) return true;\n // In collab mode, never persist remote-originated changes (the initial Yjs\n // state load or a peer's edit arriving via sync). Each client saves only its\n // OWN local edits; a peer's edit is saved by that peer. Without this, a\n // lagging Y.Doc load would write stale markdown over newer SQL.\n if (collab && transaction && isChangeOrigin(transaction)) return true;\n lastTypedAtRef.current = Date.now();\n return false;\n };\n\n const registerEmitted = (markdown: string): boolean => {\n // Don't persist an empty doc before Collaboration has seeded — that would\n // clobber the saved block content with an empty string.\n if (collab && !markdown.trim()) return false;\n lastEmittedRef.current = markdown;\n pushEmittedRing(recentEmittedRef.current, markdown);\n return true;\n };\n\n return {\n collab,\n isSettingContentRef,\n shouldIgnoreUpdate,\n registerEmitted,\n };\n}\n"]}
1
+ {"version":3,"file":"useCollabReconcile.js","sourceRoot":"","sources":["../../../src/client/rich-markdown-editor/useCollabReconcile.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAyB,MAAM,OAAO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CAAC,CAAC;IAEH,MAAM,kBAAkB,GAAG,CAAC,WAAwB,EAAW,EAAE;QAC/D,IAAI,CAAC,QAAQ,IAAI,mBAAmB,CAAC,OAAO;YAAE,OAAO,IAAI,CAAC;QAC1D,IAAI,WAAW,CAAC,OAAO,CAAC,sCAAsC,CAAC,EAAE,CAAC;YAChE,OAAO,IAAI,CAAC;QACd,CAAC;QACD,2EAA2E;QAC3E,6EAA6E;QAC7E,wEAAwE;QACxE,gEAAgE;QAChE,IAAI,MAAM,IAAI,WAAW,IAAI,cAAc,CAAC,WAAW,CAAC;YAAE,OAAO,IAAI,CAAC;QACtE,cAAc,CAAC,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACpC,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;IAEF,MAAM,eAAe,GAAG,CAAC,QAAgB,EAAW,EAAE;QACpD,0EAA0E;QAC1E,wDAAwD;QACxD,IAAI,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE;YAAE,OAAO,KAAK,CAAC;QAC7C,cAAc,CAAC,OAAO,GAAG,QAAQ,CAAC;QAClC,eAAe,CAAC,gBAAgB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACpD,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;IAEF,OAAO;QACL,MAAM;QACN,mBAAmB;QACnB,kBAAkB;QAClB,eAAe;KAChB,CAAC;AACJ,CAAC","sourcesContent":["import { useEffect, useRef, useState, type MutableRefObject } from \"react\";\nimport type { Editor } from \"@tiptap/react\";\nimport type { Transaction } from \"@tiptap/pm/state\";\nimport { isChangeOrigin } from \"@tiptap/extension-collaboration\";\nimport type { Doc as YDoc } from \"yjs\";\nimport type { Awareness } from \"y-protocols/awareness\";\nimport { isReconcileLeadClient } from \"../../collab/client.js\";\nimport { AGENT_CLIENT_ID } from \"../../collab/agent-identity.js\";\n\nexport const RICH_MARKDOWN_PROGRAMMATIC_TRANSACTION =\n \"an-rich-md-programmatic-transaction\";\n\n/** Reads the current markdown out of the tiptap-markdown storage. */\nexport function getEditorMarkdown(editor: Editor): string {\n const markdownStorage = editor.storage as unknown as {\n markdown?: { getMarkdown?: () => string };\n };\n return markdownStorage.markdown?.getMarkdown?.() ?? \"\";\n}\n\n/**\n * Push a value onto the bounded ring of recently-emitted markdown (most recent\n * last, deduped, capped). The reconcile uses this to recognize a stale-but-recent\n * echo of OUR OWN edits: a debounced autosave can persist a PARTIAL burst, and\n * the next poll re-supplies that partial value with a newer timestamp — applying\n * it would clobber the freshly-typed tail. An external change (agent/peer) never\n * byte-matches one of our own recent emissions, and if it somehow did the content\n * is identical, so skipping it is safe by construction.\n */\nconst EMITTED_RING_MAX = 16;\nfunction pushEmittedRing(ring: string[], value: string): void {\n if (!value) return;\n if (ring[ring.length - 1] === value) return;\n const dupe = ring.indexOf(value);\n if (dupe !== -1) ring.splice(dupe, 1);\n ring.push(value);\n if (ring.length > EMITTED_RING_MAX) ring.shift();\n}\n\nexport interface UseCollabReconcileOptions {\n /** The live editor, or null until it mounts. */\n editor: Editor | null;\n /** Shared Y.Doc when collaborating; null disables all collab paths. */\n ydoc?: YDoc | null;\n /** Shared awareness; null keeps the sole-client lead path. */\n awareness?: Awareness | null;\n /** Authoritative markdown value (SQL source of truth). */\n value: string;\n /** Timestamp of the authoritative value; gates newer-than reconcile. */\n contentUpdatedAt?: string | null;\n /** Whether the editor accepts edits. Reconcile/seed only run for the live editor. */\n editable: boolean;\n /**\n * Reads the current markdown from the editor. Injected so a dialect could\n * swap serializers; defaults to the tiptap-markdown storage reader. For an app\n * with a custom serializer (e.g. Content's `docToNfm(editor.getJSON())`), pass\n * it here so the seed/reconcile equality checks compare like-for-like.\n */\n getMarkdown?: (editor: Editor) => string;\n /**\n * Applies the authoritative `value` into the editor. Defaults to passing the\n * raw markdown string to `editor.commands.setContent`. Apps whose serializer\n * is NOT tiptap-markdown (Content parses `nfmToDoc(value)` into a PM doc)\n * override this so seed + reconcile write the correct content shape. The\n * supplied `options` carry the history/whitespace flags the default path uses;\n * a custom implementation should forward them when relevant.\n */\n setContent?: (\n editor: Editor,\n value: string,\n options: { emitUpdate?: boolean; addToHistory?: boolean },\n ) => void;\n /**\n * Normalizes the authoritative `value` to the canonical markdown the editor\n * would emit, so the \"already in sync / our own echo\" equality checks match a\n * serializer that re-canonicalizes (Content's `canonicalizeNfm`). Defaults to\n * identity (GFM already round-trips byte-stably).\n */\n normalizeValue?: (value: string) => string;\n /**\n * Decides whether the empty-doc seed should run for the current shared\n * fragment. Defaults to \"fragment has no nodes, or the editor holds no\n * semantic markdown\". Apps with sentinel-empty content (Content's\n * `<empty-block/>` filler) override this. Receives the live fragment length\n * and the editor's current markdown.\n */\n shouldSeed?: (info: {\n value: string;\n currentMarkdown: string;\n fragmentLength: number;\n }) => boolean;\n /**\n * The initial \"applied\" watermark. Default mirrors `contentUpdatedAt`, so a\n * fresh mount whose Y.Doc already matches SQL doesn't re-apply. Pass `null`\n * to force the first reconcile pass to adopt authoritative SQL even at the\n * same timestamp — Content does this so a stale persisted Y.Doc (an agent that\n * edited the CLOSED doc) is corrected on open. The editor is keyed per\n * document upstream, so this only affects the first mount of each doc.\n */\n initialAppliedUpdatedAt?: string | null;\n}\n\nexport interface UseCollabReconcileResult {\n /** True when a Y.Doc is bound (collaborative editing active). */\n collab: boolean;\n /**\n * Set true around any programmatic `setContent` so the editor's `onUpdate`\n * can ignore the resulting transaction (it isn't a user edit).\n */\n isSettingContentRef: MutableRefObject<boolean>;\n /**\n * Call from `onUpdate` BEFORE serializing. Returns true when the update must\n * be ignored: editor not editable, mid-programmatic-setContent, or (in collab\n * mode) a remote-origin transaction. Also records the local typing time.\n */\n shouldIgnoreUpdate: (transaction: Transaction) => boolean;\n /**\n * Call from `onUpdate` AFTER computing the markdown to emit. Returns false\n * when the value must NOT be persisted yet (an empty collab doc before the\n * seed has run); records it as the last-emitted value otherwise.\n */\n registerEmitted: (markdown: string) => boolean;\n}\n\n/**\n * The subtle seed / reconcile / lead-client logic for the shared markdown\n * editor, extracted once so it can never be duplicated across embedders.\n *\n * Responsibilities (reproducing the Plan editor's behavior exactly):\n * - Track whether THIS client is the reconcile lead (sole client always leads;\n * otherwise elected via {@link isReconcileLeadClient}) and how many other\n * visible human peers are present.\n * - Seed an empty shared Y.Doc once from `value` — lead client only — so two\n * clients opening a brand-new block don't both insert the content.\n * - Reconcile authoritative external markdown (agent edit, source patch, peer\n * edit mirrored to SQL) into the editor: in collab mode only the lead client\n * applies it through `setContent` and Yjs propagates; in non-collab mode this\n * is the original controlled-value reconcile.\n * - Provide the `onUpdate` guards (`shouldIgnoreUpdate`, `registerEmitted`) so\n * the component never persists remote-origin or pre-seed empty content.\n */\n/** Default seed predicate: seed only when the shared doc is genuinely empty. */\nfunction defaultShouldSeed({\n currentMarkdown,\n fragmentLength,\n}: {\n value: string;\n currentMarkdown: string;\n fragmentLength: number;\n}): boolean {\n return fragmentLength === 0 || !currentMarkdown.trim();\n}\n\n/**\n * Default content writer: hand the raw markdown string to `setContent`, which\n * tiptap-markdown overrides to parse the markdown into a ProseMirror doc.\n *\n * IMPORTANT: do NOT pass `parseOptions: { preserveWhitespace: \"full\" }` here.\n * In tiptap v3 the core `setContent` command routes `preserveWhitespace: \"full\"`\n * through `insertContentAt`, which tiptap-markdown ALSO overrides to re-run its\n * markdown parser. That double-parse stringifies the already-parsed PM doc and\n * re-parses it as HTML, so a clean heading/list/code block comes back as the\n * escaped, non-idempotent `&lt;h1&gt;…` — which then escalates every reconcile\n * cycle (`<p>` → `&lt;p&gt;` → `&amp;lt;p&amp;gt;` …). Letting the markdown\n * override parse the string directly (no `parseOptions`) round-trips byte-stably\n * for the GFM corpus, including code-block and empty-line whitespace. Content's\n * NFM path supplies its own `setContent` (it passes a pre-parsed PM doc) and is\n * unaffected by this default.\n */\nfunction defaultSetContent(\n editor: Editor,\n value: string,\n options: { emitUpdate?: boolean; addToHistory?: boolean },\n): void {\n if (options.addToHistory === false) {\n editor\n .chain()\n .command(({ tr }) => {\n // addToHistory:false so cmd+z (or Yjs undo) doesn't erase\n // externally-loaded content.\n tr.setMeta(\"addToHistory\", false);\n return true;\n })\n .setContent(value, { emitUpdate: options.emitUpdate })\n .run();\n return;\n }\n editor.commands.setContent(value);\n}\n\nexport function useCollabReconcile({\n editor,\n ydoc = null,\n awareness = null,\n value,\n contentUpdatedAt,\n editable,\n getMarkdown = getEditorMarkdown,\n setContent = defaultSetContent,\n normalizeValue = (v) => v,\n shouldSeed = defaultShouldSeed,\n initialAppliedUpdatedAt,\n}: UseCollabReconcileOptions): UseCollabReconcileResult {\n const collab = !!ydoc;\n const isSettingContentRef = useRef(false);\n const lastEmittedRef = useRef(\"\");\n // Ring of recent local emissions (see pushEmittedRing). Lets the reconcile\n // recognize a stale-but-recent echo of our OWN (possibly partial, debounced)\n // save so a lagging poll never clobbers freshly-typed text.\n const recentEmittedRef = useRef<string[]>([]);\n const lastTypedAtRef = useRef(0);\n // The raw authoritative `value` string the reconcile last applied. When the\n // SAME raw string is re-fetched (a lagging poll, or a source-sync that keeps\n // re-supplying the same stored markdown), applying it again would only\n // reproduce the doc we already hold — and if `value` is NON-idempotent\n // (serialize(parse(value)) !== value) re-applying compounds the divergence\n // every cycle (`<p>` → `&lt;p&gt;` → `&amp;lt;p&amp;gt;` …). Tracked so the\n // identical re-fetch is recognized and skipped.\n const lastAppliedValueRef = useRef<string | null>(null);\n // The editor's SERIALIZED output captured right AFTER the last reconcile/seed\n // apply (`getMarkdown(editor)` once the content settled). For non-idempotent\n // input this is what autosave actually persists, so the NEXT poll hands it\n // back as the new `value`. Comparing the incoming value against this lets the\n // reconcile recognize its own echo even when the raw string changed once, so\n // it never re-parses content the editor already represents. This is the\n // doc-equivalence guard that breaks the escalation loop.\n const lastAppliedSerializedRef = useRef<string | null>(null);\n const lastAppliedUpdatedAtRef = useRef<string | null>(\n initialAppliedUpdatedAt !== undefined\n ? initialAppliedUpdatedAt\n : (contentUpdatedAt ?? null),\n );\n\n // Whether THIS client is the one that seeds the empty shared doc / applies an\n // authoritative external snapshot into it. Exactly one client does, so the\n // content isn't inserted once per open editor. A sole client always leads.\n const [isLeadClient, setIsLeadClient] = useState(true);\n // Count of OTHER visible human collaborators. When >0, a peer's edit also\n // arrives via Yjs, so external markdown reconcile must defer (avoid applying\n // the same change through both Yjs and setContent).\n const peerCountRef = useRef(0);\n useEffect(() => {\n if (!collab || !awareness || !ydoc) {\n setIsLeadClient(true);\n peerCountRef.current = 0;\n return;\n }\n const update = () => {\n setIsLeadClient(isReconcileLeadClient(awareness, ydoc.clientID));\n let peers = 0;\n awareness.getStates().forEach((state, clientId) => {\n if (clientId === ydoc.clientID) return; // self\n if (clientId === AGENT_CLIENT_ID) return; // agent isn't a Yjs editor\n const s = state as { user?: unknown; visible?: boolean };\n if (s && s.user && s.visible !== false) peers += 1;\n });\n peerCountRef.current = peers;\n };\n update();\n awareness.on(\"change\", update);\n document.addEventListener(\"visibilitychange\", update);\n return () => {\n awareness.off(\"change\", update);\n document.removeEventListener(\"visibilitychange\", update);\n };\n }, [collab, awareness, ydoc]);\n\n // Collab seed: populate an empty shared Y.Doc from the markdown `value` once.\n // The Collaboration extension does NOT auto-seed; only the lead client does,\n // so two clients opening a brand-new block at once don't both seed (which\n // would duplicate the content via concurrent inserts at the same position).\n const seededRef = useRef(false);\n useEffect(() => {\n if (!collab || !editor || editor.isDestroyed || !ydoc) return;\n if (seededRef.current) return;\n if (!isLeadClient) return;\n if (!value.trim()) return;\n const fragment = ydoc.getXmlFragment(\"default\");\n const currentMarkdown = getMarkdown(editor);\n // Seed only when the shared doc is genuinely empty — either the fragment has\n // no nodes yet, or it holds no semantic markdown (an empty paragraph, or an\n // app's sentinel-empty filler via a custom `shouldSeed`).\n if (\n shouldSeed({ value, currentMarkdown, fragmentLength: fragment.length })\n ) {\n isSettingContentRef.current = true;\n setContent(editor, value, {});\n isSettingContentRef.current = false;\n const serialized = getMarkdown(editor);\n lastEmittedRef.current = serialized;\n pushEmittedRing(recentEmittedRef.current, serialized);\n lastAppliedValueRef.current = value;\n lastAppliedSerializedRef.current = serialized;\n if (contentUpdatedAt) lastAppliedUpdatedAtRef.current = contentUpdatedAt;\n }\n seededRef.current = true;\n }, [\n collab,\n editor,\n ydoc,\n value,\n isLeadClient,\n contentUpdatedAt,\n getMarkdown,\n setContent,\n shouldSeed,\n ]);\n\n // Reconcile authoritative external markdown (agent edit, source patch, or a\n // peer edit mirrored to SQL) into the live editor. In collab mode only the\n // lead client applies it through setContent; Yjs propagates the result to\n // every other client. In non-collab mode this is the original controlled-value\n // reconcile, unchanged.\n useEffect(() => {\n if (!editor || editor.isDestroyed) return;\n\n let cancelled = false;\n let retry: ReturnType<typeof setTimeout> | null = null;\n // With peers present, a peer's edit also arrives via Yjs. Defer one poll\n // cycle (+margin) and re-check before applying via setContent so the same\n // change isn't inserted twice (Yjs + setContent → duplicated region).\n const PEER_SETTLE_MS = 2500;\n\n const apply = (deferred = false) => {\n if (cancelled || editor.isDestroyed) return;\n // In collab mode, defer all reconcile until the shared doc is seeded so we\n // never setContent over an unseeded fragment.\n if (collab && !seededRef.current) {\n retry = setTimeout(() => apply(deferred), 300);\n return;\n }\n const currentMarkdown = getMarkdown(editor);\n // Compare against the canonical form the editor would emit so a serializer\n // that re-normalizes (Content's NFM) still recognizes \"already in sync\".\n const normalizedValue = normalizeValue(value);\n // Whether the editor still holds exactly what THIS hook last applied (the\n // user hasn't edited since). Only then are the round-trip echo guards\n // below safe: if the user has since edited away from the applied content,\n // an external snapshot equal to a previously-applied value is a real\n // revert and must NOT be swallowed as an echo.\n const editorUnchangedSinceApply =\n lastAppliedSerializedRef.current !== null &&\n currentMarkdown === lastAppliedSerializedRef.current;\n\n // Doc-equivalence skip. Never re-apply content the editor already\n // represents — comparing by DOC EQUIVALENCE, not raw strings/timestamps:\n // 1. `currentMarkdown === normalizedValue` — the editor's CURRENT\n // serialized doc already equals the (normalized) incoming value.\n // 2. `value === lastEmittedRef.current` — the incoming value is our own\n // just-emitted markdown echoing back.\n // 3. `value === lastAppliedValueRef.current` — the SAME raw value we\n // already applied is being re-supplied (a lagging poll or a\n // source-sync re-handing the same stored markdown). Applying it again\n // would only reproduce the doc we hold; for NON-idempotent input it\n // would compound divergence. Guarded by `editorUnchangedSinceApply`\n // so a deliberate revert-to-previous after a local edit still lands.\n // 4. `normalizedValue === lastAppliedSerializedRef.current` — the\n // incoming value round-trips to the serialized output we last\n // produced (our own autosaved echo coming back from SQL). For\n // non-idempotent input the raw string differs from what we were\n // handed, but it is doc-equivalent to what the editor already shows,\n // so re-parsing it must be skipped. This is the guard that stops the\n // `<p>` → `&lt;p&gt;` → `&amp;lt;p&amp;gt;` escalation.\n if (\n currentMarkdown === normalizedValue ||\n value === lastEmittedRef.current ||\n // A stale-but-recent echo of our own (possibly partial) save — applying\n // it would clobber the freshly-typed tail. External edits never match.\n recentEmittedRef.current.includes(value) ||\n recentEmittedRef.current.includes(normalizedValue) ||\n (editorUnchangedSinceApply &&\n (value === lastAppliedValueRef.current ||\n normalizedValue === lastAppliedSerializedRef.current))\n ) {\n if (contentUpdatedAt) {\n lastAppliedUpdatedAtRef.current = contentUpdatedAt;\n }\n return;\n }\n\n const externalNewer =\n !lastAppliedUpdatedAtRef.current ||\n !contentUpdatedAt ||\n contentUpdatedAt > lastAppliedUpdatedAtRef.current;\n\n // Only the lead client applies an authoritative snapshot into the shared\n // Y.Doc; peers receive it through Yjs sync.\n if (collab && !isLeadClient) {\n if (contentUpdatedAt && !externalNewer) {\n lastAppliedUpdatedAtRef.current = contentUpdatedAt;\n }\n return;\n }\n\n // Never clobber an in-progress edit. While the user is actively typing\n // (focused and a keystroke landed within the window) defer and re-check —\n // applying external content now would yank text out from under them and,\n // for non-idempotent input, fight every keystroke. Newer external content\n // retries so it still lands once they pause; older-or-equal content is a\n // stale poll and is dropped outright while focused.\n const typingRecently =\n editor.isFocused && Date.now() - lastTypedAtRef.current < 1500;\n if (typingRecently) {\n if (externalNewer) {\n retry = setTimeout(() => apply(deferred), 700);\n }\n return;\n }\n if (!externalNewer && editor.isFocused) return;\n\n // Race guard: with peers present, let Yjs deliver a peer's edit first.\n // Defer once and re-check — a peer edit makes the equality check above\n // no-op next pass; an agent/source edit still differs and applies.\n if (collab && externalNewer && !deferred && peerCountRef.current > 0) {\n retry = setTimeout(() => apply(true), PEER_SETTLE_MS);\n return;\n }\n\n queueMicrotask(() => {\n if (cancelled || editor.isDestroyed) return;\n // Re-check doc-equivalence at apply time. Between the decision above and\n // this microtask a peer/Yjs edit (or our own prior apply) may have made\n // the editor already represent this value — re-applying would be a\n // wasted setContent that, for non-idempotent input, re-triggers the\n // loop. Skip when the editor's current serialization already matches the\n // normalized value, or the value round-trips to what we last produced.\n const beforeMarkdown = getMarkdown(editor);\n const normalized = normalizeValue(value);\n const unchangedSinceApply =\n lastAppliedSerializedRef.current !== null &&\n beforeMarkdown === lastAppliedSerializedRef.current;\n if (\n beforeMarkdown === normalized ||\n (unchangedSinceApply &&\n normalized === lastAppliedSerializedRef.current)\n ) {\n lastAppliedValueRef.current = value;\n if (contentUpdatedAt) {\n lastAppliedUpdatedAtRef.current = contentUpdatedAt;\n }\n return;\n }\n isSettingContentRef.current = true;\n setContent(editor, value, { emitUpdate: false, addToHistory: false });\n isSettingContentRef.current = false;\n // Capture the SERIALIZED result, not the raw value. For non-idempotent\n // input these differ; recording the serialized output is what lets the\n // next poll (which returns this serialized form) be recognized as our\n // own echo and skipped — stabilizing the doc after exactly one apply.\n const serialized = getMarkdown(editor);\n lastEmittedRef.current = serialized;\n pushEmittedRing(recentEmittedRef.current, serialized);\n lastAppliedValueRef.current = value;\n lastAppliedSerializedRef.current = serialized;\n if (contentUpdatedAt) {\n lastAppliedUpdatedAtRef.current = contentUpdatedAt;\n }\n });\n };\n\n apply();\n return () => {\n cancelled = true;\n if (retry) clearTimeout(retry);\n };\n }, [\n contentUpdatedAt,\n editor,\n value,\n collab,\n isLeadClient,\n getMarkdown,\n setContent,\n normalizeValue,\n ]);\n\n const shouldIgnoreUpdate = (transaction: Transaction): boolean => {\n if (!editable || isSettingContentRef.current) return true;\n if (transaction.getMeta(RICH_MARKDOWN_PROGRAMMATIC_TRANSACTION)) {\n return true;\n }\n // In collab mode, never persist remote-originated changes (the initial Yjs\n // state load or a peer's edit arriving via sync). Each client saves only its\n // OWN local edits; a peer's edit is saved by that peer. Without this, a\n // lagging Y.Doc load would write stale markdown over newer SQL.\n if (collab && transaction && isChangeOrigin(transaction)) return true;\n lastTypedAtRef.current = Date.now();\n return false;\n };\n\n const registerEmitted = (markdown: string): boolean => {\n // Don't persist an empty doc before Collaboration has seeded — that would\n // clobber the saved block content with an empty string.\n if (collab && !markdown.trim()) return false;\n lastEmittedRef.current = markdown;\n pushEmittedRing(recentEmittedRef.current, markdown);\n return true;\n };\n\n return {\n collab,\n isSettingContentRef,\n shouldIgnoreUpdate,\n registerEmitted,\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"SettingsPanel.d.ts","sourceRoot":"","sources":["../../../src/client/settings/SettingsPanel.tsx"],"names":[],"mappings":"AAozDA,MAAM,WAAW,kBAAkB;IACjC,SAAS,EAAE,OAAO,CAAC;IACnB,eAAe,EAAE,MAAM,IAAI,CAAC;IAC5B,aAAa,EAAE,OAAO,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AA0RD,wBAAgB,aAAa,CAAC,EAC5B,SAAS,EACT,eAAe,EACf,aAAa,EACb,SAAS,EACT,cAAc,EACd,iBAAiB,GAClB,EAAE,kBAAkB,2CAwYpB"}
1
+ {"version":3,"file":"SettingsPanel.d.ts","sourceRoot":"","sources":["../../../src/client/settings/SettingsPanel.tsx"],"names":[],"mappings":"AA+yDA,MAAM,WAAW,kBAAkB;IACjC,SAAS,EAAE,OAAO,CAAC;IACnB,eAAe,EAAE,MAAM,IAAI,CAAC;IAC5B,aAAa,EAAE,OAAO,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AA0RD,wBAAgB,aAAa,CAAC,EAC5B,SAAS,EACT,eAAe,EACf,aAAa,EACb,SAAS,EACT,cAAc,EACd,iBAAiB,GAClB,EAAE,kBAAkB,2CAwYpB"}
@@ -16,6 +16,7 @@ import { PROVIDER_ENV_PLACEHOLDERS } from "../../agent/engine/provider-env-vars.
16
16
  import { Tooltip, TooltipContent, TooltipTrigger, } from "../components/ui/tooltip.js";
17
17
  import { useSession } from "../use-session.js";
18
18
  import { uploadAvatar, useAvatarUrl } from "../use-avatar.js";
19
+ import { callAction } from "../use-action.js";
19
20
  const IntegrationsPanel = lazy(() => import("../integrations/IntegrationsPanel.js").then((m) => ({
20
21
  default: m.IntegrationsPanel,
21
22
  })));
@@ -270,17 +271,13 @@ function LLMSectionInner({ builderFlow, builderLoading, connectUrl, connected, o
270
271
  refreshSettingsStatus();
271
272
  }, [refreshSettingsStatus]);
272
273
  useEffect(() => {
273
- fetch(agentNativePath("/_agent-native/actions/manage-agent-engine"), {
274
- method: "POST",
275
- headers: { "Content-Type": "application/json" },
276
- body: JSON.stringify({ action: "list" }),
277
- })
278
- .then((r) => (r.ok ? r.json() : null))
274
+ callAction("manage-agent-engine", { action: "list" })
279
275
  .then((data) => {
280
276
  if (!data)
281
277
  return;
282
- setEngines(data.engines ?? []);
283
- const cur = data.current ?? {};
278
+ const engineData = data;
279
+ setEngines(engineData.engines ?? []);
280
+ const cur = engineData.current ?? {};
284
281
  setCurrentEngine(cur.engine ?? "anthropic");
285
282
  setCurrentModel(cur.model ?? "");
286
283
  setSelectedEngine(cur.engine ?? "anthropic");
@@ -366,18 +363,13 @@ function LLMSectionInner({ builderFlow, builderLoading, connectUrl, connected, o
366
363
  setTesting(true);
367
364
  setTestResult(null);
368
365
  try {
369
- const res = await fetch(agentNativePath("/_agent-native/actions/manage-agent-engine"), {
370
- method: "POST",
371
- headers: { "Content-Type": "application/json" },
372
- body: JSON.stringify({
373
- action: "test",
374
- engine: selectedEngine,
375
- model: selectedModel || selectedEngineInfo?.defaultModel,
376
- }),
366
+ const data = await callAction("manage-agent-engine", {
367
+ action: "test",
368
+ engine: selectedEngine,
369
+ model: selectedModel || selectedEngineInfo?.defaultModel,
377
370
  });
378
- // The action endpoint wraps tool output; some paths return the JSON
379
- // string as-is, others wrap in { result }. Accept either shape.
380
- const data = await res.json();
371
+ // Older action paths wrapped tool output in { result }. Accept either
372
+ // shape while the action route normalizes JSON-string script output.
381
373
  const parsed = typeof data === "string"
382
374
  ? JSON.parse(data)
383
375
  : typeof data?.result === "string"