@pilotiq/tiptap 3.6.0 → 3.7.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.
@@ -33,7 +33,7 @@
33
33
  */
34
34
  import { Extension } from '@tiptap/core';
35
35
  import { PluginKey } from '@tiptap/pm/state';
36
- import type { EditorState } from '@tiptap/pm/state';
36
+ import type { EditorState, Transaction } from '@tiptap/pm/state';
37
37
  import type { Node as ProseMirrorNode, Slice } from '@tiptap/pm/model';
38
38
  import { ChangeSet } from 'prosemirror-changeset';
39
39
  declare module '@tiptap/core' {
@@ -49,6 +49,20 @@ declare module '@tiptap/core' {
49
49
  * the queue entry.
50
50
  */
51
51
  startAiInlineDiff: (id: string, newDocSlice: Slice) => ReturnType;
52
+ /**
53
+ * Start the inline-diff review session for a surgical edit.
54
+ * Snapshots the current doc as the baseline, then runs
55
+ * `applyFn(tr)` to mutate the transaction with a precise change
56
+ * (e.g. replace one block, insert before a position, set a mark
57
+ * on a range). The plugin folds the resulting steps into the
58
+ * changeset, so decorations land exactly on the modified ranges
59
+ * — no whole-doc replacement.
60
+ *
61
+ * Use this for `replace_block` / `insert_block_before` /
62
+ * `delete_block` / `update_block_mark` AI ops. Returns false (no
63
+ * dispatch) when `applyFn` produced no doc change.
64
+ */
65
+ applySurgicalAiInlineDiff: (id: string, applyFn: (tr: Transaction) => void) => ReturnType;
52
66
  /** Clear diff state. Current doc IS the accepted state. */
53
67
  acceptAiInlineDiff: () => ReturnType;
54
68
  /** Revert doc to the captured baseline and clear diff state. */
@@ -1 +1 @@
1
- {"version":3,"file":"AiInlineDiffExtension.d.ts","sourceRoot":"","sources":["../../src/extensions/AiInlineDiffExtension.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AACxC,OAAO,EAAU,SAAS,EAAE,MAAM,kBAAkB,CAAA;AACpD,OAAO,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AK,EAAE,IAAI,IAAI,eAAe,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAA;AACtE,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAA;AAEjD,OAAO,QAAQ,cAAc,CAAC;IAC5B,UAAU,QAAQ,CAAC,UAAU;QAC3B,YAAY,EAAE;YACZ;;;;;;;;eAQG;YACH,iBAAiB,EAAG,CAAC,EAAE,EAAE,MAAM,EAAE,WAAW,EAAE,KAAK,KAAK,UAAU,CAAA;YAClE;;;;;;;;;;;;eAYG;YACH,yBAAyB,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,WAAW,KAAK,IAAI,KAAK,UAAU,CAAA;YACzF,2DAA2D;YAC3D,kBAAkB,EAAE,MAAM,UAAU,CAAA;YACpC,gEAAgE;YAChE,kBAAkB,EAAE,MAAM,UAAU,CAAA;SACrC,CAAA;KACF;CACF;AAED,UAAU,SAAS;IACjB,EAAE,EAAS,MAAM,CAAA;IACjB,2EAA2E;IAC3E,QAAQ,EAAG,eAAe,CAAA;IAC1B,mDAAmD;IACnD,SAAS,EAAE,SAAS,CAAA;CACrB;AAED,eAAO,MAAM,qBAAqB,6BAAyD,CAAA;AAE3F;kEACkE;AAClE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAEzE;AAMD,MAAM,WAAW,4BAA4B;IAC3C;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,eAAO,MAAM,qBAAqB,8CAwHhC,CAAA"}
@@ -91,6 +91,17 @@ export const AiInlineDiffExtension = Extension.create({
91
91
  dispatch(tr);
92
92
  return true;
93
93
  },
94
+ applySurgicalAiInlineDiff: (id, applyFn) => ({ tr, state, dispatch }) => {
95
+ const baseline = state.doc;
96
+ applyFn(tr);
97
+ if (!tr.docChanged)
98
+ return false;
99
+ const meta = { type: 'start', id, baseline };
100
+ tr.setMeta(aiInlineDiffPluginKey, meta);
101
+ if (dispatch)
102
+ dispatch(tr);
103
+ return true;
104
+ },
94
105
  acceptAiInlineDiff: () => ({ tr, dispatch }) => {
95
106
  const meta = { type: 'clear' };
96
107
  tr.setMeta(aiInlineDiffPluginKey, meta);
@@ -1 +1 @@
1
- {"version":3,"file":"AiInlineDiffExtension.js","sourceRoot":"","sources":["../../src/extensions/AiInlineDiffExtension.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AACxC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAEpD,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAE3D,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAA;AA+BjD,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,SAAS,CAAmB,qBAAqB,CAAC,CAAA;AAE3F;kEACkE;AAClE,MAAM,UAAU,oBAAoB,CAAC,KAAkB;IACrD,OAAO,qBAAqB,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,IAAI,CAAA;AACtD,CAAC;AAiBD,MAAM,CAAC,MAAM,qBAAqB,GAAG,SAAS,CAAC,MAAM,CAA+B;IAClF,IAAI,EAAE,qBAAqB;IAE3B,UAAU;QACR,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,CAAA;IAC3C,CAAC;IAED,QAAQ;QACN,kEAAkE;QAClE,IAAI,OAAO,QAAQ,KAAK,WAAW;YAAE,OAAM;QAC3C,MAAM,QAAQ,GAAG,6BAA6B,CAAA;QAC9C,IAAI,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,SAAS,QAAQ,GAAG,CAAC;YAAE,OAAM;QAC7D,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,WAAW,CAAA;QACvC,MAAM,KAAK,GAAI,QAAQ,CAAC,aAAa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,CAAC,CAAA;IAChD,IAAI,CAAC,eAAe,GAAG,OAAO,CAAA;IAC9B,MAAM,KAAK,GAAG,QAAQ,CAAC,aAAa,CAAC,MAAM,CAAC,CAAA;IAC5C,KAAK,CAAC,SAAS,GAAK,GAAG,MAAM,eAAe,CAAA;IAC5C,KAAK,CAAC,WAAW,GAAG,IAAI,CAAA;IACxB,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAA;IACvB,OAAO,IAAI,CAAA;AACb,CAAC"}
package/dist/index.d.ts CHANGED
@@ -7,5 +7,7 @@ export { tiptap } from './plugin.js';
7
7
  export { TiptapEditor } from './react/TiptapEditor.js';
8
8
  export { AiSuggestionExtension, aiSuggestionPluginKey, upsertSuggestion, upsertSuggestions, removeSuggestion, remapSuggestions, sortForApproveAll, clampPos, type AiSuggestion, type AiSuggestionExtensionOptions, } from './extensions/AiSuggestionExtension.js';
9
9
  export { useAiSuggestionBridge } from './react/useAiSuggestionBridge.js';
10
+ export { AiInlineDiffExtension, aiInlineDiffPluginKey, getAiInlineDiffState, type AiInlineDiffExtensionOptions, } from './extensions/AiInlineDiffExtension.js';
11
+ export { planReplaceBlock, planInsertBlockBefore, planDeleteBlock, planUpdateBlockMark, summarizeBlockStructure, type BlockMarkRange, type TransactionModifier, } from './surgicalOps.js';
10
12
  export { renderRichTextToHtml, isRichTextValue, type RenderRichTextOptions, type TiptapNode, type TiptapMark, } from './render.js';
11
13
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,sBAAsB,EACtB,mBAAmB,EACnB,wBAAwB,EACxB,KAAK,WAAW,EAChB,KAAK,4BAA4B,EACjC,KAAK,iBAAiB,EACtB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,aAAa,GACnB,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,KAAK,EAAE,KAAK,SA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,EACX,cAAc,EACd,KAAK,sBAAsB,GAC5B,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAA;AACtD,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,QAAQ,EACR,KAAK,YAAY,EACjB,KAAK,4BAA4B,GAClC,MAAM,uCAAuC,CAAA;AAC9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAA;AACxE,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,oBAAoB,EACpB,KAAK,4BAA4B,GAClC,MAAM,uCAAuC,CAAA;AAC9C,OAAO,EACL,gBAAgB,EAChB,qBAAqB,EACrB,eAAe,EACf,mBAAmB,EACnB,uBAAuB,EACvB,KAAK,cAAc,EACnB,KAAK,mBAAmB,GACzB,MAAM,kBAAkB,CAAA;AACzB,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,KAAK,qBAAqB,EAC1B,KAAK,UAAU,EACf,KAAK,UAAU,GAChB,MAAM,aAAa,CAAA"}
package/dist/index.js CHANGED
@@ -7,5 +7,7 @@ export { tiptap } from './plugin.js';
7
7
  export { TiptapEditor } from './react/TiptapEditor.js';
8
8
  export { AiSuggestionExtension, aiSuggestionPluginKey, upsertSuggestion, upsertSuggestions, removeSuggestion, remapSuggestions, sortForApproveAll, clampPos, } from './extensions/AiSuggestionExtension.js';
9
9
  export { useAiSuggestionBridge } from './react/useAiSuggestionBridge.js';
10
+ export { AiInlineDiffExtension, aiInlineDiffPluginKey, getAiInlineDiffState, } from './extensions/AiInlineDiffExtension.js';
11
+ export { planReplaceBlock, planInsertBlockBefore, planDeleteBlock, planUpdateBlockMark, summarizeBlockStructure, } from './surgicalOps.js';
10
12
  export { renderRichTextToHtml, isRichTextValue, } from './render.js';
11
13
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,sBAAsB,EACtB,mBAAmB,EACnB,wBAAwB,GAOzB,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,KAAK,EAAkB,MAAM,YAAY,CAAA;AAClD,OAAO,EACL,eAAe,GAGhB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAA;AAC9C,OAAO,EACL,qBAAqB,EACrB,WAAW,EACX,cAAc,GAEf,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAA;AACtD,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,QAAQ,GAGT,MAAM,uCAAuC,CAAA;AAC9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAA;AACxE,OAAO,EACL,oBAAoB,EACpB,eAAe,GAIhB,MAAM,aAAa,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,sBAAsB,EACtB,mBAAmB,EACnB,wBAAwB,GAOzB,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,KAAK,EAAkB,MAAM,YAAY,CAAA;AAClD,OAAO,EACL,eAAe,GAGhB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAA;AAC9C,OAAO,EACL,qBAAqB,EACrB,WAAW,EACX,cAAc,GAEf,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAA;AACtD,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,QAAQ,GAGT,MAAM,uCAAuC,CAAA;AAC9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAA;AACxE,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,oBAAoB,GAErB,MAAM,uCAAuC,CAAA;AAC9C,OAAO,EACL,gBAAgB,EAChB,qBAAqB,EACrB,eAAe,EACf,mBAAmB,EACnB,uBAAuB,GAGxB,MAAM,kBAAkB,CAAA;AACzB,OAAO,EACL,oBAAoB,EACpB,eAAe,GAIhB,MAAM,aAAa,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"useAiInlineDiff.d.ts","sourceRoot":"","sources":["../../src/react/useAiInlineDiff.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAGH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAC1C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAA;AAS7C,MAAM,WAAW,sBAAsB;IACrC;;;;;;;;;;;OAWG;IACH,eAAe,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,KAAK,GAAG,IAAI,CAAA;CACjE;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAatE;AAED,wBAAgB,eAAe,CAC7B,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,sBAAsB,GAC9B,IAAI,CA+CN"}
1
+ {"version":3,"file":"useAiInlineDiff.d.ts","sourceRoot":"","sources":["../../src/react/useAiInlineDiff.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAGH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAC1C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAA;AAkB7C,MAAM,WAAW,sBAAsB;IACrC;;;;;;;;;;;OAWG;IACH,eAAe,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,KAAK,GAAG,IAAI,CAAA;CACjE;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAMtE;AAED,wBAAgB,eAAe,CAC7B,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,sBAAsB,GAC9B,IAAI,CA6DN"}
@@ -30,8 +30,10 @@
30
30
  * suggestion at a time per id.
31
31
  */
32
32
  import { useEffect, useRef } from 'react';
33
+ import { useEditorState } from '@tiptap/react';
33
34
  import { registerPendingSuggestionApplier, usePendingSuggestionsForField, } from '@pilotiq/pilotiq/react';
34
35
  import { aiInlineDiffPluginKey } from '../extensions/AiInlineDiffExtension.js';
36
+ import { planReplaceBlock, planInsertBlockBefore, planDeleteBlock, planUpdateBlockMark, } from '../surgicalOps.js';
35
37
  /**
36
38
  * Returns whether a diff is currently active in the editor. Hosts use
37
39
  * this to gate the banner's UI between the legacy `onApplyWholeField`
@@ -39,20 +41,11 @@ import { aiInlineDiffPluginKey } from '../extensions/AiInlineDiffExtension.js';
39
41
  * `rejectAiInlineDiff` to revert the doc).
40
42
  */
41
43
  export function useIsAiInlineDiffActive(editor) {
42
- // Re-render on every editor transaction so the hook tracks state
43
- // changes (start / accept / reject). useEditorState would be the
44
- // idiomatic way; we read directly here to keep the dep surface tiny.
45
- const [, force] = useReducerForceUpdate();
46
- useEffect(() => {
47
- if (!editor)
48
- return;
49
- const handler = () => force();
50
- editor.on('transaction', handler);
51
- return () => { editor.off('transaction', handler); };
52
- }, [editor, force]);
53
- if (!editor)
54
- return false;
55
- return aiInlineDiffPluginKey.getState(editor.state) !== null;
44
+ const active = useEditorState({
45
+ editor,
46
+ selector: ({ editor: ed }) => !!ed && aiInlineDiffPluginKey.getState(ed.state) !== null,
47
+ });
48
+ return active ?? false;
56
49
  }
57
50
  export function useAiInlineDiff(editor, fieldName, options) {
58
51
  const { list } = usePendingSuggestionsForField(fieldName);
@@ -62,21 +55,34 @@ export function useAiInlineDiff(editor, fieldName, options) {
62
55
  // so we don't re-start the diff every render or for already-active
63
56
  // suggestions.
64
57
  const startedRef = useRef(new Set());
65
- // Context → editor: start the diff for each new whole-field suggestion.
58
+ // Context → editor: start the diff for each new whole-field /
59
+ // surgical-block suggestion. `meta.surgical` (if present) routes to a
60
+ // precise PM transaction; otherwise we treat the suggested value as a
61
+ // whole-field replacement. `meta.editorRange` (chip path) is filtered
62
+ // out — handled by AiSuggestionExtension elsewhere.
66
63
  useEffect(() => {
67
64
  if (!editor)
68
65
  return;
69
- const wholeField = list.filter(s => !hasEditorRange(s));
70
- for (const s of wholeField) {
66
+ const diffable = list.filter(s => !hasEditorRange(s));
67
+ for (const s of diffable) {
71
68
  if (startedRef.current.has(s.id))
72
69
  continue;
73
- if (typeof s.suggestedValue !== 'string')
74
- continue;
75
70
  // Bail when a different diff is already showing — one at a time.
76
71
  // Producer should serialize calls; if not, the second suggestion
77
72
  // sits in the queue until the first is approved/rejected.
78
73
  if (aiInlineDiffPluginKey.getState(editor.state) !== null)
79
74
  continue;
75
+ const surgical = readSurgicalMeta(s);
76
+ if (surgical) {
77
+ const modifier = planSurgicalModifier(editor, surgical);
78
+ if (!modifier)
79
+ continue;
80
+ editor.commands.applySurgicalAiInlineDiff(s.id, modifier);
81
+ startedRef.current.add(s.id);
82
+ continue;
83
+ }
84
+ if (typeof s.suggestedValue !== 'string')
85
+ continue;
80
86
  const slice = parseRef.current(editor, s.suggestedValue);
81
87
  if (!slice)
82
88
  continue;
@@ -111,11 +117,102 @@ function hasEditorRange(s) {
111
117
  const range = meta['editorRange'];
112
118
  return !!(range && typeof range.from === 'number' && typeof range.to === 'number');
113
119
  }
114
- // useReducer + dispatch is the smallest-API force-update primitive React
115
- // ships. Hoisted into a helper so the call site stays one line.
116
- import { useReducer } from 'react';
117
- function useReducerForceUpdate() {
118
- const [n, inc] = useReducer((x) => (x + 1) | 0, 0);
119
- return [n, () => inc()];
120
+ function parseSurgicalOp(obj) {
121
+ const op = obj['op'];
122
+ const blockIndex = obj['blockIndex'];
123
+ if (typeof blockIndex !== 'number')
124
+ return null;
125
+ switch (op) {
126
+ case 'replace_block':
127
+ case 'insert_block_before': {
128
+ const content = obj['content'];
129
+ if (typeof content !== 'string')
130
+ return null;
131
+ return { op, blockIndex, content };
132
+ }
133
+ case 'delete_block':
134
+ return { op, blockIndex };
135
+ case 'update_block_mark': {
136
+ const mark = obj['mark'];
137
+ const range = obj['range'];
138
+ const apply = obj['apply'];
139
+ const attrs = obj['attrs'];
140
+ if (typeof mark !== 'string')
141
+ return null;
142
+ if (!range || typeof range.from !== 'number' || typeof range.to !== 'number')
143
+ return null;
144
+ if (typeof apply !== 'boolean')
145
+ return null;
146
+ return {
147
+ op,
148
+ blockIndex,
149
+ mark,
150
+ range: { from: range.from, to: range.to },
151
+ apply,
152
+ ...(attrs && typeof attrs === 'object' ? { attrs: attrs } : {}),
153
+ };
154
+ }
155
+ default:
156
+ return null;
157
+ }
158
+ }
159
+ function readSurgicalMeta(s) {
160
+ const meta = (s.meta ?? {});
161
+ const raw = meta['surgical'];
162
+ if (!raw || typeof raw !== 'object')
163
+ return null;
164
+ const obj = raw;
165
+ // Batch form: { ops: [SurgicalOp, ...] }
166
+ if (Array.isArray(obj['ops'])) {
167
+ const parsed = [];
168
+ for (const entry of obj['ops']) {
169
+ if (!entry || typeof entry !== 'object')
170
+ continue;
171
+ const op = parseSurgicalOp(entry);
172
+ if (op)
173
+ parsed.push(op);
174
+ }
175
+ if (parsed.length === 0)
176
+ return null;
177
+ return { ops: parsed };
178
+ }
179
+ return parseSurgicalOp(obj);
180
+ }
181
+ function planOp(editor, op) {
182
+ switch (op.op) {
183
+ case 'replace_block': return planReplaceBlock(editor, op.blockIndex, op.content);
184
+ case 'insert_block_before': return planInsertBlockBefore(editor, op.blockIndex, op.content);
185
+ case 'delete_block': return planDeleteBlock(editor, op.blockIndex);
186
+ case 'update_block_mark': return planUpdateBlockMark(editor, op.blockIndex, op.mark, op.range, op.apply, op.attrs);
187
+ }
188
+ }
189
+ /**
190
+ * Translate a surgical meta into a single TransactionModifier the diff
191
+ * extension can wrap with a snapshot. For batches, modifiers are
192
+ * computed against the original (pre-transaction) doc and then applied
193
+ * in DESC `blockIndex` order — each subsequent modifier touches earlier
194
+ * positions, so the prior modifiers' edits (at higher positions) don't
195
+ * shift the absolute positions the later modifiers were planned with.
196
+ *
197
+ * Returns null when the batch has no plannable ops (all out-of-range /
198
+ * unparseable). Drops individual non-plannable ops from a batch but
199
+ * still runs whatever did plan, so a single bad op doesn't kill the
200
+ * whole batch.
201
+ */
202
+ function planSurgicalModifier(editor, surgical) {
203
+ if ('ops' in surgical) {
204
+ const sorted = [...surgical.ops].sort((a, b) => b.blockIndex - a.blockIndex);
205
+ const modifiers = [];
206
+ for (const op of sorted) {
207
+ const mod = planOp(editor, op);
208
+ if (mod)
209
+ modifiers.push(mod);
210
+ }
211
+ if (modifiers.length === 0)
212
+ return null;
213
+ return (tr) => { for (const mod of modifiers)
214
+ mod(tr); };
215
+ }
216
+ return planOp(editor, surgical);
120
217
  }
121
218
  //# sourceMappingURL=useAiInlineDiff.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useAiInlineDiff.js","sourceRoot":"","sources":["../../src/react/useAiInlineDiff.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAA;AAGzC,OAAO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-0,0 +1,72 @@
1
+ /**
2
+ * Surgical block-op planners for AI-driven precise edits.
3
+ *
4
+ * Each planner takes the editor + a logical block index + a payload and
5
+ * returns a `TransactionModifier` — a function the caller (typically
6
+ * `useAiInlineDiff`) feeds into
7
+ * `editor.commands.applySurgicalAiInlineDiff(id, modifier)`. The diff
8
+ * extension wraps the modifier in a snapshot-then-apply step so the
9
+ * inline-diff overlay renders against the precise changed range.
10
+ *
11
+ * "Block index" refers to a 0-based position across the doc's top-level
12
+ * children — what the AI agent sees as a numbered structural summary.
13
+ * Planners translate that to absolute ProseMirror positions internally.
14
+ *
15
+ * Planners return `null` when the request can't be satisfied (out-of-
16
+ * range index, unparseable HTML, unknown mark). Callers should treat
17
+ * `null` as "abort the surgical op" and surface a clear error to the
18
+ * agent so it can retry with a different plan.
19
+ */
20
+ import type { Editor } from '@tiptap/core';
21
+ import type { Transaction } from '@tiptap/pm/state';
22
+ import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
23
+ export type TransactionModifier = (tr: Transaction) => void;
24
+ /**
25
+ * Replace the top-level block at `blockIndex` with the parsed content.
26
+ * Caller-supplied `content` is HTML — multiple top-level nodes are
27
+ * allowed and will all land where the original block was.
28
+ */
29
+ export declare function planReplaceBlock(editor: Editor, blockIndex: number, content: string): TransactionModifier | null;
30
+ /**
31
+ * Insert one or more top-level nodes (parsed from `content` HTML)
32
+ * before the block at `blockIndex`. `blockIndex === doc.childCount`
33
+ * appends at the end.
34
+ */
35
+ export declare function planInsertBlockBefore(editor: Editor, blockIndex: number, content: string): TransactionModifier | null;
36
+ /**
37
+ * Delete the top-level block at `blockIndex`. Doc must retain at least
38
+ * one child after the delete (most schemas require this) — refuses to
39
+ * delete the last remaining block.
40
+ */
41
+ export declare function planDeleteBlock(editor: Editor, blockIndex: number): TransactionModifier | null;
42
+ export interface BlockMarkRange {
43
+ /** 0-based text offset from the start of the block's content. */
44
+ from: number;
45
+ /** Exclusive end offset. */
46
+ to: number;
47
+ }
48
+ /**
49
+ * Apply or remove an inline mark on a range *within* the block at
50
+ * `blockIndex`. `range.from` / `range.to` are text offsets relative to
51
+ * the start of the block's content (so `0` is the first character of
52
+ * the block, not the start of the doc).
53
+ *
54
+ * `apply = true` sets the mark (with optional `attrs`); `apply = false`
55
+ * removes it. Unknown marks (not in the editor's schema) return `null`
56
+ * so the caller can surface a clean error to the agent.
57
+ */
58
+ export declare function planUpdateBlockMark(editor: Editor, blockIndex: number, mark: string, range: BlockMarkRange, apply: boolean, attrs?: Record<string, unknown>): TransactionModifier | null;
59
+ /**
60
+ * Summarize a doc's top-level structure as a numbered list the AI can
61
+ * cite by index when proposing surgical ops. Each entry includes the
62
+ * block index, node type, and a truncated text preview — enough for the
63
+ * model to identify which block it wants to modify without sending the
64
+ * whole HTML/markdown back through token-priced channels.
65
+ *
66
+ * Returns one line per top-level child:
67
+ * `[0] heading: Welcome to the docs`
68
+ * `[1] paragraph: Lorem ipsum dolor sit amet…`
69
+ * `[2] bulletList: 3 items`
70
+ */
71
+ export declare function summarizeBlockStructure(doc: ProseMirrorNode, maxChars?: number): string;
72
+ //# sourceMappingURL=surgicalOps.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"surgicalOps.d.ts","sourceRoot":"","sources":["../src/surgicalOps.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAC1C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AACnD,OAAO,KAAK,EAAkB,IAAI,IAAI,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAG/E,MAAM,MAAM,mBAAmB,GAAG,CAAC,EAAE,EAAE,WAAW,KAAK,IAAI,CAAA;AAyB3D;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAM,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAK,MAAM,GACjB,mBAAmB,GAAG,IAAI,CAQ5B;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAM,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAK,MAAM,GACjB,mBAAmB,GAAG,IAAI,CAQ5B;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAM,MAAM,EAClB,UAAU,EAAE,MAAM,GACjB,mBAAmB,GAAG,IAAI,CAO5B;AAED,MAAM,WAAW,cAAc;IAC7B,iEAAiE;IACjE,IAAI,EAAE,MAAM,CAAA;IACZ,4BAA4B;IAC5B,EAAE,EAAI,MAAM,CAAA;CACb;AAED;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAM,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,IAAI,EAAQ,MAAM,EAClB,KAAK,EAAO,cAAc,EAC1B,KAAK,EAAO,OAAO,EACnB,KAAK,CAAC,EAAM,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAClC,mBAAmB,GAAG,IAAI,CAwB5B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,eAAe,EAAE,QAAQ,SAAK,GAAG,MAAM,CAWnF"}
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Surgical block-op planners for AI-driven precise edits.
3
+ *
4
+ * Each planner takes the editor + a logical block index + a payload and
5
+ * returns a `TransactionModifier` — a function the caller (typically
6
+ * `useAiInlineDiff`) feeds into
7
+ * `editor.commands.applySurgicalAiInlineDiff(id, modifier)`. The diff
8
+ * extension wraps the modifier in a snapshot-then-apply step so the
9
+ * inline-diff overlay renders against the precise changed range.
10
+ *
11
+ * "Block index" refers to a 0-based position across the doc's top-level
12
+ * children — what the AI agent sees as a numbered structural summary.
13
+ * Planners translate that to absolute ProseMirror positions internally.
14
+ *
15
+ * Planners return `null` when the request can't be satisfied (out-of-
16
+ * range index, unparseable HTML, unknown mark). Callers should treat
17
+ * `null` as "abort the surgical op" and surface a clear error to the
18
+ * agent so it can retry with a different plan.
19
+ */
20
+ import { DOMParser as PMDOMParser } from '@tiptap/pm/model';
21
+ /** Resolve the start position of the top-level child at `blockIndex`. */
22
+ function blockStartPos(doc, blockIndex) {
23
+ if (!Number.isInteger(blockIndex) || blockIndex < 0 || blockIndex >= doc.childCount)
24
+ return null;
25
+ let pos = 0;
26
+ for (let i = 0; i < blockIndex; i++)
27
+ pos += doc.child(i).nodeSize;
28
+ return pos;
29
+ }
30
+ /**
31
+ * Parse an HTML fragment into a doc-replaceable Slice. Uses the
32
+ * editor's own schema so block types unknown to the schema fail loudly
33
+ * rather than silently degrading.
34
+ *
35
+ * Returns `null` when DOM isn't available (SSR — shouldn't happen here,
36
+ * but keeps the planner safe).
37
+ */
38
+ function parseHtmlToSlice(editor, html) {
39
+ if (typeof document === 'undefined')
40
+ return null;
41
+ const container = document.createElement('div');
42
+ container.innerHTML = html;
43
+ return PMDOMParser.fromSchema(editor.schema).parseSlice(container);
44
+ }
45
+ /**
46
+ * Replace the top-level block at `blockIndex` with the parsed content.
47
+ * Caller-supplied `content` is HTML — multiple top-level nodes are
48
+ * allowed and will all land where the original block was.
49
+ */
50
+ export function planReplaceBlock(editor, blockIndex, content) {
51
+ const doc = editor.state.doc;
52
+ const start = blockStartPos(doc, blockIndex);
53
+ if (start === null)
54
+ return null;
55
+ const slice = parseHtmlToSlice(editor, content);
56
+ if (!slice)
57
+ return null;
58
+ const end = start + doc.child(blockIndex).nodeSize;
59
+ return (tr) => { tr.replace(start, end, slice); };
60
+ }
61
+ /**
62
+ * Insert one or more top-level nodes (parsed from `content` HTML)
63
+ * before the block at `blockIndex`. `blockIndex === doc.childCount`
64
+ * appends at the end.
65
+ */
66
+ export function planInsertBlockBefore(editor, blockIndex, content) {
67
+ const doc = editor.state.doc;
68
+ if (!Number.isInteger(blockIndex) || blockIndex < 0 || blockIndex > doc.childCount)
69
+ return null;
70
+ const slice = parseHtmlToSlice(editor, content);
71
+ if (!slice)
72
+ return null;
73
+ let pos = 0;
74
+ for (let i = 0; i < blockIndex; i++)
75
+ pos += doc.child(i).nodeSize;
76
+ return (tr) => { tr.replace(pos, pos, slice); };
77
+ }
78
+ /**
79
+ * Delete the top-level block at `blockIndex`. Doc must retain at least
80
+ * one child after the delete (most schemas require this) — refuses to
81
+ * delete the last remaining block.
82
+ */
83
+ export function planDeleteBlock(editor, blockIndex) {
84
+ const doc = editor.state.doc;
85
+ const start = blockStartPos(doc, blockIndex);
86
+ if (start === null)
87
+ return null;
88
+ if (doc.childCount <= 1)
89
+ return null;
90
+ const end = start + doc.child(blockIndex).nodeSize;
91
+ return (tr) => { tr.delete(start, end); };
92
+ }
93
+ /**
94
+ * Apply or remove an inline mark on a range *within* the block at
95
+ * `blockIndex`. `range.from` / `range.to` are text offsets relative to
96
+ * the start of the block's content (so `0` is the first character of
97
+ * the block, not the start of the doc).
98
+ *
99
+ * `apply = true` sets the mark (with optional `attrs`); `apply = false`
100
+ * removes it. Unknown marks (not in the editor's schema) return `null`
101
+ * so the caller can surface a clean error to the agent.
102
+ */
103
+ export function planUpdateBlockMark(editor, blockIndex, mark, range, apply, attrs) {
104
+ const doc = editor.state.doc;
105
+ const start = blockStartPos(doc, blockIndex);
106
+ if (start === null)
107
+ return null;
108
+ const markType = editor.schema.marks[mark];
109
+ if (!markType)
110
+ return null;
111
+ const block = doc.child(blockIndex);
112
+ const blockInner = start + 1; // step inside the block's opening token
113
+ const contentMax = block.content.size;
114
+ if (!Number.isInteger(range.from) || !Number.isInteger(range.to))
115
+ return null;
116
+ const clampedFrom = Math.max(0, Math.min(range.from, contentMax));
117
+ const clampedTo = Math.max(clampedFrom, Math.min(range.to, contentMax));
118
+ if (clampedTo === clampedFrom)
119
+ return null;
120
+ const from = blockInner + clampedFrom;
121
+ const to = blockInner + clampedTo;
122
+ if (apply) {
123
+ const m = markType.create(attrs ?? null);
124
+ return (tr) => { tr.addMark(from, to, m); };
125
+ }
126
+ return (tr) => { tr.removeMark(from, to, markType); };
127
+ }
128
+ /**
129
+ * Summarize a doc's top-level structure as a numbered list the AI can
130
+ * cite by index when proposing surgical ops. Each entry includes the
131
+ * block index, node type, and a truncated text preview — enough for the
132
+ * model to identify which block it wants to modify without sending the
133
+ * whole HTML/markdown back through token-priced channels.
134
+ *
135
+ * Returns one line per top-level child:
136
+ * `[0] heading: Welcome to the docs`
137
+ * `[1] paragraph: Lorem ipsum dolor sit amet…`
138
+ * `[2] bulletList: 3 items`
139
+ */
140
+ export function summarizeBlockStructure(doc, maxChars = 80) {
141
+ const lines = [];
142
+ for (let i = 0; i < doc.childCount; i++) {
143
+ const node = doc.child(i);
144
+ const text = node.textContent.trim().replace(/\s+/g, ' ');
145
+ const preview = text.length === 0
146
+ ? describeStructuralNode(node)
147
+ : text.length > maxChars ? `${text.slice(0, maxChars)}…` : text;
148
+ lines.push(`[${i}] ${node.type.name}: ${preview}`);
149
+ }
150
+ return lines.join('\n');
151
+ }
152
+ function describeStructuralNode(node) {
153
+ const kids = node.childCount;
154
+ if (kids === 0)
155
+ return '(empty)';
156
+ if (kids === 1)
157
+ return `1 ${node.firstChild?.type.name ?? 'child'}`;
158
+ return `${kids} children`;
159
+ }
160
+ //# sourceMappingURL=surgicalOps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"surgicalOps.js","sourceRoot":"","sources":["../src/surgicalOps.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAKH,OAAO,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAI3D,yEAAyE;AACzE,SAAS,aAAa,CAAC,GAAoB,EAAE,UAAkB;IAC7D,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,UAAU,GAAG,CAAC,IAAI,UAAU,IAAI,GAAG,CAAC,UAAU;QAAE,OAAO,IAAI,CAAA;IAChG,IAAI,GAAG,GAAG,CAAC,CAAA;IACX,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU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,KAAK,CAAC;QAAE,OAAO,KAAK,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,IAAI,OAAO,EAAE,CAAA;IACnE,OAAO,GAAG,IAAI,WAAW,CAAA;AAC3B,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pilotiq/tiptap",
3
- "version": "3.6.0",
3
+ "version": "3.7.0",
4
4
  "description": "Tiptap rich-text editor adapter for @pilotiq/pilotiq — slash menu, draggable blocks, custom-block API",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -52,6 +52,20 @@ declare module '@tiptap/core' {
52
52
  * the queue entry.
53
53
  */
54
54
  startAiInlineDiff: (id: string, newDocSlice: Slice) => ReturnType
55
+ /**
56
+ * Start the inline-diff review session for a surgical edit.
57
+ * Snapshots the current doc as the baseline, then runs
58
+ * `applyFn(tr)` to mutate the transaction with a precise change
59
+ * (e.g. replace one block, insert before a position, set a mark
60
+ * on a range). The plugin folds the resulting steps into the
61
+ * changeset, so decorations land exactly on the modified ranges
62
+ * — no whole-doc replacement.
63
+ *
64
+ * Use this for `replace_block` / `insert_block_before` /
65
+ * `delete_block` / `update_block_mark` AI ops. Returns false (no
66
+ * dispatch) when `applyFn` produced no doc change.
67
+ */
68
+ applySurgicalAiInlineDiff: (id: string, applyFn: (tr: Transaction) => void) => ReturnType
55
69
  /** Clear diff state. Current doc IS the accepted state. */
56
70
  acceptAiInlineDiff: () => ReturnType
57
71
  /** Revert doc to the captured baseline and clear diff state. */
@@ -141,6 +155,15 @@ export const AiInlineDiffExtension = Extension.create<AiInlineDiffExtensionOptio
141
155
  if (dispatch) dispatch(tr)
142
156
  return true
143
157
  },
158
+ applySurgicalAiInlineDiff: (id, applyFn) => ({ tr, state, dispatch }) => {
159
+ const baseline = state.doc
160
+ applyFn(tr)
161
+ if (!tr.docChanged) return false
162
+ const meta: StartMeta = { type: 'start', id, baseline }
163
+ tr.setMeta(aiInlineDiffPluginKey, meta)
164
+ if (dispatch) dispatch(tr)
165
+ return true
166
+ },
144
167
  acceptAiInlineDiff: () => ({ tr, dispatch }) => {
145
168
  const meta: ClearMeta = { type: 'clear' }
146
169
  tr.setMeta(aiInlineDiffPluginKey, meta)
package/src/index.ts CHANGED
@@ -38,6 +38,21 @@ export {
38
38
  type AiSuggestionExtensionOptions,
39
39
  } from './extensions/AiSuggestionExtension.js'
40
40
  export { useAiSuggestionBridge } from './react/useAiSuggestionBridge.js'
41
+ export {
42
+ AiInlineDiffExtension,
43
+ aiInlineDiffPluginKey,
44
+ getAiInlineDiffState,
45
+ type AiInlineDiffExtensionOptions,
46
+ } from './extensions/AiInlineDiffExtension.js'
47
+ export {
48
+ planReplaceBlock,
49
+ planInsertBlockBefore,
50
+ planDeleteBlock,
51
+ planUpdateBlockMark,
52
+ summarizeBlockStructure,
53
+ type BlockMarkRange,
54
+ type TransactionModifier,
55
+ } from './surgicalOps.js'
41
56
  export {
42
57
  renderRichTextToHtml,
43
58
  isRichTextValue,
@@ -33,6 +33,7 @@
33
33
  import { useEffect, useRef } from 'react'
34
34
  import type { Editor } from '@tiptap/core'
35
35
  import type { Slice } from '@tiptap/pm/model'
36
+ import { useEditorState } from '@tiptap/react'
36
37
  import {
37
38
  registerPendingSuggestionApplier,
38
39
  usePendingSuggestionsForField,
@@ -40,6 +41,14 @@ import {
40
41
  type PendingSuggestionApplier,
41
42
  } from '@pilotiq/pilotiq/react'
42
43
  import { aiInlineDiffPluginKey } from '../extensions/AiInlineDiffExtension.js'
44
+ import {
45
+ planReplaceBlock,
46
+ planInsertBlockBefore,
47
+ planDeleteBlock,
48
+ planUpdateBlockMark,
49
+ type BlockMarkRange,
50
+ type TransactionModifier,
51
+ } from '../surgicalOps.js'
43
52
 
44
53
  export interface UseAiInlineDiffOptions {
45
54
  /**
@@ -64,18 +73,11 @@ export interface UseAiInlineDiffOptions {
64
73
  * `rejectAiInlineDiff` to revert the doc).
65
74
  */
66
75
  export function useIsAiInlineDiffActive(editor: Editor | null): boolean {
67
- // Re-render on every editor transaction so the hook tracks state
68
- // changes (start / accept / reject). useEditorState would be the
69
- // idiomatic way; we read directly here to keep the dep surface tiny.
70
- const [, force] = useReducerForceUpdate()
71
- useEffect(() => {
72
- if (!editor) return
73
- const handler = () => force()
74
- editor.on('transaction', handler)
75
- return () => { editor.off('transaction', handler) }
76
- }, [editor, force])
77
- if (!editor) return false
78
- return aiInlineDiffPluginKey.getState(editor.state) !== null
76
+ const active = useEditorState({
77
+ editor,
78
+ selector: ({ editor: ed }) => !!ed && aiInlineDiffPluginKey.getState(ed.state) !== null,
79
+ })
80
+ return active ?? false
79
81
  }
80
82
 
81
83
  export function useAiInlineDiff(
@@ -93,17 +95,31 @@ export function useAiInlineDiff(
93
95
  // suggestions.
94
96
  const startedRef = useRef<Set<string>>(new Set())
95
97
 
96
- // Context → editor: start the diff for each new whole-field suggestion.
98
+ // Context → editor: start the diff for each new whole-field /
99
+ // surgical-block suggestion. `meta.surgical` (if present) routes to a
100
+ // precise PM transaction; otherwise we treat the suggested value as a
101
+ // whole-field replacement. `meta.editorRange` (chip path) is filtered
102
+ // out — handled by AiSuggestionExtension elsewhere.
97
103
  useEffect(() => {
98
104
  if (!editor) return
99
- const wholeField = list.filter(s => !hasEditorRange(s))
100
- for (const s of wholeField) {
105
+ const diffable = list.filter(s => !hasEditorRange(s))
106
+ for (const s of diffable) {
101
107
  if (startedRef.current.has(s.id)) continue
102
- if (typeof s.suggestedValue !== 'string') continue
103
108
  // Bail when a different diff is already showing — one at a time.
104
109
  // Producer should serialize calls; if not, the second suggestion
105
110
  // sits in the queue until the first is approved/rejected.
106
111
  if (aiInlineDiffPluginKey.getState(editor.state) !== null) continue
112
+
113
+ const surgical = readSurgicalMeta(s)
114
+ if (surgical) {
115
+ const modifier = planSurgicalModifier(editor, surgical)
116
+ if (!modifier) continue
117
+ editor.commands.applySurgicalAiInlineDiff(s.id, modifier)
118
+ startedRef.current.add(s.id)
119
+ continue
120
+ }
121
+
122
+ if (typeof s.suggestedValue !== 'string') continue
107
123
  const slice = parseRef.current(editor, s.suggestedValue)
108
124
  if (!slice) continue
109
125
  editor.commands.startAiInlineDiff(s.id, slice)
@@ -137,10 +153,115 @@ function hasEditorRange(s: PendingSuggestion): boolean {
137
153
  return !!(range && typeof range.from === 'number' && typeof range.to === 'number')
138
154
  }
139
155
 
140
- // useReducer + dispatch is the smallest-API force-update primitive React
141
- // ships. Hoisted into a helper so the call site stays one line.
142
- import { useReducer } from 'react'
143
- function useReducerForceUpdate(): [number, () => void] {
144
- const [n, inc] = useReducer((x: number) => (x + 1) | 0, 0)
145
- return [n, () => inc()]
156
+ /**
157
+ * Surgical op carried in `PendingSuggestion.meta.surgical`. The pilotiq-
158
+ * pro `update_form_state` client handler stamps this when the AI agent
159
+ * picks a block-level op instead of `set_value`.
160
+ *
161
+ * `content` is HTML for replace/insert ops, ignored otherwise. `mark` +
162
+ * `range` apply only to the mark op. Discriminated union; readers should
163
+ * narrow on `op`.
164
+ */
165
+ type SurgicalOp =
166
+ | { op: 'replace_block'; blockIndex: number; content: string }
167
+ | { op: 'insert_block_before'; blockIndex: number; content: string }
168
+ | { op: 'delete_block'; blockIndex: number }
169
+ | { op: 'update_block_mark'; blockIndex: number; mark: string; range: BlockMarkRange; apply: boolean; attrs?: Record<string, unknown> }
170
+
171
+ /**
172
+ * Either a single op (when the AI emitted only one surgical change) or
173
+ * an `{ ops: [...] }` batch (when the AI emitted multiple surgical ops
174
+ * in one `update_form_state` tool call). We apply a batch as a single
175
+ * combined diff so the user sees one Accept / Reject for the whole set.
176
+ */
177
+ type SurgicalMeta = SurgicalOp | { ops: SurgicalOp[] }
178
+
179
+ function parseSurgicalOp(obj: Record<string, unknown>): SurgicalOp | null {
180
+ const op = obj['op']
181
+ const blockIndex = obj['blockIndex']
182
+ if (typeof blockIndex !== 'number') return null
183
+ switch (op) {
184
+ case 'replace_block':
185
+ case 'insert_block_before': {
186
+ const content = obj['content']
187
+ if (typeof content !== 'string') return null
188
+ return { op, blockIndex, content }
189
+ }
190
+ case 'delete_block':
191
+ return { op, blockIndex }
192
+ case 'update_block_mark': {
193
+ const mark = obj['mark']
194
+ const range = obj['range'] as { from?: unknown; to?: unknown } | undefined
195
+ const apply = obj['apply']
196
+ const attrs = obj['attrs']
197
+ if (typeof mark !== 'string') return null
198
+ if (!range || typeof range.from !== 'number' || typeof range.to !== 'number') return null
199
+ if (typeof apply !== 'boolean') return null
200
+ return {
201
+ op,
202
+ blockIndex,
203
+ mark,
204
+ range: { from: range.from, to: range.to },
205
+ apply,
206
+ ...(attrs && typeof attrs === 'object' ? { attrs: attrs as Record<string, unknown> } : {}),
207
+ }
208
+ }
209
+ default:
210
+ return null
211
+ }
212
+ }
213
+
214
+ function readSurgicalMeta(s: PendingSuggestion): SurgicalMeta | null {
215
+ const meta = (s.meta ?? {}) as Record<string, unknown>
216
+ const raw = meta['surgical']
217
+ if (!raw || typeof raw !== 'object') return null
218
+ const obj = raw as Record<string, unknown>
219
+ // Batch form: { ops: [SurgicalOp, ...] }
220
+ if (Array.isArray(obj['ops'])) {
221
+ const parsed: SurgicalOp[] = []
222
+ for (const entry of obj['ops'] as unknown[]) {
223
+ if (!entry || typeof entry !== 'object') continue
224
+ const op = parseSurgicalOp(entry as Record<string, unknown>)
225
+ if (op) parsed.push(op)
226
+ }
227
+ if (parsed.length === 0) return null
228
+ return { ops: parsed }
229
+ }
230
+ return parseSurgicalOp(obj)
231
+ }
232
+
233
+ function planOp(editor: Editor, op: SurgicalOp): TransactionModifier | null {
234
+ switch (op.op) {
235
+ case 'replace_block': return planReplaceBlock(editor, op.blockIndex, op.content)
236
+ case 'insert_block_before': return planInsertBlockBefore(editor, op.blockIndex, op.content)
237
+ case 'delete_block': return planDeleteBlock(editor, op.blockIndex)
238
+ case 'update_block_mark': return planUpdateBlockMark(editor, op.blockIndex, op.mark, op.range, op.apply, op.attrs)
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Translate a surgical meta into a single TransactionModifier the diff
244
+ * extension can wrap with a snapshot. For batches, modifiers are
245
+ * computed against the original (pre-transaction) doc and then applied
246
+ * in DESC `blockIndex` order — each subsequent modifier touches earlier
247
+ * positions, so the prior modifiers' edits (at higher positions) don't
248
+ * shift the absolute positions the later modifiers were planned with.
249
+ *
250
+ * Returns null when the batch has no plannable ops (all out-of-range /
251
+ * unparseable). Drops individual non-plannable ops from a batch but
252
+ * still runs whatever did plan, so a single bad op doesn't kill the
253
+ * whole batch.
254
+ */
255
+ function planSurgicalModifier(editor: Editor, surgical: SurgicalMeta): TransactionModifier | null {
256
+ if ('ops' in surgical) {
257
+ const sorted = [...surgical.ops].sort((a, b) => b.blockIndex - a.blockIndex)
258
+ const modifiers: TransactionModifier[] = []
259
+ for (const op of sorted) {
260
+ const mod = planOp(editor, op)
261
+ if (mod) modifiers.push(mod)
262
+ }
263
+ if (modifiers.length === 0) return null
264
+ return (tr) => { for (const mod of modifiers) mod(tr) }
265
+ }
266
+ return planOp(editor, surgical)
146
267
  }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Surgical block-op planners for AI-driven precise edits.
3
+ *
4
+ * Each planner takes the editor + a logical block index + a payload and
5
+ * returns a `TransactionModifier` — a function the caller (typically
6
+ * `useAiInlineDiff`) feeds into
7
+ * `editor.commands.applySurgicalAiInlineDiff(id, modifier)`. The diff
8
+ * extension wraps the modifier in a snapshot-then-apply step so the
9
+ * inline-diff overlay renders against the precise changed range.
10
+ *
11
+ * "Block index" refers to a 0-based position across the doc's top-level
12
+ * children — what the AI agent sees as a numbered structural summary.
13
+ * Planners translate that to absolute ProseMirror positions internally.
14
+ *
15
+ * Planners return `null` when the request can't be satisfied (out-of-
16
+ * range index, unparseable HTML, unknown mark). Callers should treat
17
+ * `null` as "abort the surgical op" and surface a clear error to the
18
+ * agent so it can retry with a different plan.
19
+ */
20
+
21
+ import type { Editor } from '@tiptap/core'
22
+ import type { Transaction } from '@tiptap/pm/state'
23
+ import type { Mark, MarkType, Node as ProseMirrorNode } from '@tiptap/pm/model'
24
+ import { DOMParser as PMDOMParser } from '@tiptap/pm/model'
25
+
26
+ export type TransactionModifier = (tr: Transaction) => void
27
+
28
+ /** Resolve the start position of the top-level child at `blockIndex`. */
29
+ function blockStartPos(doc: ProseMirrorNode, blockIndex: number): number | null {
30
+ if (!Number.isInteger(blockIndex) || blockIndex < 0 || blockIndex >= doc.childCount) return null
31
+ let pos = 0
32
+ for (let i = 0; i < blockIndex; i++) pos += doc.child(i).nodeSize
33
+ return pos
34
+ }
35
+
36
+ /**
37
+ * Parse an HTML fragment into a doc-replaceable Slice. Uses the
38
+ * editor's own schema so block types unknown to the schema fail loudly
39
+ * rather than silently degrading.
40
+ *
41
+ * Returns `null` when DOM isn't available (SSR — shouldn't happen here,
42
+ * but keeps the planner safe).
43
+ */
44
+ function parseHtmlToSlice(editor: Editor, html: string): ReturnType<typeof PMDOMParser.prototype.parseSlice> | null {
45
+ if (typeof document === 'undefined') return null
46
+ const container = document.createElement('div')
47
+ container.innerHTML = html
48
+ return PMDOMParser.fromSchema(editor.schema).parseSlice(container)
49
+ }
50
+
51
+ /**
52
+ * Replace the top-level block at `blockIndex` with the parsed content.
53
+ * Caller-supplied `content` is HTML — multiple top-level nodes are
54
+ * allowed and will all land where the original block was.
55
+ */
56
+ export function planReplaceBlock(
57
+ editor: Editor,
58
+ blockIndex: number,
59
+ content: string,
60
+ ): TransactionModifier | null {
61
+ const doc = editor.state.doc
62
+ const start = blockStartPos(doc, blockIndex)
63
+ if (start === null) return null
64
+ const slice = parseHtmlToSlice(editor, content)
65
+ if (!slice) return null
66
+ const end = start + doc.child(blockIndex).nodeSize
67
+ return (tr) => { tr.replace(start, end, slice) }
68
+ }
69
+
70
+ /**
71
+ * Insert one or more top-level nodes (parsed from `content` HTML)
72
+ * before the block at `blockIndex`. `blockIndex === doc.childCount`
73
+ * appends at the end.
74
+ */
75
+ export function planInsertBlockBefore(
76
+ editor: Editor,
77
+ blockIndex: number,
78
+ content: string,
79
+ ): TransactionModifier | null {
80
+ const doc = editor.state.doc
81
+ if (!Number.isInteger(blockIndex) || blockIndex < 0 || blockIndex > doc.childCount) return null
82
+ const slice = parseHtmlToSlice(editor, content)
83
+ if (!slice) return null
84
+ let pos = 0
85
+ for (let i = 0; i < blockIndex; i++) pos += doc.child(i).nodeSize
86
+ return (tr) => { tr.replace(pos, pos, slice) }
87
+ }
88
+
89
+ /**
90
+ * Delete the top-level block at `blockIndex`. Doc must retain at least
91
+ * one child after the delete (most schemas require this) — refuses to
92
+ * delete the last remaining block.
93
+ */
94
+ export function planDeleteBlock(
95
+ editor: Editor,
96
+ blockIndex: number,
97
+ ): TransactionModifier | null {
98
+ const doc = editor.state.doc
99
+ const start = blockStartPos(doc, blockIndex)
100
+ if (start === null) return null
101
+ if (doc.childCount <= 1) return null
102
+ const end = start + doc.child(blockIndex).nodeSize
103
+ return (tr) => { tr.delete(start, end) }
104
+ }
105
+
106
+ export interface BlockMarkRange {
107
+ /** 0-based text offset from the start of the block's content. */
108
+ from: number
109
+ /** Exclusive end offset. */
110
+ to: number
111
+ }
112
+
113
+ /**
114
+ * Apply or remove an inline mark on a range *within* the block at
115
+ * `blockIndex`. `range.from` / `range.to` are text offsets relative to
116
+ * the start of the block's content (so `0` is the first character of
117
+ * the block, not the start of the doc).
118
+ *
119
+ * `apply = true` sets the mark (with optional `attrs`); `apply = false`
120
+ * removes it. Unknown marks (not in the editor's schema) return `null`
121
+ * so the caller can surface a clean error to the agent.
122
+ */
123
+ export function planUpdateBlockMark(
124
+ editor: Editor,
125
+ blockIndex: number,
126
+ mark: string,
127
+ range: BlockMarkRange,
128
+ apply: boolean,
129
+ attrs?: Record<string, unknown>,
130
+ ): TransactionModifier | null {
131
+ const doc = editor.state.doc
132
+ const start = blockStartPos(doc, blockIndex)
133
+ if (start === null) return null
134
+ const markType: MarkType | undefined = editor.schema.marks[mark]
135
+ if (!markType) return null
136
+
137
+ const block = doc.child(blockIndex)
138
+ const blockInner = start + 1 // step inside the block's opening token
139
+ const contentMax = block.content.size
140
+
141
+ if (!Number.isInteger(range.from) || !Number.isInteger(range.to)) return null
142
+ const clampedFrom = Math.max(0, Math.min(range.from, contentMax))
143
+ const clampedTo = Math.max(clampedFrom, Math.min(range.to, contentMax))
144
+ if (clampedTo === clampedFrom) return null
145
+
146
+ const from = blockInner + clampedFrom
147
+ const to = blockInner + clampedTo
148
+
149
+ if (apply) {
150
+ const m: Mark = markType.create(attrs ?? null)
151
+ return (tr) => { tr.addMark(from, to, m) }
152
+ }
153
+ return (tr) => { tr.removeMark(from, to, markType) }
154
+ }
155
+
156
+ /**
157
+ * Summarize a doc's top-level structure as a numbered list the AI can
158
+ * cite by index when proposing surgical ops. Each entry includes the
159
+ * block index, node type, and a truncated text preview — enough for the
160
+ * model to identify which block it wants to modify without sending the
161
+ * whole HTML/markdown back through token-priced channels.
162
+ *
163
+ * Returns one line per top-level child:
164
+ * `[0] heading: Welcome to the docs`
165
+ * `[1] paragraph: Lorem ipsum dolor sit amet…`
166
+ * `[2] bulletList: 3 items`
167
+ */
168
+ export function summarizeBlockStructure(doc: ProseMirrorNode, maxChars = 80): string {
169
+ const lines: string[] = []
170
+ for (let i = 0; i < doc.childCount; i++) {
171
+ const node = doc.child(i)
172
+ const text = node.textContent.trim().replace(/\s+/g, ' ')
173
+ const preview = text.length === 0
174
+ ? describeStructuralNode(node)
175
+ : text.length > maxChars ? `${text.slice(0, maxChars)}…` : text
176
+ lines.push(`[${i}] ${node.type.name}: ${preview}`)
177
+ }
178
+ return lines.join('\n')
179
+ }
180
+
181
+ function describeStructuralNode(node: ProseMirrorNode): string {
182
+ const kids = node.childCount
183
+ if (kids === 0) return '(empty)'
184
+ if (kids === 1) return `1 ${node.firstChild?.type.name ?? 'child'}`
185
+ return `${kids} children`
186
+ }