feat(editor): embed studio with data files and agent-aware editing
Browse filesEditor
- New Embed Studio panel for AI-assisted chart creation: upload and
manage data files (3MB limit), browse them in a dedicated viewer,
and iterate on the generated HTML via a chat wired to a dedicated
embed agent (embed-chat + embed-system-prompt + embed-tools +
tiptap-catalog) that can create, rename and edit embeds.
- Tiptap extensions for agent-driven editing:
- agent-focus: Yjs-awareness ranges so every peer sees where
another user's AI is working ("<Name> agent" label).
- agent-highlight: local PM decoration to mark the paragraph the
agent is currently rewriting.
- agent-rewrite: typewriter-animated range rewrite command used
by the rephrase flow.
- Rephrase flow now goes through agent-rewrite (typewriter) instead
of a plain replace; bold demonstration moved to the floating bubble
toolbar above a selection.
- SlashMenu reorganised with grouping and dev-only items dropped.
- New components: DataFileViewer, FilesSidebar, UploadZone.
- Refreshed TopBar, ChatPanel, SettingsDrawer, Editor.
- Hooks: useEmbedChat + useEmbedData (data file store) + refreshed
useAgentChat.
- data-files helper + ai-tool-parts update.
Made-with: Cursor
Files changed (27)
- backend/src/agent/embed-chat.ts+13
- backend/src/agent/embed-system-prompt.ts+55-6
- backend/src/agent/embed-tools.ts+36
- backend/src/agent/system-prompt.ts+99-7
- backend/src/agent/tiptap-catalog.tsAdded+266
- backend/src/agent/tools.ts+17-2
- frontend/src/components/ChatPanel.tsx+1-43
- frontend/src/components/DataFileViewer.tsxAdded+157
- frontend/src/components/EmbedStudio.tsx+87-7
- frontend/src/components/FilesSidebar.tsxAdded+132
- frontend/src/components/TopBar.tsx+99-1
- frontend/src/components/UploadZone.tsxAdded+65
- frontend/src/editor/Editor.tsx+19-1
- frontend/src/editor/SlashMenu.tsx+150-33
- frontend/src/editor/agent-executor.tsAdded+218
- frontend/src/editor/embeds/embed-data-store.tsAdded+107
- frontend/src/editor/extensions/agent-focus.tsAdded+315
- frontend/src/editor/extensions/agent-highlight.tsAdded+165
- frontend/src/editor/extensions/agent-rewrite.tsAdded+267
- frontend/src/editor/frontmatter/SettingsDrawer.tsx-9
- frontend/src/hooks/useAgentChat.ts+33-28
- frontend/src/hooks/useEmbedChat.ts+157-9
- frontend/src/hooks/useEmbedData.tsAdded+109
- frontend/src/styles/components/_embed-studio.css+388
- frontend/src/styles/editor/_block-tools.css+22-3
- frontend/src/utils/ai-tool-parts.ts+5-1
- frontend/src/utils/data-files.tsAdded+145
1 unmodified line2345673 unmodified lines111213141516171819201 unmodified lineEMBED_SYSTEM_PROMPT,BANNER_SYSTEM_PROMPT,buildEmbedContext,} from "./embed-system-prompt.js";import { embedTools } from "./embed-tools.js";import { streamChatResponse } from "./stream-handler.js";3 unmodified linesconst { context } = req.body;const contextBlock = buildEmbedContext(context?.embedHtml);const isBanner = Boolean(context?.isBanner);const parts = [EMBED_SYSTEM_PROMPT];if (isBanner) parts.push(BANNER_SYSTEM_PROMPT);if (contextBlock) parts.push(`## Current chart\n\n${contextBlock}`);const systemPrompt = parts.join("\n\n");return streamChatResponse(req, res, {1 unmodified line23456783 unmodified lines121314151617181920212223242526272829303132331 unmodified lineEMBED_SYSTEM_PROMPT,BANNER_SYSTEM_PROMPT,buildEmbedContext,buildDataFilesContext,} from "./embed-system-prompt.js";import { embedTools } from "./embed-tools.js";import { streamChatResponse } from "./stream-handler.js";3 unmodified linesconst { context } = req.body;const contextBlock = buildEmbedContext(context?.embedHtml);const isBanner = Boolean(context?.isBanner);const isScratch = Boolean(context?.isScratch);const dataFilesBlock = buildDataFilesContext(context?.dataFiles);const parts = [EMBED_SYSTEM_PROMPT];if (isBanner) parts.push(BANNER_SYSTEM_PROMPT);if (isScratch) {parts.push("## New chart\n\nThis chart is BRAND NEW - it has an auto-generated " +"placeholder filename. Your VERY FIRST `createEmbed` call MUST include " +"a descriptive `filename` slug (kebab-case, no extension, 2-4 words) " +"that reflects what the chart represents. The client will rename the " +"underlying file and keep the document in sync.",);}if (contextBlock) parts.push(`## Current chart\n\n${contextBlock}`);if (dataFilesBlock) parts.push(`## Attached data\n\n${dataFilesBlock}`);const systemPrompt = parts.join("\n\n");return streamChatResponse(req, res, {
10 unmodified lines1112131415161718192085 unmodified lines10610710810911011111211311411511611711811912012112212312412512612712812913013113213310 unmodified lines## Tools- **createEmbed**: Create or fully replace the chart HTML. Use for new charts or extensive rewrites.- **patchEmbed**: Surgically edit a specific part of the chart. Preferred for small changes.The search string must be an exact verbatim copy from the current HTML.Call readEmbed first if you're unsure of the exact content.- **readEmbed**: Read the full current HTML. Call before patching.## Chart conventions85 unmodified lines- Select closest previous sibling with root class, fallback to last unmounted### Data- For inline data, embed it directly in the script- For CSV loading, implement \`fetchFirstAvailable(['/data/file.csv', './assets/data/file.csv'])\`- Handle errors gracefully with a red \`<pre>\` message## Guidelines1. **Act immediately.** When the user asks for a chart, create it right away with createEmbed.2. **Use patchEmbed for edits.** Read the current chart first, then apply surgical patches.3. **Follow conventions strictly.** Every chart must have: root div, scoped style, IIFE script, ColorPalettes, mount guard, responsive layout.4. **Be creative with design.** Make charts visually appealing with clean typography, proper spacing, and smooth transitions.5. **Keep it concise.** Don't explain what you're doing unless asked.## ContextThe current chart HTML (if any) is provided between <embed> tags.Use this to understand the existing chart structure before making edits.`;export function buildEmbedContext(embedHtml?: string): string {if (!embedHtml) return "";return `<embed>\n${embedHtml}\n</embed>`;}/*** Extra instructions layered on top of the base system prompt when the* chart being edited is the article banner (top-of-article hero).10 unmodified lines11121314151617181920212223242526272829303132333485 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118210 unmodified lines## Tools- **createEmbed**: Create or fully replace the chart HTML. Use for new charts or extensive rewrites.On the FIRST call for a new chart, you MUST pass a descriptive \`filename\`slug (kebab-case, no extension, e.g. "attention-heatmap", "model-accuracy","sales-by-region") that reflects what the chart represents. The clientwill rename the underlying file and keep the doc in sync. Omit\`filename\` on subsequent calls that only refresh the same chart.- **patchEmbed**: Surgically edit a specific part of the chart. Preferred for small changes.The search string must be an exact verbatim copy from the current HTML.Call readEmbed first if you're unsure of the exact content.- **readEmbed**: Read the full current HTML. Call before patching.- **listDataFiles**: List user-attached data files (CSV, TSV, JSON, NDJSON, TXT).Call this as soon as the user references "the data", "my dataset", a filename,or otherwise implies real content should drive the chart.- **readDataFile**: Read the raw content of a single attached data file.Use to inspect structure, sample values, and pull the data you need. Becausethe chart iframe is sandboxed and cannot fetch external files, you must**inline** the data you use inside the chart script (ideally as a parsedJSON array). For very large files, aggregate / downsample the data beforeinlining it rather than embedding the raw content verbatim.## Chart conventions85 unmodified lines- Select closest previous sibling with root class, fallback to last unmounted### Data- Prefer user-attached data files: call \`listDataFiles\` first, then\`readDataFile\` on the one that matches the user's intent, and **inline**the parsed data directly in the script (the iframe is sandboxed and cannotfetch external files).- For demo/synthetic data, embed it inline as a JS array/object literal.- Handle parse/render errors gracefully with a red \`<pre>\` message.## Guidelines1. **Act immediately.** When the user asks for a chart, create it right away with createEmbed.2. **Use patchEmbed for edits.** Read the current chart first, then apply surgical patches.3. **Follow conventions strictly.** Every chart must have: root div, scoped style, IIFE script, ColorPalettes, mount guard, responsive layout.4. **Use attached data when relevant.** If the user mentions their data, afilename, or a dataset, inspect the <data-files> manifest, callreadDataFile on the best match, and inline a parsed subset into the chart.Never fabricate column names - only use what the file actually contains.5. **Be creative with design.** Make charts visually appealing with clean typography, proper spacing, and smooth transitions.6. **Keep it concise.** Don't explain what you're doing unless asked.## ContextThe current chart HTML (if any) is provided between <embed> tags.Use this to understand the existing chart structure before making edits.When data files are attached, a manifest of each file (name, type, size,shape) is provided between <data-files> tags. Treat this as the source oftruth: never invent file names or columns. To inspect raw values, callreadDataFile.`;export interface DataFileMeta {name: string;ext: string;size: number;rowCount?: number;columns?: string[];}export function buildEmbedContext(embedHtml?: string): string {if (!embedHtml) return "";return `<embed>\n${embedHtml}\n</embed>`;}function formatDataFileLine(file: DataFileMeta): string {const sizeKb = (file.size / 1024).toFixed(1);const rows = file.rowCount !== undefined ? ` rows=${file.rowCount}` : "";const cols = file.columns && file.columns.length > 0? ` columns=[${file.columns.slice(0, 20).join(", ")}${file.columns.length > 20 ? ", ..." : ""}]`: "";return `- ${file.name} (${file.ext}, ${sizeKb} KB)${rows}${cols}`;}export function buildDataFilesContext(files?: DataFileMeta[]): string {if (!files || files.length === 0) return "";const lines = files.map(formatDataFileLine).join("\n");return `<data-files>\n${lines}\n</data-files>`;}/*** Extra instructions layered on top of the base system prompt when the* chart being edited is the article banner (top-of-article hero).
27 unmodified lines28293031323323 unmodified lines5758596027 unmodified lines.string().optional().describe("Data source attribution"),}),}),23 unmodified lines"to verify the exact content, or to understand the current structure before editing.",inputSchema: z.object({}),}),};27 unmodified lines28293031323334353637383940414243444523 unmodified lines6970717273747576777879808182838485868788899091929394959627 unmodified lines.string().optional().describe("Data source attribution"),filename: z.string().optional().describe("Descriptive file name slug for this chart, WITHOUT extension " +"(e.g. 'attention-heatmap', 'model-accuracy', 'sales-by-region'). " +"Use kebab-case, ASCII only, concise (2-4 words, <40 chars). " +"REQUIRED on the first createEmbed call for a new chart - the " +"client will slugify it, ensure uniqueness, and rename the file " +"automatically. Omit on subsequent calls that only update the " +"existing chart (the current name will be kept).",),}),}),23 unmodified lines"to verify the exact content, or to understand the current structure before editing.",inputSchema: z.object({}),}),listDataFiles: tool({description:"List all data files (CSV, TSV, JSON, NDJSON, TXT) the user has " +"attached to this document. Returns one line per file with name, " +"extension, size, row count, and column names when available. " +"Call this when the user mentions data, a dataset, or wants to " +"visualize content from a specific file.",inputSchema: z.object({}),}),readDataFile: tool({description:"Read the full raw content of a data file previously listed by " +"listDataFiles. Use this to inspect the exact structure, sample " +"values, or to embed small datasets directly into the chart. Large " +"files may be truncated - prefer loading via fetch from " +"/data/<name> for charts that rely on the full dataset.",inputSchema: z.object({name: z.string().describe("Exact file name as returned by listDataFiles (e.g. 'sales.csv')"),}),}),};
12345678910111213141516171819202122232425262716 unmodified lines444546474849export const SYSTEM_PROMPT = `You are a writing assistant embedded in a collaborative article editor.You help users write, edit, and improve their articles.## Tools### Document editing- **applyDiff**: Your PRIMARY editing tool. Surgically edit the document with context-aware diffs.Provide surrounding context (contextBefore / contextAfter) to locate the exact position, evenwhen the same text appears multiple times. Call it multiple times for multiple edits.- **replaceSelection**: Replace selected text. Use ONLY when the user has text selected.- **insertAtCursor**: Insert new text at cursor. Use for additions only.### Article metadata (frontmatter)- **updateFrontmatter**: Update article metadata fields (title, subtitle, template, DOI, etc.).Only include the fields you want to change. Use when the user asks to modify article settings.- **addAuthor**: Add an author with name, optional URL, and affiliation indices.Can also create a new affiliation in the same call.- **removeAuthor**: Remove an author by 0-based index.## Editing strategy - applyDiffYou MUST work with surgical, minimal diffs using applyDiff:1. **contextBefore**: Copy a few words that appear just before the text you want to change.This helps locate the right spot when the same phrase exists in multiple places.2. **contentToDelete**: The exact verbatim text to remove. Even a single extra space willcause the edit to fail. Keep it as short as possible while being unique.3. **contentToInsert**: The replacement text. Can be empty to simply delete.16 unmodified lines- To remove an author: use **removeAuthor** with the 0-based index from the current authors list.- The current frontmatter is provided in <frontmatter> tags when available.## Guidelines1. **Be concise.** When the user asks for an edit, use tools immediately instead of123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949516 unmodified lines112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141import { classifyBySelectionEffect, groupByCategory } from "./tiptap-catalog.js";/*** System prompt for the article writing assistant.** The "Available editor commands" and "Selection State Machine" sections* are generated dynamically from the Tiptap command catalog so that* adding a new command automatically updates the prompt.** The state-machine framing is borrowed from tiptap-apcore: telling the* LLM which commands REQUIRE / PRESERVE / DESTROY / have NO effect on the* selection eliminates most "selected text was lost, next command did* nothing" bugs.*/function buildCommandListSection(): string {const byCategory = groupByCategory();const lines: string[] = [];for (const [category, names] of Object.entries(byCategory)) {if (names.length === 0) continue;lines.push(`- **${category}**: ${names.join(", ")}`);}return lines.join("\n");}function buildSelectionStateMachineSection(): string {const groups = classifyBySelectionEffect();const fmt = (names: string[]) => (names.length > 0 ? names.join(", ") : "(none)");return `REQUIRE SELECTION (no effect without an active text range - call selectText first):${fmt(groups.require)}PRESERVE SELECTION (selection survives - safe to chain more format commands after):${fmt(groups.preserve)}DESTROY SELECTION (cursor collapses after - you MUST re-select before applying format commands):${fmt(groups.destroy)}NO SELECTION NEEDED (operates on the block at the cursor):${fmt(groups.none)}`;}export const SYSTEM_PROMPT = `You are a writing assistant embedded in a collaborative research article editor.You help users write, edit, and improve their articles.## Tools overview### Prose editing (primary)- **applyDiff**: Your PRIMARY editing tool. Surgically edit prose with context-aware diffs.Provide surrounding context (contextBefore / contextAfter) to locate the exact position, evenwhen the same text appears multiple times. Call it multiple times for multiple edits.- **replaceSelection**: Replace selected text. Use ONLY when the user has text selected.- **insertAtCursor**: Insert new text at cursor. Use for additions only.### Structured editor commands (format, lists, headings, links)${buildCommandListSection()}These commands translate directly to Tiptap \`editor.chain()\` calls on the client.Use them when the user asks to change formatting, block types, or create links - NOT forrewriting prose (use applyDiff for that).### Article metadata (frontmatter)- **updateFrontmatter**: Update article metadata fields (title, subtitle, template, DOI, etc.).- **addAuthor**: Add an author with name, optional URL, and affiliation indices.- **removeAuthor**: Remove an author by 0-based index.## Selection State Machine - THE CORE RULEEvery editor command interacts with an invisible "selection state". You MUST track it mentally.${buildSelectionStateMachineSection()}**Key rule**: After any selection-destroying command (insertAtCursor, applyDiff, replaceSelection),you MUST call \`selectText\` again before issuing a REQUIRE-SELECTION command like toggleBold.**Multi-occurrence rule**: When the user says "make all X bold", you MUST loop:call \`selectText(X, occurrence=1)\` then \`toggleBold\`, then again with \`occurrence=1\` (not 2 -after toggling the first one the indices shift). Stop when \`found\` is false.## Common task patterns1. Format existing text: \`selectText(phrase)\` then \`toggleBold\`.2. Replace AND format in one step: prefer \`applyDiff\` with markdown-like output, or use \`replaceSelection\`with inline markdown.3. Multi-format same text: \`selectText\` then \`toggleBold\` then \`toggleItalic\` (format commands preserve selection).4. Change block type: place cursor in target block (via selectText on any text in it) then \`toggleHeading({ level: 2 })\`.5. Add a link: \`selectText(anchor)\` then \`setLink({ href: 'https://...' })\`.6. Convert paragraph to list: \`selectText(first-line)\` then \`toggleBulletList\`.## Editing strategy - applyDiffYou MUST work with surgical, minimal diffs using applyDiff:1. **contextBefore**: Copy a few words that appear just before the text you want to change.2. **contentToDelete**: The exact verbatim text to remove. Even a single extra space willcause the edit to fail. Keep it as short as possible while being unique.3. **contentToInsert**: The replacement text. Can be empty to simply delete.16 unmodified lines- To remove an author: use **removeAuthor** with the 0-based index from the current authors list.- The current frontmatter is provided in <frontmatter> tags when available.## Stop condition - CRITICALOnce you have executed the commands needed to fulfil the user's request,you MUST end the turn with a short plain-text confirmation (one sentence)and STOP calling tools.- If the last tool returned success, emit text like "Done." and stop.- If the last tool failed (e.g. \`selectText: text not found\`), emit ashort explanation of what went wrong and stop - do NOT retry indefinitely.- NEVER call the same tool with the same arguments twice in a row.- Hard limit: at most 8 tool calls per user request. If you need more,stop and ask the user to split their request.The UI shows a "Thinking..." spinner while tool rounds are in flight, sostaying in a tool-call loop without emitting text looks broken to the user.## Anti-patterns - NEVER DO THESE- NEVER call a mark-level format command (toggleBold, setLink, etc.) without a preceding selectText.- NEVER assume \`selectText\` succeeded - check the \`found\` field in its result.- NEVER call \`toggleBold\` right after \`insertAtCursor\` or \`applyDiff\` - the selection is gone.- NEVER guess Tiptap positions - use \`selectText\` with text content instead.- NEVER end a turn with only tool calls - always conclude with a one-line text reply.## Guidelines1. **Be concise.** When the user asks for an edit, use tools immediately instead of
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266import { tool, type Tool } from "ai";import { z } from "zod";
/** * Catalog of Tiptap editor commands exposed to the AI agent. * * Each entry pairs: * - an AI SDK tool definition (description + zod input schema) * - safety metadata used to build the system prompt dynamically * (category, selectionEffect, destructive) * * The frontend's agent executor dispatches on `name` and calls * `editor.chain()[command](args).run()`, so the catalog is the single * source of truth for what the agent can do. * * Inspired by `tiptap-apcore`'s Registry + AnnotationCatalog pattern, * but intentionally pared down to the ~15 commands that make sense for * a research article editor. */
type Category = "query" | "selection" | "format" | "content";
/** * How a command interacts with the current text selection. * * - `require`: must have a non-collapsed selection (mark toggles) * - `preserve`: selection survives execution (most mark toggles, alignment) * - `destroy`: cursor collapses after execution (insertContent) * - `none`: operates on the block at cursor, no selection needed */type SelectionEffect = "require" | "preserve" | "destroy" | "none";
// `tool()` returns a strongly-typed Tool<InputSchema, Output>; storing them// in a homogeneous array requires the most permissive Tool generic.type AnyTool = Tool<any, any>;
export interface TiptapCommandEntry { name: string; category: Category; selectionEffect: SelectionEffect; destructive: boolean; tool: AnyTool;}
// ---------------------------------------------------------------------------// Command entries// ---------------------------------------------------------------------------
export const TIPTAP_COMMANDS: TiptapCommandEntry[] = [ // -- Selection --------------------------------------------------------- { name: "selectText", category: "selection", selectionEffect: "preserve", destructive: false, tool: tool({ description: "Find a text substring in the document and select it. Use this BEFORE applying " + "mark-level formatting commands (toggleBold, setLink, etc.). Returns { found, from, to } " + "so you can verify the match. When the same text appears multiple times, use `occurrence` " + "(1-based) or provide `contextBefore` / `contextAfter` to disambiguate.", inputSchema: z.object({ text: z.string().describe("The exact text to select (substring match)"), occurrence: z .number() .int() .min(1) .optional() .describe( "Which occurrence to select (1-based). Defaults to 1. Ignored if contextBefore/After are provided.", ), contextBefore: z .string() .optional() .describe("A few words appearing just before the target text, used to disambiguate."), contextAfter: z .string() .optional() .describe("A few words appearing just after the target text, used to disambiguate."), }), }), },
// -- Format: marks (require selection) -------------------------------- { name: "toggleBold", category: "format", selectionEffect: "require", destructive: false, tool: tool({ description: "Toggle bold on the current selection. MUST be called after selectText - has no effect without an active text range.", inputSchema: z.object({}), }), }, { name: "toggleItalic", category: "format", selectionEffect: "require", destructive: false, tool: tool({ description: "Toggle italic on the current selection. MUST be called after selectText - has no effect without an active text range.", inputSchema: z.object({}), }), }, { name: "toggleStrike", category: "format", selectionEffect: "require", destructive: false, tool: tool({ description: "Toggle strikethrough on the current selection. MUST be called after selectText.", inputSchema: z.object({}), }), }, { name: "toggleCode", category: "format", selectionEffect: "require", destructive: false, tool: tool({ description: "Toggle inline code formatting on the current selection. MUST be called after selectText.", inputSchema: z.object({}), }), }, { name: "setLink", category: "format", selectionEffect: "require", destructive: false, tool: tool({ description: "Turn the current selection into a hyperlink. MUST be called after selectText. " + "Only http(s)/mailto/tel/relative URLs are accepted.", inputSchema: z.object({ href: z.string().describe("Target URL (http/https/mailto/tel or relative)"), }), }), }, { name: "unsetLink", category: "format", selectionEffect: "require", destructive: false, tool: tool({ description: "Remove hyperlink formatting from the current selection.", inputSchema: z.object({}), }), },
// -- Format: node-level (no selection needed) ------------------------- { name: "toggleHeading", category: "format", selectionEffect: "none", destructive: false, tool: tool({ description: "Convert the block at the cursor to a heading (or back to a paragraph if already that level). " + "Operates on the containing block - no text selection needed.", inputSchema: z.object({ level: z.number().int().min(1).max(3).describe("Heading level (1, 2 or 3)"), }), }), }, { name: "setParagraph", category: "format", selectionEffect: "none", destructive: false, tool: tool({ description: "Convert the block at the cursor to a plain paragraph.", inputSchema: z.object({}), }), }, { name: "toggleBulletList", category: "format", selectionEffect: "none", destructive: false, tool: tool({ description: "Toggle the block at the cursor between a bullet list item and a paragraph.", inputSchema: z.object({}), }), }, { name: "toggleOrderedList", category: "format", selectionEffect: "none", destructive: false, tool: tool({ description: "Toggle the block at the cursor between an ordered (numbered) list item and a paragraph.", inputSchema: z.object({}), }), }, { name: "toggleBlockquote", category: "format", selectionEffect: "none", destructive: false, tool: tool({ description: "Toggle blockquote on the block at the cursor.", inputSchema: z.object({}), }), }, { name: "toggleCodeBlock", category: "format", selectionEffect: "none", destructive: false, tool: tool({ description: "Toggle code block on the block at the cursor. Use for multi-line code snippets.", inputSchema: z.object({ language: z .string() .optional() .describe("Language hint for syntax highlighting (e.g. 'python', 'typescript')"), }), }), },];
// ---------------------------------------------------------------------------// Helpers// ---------------------------------------------------------------------------
/** AI SDK tool definitions keyed by command name. Pass directly to streamText. */export function buildTiptapTools(): Record<string, AnyTool> { const out: Record<string, AnyTool> = {}; for (const entry of TIPTAP_COMMANDS) { out[entry.name] = entry.tool; } return out;}
/** Commands grouped by how they interact with the selection. */export function classifyBySelectionEffect(): Record<SelectionEffect, string[]> { const groups: Record<SelectionEffect, string[]> = { require: [], preserve: [], destroy: [], none: [], }; for (const entry of TIPTAP_COMMANDS) { groups[entry.selectionEffect].push(entry.name); } return groups;}
/** Commands grouped by category, used to build a concise command list in the prompt. */export function groupByCategory(): Record<Category, string[]> { const groups: Record<Category, string[]> = { query: [], selection: [], format: [], content: [], }; for (const entry of TIPTAP_COMMANDS) { groups[entry.category].push(entry.name); } return groups;}123453 unmodified lines9101112131415161716 unmodified lines3435363738394023 unmodified lines6465666768697045 unmodified lines116117118import { tool } from "ai";import { z } from "zod";/*** Tools exposed to the LLM. These return instructions that the frontend3 unmodified lines** All edits from a single agent turn are grouped into one Yjs undo step,* so the user can revert an entire agent action with a single Cmd+Z.*/export const editorTools = {replaceSelection: tool({description:"Replace the currently selected text in the editor with new content. " +16 unmodified linesapplyDiff: tool({description:"The PRIMARY tool for editing. Locates a piece of text in the document using " +"context and replaces it. Provide surrounding context to disambiguate when the " +"same text appears multiple times. For multiple edits, call this tool multiple " +"times in a single response. Each call should be a minimal, surgical edit.",23 unmodified lines),}),}),updateFrontmatter: tool({description:"Update article metadata (frontmatter). Use when the user asks to change the title, " +45 unmodified lines}),}),};1234563 unmodified lines10111213141516171819202122232416 unmodified lines4142434445464723 unmodified lines71727374757677787945 unmodified lines125126127128129130131132133import { tool } from "ai";import { z } from "zod";import { buildTiptapTools } from "./tiptap-catalog.js";/*** Tools exposed to the LLM. These return instructions that the frontend3 unmodified lines** All edits from a single agent turn are grouped into one Yjs undo step,* so the user can revert an entire agent action with a single Cmd+Z.** The editor commands come from a static catalog (`tiptap-catalog.ts`)* that also drives the system prompt's "Selection State Machine" section.* The domain-specific tools (applyDiff, replaceSelection, insertAtCursor,* frontmatter) are defined inline here since they don't map 1:1 to a* native Tiptap command.*/const customEditorTools = {replaceSelection: tool({description:"Replace the currently selected text in the editor with new content. " +16 unmodified linesapplyDiff: tool({description:"The PRIMARY tool for editing prose. Locates a piece of text in the document using " +"context and replaces it. Provide surrounding context to disambiguate when the " +"same text appears multiple times. For multiple edits, call this tool multiple " +"times in a single response. Each call should be a minimal, surgical edit.",23 unmodified lines),}),}),};const frontmatterTools = {updateFrontmatter: tool({description:"Update article metadata (frontmatter). Use when the user asks to change the title, " +45 unmodified lines}),}),};export const editorTools = {...buildTiptapTools(),...customEditorTools,...frontmatterTools,};
1 unmodified line2345678910111213141516171819209 unmodified lines30313233343536373839404142434445464748495051525354555627 unmodified lines84858687888990919293949592 unmodified lines1881891901911921931941951961971981992002012022032042052062072082092101 unmodified lineimport ReactMarkdown from "react-markdown";import remarkGfm from "remark-gfm";import { Tooltip } from "./Tooltip";import {Send,Square,Plus,X,Sparkles,AlignLeft,Expand,SpellCheck,Languages,Shrink,Loader,} from "lucide-react";import type { UIMessage } from "ai";import { isToolPart, normalizeToolPart } from "../utils/ai-tool-parts";9 unmodified linesisLoading: boolean;error: Error | undefined;input: string;hasSelection: boolean;models: ModelOption[];selectedModel: string;onModelChange: (modelId: string) => void;onSend: (content: string) => void;onQuickAction: (action: string) => void;onSetInput: (value: string) => void;onStop: () => void;onNewChat: () => void;onClose?: () => void;}const QUICK_ACTIONS = [{ id: "rewrite", label: "Rewrite", Icon: Sparkles },{ id: "expand", label: "Expand", Icon: Expand },{ id: "summarize", label: "Summarize", Icon: Shrink },{ id: "fix-grammar", label: "Fix grammar", Icon: SpellCheck },{ id: "translate", label: "Translate", Icon: Languages },{ id: "simplify", label: "Simplify", Icon: AlignLeft },];function TokenGauge({ tokens, ratio }: { tokens: number; ratio: number }) {const r = 8;const circ = 2 * Math.PI * r;27 unmodified linesisLoading,error,input,hasSelection,models,selectedModel,onModelChange,onSend,onQuickAction,onSetInput,onStop,onNewChat,92 unmodified lines)}</div>{/* Quick actions */}{hasSelection && (<div className="chat-panel__actions">{QUICK_ACTIONS.map((action) => (<buttonkey={action.id}className="chip chip--outlined chip--clickable"onClick={() => onQuickAction(action.id)}style={{ height: 24, fontSize: "0.65rem", gap: 3 }}><action.Icon size={12} />{action.label}</button>))}</div>)}{/* Input */}<div className="chat-panel__input"><div className="chat-panel__input-row">1 unmodified line23456789 unmodified lines1819202122232425262728293031323327 unmodified lines6162636465666768697092 unmodified lines1631641651661671681 unmodified lineimport ReactMarkdown from "react-markdown";import remarkGfm from "remark-gfm";import { Tooltip } from "./Tooltip";import { Send, Square, Plus, X, Sparkles, Loader } from "lucide-react";import type { UIMessage } from "ai";import { isToolPart, normalizeToolPart } from "../utils/ai-tool-parts";9 unmodified linesisLoading: boolean;error: Error | undefined;input: string;models: ModelOption[];selectedModel: string;onModelChange: (modelId: string) => void;onSend: (content: string) => void;onSetInput: (value: string) => void;onStop: () => void;onNewChat: () => void;onClose?: () => void;}function TokenGauge({ tokens, ratio }: { tokens: number; ratio: number }) {const r = 8;const circ = 2 * Math.PI * r;27 unmodified linesisLoading,error,input,models,selectedModel,onModelChange,onSend,onSetInput,onStop,onNewChat,92 unmodified lines)}</div>{/* Input */}<div className="chat-panel__input"><div className="chat-panel__input-row">
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157import { useMemo, useState } from "react";import { X, Table as TableIcon, FileText } from "lucide-react";import type { EmbedDataFile } from "../editor/embeds/embed-data-store";import { formatBytes } from "../utils/data-files";
interface DataFileViewerProps { file: EmbedDataFile; onClose: () => void;}
const MAX_PREVIEW_ROWS = 100;
function splitCsvLine(line: string, delim: string): string[] { const out: string[] = []; let cur = ""; let inQuotes = false; for (let i = 0; i < line.length; i++) { const c = line[i]; if (inQuotes) { if (c === '"') { if (line[i + 1] === '"') { cur += '"'; i++; } else { inQuotes = false; } } else { cur += c; } } else if (c === '"') { inQuotes = true; } else if (c === delim) { out.push(cur); cur = ""; } else { cur += c; } } out.push(cur); return out;}
function parseTable(content: string, delim: string, maxRows: number): { columns: string[]; rows: string[][]; total: number;} { const lines = content.split(/\r\n|\n|\r/).filter((l) => l.length > 0); if (lines.length === 0) return { columns: [], rows: [], total: 0 }; const columns = splitCsvLine(lines[0], delim); const rows = lines .slice(1, 1 + maxRows) .map((l) => splitCsvLine(l, delim)); return { columns, rows, total: Math.max(0, lines.length - 1) };}
function prettyJson(content: string): string { try { return JSON.stringify(JSON.parse(content), null, 2); } catch { return content; }}
export function DataFileViewer({ file, onClose }: DataFileViewerProps) { const { ext } = file.meta; const isTabular = ext === "csv" || ext === "tsv"; const [mode, setMode] = useState<"table" | "raw">(isTabular ? "table" : "raw");
const parsed = useMemo(() => { if (!isTabular) return null; return parseTable(file.content, ext === "tsv" ? "\t" : ",", MAX_PREVIEW_ROWS); }, [file.content, ext, isTabular]);
const raw = useMemo(() => { if (ext === "json") return prettyJson(file.content); return file.content; }, [file.content, ext]);
return ( <div className="es-data-viewer"> <div className="es-data-viewer__header"> <div className="es-data-viewer__title"> <strong>{file.meta.name}</strong> <span className="es-data-viewer__meta"> {ext.toUpperCase()} - {formatBytes(file.meta.size)} {file.meta.rowCount !== undefined ? ` - ${file.meta.rowCount} rows` : ""} </span> </div> <div className="es-data-viewer__actions"> {isTabular && ( <div className="es-data-viewer__tabs"> <button type="button" className={`es-preview__tab ${mode === "table" ? "es-preview__tab--active" : ""}`} onClick={() => setMode("table")} > <TableIcon size={12} /> Table </button> <button type="button" className={`es-preview__tab ${mode === "raw" ? "es-preview__tab--active" : ""}`} onClick={() => setMode("raw")} > <FileText size={12} /> Raw </button> </div> )} <button type="button" className="embed-btn" onClick={onClose} aria-label="Close file viewer" > <X size={14} /> </button> </div> </div>
<div className="es-data-viewer__body"> {isTabular && mode === "table" && parsed ? ( <div className="es-data-table-wrap"> <table className="es-data-table"> <thead> <tr> {parsed.columns.map((col, i) => ( <th key={i}>{col}</th> ))} </tr> </thead> <tbody> {parsed.rows.map((row, ri) => ( <tr key={ri}> {parsed.columns.map((_, ci) => ( <td key={ci}>{row[ci] ?? ""}</td> ))} </tr> ))} </tbody> </table> {parsed.total > parsed.rows.length && ( <div className="es-data-table__footer"> Showing first {parsed.rows.length} of {parsed.total} rows </div> )} </div> ) : ( <pre className="es-data-viewer__raw"> <code>{raw}</code> </pre> )} </div> </div> );}3 unmodified lines45678910111213141516171819202122232425262 unmodified lines29303132333411 unmodified lines464748495051525354555637 unmodified lines9495969798991001011021034 unmodified lines108109110111112113114110 unmodified lines22522622722822923054 unmodified lines28528628728828929029129229315 unmodified lines30931031131231331431518 unmodified lines3343353363373383393403 unmodified linesimport { X, Send, Square, Code, Eye, Plus, Loader } from "lucide-react";import type { UIMessage } from "ai";import type { EmbedStore } from "../editor/embeds/embed-store";import { buildDoc } from "../editor/embeds/build-doc";import { useEmbedChat } from "../hooks/useEmbedChat";import { useTheme } from "../hooks/useTheme";import { isToolPart, normalizeToolPart } from "../utils/ai-tool-parts";interface EmbedStudioProps {src: string;embedStore: EmbedStore | null;modelRef: React.RefObject<string>;userId: string;onClose: () => void;}const EMBED_TOOL_LABELS: Record<string, [string, string]> = {createEmbed: ["Creating chart...", "Created chart"],patchEmbed: ["Updating chart...", "Updated chart"],readEmbed: ["Reading chart...", "Read chart"],};function embedToolLabel(name: string, state: string): string {2 unmodified linesreturn state === "result" ? pair[1] : pair[0];}function MessageBubble({ message }: { message: UIMessage }) {const isUser = message.role === "user";return (11 unmodified linesif (isToolPart(part)) {const tool = normalizeToolPart(part);if (!tool) return null;return (<div key={i} className="es-message__tool"><span className="es-message__tool-name">{embedToolLabel(tool.toolName, tool.state)}</span></div>);}37 unmodified lines);}export function EmbedStudio({ src, embedStore, modelRef, userId, onClose }: EmbedStudioProps) {const { isDark, primaryColor } = useTheme();const [html, setHtml] = useState("");const [viewMode, setViewMode] = useState<"preview" | "code">("preview");const messagesEndRef = useRef<HTMLDivElement>(null);const textareaRef = useRef<HTMLTextAreaElement>(null);4 unmodified linesconst activeRef = useRef<"a" | "b">("a");activeRef.current = activeFrame;const chat = useEmbedChat({ embedStore, src, modelRef, userId });// Sync from embed storeuseEffect(() => {110 unmodified lines{/* Body: split panel */}<div className="es-body">{/* Left: Chat */}<div className="es-chat"><div className="es-chat__messages">54 unmodified lines</div></div>{/* Right: Preview */}<div className="es-preview"><div className="es-preview__toolbar"><buttonclassName={`es-preview__tab ${viewMode === "preview" ? "es-preview__tab--active" : ""}`}onClick={() => setViewMode("preview")}15 unmodified lines</div>{/* Both panels always mounted - toggle with hidden class to preserve iframe state */}<div className={`es-preview__frame-container ${viewMode !== "preview" ? "es-hidden" : ""}`}>{html ? (<><iframe18 unmodified lines</div>)}</div><div className={`es-preview__code ${viewMode !== "code" ? "es-hidden" : ""}`}><pre className="es-preview__pre"><code>{html || "// No chart HTML yet"}</code></pre>3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839402 unmodified lines43444546474849505152535455565758596061626364656667686911 unmodified lines8182838485868788899091929394959697989910037 unmodified lines1381391401411421431441451461471481491501511521531541551564 unmodified lines161162163164165166167168169170110 unmodified lines28128228328428528628728828929029129229329429529629754 unmodified lines35235335435535635735835936036136236336436536636736836915 unmodified lines38538638738838939039139239318 unmodified lines4124134144154164174184194203 unmodified linesimport { X, Send, Square, Code, Eye, Plus, Loader } from "lucide-react";import type { UIMessage } from "ai";import type { EmbedStore } from "../editor/embeds/embed-store";import type { EmbedDataStore } from "../editor/embeds/embed-data-store";import { buildDoc } from "../editor/embeds/build-doc";import { useEmbedChat } from "../hooks/useEmbedChat";import { useEmbedData } from "../hooks/useEmbedData";import { useTheme } from "../hooks/useTheme";import { isToolPart, normalizeToolPart } from "../utils/ai-tool-parts";import { FilesSidebar } from "./FilesSidebar";import { DataFileViewer } from "./DataFileViewer";interface EmbedStudioProps {src: string;embedStore: EmbedStore | null;dataStore?: EmbedDataStore | null;modelRef: React.RefObject<string>;userId: string;onClose: () => void;/*** Invoked when the agent chooses a descriptive filename for a brand* new chart. Parent should update the htmlEmbed node in the doc and* lift the new src into its own state so subsequent actions (close,* reopen, etc.) reference the renamed file.*/onRename?: (oldSrc: string, newSrc: string) => void;}const EMBED_TOOL_LABELS: Record<string, [string, string]> = {createEmbed: ["Creating chart...", "Created chart"],patchEmbed: ["Updating chart...", "Updated chart"],readEmbed: ["Reading chart...", "Read chart"],listDataFiles: ["Listing data files...", "Listed data files"],readDataFile: ["Reading data file...", "Read data file"],};function embedToolLabel(name: string, state: string): string {2 unmodified linesreturn state === "result" ? pair[1] : pair[0];}function toolSubtitle(name: string,input: unknown,): string | null {if (!input || typeof input !== "object") return null;const args = input as Record<string, unknown>;switch (name) {case "createEmbed":return typeof args.title === "string" ? String(args.title) : null;case "readDataFile":return typeof args.name === "string" ? String(args.name) : null;case "patchEmbed": {const search = typeof args.search === "string" ? args.search : "";const firstLine = search.split("\n")[0]?.trim() ?? "";return firstLine ? firstLine.slice(0, 60) : null;}default:return null;}}function MessageBubble({ message }: { message: UIMessage }) {const isUser = message.role === "user";return (11 unmodified linesif (isToolPart(part)) {const tool = normalizeToolPart(part);if (!tool) return null;const subtitle = toolSubtitle(tool.toolName, tool.input);const isDone = tool.state === "result";return (<divkey={i}className={`es-message__tool ${isDone ? "es-message__tool--done" : "es-message__tool--running"}`}>{!isDone && <Loader size={11} className="spin" />}<span className="es-message__tool-name">{embedToolLabel(tool.toolName, tool.state)}</span>{subtitle && (<span className="es-message__tool-subtitle">{subtitle}</span>)}</div>);}37 unmodified lines);}export function EmbedStudio({src,embedStore,dataStore = null,modelRef,userId,onClose,onRename,}: EmbedStudioProps) {const { isDark, primaryColor } = useTheme();const [html, setHtml] = useState("");const [viewMode, setViewMode] = useState<"preview" | "code">("preview");const [selectedDataFile, setSelectedDataFile] = useState<string | null>(null);const messagesEndRef = useRef<HTMLDivElement>(null);const textareaRef = useRef<HTMLTextAreaElement>(null);4 unmodified linesconst activeRef = useRef<"a" | "b">("a");activeRef.current = activeFrame;const data = useEmbedData({ dataStore, userId });const chat = useEmbedChat({ embedStore, dataStore, src, modelRef, userId, onRename });const selectedFile = selectedDataFile ? data.getFile(selectedDataFile) : undefined;// Sync from embed storeuseEffect(() => {110 unmodified lines{/* Body: split panel */}<div className="es-body">{/* Far-left: Files */}<FilesSidebarembedStore={embedStore}currentSrc={src}dataFiles={data.files}selectedDataFile={selectedDataFile}onSelectDataFile={setSelectedDataFile}onUploadFiles={data.uploadFiles}onRemoveDataFile={data.removeFile}/>{/* Left: Chat */}<div className="es-chat"><div className="es-chat__messages">54 unmodified lines</div></div>{/* Right: Preview (chart) or data file viewer */}<div className="es-preview">{selectedFile ? (<DataFileViewerfile={selectedFile}onClose={() => setSelectedDataFile(null)}/>) : null}<divclassName={`es-preview__toolbar ${selectedFile ? "es-hidden" : ""}`}><buttonclassName={`es-preview__tab ${viewMode === "preview" ? "es-preview__tab--active" : ""}`}onClick={() => setViewMode("preview")}15 unmodified lines</div>{/* Both panels always mounted - toggle with hidden class to preserve iframe state */}<divclassName={`es-preview__frame-container ${viewMode !== "preview" || selectedFile ? "es-hidden" : ""}`}>{html ? (<><iframe18 unmodified lines</div>)}</div><divclassName={`es-preview__code ${viewMode !== "code" || selectedFile ? "es-hidden" : ""}`}><pre className="es-preview__pre"><code>{html || "// No chart HTML yet"}</code></pre>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132import { useEffect, useState } from "react";import { FileText, Trash2, BarChart3, Database, AlertCircle } from "lucide-react";import type { EmbedStore } from "../editor/embeds/embed-store";import type { EmbedDataFileMeta } from "../editor/embeds/embed-data-store";import { UploadZone } from "./UploadZone";import { formatBytes } from "../utils/data-files";import type { UploadResult } from "../hooks/useEmbedData";
interface FilesSidebarProps { embedStore: EmbedStore | null; currentSrc: string; dataFiles: EmbedDataFileMeta[]; selectedDataFile: string | null; onSelectDataFile: (name: string | null) => void; onUploadFiles: (files: FileList | File[]) => Promise<UploadResult[]>; onRemoveDataFile: (name: string) => void;}
export function FilesSidebar({ embedStore, currentSrc, dataFiles, selectedDataFile, onSelectDataFile, onUploadFiles, onRemoveDataFile,}: FilesSidebarProps) { const [charts, setCharts] = useState<string[]>(() => embedStore ? embedStore.keys() : [], ); const [uploadError, setUploadError] = useState<string | null>(null);
useEffect(() => { if (!embedStore) return; setCharts(embedStore.keys()); return embedStore.observe(() => setCharts(embedStore.keys())); }, [embedStore]);
const handleUpload = async (files: FileList | File[]) => { setUploadError(null); const results = await onUploadFiles(files); const firstError = results.find((r) => !r.ok); if (firstError?.error) setUploadError(firstError.error); const firstOk = results.find((r) => r.ok && r.name); if (firstOk?.name) onSelectDataFile(firstOk.name); };
return ( <div className="es-files"> <section className="es-files__section"> <header className="es-files__section-title"> <BarChart3 size={13} /> <span>Charts</span> <span className="es-files__count">{charts.length}</span> </header> <ul className="es-files__list"> {charts.length === 0 && ( <li className="es-files__empty">No charts yet</li> )} {charts.map((name) => ( <li key={name} className={`es-files__item ${name === currentSrc ? "es-files__item--current" : ""}`} title={name === currentSrc ? "Current chart" : name} > <FileText size={12} /> <span className="es-files__name">{name}</span> {name === currentSrc && ( <span className="es-files__badge">editing</span> )} </li> ))} </ul> </section>
<section className="es-files__section"> <header className="es-files__section-title"> <Database size={13} /> <span>Data</span> <span className="es-files__count">{dataFiles.length}</span> </header>
<ul className="es-files__list"> {dataFiles.length === 0 && ( <li className="es-files__empty">No data uploaded yet</li> )} {dataFiles.map((file) => { const isSelected = file.name === selectedDataFile; return ( <li key={file.name} className={`es-files__item es-files__item--data ${isSelected ? "es-files__item--current" : ""}`} > <button type="button" className="es-files__item-main" onClick={() => onSelectDataFile(isSelected ? null : file.name)} title={file.name} > <FileText size={12} /> <span className="es-files__name">{file.name}</span> <span className="es-files__size">{formatBytes(file.size)}</span> </button> <button type="button" className="es-files__item-remove" onClick={(e) => { e.stopPropagation(); if (isSelected) onSelectDataFile(null); onRemoveDataFile(file.name); }} aria-label={`Remove ${file.name}`} title="Remove file" > <Trash2 size={12} /> </button> </li> ); })} </ul>
<UploadZone onFiles={handleUpload} compact={dataFiles.length > 0} /> {uploadError && ( <div className="es-files__error"> <AlertCircle size={12} /> <span>{uploadError}</span> </div> )} </section> </div> );}12345641 unmodified lines48495051525349 unmodified lines103104105106107108import type { Editor as TiptapEditor } from "@tiptap/core";import type { HocuspocusProvider } from "@hocuspocus/provider";import { Undo2, Redo2, Settings, Upload, Eye, Sun, Moon, Menu, LogIn } from "lucide-react";import { Tooltip } from "./Tooltip";import { SyncIndicator } from "./SyncIndicator";import type { CollabUser } from "../utils/user";41 unmodified lines? `${publishingUserName} is publishing...`: "Publish in progress...": "Publish article";return (<div className="top-bar"><button49 unmodified lines{theme === "dark" ? <Sun size={18} /> : <Moon size={18} />}</button></Tooltip><span className="divider-v" /><Tooltip title={publishTooltip}><button123456789101112131415161718192041 unmodified lines626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310449 unmodified lines154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206import { useEffect, useRef, useState } from "react";import type { Editor as TiptapEditor } from "@tiptap/core";import type { HocuspocusProvider } from "@hocuspocus/provider";import {Undo2,Redo2,Settings,Upload,Eye,Sun,Moon,Menu,LogIn,MoreHorizontal,FileText,Trash2,} from "lucide-react";import { Tooltip } from "./Tooltip";import { SyncIndicator } from "./SyncIndicator";import type { CollabUser } from "../utils/user";41 unmodified lines? `${publishingUserName} is publishing...`: "Publish in progress...": "Publish article";// Dev / utility menu state (Load demo, Reset article). Kept out of// the slash menu so it doesn't clutter the authoring surface.const [devMenuOpen, setDevMenuOpen] = useState(false);const devMenuRef = useRef<HTMLDivElement | null>(null);useEffect(() => {if (!devMenuOpen) return;const onDocClick = (e: MouseEvent) => {if (!devMenuRef.current) return;if (!devMenuRef.current.contains(e.target as Node)) setDevMenuOpen(false);};const onKey = (e: KeyboardEvent) => {if (e.key === "Escape") setDevMenuOpen(false);};document.addEventListener("mousedown", onDocClick);document.addEventListener("keydown", onKey);return () => {document.removeEventListener("mousedown", onDocClick);document.removeEventListener("keydown", onKey);};}, [devMenuOpen]);const handleLoadDemo = () => {setDevMenuOpen(false);window.dispatchEvent(new CustomEvent("load-demo-content"));};const handleReset = () => {setDevMenuOpen(false);if (window.confirm("Reset the article? This wipes the document, banner, frontmatter and citations.",)) {window.dispatchEvent(new CustomEvent("reset-article"));}};return (<div className="top-bar"><button49 unmodified lines{theme === "dark" ? <Sun size={18} /> : <Moon size={18} />}</button></Tooltip><div className="top-bar__menu" ref={devMenuRef}><Tooltip title="More actions"><buttonclassName="icon-btn"onClick={() => setDevMenuOpen((v) => !v)}aria-label="More actions"aria-haspopup="menu"aria-expanded={devMenuOpen || undefined}><MoreHorizontal size={18} /></button></Tooltip>{devMenuOpen && (<div className="top-bar__menu-pop" role="menu"><buttonclassName="top-bar__menu-item"role="menuitem"onClick={handleLoadDemo}><FileText size={14} /><span className="top-bar__menu-item-content"><span className="top-bar__menu-item-title">Load demo content</span><span className="top-bar__menu-item-desc">Replace document with a full demo article</span></span></button><buttonclassName="top-bar__menu-item top-bar__menu-item--danger"role="menuitem"onClick={handleReset}><Trash2 size={14} /><span className="top-bar__menu-item-content"><span className="top-bar__menu-item-title">Reset article</span><span className="top-bar__menu-item-desc">Wipe document, banner, frontmatter, citations</span></span></button></div>)}</div><span className="divider-v" /><Tooltip title={publishTooltip}><button
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465import { useRef, useState, type DragEvent } from "react";import { Upload } from "lucide-react";import { ACCEPTED_DATA_EXTS, MAX_DATA_FILE_SIZE } from "../utils/data-files";
interface UploadZoneProps { onFiles: (files: FileList | File[]) => void | Promise<void>; disabled?: boolean; compact?: boolean;}
const ACCEPT_ATTR = ACCEPTED_DATA_EXTS.map((e) => `.${e}`).join(",");const MAX_MB = (MAX_DATA_FILE_SIZE / (1024 * 1024)).toFixed(0);
export function UploadZone({ onFiles, disabled, compact }: UploadZoneProps) { const inputRef = useRef<HTMLInputElement>(null); const [isDragging, setIsDragging] = useState(false);
const handleDrop = (e: DragEvent<HTMLDivElement>) => { e.preventDefault(); setIsDragging(false); if (disabled) return; if (e.dataTransfer.files?.length) void onFiles(e.dataTransfer.files); };
const handleDragOver = (e: DragEvent<HTMLDivElement>) => { e.preventDefault(); if (!disabled) setIsDragging(true); };
const handleDragLeave = () => setIsDragging(false);
return ( <div className={`es-upload-zone ${isDragging ? "es-upload-zone--active" : ""} ${compact ? "es-upload-zone--compact" : ""}`} onDrop={handleDrop} onDragOver={handleDragOver} onDragLeave={handleDragLeave} onClick={() => !disabled && inputRef.current?.click()} role="button" tabIndex={disabled ? -1 : 0} aria-label="Upload data file" > <input ref={inputRef} type="file" accept={ACCEPT_ATTR} multiple onChange={(e) => { if (e.target.files?.length) void onFiles(e.target.files); e.target.value = ""; }} style={{ display: "none" }} /> <Upload size={compact ? 14 : 18} /> {compact ? ( <span>Add data file</span> ) : ( <div className="es-upload-zone__text"> <strong>Drop a data file</strong> <span>CSV, TSV, JSON, NDJSON, TXT - up to {MAX_MB} MB</span> </div> )} </div> );}28 unmodified lines293031323334353637385 unmodified lines4445464748498 unmodified lines58596061626331 unmodified lines95969798991008 unmodified lines10911011111211311499 unmodified lines21421521621721821948 unmodified lines26826927027127227327415 unmodified lines29029129229329429528 unmodified linesimport { Footnote } from "./extensions/footnote";import { Stack, StackColumn } from "./extensions/stack";import { ScrollGuard } from "./extensions/scroll-guard";import { CitationPanel } from "./CitationPanel";import { createCommentStore, CommentStore } from "./comments";import { createFrontmatterStore, FrontmatterStore } from "./frontmatter/frontmatter-store";import { createEmbedStore, EmbedStore } from "./embeds/embed-store";import { COMPONENTS, createComponentExtension } from "./components";import { uploadImage } from "./upload";import { loadDemoContent } from "./load-demo";5 unmodified linesonCommentStoreReady: (store: CommentStore) => void;onFrontmatterStoreReady: (store: FrontmatterStore) => void;onEmbedStoreReady?: (store: EmbedStore) => void;onSettingsMapReady?: (map: Y.Map<any>) => void;onEditorReady: (editor: TiptapEditor | null) => void;onUndoManagerReady?: (manager: UndoManager) => void;8 unmodified linesonCommentStoreReady,onFrontmatterStoreReady,onEmbedStoreReady,onProviderReady,onSettingsMapReady,onEditorReady,31 unmodified linesconst commentStore = useMemo(() => createCommentStore(ydoc), [ydoc]);const frontmatterStore = useMemo(() => createFrontmatterStore(ydoc), [ydoc]);const embedStore = useMemo(() => createEmbedStore(ydoc), [ydoc]);const [showCitationPanel, setShowCitationPanel] = useState(false);useEffect(() => {8 unmodified linesonEmbedStoreReady?.(embedStore);}, [embedStore, onEmbedStoreReady]);useEffect(() => {onSettingsMapReady?.(settingsMap);}, [settingsMap, onSettingsMapReady]);99 unmodified lines}),Comment,ScrollGuard,],},[ydoc, provider],48 unmodified linesreturn () => window.removeEventListener("reset-article", handler);}, [editor, frontmatterStore, citationsMap, settingsMap, embedStore, ydoc]);// Dev-only hook used by the demo recording script (backend/demo/trio.ts).// Lets the script swap the banner HTML deterministically, simulating a// successful Embed Studio agent run without depending on the LLM backend.useEffect(() => {15 unmodified linesuseEffect(() => {if (!editor) return;(editor.commands as any).updateUser(user);}, [editor, user]);useEffect(() => {28 unmodified lines29303132333435363738394041425 unmodified lines484950515253548 unmodified lines6364656667686931 unmodified lines1011021031041051061078 unmodified lines11611711811912012112212312412599 unmodified lines22522622722822923023123223323423523648 unmodified lines28528628728828929029115 unmodified lines30730830931031131231328 unmodified linesimport { Footnote } from "./extensions/footnote";import { Stack, StackColumn } from "./extensions/stack";import { ScrollGuard } from "./extensions/scroll-guard";import { AgentHighlight } from "./extensions/agent-highlight";import { AgentFocus } from "./extensions/agent-focus";import { AgentRewrite } from "./extensions/agent-rewrite";import { CitationPanel } from "./CitationPanel";import { createCommentStore, CommentStore } from "./comments";import { createFrontmatterStore, FrontmatterStore } from "./frontmatter/frontmatter-store";import { createEmbedStore, EmbedStore } from "./embeds/embed-store";import { createEmbedDataStore, EmbedDataStore } from "./embeds/embed-data-store";import { COMPONENTS, createComponentExtension } from "./components";import { uploadImage } from "./upload";import { loadDemoContent } from "./load-demo";5 unmodified linesonCommentStoreReady: (store: CommentStore) => void;onFrontmatterStoreReady: (store: FrontmatterStore) => void;onEmbedStoreReady?: (store: EmbedStore) => void;onEmbedDataStoreReady?: (store: EmbedDataStore) => void;onSettingsMapReady?: (map: Y.Map<any>) => void;onEditorReady: (editor: TiptapEditor | null) => void;onUndoManagerReady?: (manager: UndoManager) => void;8 unmodified linesonCommentStoreReady,onFrontmatterStoreReady,onEmbedStoreReady,onEmbedDataStoreReady,onProviderReady,onSettingsMapReady,onEditorReady,31 unmodified linesconst commentStore = useMemo(() => createCommentStore(ydoc), [ydoc]);const frontmatterStore = useMemo(() => createFrontmatterStore(ydoc), [ydoc]);const embedStore = useMemo(() => createEmbedStore(ydoc), [ydoc]);const embedDataStore = useMemo(() => createEmbedDataStore(ydoc), [ydoc]);const [showCitationPanel, setShowCitationPanel] = useState(false);useEffect(() => {8 unmodified linesonEmbedStoreReady?.(embedStore);}, [embedStore, onEmbedStoreReady]);useEffect(() => {onEmbedDataStoreReady?.(embedDataStore);}, [embedDataStore, onEmbedDataStoreReady]);useEffect(() => {onSettingsMapReady?.(settingsMap);}, [settingsMap, onSettingsMapReady]);99 unmodified lines}),Comment,ScrollGuard,AgentHighlight,AgentFocus.configure({provider,user,}),AgentRewrite,],},[ydoc, provider],48 unmodified linesreturn () => window.removeEventListener("reset-article", handler);}, [editor, frontmatterStore, citationsMap, settingsMap, embedStore, ydoc]);// Dev-only hook used by the demo recording script (backend/demo/showcase.ts).// Lets the script swap the banner HTML deterministically, simulating a// successful Embed Studio agent run without depending on the LLM backend.useEffect(() => {15 unmodified linesuseEffect(() => {if (!editor) return;(editor.commands as any).updateUser(user);editor.commands.updateAgentFocusUser(user);}, [editor, user]);useEffect(() => {
4 unmodified lines5678910111213141516171819202 unmodified lines2324252627281 unmodified line3031323334351 unmodified line3738394041421 unmodified line4445464748495051525354555657585960616263646566676869707172737475767778792 unmodified lines8283848586872 unmodified lines9091929394952 unmodified lines98991001011021032 unmodified lines1061071081091101112 unmodified lines11411511611711811912012112212312418 unmodified lines1431441451461471481491501511521531541551561571581591601611621631641651661678 unmodified lines17617717817918018128 unmodified lines2102112122132142152162172182192202212222232242252262275 unmodified lines2332342352362372382392404 unmodified linesforwardRef,useEffect,useImperativeHandle,useState,useCallback,} from "react";import type { Editor } from "@tiptap/core";import { getComponentSlashItems } from "./components";interface SlashItem {title: string;description: string;icon: string;command: (editor: Editor) => void;}2 unmodified linestitle: "Heading 1",description: "Large section heading",icon: "H1",command: (editor) =>editor.chain().focus().toggleHeading({ level: 1 }).run(),},1 unmodified linetitle: "Heading 2",description: "Medium section heading",icon: "H2",command: (editor) =>editor.chain().focus().toggleHeading({ level: 2 }).run(),},1 unmodified linetitle: "Heading 3",description: "Small section heading",icon: "H3",command: (editor) =>editor.chain().focus().toggleHeading({ level: 3 }).run(),},1 unmodified linetitle: "Bullet list",description: "Unordered list",icon: "•",command: (editor) => editor.chain().focus().toggleBulletList().run(),},{title: "Numbered list",description: "Ordered list",icon: "1.",command: (editor) => editor.chain().focus().toggleOrderedList().run(),},{title: "Quote",description: "Blockquote",icon: "❝",command: (editor) => editor.chain().focus().toggleBlockquote().run(),},{title: "Code block",description: "Code with syntax highlighting",icon: "<>",command: (editor) => editor.chain().focus().toggleCodeBlock().run(),},{title: "Divider",description: "Horizontal rule",icon: "—",command: (editor) => editor.chain().focus().setHorizontalRule().run(),},{title: "Image",description: "Upload or embed an image",icon: "🖼",command: (editor) => {editor.chain().focus().insertImageUpload().run();},2 unmodified linestitle: "Citation",description: "Cite a paper (DOI or BibTeX)",icon: "📎",command: () => {window.dispatchEvent(new CustomEvent("open-citation-panel"));},2 unmodified linestitle: "Glossary",description: "Highlighted term with tooltip definition",icon: "📖",command: (editor) => {editor.chain().focus().insertGlossary("term", "Definition here…").run();},2 unmodified linestitle: "Footnote",description: "Numbered footnote reference",icon: "¹",command: (editor) => {editor.chain().focus().insertFootnote("Footnote content…").run();},2 unmodified linestitle: "Stack",description: "Multi-column layout (2-4 columns)",icon: "▥",command: (editor) => {editor.chain().focus().insertStack(2).run();},2 unmodified linestitle: "New Chart",description: "Create a D3 chart with AI (Embed Studio)",icon: "📊",command: (editor) => {const id = `d3-chart-${Date.now().toString(36)}`;const src = `${id}.html`;(editor.chain().focus() as any).inserthtmlEmbed().run();// Find the just-inserted htmlEmbed node and set its srcsetTimeout(() => {const { doc } = editor.state;let targetPos = -1;18 unmodified lines}, 50);},},{title: "Load demo content",description: "Replace document with a full demo article",icon: "📄",command: () => {window.dispatchEvent(new CustomEvent("load-demo-content"));},},{title: "Reset article",description: "Wipe document, banner, frontmatter and citations",icon: "🗑",command: () => {window.dispatchEvent(new CustomEvent("reset-article"));},},];const ITEMS: SlashItem[] = [...BUILT_IN_ITEMS, ...getComponentSlashItems()];interface SlashMenuListProps {items: SlashItem[];8 unmodified lines({ items, command }, ref) => {const [selectedIndex, setSelectedIndex] = useState(0);useEffect(() => {setSelectedIndex(0);}, [items]);28 unmodified linesreturn (<div className="slash-menu">{items.map((item, index) => (<buttonkey={item.title}className={`slash-menu-item ${index === selectedIndex ? "is-selected" : ""}`}onClick={() => selectItem(index)}><span className="slash-menu-item-icon">{item.icon}</span><span className="slash-menu-item-content"><span className="slash-menu-item-title">{item.title}</span><span className="slash-menu-item-desc">{item.description}</span></span></button>))}</div>);5 unmodified linesexport function slashMenuSuggestion() {return {items: ({ query }: { query: string }) => {return ITEMS.filter((item) =>item.title.toLowerCase().includes(query.toLowerCase()),);},4 unmodified lines567891011121314151617181920212223242526272829302 unmodified lines333435363738391 unmodified line414243444546471 unmodified line495051525354551 unmodified line5758596061626364656667686970717273747576777879808182838485868788899091929394959697982 unmodified lines1011021031041051061072 unmodified lines1101111121131141151162 unmodified lines1191201211221231241252 unmodified lines1281291301311321331342 unmodified lines13713813914014114214314414514614718 unmodified lines1661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582598 unmodified lines26826927027127227327427527627727827928 unmodified lines3083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373385 unmodified lines3443453463473483493503513523533543553563574 unmodified linesforwardRef,useEffect,useImperativeHandle,useMemo,useState,useCallback,} from "react";import type { Editor } from "@tiptap/core";import { getComponentSlashItems } from "./components";type SlashSection =| "Insert"| "Text"| "Academic"| "Media"| "Layout"| "Advanced";interface SlashItem {title: string;description: string;icon: string;section: SlashSection;command: (editor: Editor) => void;}2 unmodified linestitle: "Heading 1",description: "Large section heading",icon: "H1",section: "Text",command: (editor) =>editor.chain().focus().toggleHeading({ level: 1 }).run(),},1 unmodified linetitle: "Heading 2",description: "Medium section heading",icon: "H2",section: "Text",command: (editor) =>editor.chain().focus().toggleHeading({ level: 2 }).run(),},1 unmodified linetitle: "Heading 3",description: "Small section heading",icon: "H3",section: "Text",command: (editor) =>editor.chain().focus().toggleHeading({ level: 3 }).run(),},1 unmodified linetitle: "Bullet list",description: "Unordered list",icon: "•",section: "Text",command: (editor) => editor.chain().focus().toggleBulletList().run(),},{title: "Numbered list",description: "Ordered list",icon: "1.",section: "Text",command: (editor) => editor.chain().focus().toggleOrderedList().run(),},{title: "Quote",description: "Blockquote",icon: "❝",section: "Text",command: (editor) => editor.chain().focus().toggleBlockquote().run(),},{title: "Code block",description: "Code with syntax highlighting",icon: "<>",section: "Text",command: (editor) => editor.chain().focus().toggleCodeBlock().run(),},{title: "Divider",description: "Horizontal rule",icon: "—",section: "Text",command: (editor) => editor.chain().focus().setHorizontalRule().run(),},{title: "Image",description: "Upload or embed an image",icon: "🖼",section: "Insert",command: (editor) => {editor.chain().focus().insertImageUpload().run();},2 unmodified linestitle: "Citation",description: "Cite a paper (DOI or BibTeX)",icon: "📎",section: "Academic",command: () => {window.dispatchEvent(new CustomEvent("open-citation-panel"));},2 unmodified linestitle: "Glossary",description: "Highlighted term with tooltip definition",icon: "📖",section: "Academic",command: (editor) => {editor.chain().focus().insertGlossary("term", "Definition here…").run();},2 unmodified linestitle: "Footnote",description: "Numbered footnote reference",icon: "¹",section: "Academic",command: (editor) => {editor.chain().focus().insertFootnote("Footnote content…").run();},2 unmodified linestitle: "Stack",description: "Multi-column layout (2-4 columns)",icon: "▥",section: "Layout",command: (editor) => {editor.chain().focus().insertStack(2).run();},2 unmodified linestitle: "New Chart",description: "Create a D3 chart with AI (Embed Studio)",icon: "📊",section: "Insert",command: (editor) => {const id = `d3-chart-${Date.now().toString(36)}`;const src = `${id}.html`;(editor.chain().focus() as any).insertHtmlEmbed().run();setTimeout(() => {const { doc } = editor.state;let targetPos = -1;18 unmodified lines}, 50);},},];/*** Component-driven slash items (Accordion, Note, HtmlEmbed, ...) come* from the shared component registry. We map each tag to its slash* section here so the menu stays categorized when new components are* added.*/const COMPONENT_SECTION_MAP: Record<string, SlashSection> = {Accordion: "Layout",Note: "Academic",Quote: "Text",Wide: "Layout",FullWidth: "Layout",Sidenote: "Academic",Reference: "Media",HtmlEmbed: "Media",HfUser: "Media",RawHtml: "Advanced",Mermaid: "Media",};function inferSection(title: string): SlashSection {// Component slash items don't carry the original tag; match by label.const byLabel: Record<string, SlashSection> = {Accordion: "Layout","Note / Callout": "Academic","Quote block": "Text",Wide: "Layout","Full width": "Layout",Sidenote: "Academic","Reference / Figure": "Media","HTML Embed": "Media","HF User card": "Media","Raw HTML": "Advanced","Mermaid diagram": "Media",};return byLabel[title] ?? "Layout";}function withInferredSection(items: Array<Omit<SlashItem, "section"> & { section?: SlashSection }>,): SlashItem[] {return items.map((item) => ({...item,section: item.section ?? inferSection(item.title),}));}const ITEMS: SlashItem[] = [...BUILT_IN_ITEMS,...withInferredSection(getComponentSlashItems()),];// Display order of section groups in the menu. "Insert" is a tiny// featured section at the very top holding the two flagship heavy// inserts (New Chart, Image) - this editor's signature features.// Text blocks follow because they're 80% of real usage.const SECTION_ORDER: SlashSection[] = ["Insert","Text","Media","Academic","Layout","Advanced",];// Used to re-export so we can also feed the section map to anyone who// wants it (e.g. the TopBar "more" menu could list categories).export { SECTION_ORDER, COMPONENT_SECTION_MAP };interface SlashGroup {section: SlashSection;items: SlashItem[];}function groupItems(items: SlashItem[]): SlashGroup[] {const map = new Map<SlashSection, SlashItem[]>();for (const item of items) {const list = map.get(item.section) ?? [];list.push(item);map.set(item.section, list);}return SECTION_ORDER.filter((s) => map.has(s)).map((section) => ({section,items: map.get(section)!,}));}interface SlashMenuListProps {items: SlashItem[];8 unmodified lines({ items, command }, ref) => {const [selectedIndex, setSelectedIndex] = useState(0);// We render items in section groups. Keyboard navigation still// operates on the flat `items` array (not on section headers),// so ArrowDown moves between actual items regardless of their// section.const groups = useMemo(() => groupItems(items), [items]);useEffect(() => {setSelectedIndex(0);}, [items]);28 unmodified linesreturn (<div className="slash-menu">{groups.map((group) => (<div key={group.section} className="slash-menu-group"><div className="slash-menu-section" aria-hidden="true">{group.section}</div>{group.items.map((item) => {// Map back to the flat index so keyboard state and// click highlight stay in sync.const flatIndex = items.indexOf(item);return (<buttonkey={`${group.section}:${item.title}`}className={`slash-menu-item ${flatIndex === selectedIndex ? "is-selected" : ""}`}onClick={() => selectItem(flatIndex)}onMouseEnter={() => setSelectedIndex(flatIndex)}><span className="slash-menu-item-icon">{item.icon}</span><span className="slash-menu-item-content"><span className="slash-menu-item-title">{item.title}</span><span className="slash-menu-item-desc">{item.description}</span></span></button>);})}</div>))}</div>);5 unmodified linesexport function slashMenuSuggestion() {return {items: ({ query }: { query: string }) => {const q = query.toLowerCase();if (!q) return ITEMS;// Match on title OR description so typing "image" surfaces// both "Image" and "HTML Embed", etc.return ITEMS.filter((item) =>item.title.toLowerCase().includes(q) ||item.description.toLowerCase().includes(q),);},
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218import type { Editor } from "@tiptap/core";
/** * Frontend executor for Tiptap commands issued by the AI agent. * * The backend exposes a catalog of commands (see `backend/src/agent/tiptap-catalog.ts`). * When the LLM calls one, `useAgentChat` receives the tool call and * dispatches it here. Most commands map directly to * `editor.chain().focus()[commandName](args).run()`; a few need * specific handling (selectText, setLink). * * Returns a short human-readable status string that is sent back to the * LLM as the tool result so it can plan its next step. * * Inspired by `tiptap-apcore`'s TiptapExecutor but intentionally tiny - * we only cover the commands declared in the catalog. */
const SAFE_URL_PROTOCOLS = /^(https?|mailto|tel):/i;const SAFE_URL_RELATIVE = /^[/#?]/;
function isSafeUrl(url: string): boolean { const trimmed = url.trim(); return SAFE_URL_PROTOCOLS.test(trimmed) || SAFE_URL_RELATIVE.test(trimmed);}
// ---------------------------------------------------------------------------// selectText: semantic selection by text content// ---------------------------------------------------------------------------
/** * Extract all text from the ProseMirror document as a flat string, * keeping a mapping from string offsets to document positions. * * Duplicated from the logic inside `useAgentChat.findTextPosition` so * this module has no React dependency. */function getDocTextWithPositions(editor: Editor): { text: string; map: number[] } { const chunks: string[] = []; const map: number[] = [];
editor.state.doc.descendants((node, pos) => { if (node.isText && node.text) { for (let i = 0; i < node.text.length; i++) { map.push(pos + i); chunks.push(node.text[i]); } } else if (node.isBlock && chunks.length > 0) { map.push(pos); chunks.push("\n"); } });
return { text: chunks.join(""), map };}
interface SelectTextResult { found: boolean; from?: number; to?: number;}
function handleSelectText( editor: Editor, args: { text: string; occurrence?: number; contextBefore?: string; contextAfter?: string; },): SelectTextResult { const { text, occurrence = 1, contextBefore, contextAfter } = args; if (!text) return { found: false };
const { text: docText, map } = getDocTextWithPositions(editor);
// Collect all candidate indices const candidates: number[] = []; let startIdx = 0; while (true) { const idx = docText.indexOf(text, startIdx); if (idx === -1) break; candidates.push(idx); startIdx = idx + 1; } if (candidates.length === 0) return { found: false };
let chosenIdx: number; if (contextBefore || contextAfter) { let bestIdx = candidates[0]; let bestScore = -1; for (const idx of candidates) { let score = 0; if (contextBefore) { const before = docText.slice(Math.max(0, idx - contextBefore.length - 10), idx); if (before.includes(contextBefore)) score += 2; else if (before.toLowerCase().includes(contextBefore.toLowerCase())) score += 1; } if (contextAfter) { const after = docText.slice(idx + text.length, idx + text.length + contextAfter.length + 10); if (after.includes(contextAfter)) score += 2; else if (after.toLowerCase().includes(contextAfter.toLowerCase())) score += 1; } if (score > bestScore) { bestScore = score; bestIdx = idx; } } chosenIdx = bestIdx; } else { const occIdx = Math.max(0, Math.min(occurrence - 1, candidates.length - 1)); chosenIdx = candidates[occIdx]; }
const from = map[chosenIdx]; const to = map[chosenIdx + text.length - 1] + 1; editor.chain().focus().setTextSelection({ from, to }).run(); return { found: true, from, to };}
// ---------------------------------------------------------------------------// Catalog command dispatch// ---------------------------------------------------------------------------
/** * Tiptap commands that take no arguments. Called as * `editor.chain().focus()[name]().run()`. */const EMPTY_ARG_COMMANDS = new Set([ "toggleBold", "toggleItalic", "toggleStrike", "toggleCode", "unsetLink", "setParagraph", "toggleBulletList", "toggleOrderedList", "toggleBlockquote",]);
/** * Map a tool call to an `editor.chain()` invocation. * * Returns null when the tool name is not in the Tiptap catalog (so the * caller can fall back to its own handling for applyDiff, frontmatter, etc.). */export function executeTiptapCommand( editor: Editor, toolName: string, args: Record<string, unknown>,): string | null { // selectText is not a native Tiptap command. if (toolName === "selectText") { const result = handleSelectText(editor, args as Parameters<typeof handleSelectText>[1]); if (!result.found) { return `selectText: text not found in the document`; } return `selectText: selected range ${result.from}-${result.to}`; }
// Empty-arg commands - just call them directly. if (EMPTY_ARG_COMMANDS.has(toolName)) { const chain = editor.chain().focus(); const fn = (chain as unknown as Record<string, () => typeof chain>)[toolName]; if (typeof fn !== "function") { return `Unknown editor command: ${toolName}`; } const success = fn.call(chain).run(); return success ? `${toolName} applied` : `${toolName} failed (selection state?)`; }
// Commands with specific argument shapes. switch (toolName) { case "toggleHeading": { const level = (args as { level?: number }).level; if (!level || level < 1 || level > 3) return "toggleHeading: invalid level"; const ok = editor .chain() .focus() .toggleHeading({ level: level as 1 | 2 | 3 }) .run(); return ok ? `toggleHeading (level ${level}) applied` : "toggleHeading failed"; } case "toggleCodeBlock": { const language = (args as { language?: string }).language; const chain = editor.chain().focus(); const ok = language ? chain.toggleCodeBlock({ language }).run() : chain.toggleCodeBlock().run(); return ok ? "toggleCodeBlock applied" : "toggleCodeBlock failed"; } case "setLink": { const href = (args as { href?: string }).href; if (!href || !isSafeUrl(href)) return `setLink: unsafe or missing URL`; const ok = editor.chain().focus().setLink({ href }).run(); return ok ? `setLink applied (${href})` : "setLink failed (is text selected?)"; } default: return null; }}
/** Tool names handled by `executeTiptapCommand`, useful for dispatch. */export const TIPTAP_TOOL_NAMES = new Set<string>([ "selectText", "toggleBold", "toggleItalic", "toggleStrike", "toggleCode", "setLink", "unsetLink", "toggleHeading", "setParagraph", "toggleBulletList", "toggleOrderedList", "toggleBlockquote", "toggleCodeBlock",]);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107import * as Y from "yjs";
/** * Metadata describing a data file uploaded into the embed data store. * * Kept intentionally lean (strings + small numbers) so it can live * alongside the raw content inside a single Y.Map entry without * bloating the document size. */export interface EmbedDataFileMeta { name: string; /** Extension without leading dot, lowercased: "csv" | "tsv" | "json" | "txt" */ ext: string; /** Size of the stored text content in bytes (UTF-8). */ size: number; /** Uploader user id (if available). */ uploader?: string; /** Epoch ms when the file was added. */ addedAt: number; /** Light metadata computed client-side after parsing. */ rowCount?: number; columns?: string[];}
export interface EmbedDataFile { meta: EmbedDataFileMeta; /** Raw text content (UTF-8). */ content: string;}
/** * Collaborative store for tabular/textual data files attached to a * document. Each key is a filename (e.g. "sales.csv") and the value is * an `EmbedDataFile` object (meta + raw text content). * * These files are accessible to the Embed Studio AI via tool calls so * charts can reference user-provided datasets. The store is backed by * `Y.Map("embed-data")` for realtime collaboration. */export function createEmbedDataStore(ydoc: Y.Doc) { const ymap = ydoc.getMap<EmbedDataFile>("embed-data");
function get(name: string): EmbedDataFile | undefined { return ymap.get(name); }
function getContent(name: string): string { return ymap.get(name)?.content ?? ""; }
function getMeta(name: string): EmbedDataFileMeta | undefined { return ymap.get(name)?.meta; }
function has(name: string): boolean { return ymap.has(name); }
function set(file: EmbedDataFile) { ymap.set(file.meta.name, file); }
function remove(name: string) { ymap.delete(name); }
function rename(oldName: string, newName: string) { const file = ymap.get(oldName); if (!file) return; ydoc.transact(() => { ymap.set(newName, { ...file, meta: { ...file.meta, name: newName } }); ymap.delete(oldName); }); }
function keys(): string[] { return Array.from(ymap.keys()); }
function list(): EmbedDataFileMeta[] { const items: EmbedDataFileMeta[] = []; ymap.forEach((file) => { items.push(file.meta); }); return items.sort((a, b) => a.name.localeCompare(b.name)); }
function observe(callback: () => void) { ymap.observe(callback); return () => ymap.unobserve(callback); }
return { get, getContent, getMeta, has, set, remove, rename, keys, list, observe, };}
export type EmbedDataStore = ReturnType<typeof createEmbedDataStore>;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315/** * Broadcasts "this user's AI agent is currently focused on this range" to * every collaborator via Yjs awareness, and renders it as a ProseMirror * decoration tinted with the owner's color. * * Design notes * ------------ * - We combine two Tiptap patterns that already exist separately in the * ecosystem: * 1. the paid `@tiptap-pro/ai-toolkit` `setActiveSelection` feature, * which freezes a range locally while the agent is working on it; * 2. `@tiptap/extension-collaboration-caret`, which shares cursor * positions across peers via Yjs awareness using relative * positions. * * - Ranges are stored in awareness as **Y.js relative positions** * (JSON form for safe transport) so they remain meaningful on every * peer's doc even as Bob or Carol are typing concurrently. We resolve * them back to absolute positions at decoration time. * * - Every peer (including self) gets both the inline tint AND the * floating "<Name> agent" label. When the chat panel is open the * editor often loses DOM focus to the chat textarea, which makes * the native `::selection` fade or disappear: the PM decoration is * then the ONLY thing keeping the range visible on the owner's * screen. To avoid stacking two tints when the editor still has * focus, `_ui.css` hides the native `::selection` inside * `.ProseMirror` while `.editor-app--chat-open` is set. * * Usage (from App.tsx): * editor.commands.setAgentFocus({ from, to }); // on chat open * editor.commands.clearAgentFocus(); // on chat close */import { Extension } from "@tiptap/core";import { Plugin, PluginKey } from "@tiptap/pm/state";import { Decoration, DecorationSet } from "@tiptap/pm/view";import { absolutePositionToRelativePosition, relativePositionToAbsolutePosition, ySyncPluginKey,} from "@tiptap/y-tiptap";import * as Y from "yjs";
export interface AgentFocusUser { name: string; color: string; avatarUrl?: string;}
export interface AgentFocusOptions { // Any Yjs provider with a `.awareness` API (Hocuspocus, y-websocket, ...) provider: any; user: AgentFocusUser;}
interface AwarenessFocus { anchor: unknown; head: unknown; user: AgentFocusUser;}
export const agentFocusPluginKey = new PluginKey("agent-focus");
declare module "@tiptap/core" { // eslint-disable-next-line @typescript-eslint/no-unused-vars interface Commands<ReturnType> { agentFocus: { /** Mark `[from, to]` as "my agent is working on this". */ setAgentFocus: (args: { from: number; to: number }) => ReturnType; /** Remove our own agent-focus highlight. */ clearAgentFocus: () => ReturnType; /** Update the awareness user (name / color / avatar). */ updateAgentFocusUser: (user: AgentFocusUser) => ReturnType; }; }}
export const AgentFocus = Extension.create<AgentFocusOptions>({ name: "agentFocus",
addOptions() { return { provider: null, user: { name: "Anonymous", color: "#5c7cfa" }, }; },
onCreate() { if (!this.options.provider) { throw new Error('The "provider" option is required for AgentFocus'); } },
addCommands() { // None of these commands mutate the ProseMirror document - they only // touch Yjs awareness. That's what guarantees they stay out of the // undo stack: `Y.UndoManager` tracks CRDT ops, awareness is // ephemeral metadata. Tiptap will still dispatch an empty transaction // after each command returns `true`, but an empty tr has // `tr.docChanged === false`, so y-sync ignores it and undo is clean. return { setAgentFocus: ({ from, to }) => ({ state }) => { const ystate = ySyncPluginKey.getState(state); if (!ystate?.binding) return false;
const size = state.doc.content.size; const a = Math.max(0, Math.min(from, size)); const b = Math.max(0, Math.min(to, size)); if (a === b) return false; const [lo, hi] = a < b ? [a, b] : [b, a];
const anchor = absolutePositionToRelativePosition( lo, ystate.type, ystate.binding.mapping, ); const head = absolutePositionToRelativePosition( hi, ystate.type, ystate.binding.mapping, );
this.options.provider.awareness.setLocalStateField("agentFocus", { anchor: Y.relativePositionToJSON(anchor), head: Y.relativePositionToJSON(head), user: this.options.user, }); return true; },
clearAgentFocus: () => () => { this.options.provider.awareness.setLocalStateField("agentFocus", null); return true; },
updateAgentFocusUser: (user) => () => { this.options.user = user; // Re-emit current focus with the updated user payload, if any. const current = this.options.provider.awareness.getLocalState() ?.agentFocus as AwarenessFocus | null | undefined; if (current?.anchor && current?.head) { this.options.provider.awareness.setLocalStateField("agentFocus", { ...current, user, }); } return true; }, }; },
addProseMirrorPlugins() { const awareness = this.options.provider.awareness;
return [ new Plugin({ key: agentFocusPluginKey, state: { init: () => ({ stamp: 0 }), apply(tr, prev) { if (tr.getMeta(agentFocusPluginKey)) { return { stamp: prev.stamp + 1 }; } return prev; }, }, props: { decorations(state) { const ystate = ySyncPluginKey.getState(state); if (!ystate?.binding) return null;
const decorations: Decoration[] = []; const localClientId = awareness.clientID;
awareness.getStates().forEach((s: any, clientId: number) => { const focus = s?.agentFocus as | AwarenessFocus | null | undefined; if (!focus || !focus.anchor || !focus.head) return; const isSelf = clientId === localClientId;
let from: number | null = null; let to: number | null = null; try { from = relativePositionToAbsolutePosition( ystate.doc, ystate.type, Y.createRelativePositionFromJSON(focus.anchor), ystate.binding.mapping, ); to = relativePositionToAbsolutePosition( ystate.doc, ystate.type, Y.createRelativePositionFromJSON(focus.head), ystate.binding.mapping, ); } catch { return; }
if (from == null || to == null || from === to) return; const [lo, hi] = from < to ? [from, to] : [to, from];
const color = focus.user?.color || "#5c7cfa"; const name = focus.user?.name || ""; // Match Tiptap's `defaultSelectionBuilder` exactly: a flat // `{color}70` tint (hex + alpha), no underline, no shadow - // so an agent focus is visually the same as a collaborator // selection, only the label name ("… agent") tells them apart. const style = `background-color: ${color}70`;
decorations.push( Decoration.inline( lo, hi, { class: `agent-focus${isSelf ? " agent-focus--self" : ""}`, style, "data-agent-focus-user": name, "data-agent-focus-color": color, } as any, // inclusiveStart:false / inclusiveEnd:false -> typing // at either edge should not extend the highlight, the // Y.js relative position already pins the true // boundary. { inclusiveStart: false, inclusiveEnd: false } as any, ), );
// Floating label anchored at the END of the range, i.e. // on the last line of the selection at the cursor // position. This mirrors `.collaboration-cursor__label`, // which also renders on the right of the last line (at // the selection head). Using `hi` instead of `lo` keeps // the badge visually coupled to "where the agent's cursor // would sit if it were typing right now". decorations.push( Decoration.widget( hi, () => { const anchor = document.createElement("span"); anchor.className = "agent-focus__anchor";
const label = document.createElement("span"); label.className = "agent-focus__label"; label.setAttribute( "style", `background-color: ${color}`, );
const avatarUrl = focus.user?.avatarUrl; if (avatarUrl) { const avatar = document.createElement("img"); avatar.src = avatarUrl; avatar.className = "agent-focus__avatar"; avatar.alt = ""; label.appendChild(avatar); }
const text = document.createElement("span"); text.className = "agent-focus__text"; text.textContent = `${name || "Someone"} agent`; label.appendChild(text);
anchor.appendChild(label); return anchor; }, { // `side: 1` -> the widget stays on the RIGHT side of // the `hi` position, so if the user types inside the // range the label doesn't get pushed into the middle // of new content. `key` lets PM reuse the DOM on // every awareness tick instead of re-creating it. side: 1, key: `agent-focus-label-${clientId}-${name}`, } as any, ), ); });
if (decorations.length === 0) return null; return DecorationSet.create(state.doc, decorations); }, }, view(view) { // `change` fires only when an awareness state is actually added, // updated, or removed - NOT on heartbeat ticks. Listening to // `update` instead (as some examples do) would trigger a // re-render every ~30s for nothing. // // The dispatched transaction is meta-only: no steps, no doc // change, no selection change. y-sync ignores it because // `tr.docChanged` is false, and the Yjs UndoManager only // tracks CRDT operations - so this never pollutes the undo // stack. Agent-focus is 100% ephemeral decoration state. const handler = () => { if (view.isDestroyed) return; view.dispatch( view.state.tr.setMeta(agentFocusPluginKey, { refresh: true }), ); }; awareness.on("change", handler); return { destroy() { awareness.off("change", handler); }, }; }, }), ]; },});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165/** * Demo-only Tiptap extension that lets the Playwright showcase script mark a * paragraph as "the one an agent is currently working on" and have the * highlight survive any amount of concurrent Yjs syncing, remote typing, * or local selection changes. * * Why a ProseMirror decoration and not a DOM class? * ------------------------------------------------- * In a Tiptap + Yjs editor, the DOM for a paragraph can be torn down and * re-created at any time: every remote update from Bob or Carol triggers * a sync transaction, and PM may decide to rebuild the `<p>` (especially * under the collaboration plugin). Any `className` we slap on the `<p>` * is lost on the next render, which is why previous versions of the * demo relied on a 150 ms polling timer to re-apply the class. That * worked, but it flickers and leaves a visible gap between "selection * happens" and "class comes back". * * ProseMirror decorations solve this at the right layer: they live in * editor state, are re-rendered on every view update, and are remapped * through doc changes automatically. Here we store a `{ from, to, phase }` * range in plugin state, decorate the paragraph containing `from` with * the appropriate `demo-agent-{pending|rewriting}` class, and let PM do * the rest. * * Usage (from the demo script or App.tsx): * editor.commands.setAgentHighlight({ from, to, phase: "pending" }); * editor.commands.setAgentHighlight({ phase: "rewriting" }); * editor.commands.clearAgentHighlight(); */import { Extension } from "@tiptap/core";import { Plugin, PluginKey } from "@tiptap/pm/state";import { Decoration, DecorationSet } from "@tiptap/pm/view";
export type AgentHighlightPhase = "pending" | "rewriting";
interface AgentHighlightState { from: number | null; to: number | null; phase: AgentHighlightPhase | null;}
interface AgentHighlightMeta { from?: number | null; to?: number | null; phase?: AgentHighlightPhase | null; clear?: boolean;}
export const agentHighlightPluginKey = new PluginKey<AgentHighlightState>("agent-highlight");
declare module "@tiptap/core" { // eslint-disable-next-line @typescript-eslint/no-unused-vars interface Commands<ReturnType> { agentHighlight: { /** * Set (or update) the highlighted range and phase. Omitting * `from`/`to` keeps the existing range; omitting `phase` keeps * the existing phase. Both can be updated independently so the * App.tsx rewrite handler can flip `pending -> rewriting` without * recomputing the range. */ setAgentHighlight: (args: { from?: number; to?: number; phase?: AgentHighlightPhase; }) => ReturnType; /** Remove any active highlight. */ clearAgentHighlight: () => ReturnType; }; }}
export const AgentHighlight = Extension.create({ name: "agentHighlight",
addProseMirrorPlugins() { return [ new Plugin<AgentHighlightState>({ key: agentHighlightPluginKey, state: { init: (): AgentHighlightState => ({ from: null, to: null, phase: null, }), apply(tr, prev): AgentHighlightState { const meta = tr.getMeta(agentHighlightPluginKey) as | AgentHighlightMeta | undefined; if (meta) { if (meta.clear) { return { from: null, to: null, phase: null }; } return { from: meta.from !== undefined ? meta.from : prev.from, to: meta.to !== undefined ? meta.to : prev.to, phase: meta.phase !== undefined ? meta.phase : prev.phase, }; }
if (prev.from !== null && prev.to !== null) { const from = tr.mapping.map(prev.from, 1); const to = tr.mapping.map(prev.to, -1); if (to > from) { if (from === prev.from && to === prev.to) return prev; return { ...prev, from, to }; } return { from: null, to: null, phase: null }; }
return prev; }, }, props: { decorations(state) { const s = agentHighlightPluginKey.getState(state); if (!s || s.from === null || s.to === null || !s.phase) { return null; }
let $pos; try { $pos = state.doc.resolve(s.from); } catch { return null; }
const depth = $pos.depth; if (depth <= 0) return null;
const nodeStart = $pos.before(depth); const nodeEnd = $pos.after(depth); const cls = `demo-agent-${s.phase}`;
return DecorationSet.create(state.doc, [ Decoration.node(nodeStart, nodeEnd, { class: cls }), ]); }, }, }), ]; },
addCommands() { return { setAgentHighlight: (args) => ({ tr, dispatch }) => { if (dispatch) { tr.setMeta(agentHighlightPluginKey, args); } return true; }, clearAgentHighlight: () => ({ tr, dispatch }) => { if (dispatch) { tr.setMeta(agentHighlightPluginKey, { clear: true }); } return true; }, }; },});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267/** * AgentRewrite * ============ * * One canonical Tiptap command to perform an agent-driven replacement * of a range in the document - optionally with a typewriter animation * so the user sees the agent "typing" the new content in place of the * old one. * * Called by: * - the real agent's tool calls (applyDiff / rewrite / rephrase), * - the Playwright showcase demo script via the `__demo-chat` event. * * Why this lives in an extension (and not in App.tsx or the demo) * --------------------------------------------------------------- * The previous design had an ad-hoc `setTimeout` loop in App.tsx that * re-inserted characters at `startPos + i` - a fixed numeric origin. * Under Yjs collaboration any concurrent remote edit that shifted * `startPos` (e.g. another user inserting a character before it) would * desync the animation and land subsequent chunks inside the wrong * paragraph, producing a visible "write-over-itself" artifact. * * Here we track the insertion `cursor` in PM plugin state and remap it * through `tr.mapping` on every transaction - local OR remote. This * guarantees the typewriter resumes at the correct absolute position * no matter what Bob or Carol are doing elsewhere in the doc. * * Cancellation * ------------ * Each call to `agentRewriteRange` bumps a cancel token stored in * plugin state. Any still-scheduled animation step that observes a * different token aborts. That way, if the agent fires two * overlapping rewrites, the first one stops immediately instead of * fighting the second for control of the doc. * * Undo-friendliness * ----------------- * Every animation step is a small atomic `insertText` transaction, * so y-undo sees a tidy sequence of ReplaceSteps instead of one huge * debug-hostile mega-op. Undo works as expected (one step per chunk). */import { Extension } from "@tiptap/core";import { Plugin, PluginKey } from "@tiptap/pm/state";
export type AgentRewriteAnimation = "none" | "typewriter";
export interface AgentRewriteArgs { /** Absolute PM position of the start of the range to replace. */ from: number; /** Absolute PM position of the end of the range to replace. */ to: number; /** New text to insert in place of the deleted range. */ text: string; /** * "none" -> replace the range atomically in one transaction. * "typewriter" -> stream the replacement chunk-by-chunk with small * delays so the UI shows the agent "typing". * Default: "none" (safer for programmatic / non-demo callers). */ animation?: AgentRewriteAnimation; /** * Characters per animation tick. A random int in [min,max] is chosen * each step, which makes the typing feel organic. Default [1, 2]. */ chunkSize?: [number, number]; /** * Milliseconds between animation ticks. Default [22, 48]. */ chunkMs?: [number, number];}
interface AgentRewriteState { /** * Current insertion position for the in-flight typewriter animation. * Mapped through every transaction so local + remote edits never * shift the cursor out of sync with the actual doc content. */ cursor: number | null; /** * Monotonically-increasing token. Any call to `agentRewriteRange` * bumps this, which retroactively cancels any animation step still * scheduled from a previous call. */ cancelToken: number;}
interface AgentRewriteMeta { cancel?: boolean; setCursor?: number | null;}
const agentRewriteKey = new PluginKey<AgentRewriteState>("agent-rewrite");
declare module "@tiptap/core" { // eslint-disable-next-line @typescript-eslint/no-unused-vars interface Commands<ReturnType> { agentRewrite: { /** * Replace `[from, to]` with `text`. When `animation === "typewriter"` * the insertion is streamed chunk-by-chunk; otherwise it's one * atomic transaction. */ agentRewriteRange: (args: AgentRewriteArgs) => ReturnType; /** Abort any in-flight typewriter animation immediately. */ cancelAgentRewrite: () => ReturnType; }; }}
export const AgentRewrite = Extension.create({ name: "agentRewrite",
addProseMirrorPlugins() { return [ new Plugin<AgentRewriteState>({ key: agentRewriteKey, state: { init: (): AgentRewriteState => ({ cursor: null, cancelToken: 0 }), apply(tr, prev): AgentRewriteState { let next = prev; // Remap the tracked cursor through any doc change (local or // remote). This is the whole point of using a plugin state // instead of a closure-captured number: Yjs pushes tr's for // remote edits and we ride their mapping. if (tr.docChanged && next.cursor !== null) { next = { ...next, cursor: tr.mapping.map(next.cursor) }; } const meta = tr.getMeta(agentRewriteKey) as | AgentRewriteMeta | undefined; if (meta) { if (meta.cancel) { // `cancel` wipes the cursor AND advances the token so // in-flight steps observe a mismatch and bail out. next = { cursor: null, cancelToken: next.cancelToken + 1, }; } if (meta.setCursor !== undefined) { // `setCursor` is the primitive used by the command to // re-arm the plugin with a fresh starting position // (AFTER any cancel has taken effect in the same meta). next = { ...next, cursor: meta.setCursor }; } } return next; }, }, }), ]; },
addCommands() { return { cancelAgentRewrite: () => ({ tr, dispatch }) => { if (dispatch) { tr.setMeta(agentRewriteKey, { cancel: true }); } return true; },
agentRewriteRange: (args) => ({ editor, state, view, tr, dispatch }) => { const docSize = state.doc.content.size; const a = Math.max(0, Math.min(args.from, docSize)); const b = Math.max(0, Math.min(args.to, docSize)); if (b < a) return false; if (!dispatch) return true;
// Step 1: single atomic transaction that (a) cancels any // in-flight rewrite, (b) deletes the target range, and (c) // plants the insertion cursor at `a`. Done in one tr so the // deletion and cursor seed land together - avoids a visible // gap between delete and first insert. tr.setMeta(agentRewriteKey, { cancel: true, setCursor: a, } as AgentRewriteMeta); if (b > a) tr.delete(a, b); dispatch(tr);
const text = args.text ?? ""; if (!text) { // Nothing to insert, just a deletion. Done. view.dispatch( view.state.tr.setMeta(agentRewriteKey, { setCursor: null, } as AgentRewriteMeta), ); return true; }
const animation = args.animation ?? "none"; if (animation === "none") { // Synchronous, one-shot insert. Single tr -> one undo step. const cursor = agentRewriteKey.getState(editor.state)?.cursor ?? a; view.dispatch( view.state.tr .insertText(text, cursor) .setMeta(agentRewriteKey, { setCursor: null, } as AgentRewriteMeta), ); return true; }
// Typewriter: async stream of small insertText trs. Each step // reads the CURRENT cursor from plugin state (mapped through // every intervening tr, including remote Yjs updates), so the // animation is immune to concurrent edits. const [chunkMin, chunkMax] = args.chunkSize ?? [1, 2]; const [delayMin, delayMax] = args.chunkMs ?? [22, 48]; const myToken = agentRewriteKey.getState(editor.state)?.cancelToken ?? 0; let i = 0;
const step = () => { if (view.isDestroyed) return; const ps = agentRewriteKey.getState(view.state); if (!ps) return; // Another rewrite started (or cancel was called) -> stop. if (ps.cancelToken !== myToken) return; if (ps.cursor === null) return;
if (i >= text.length) { // Done: clear the cursor marker so nothing lingers in // plugin state. The caller is responsible for any visual // cleanup (e.g. `clearAgentFocus`). view.dispatch( view.state.tr.setMeta(agentRewriteKey, { setCursor: null, } as AgentRewriteMeta), ); return; }
const remaining = text.length - i; const maxTake = Math.max(1, Math.min(chunkMax, remaining)); const minTake = Math.max(1, Math.min(chunkMin, maxTake)); const take = minTake + Math.floor(Math.random() * (maxTake - minTake + 1)); const chunk = text.slice(i, i + take);
// `insertText(chunk, cursor)` advances the cursor via the // plugin's `apply` mapping (see state.apply above). view.dispatch(view.state.tr.insertText(chunk, ps.cursor)); i += chunk.length;
const delay = delayMin + Math.random() * Math.max(0, delayMax - delayMin); setTimeout(step, delay); }; // Kick off on a macrotask so the initial delete tr has fully // applied (and the cursor seed is live in plugin state) // before the first step reads it. setTimeout(step, 0); return true; }, }; },});76 unmodified lines77787980818283848586878889909176 unmodified lines/></FieldGroup><FieldGroup label="Banner embed"><inputclassName="form-input"placeholder="banner.html"value={data.banner}onChange={(e) => update("banner", e.target.value)}/></FieldGroup><FieldGroup label="Citation style"><selectclassName="form-select"76 unmodified lines77787980818276 unmodified lines/></FieldGroup><FieldGroup label="Citation style"><selectclassName="form-select"
7 unmodified lines8910111213135 unmodified lines149150151152153154103 unmodified lines25825926026126226326426526626742 unmodified lines31031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034111 unmodified lines3533543553563573583597 unmodified linesimport type { UndoManager } from "yjs";import type { UIMessage } from "ai";import type { FrontmatterStore } from "../editor/frontmatter/frontmatter-store";interface UseAgentChatOptions {editor: Editor | null;135 unmodified linesconst executeToolCall = useCallback((toolCall: { toolName: string; args: unknown; toolCallId: string }) => {switch (toolCall.toolName) {// --- Frontmatter tools (no editor needed) ---case "updateFrontmatter": {103 unmodified lines[editor, frontmatterStore, startAgentBatch, findTextPosition],);const { addToolOutput, ...chat } = useChat({transport,messages: initialMessages,sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({ toolCall }) {if (toolCall.dynamic) return;42 unmodified lines[chat, getEditorContext, endAgentBatch, modelRef],);const sendQuickAction = useCallback((action: string) => {endAgentBatch();const context = getEditorContext();const prompts: Record<string, string> = {rewrite:"Rewrite the selected text to be clearer and more concise.",expand:"Expand the selected text with more detail and examples.",summarize:"Summarize the selected text into a shorter version.","fix-grammar":"Fix any grammar and spelling errors in the selected text.",translate:"Translate the selected text to English (or French if already in English).",simplify:"Simplify the selected text so it's easier to understand.",};const prompt = prompts[action] || action;const model = modelRef.current;chat.sendMessage({ text: prompt }, { body: { context, model } });},[chat, getEditorContext, endAgentBatch, modelRef],);const isLoading =chat.status === "streaming" || chat.status === "submitted";11 unmodified linesisLoading,error: chat.error,sendMessage,sendQuickAction,clearMessages,setMessages,input,7 unmodified lines891011121314135 unmodified lines150151152153154155156157158159160161162163164165166167103 unmodified lines27127227327427527627727827928028128228328428528628728828929029129229329429529629729829942 unmodified lines34234334434534634711 unmodified lines3593603613623633647 unmodified linesimport type { UndoManager } from "yjs";import type { UIMessage } from "ai";import type { FrontmatterStore } from "../editor/frontmatter/frontmatter-store";import { executeTiptapCommand, TIPTAP_TOOL_NAMES } from "../editor/agent-executor";interface UseAgentChatOptions {editor: Editor | null;135 unmodified linesconst executeToolCall = useCallback((toolCall: { toolName: string; args: unknown; toolCallId: string }) => {// --- Tiptap catalog commands (select, toggleBold, toggleHeading, ...) ---if (TIPTAP_TOOL_NAMES.has(toolCall.toolName)) {if (!editor) return "Editor not available";startAgentBatch();const result = executeTiptapCommand(editor,toolCall.toolName,(toolCall.args as Record<string, unknown>) ?? {},);return result ?? `Unknown editor command: ${toolCall.toolName}`;}switch (toolCall.toolName) {// --- Frontmatter tools (no editor needed) ---case "updateFrontmatter": {103 unmodified lines[editor, frontmatterStore, startAgentBatch, findTextPosition],);/*** Hard cap on consecutive auto-sent tool-call rounds to prevent* runaway loops (e.g. a model that keeps calling tools instead of* emitting a final text response).*/const MAX_TOOL_ROUNDS = 8;const { addToolOutput, ...chat } = useChat({transport,messages: initialMessages,sendAutomaticallyWhen: ({ messages }) => {let toolRounds = 0;for (let i = messages.length - 1; i >= 0; i--) {const m = messages[i];if (m.role !== "assistant") break;const hasToolPart = (m.parts ?? []).some((p) =>typeof p.type === "string" && p.type.startsWith("tool-"),);if (!hasToolPart) break;toolRounds += 1;}if (toolRounds >= MAX_TOOL_ROUNDS) return false;return lastAssistantMessageIsCompleteWithToolCalls({ messages });},async onToolCall({ toolCall }) {if (toolCall.dynamic) return;42 unmodified lines[chat, getEditorContext, endAgentBatch, modelRef],);const isLoading =chat.status === "streaming" || chat.status === "submitted";11 unmodified linesisLoading,error: chat.error,sendMessage,clearMessages,setMessages,input,
5 unmodified lines6789101112131415161718192021221 unmodified line2425262728293031323334352 unmodified lines383940414243444546474849503 unmodified lines5455565758596061626364656667686970717228 unmodified lines1011021031041051061071081091101115 unmodified linesimport { useCallback, useEffect, useRef, useState } from "react";import type { UIMessage } from "ai";import type { EmbedStore } from "../editor/embeds/embed-store";import { loadMessages, saveMessages } from "../utils/chat-persistence";interface UseEmbedChatOptions {embedStore: EmbedStore | null;/** Current embed src key (filename) */src: string;modelRef: React.RefObject<string>;userId: string;}const MAX_EMBED_SIZE = 512_000;const transport = new DefaultChatTransport({ api: "/api/embed-chat" });1 unmodified linereturn `embed:${src}`;}export function useEmbedChat({ embedStore, src, modelRef, userId }: UseEmbedChatOptions) {const [input, setInput] = useState("");const srcRef = useRef(src);srcRef.current = src;const userIdRef = useRef(userId);userIdRef.current = userId;// Guard: only allow sendAutomaticallyWhen AFTER the user has sent at// least one message in this session. Prevents auto-send on mount when2 unmodified linesconst getEmbedContext = useCallback(() => {if (!embedStore || !srcRef.current) return {};const embedHtml = embedStore.get(srcRef.current);const isBanner = srcRef.current === "banner.html";return {embedHtml: embedHtml || undefined,isBanner,};}, [embedStore]);const executeToolCall = useCallback((toolCall: { toolName: string; args: unknown; toolCallId: string }) => {3 unmodified linesswitch (toolCall.toolName) {case "createEmbed": {const { html, title } = toolCall.args as {html: string;title?: string;source?: string;};if (!html?.trim()) return "ERROR: html cannot be empty";const stripped = html.trim();if (stripped.length > MAX_EMBED_SIZE) {return `ERROR: chart too large (${stripped.length} bytes, max ${MAX_EMBED_SIZE}). Simplify the code.`;}embedStore.set(currentSrc, stripped);const lines = stripped.split("\n").length;return `chart created (${lines} lines, ${stripped.length} chars)${title ? ` - "${title}"` : ""}`;}case "patchEmbed": {28 unmodified linesreturn current;}default:return `Unknown tool: ${toolCall.toolName}`;}},[embedStore],);const { addToolOutput, setMessages: chatSetMessages, ...chat } = useChat({5 unmodified lines678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970711 unmodified line737475767778798081828384858687888990919293949596972 unmodified lines1001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291303 unmodified lines13413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019128 unmodified lines2202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582595 unmodified linesimport { useCallback, useEffect, useRef, useState } from "react";import type { UIMessage } from "ai";import type { EmbedStore } from "../editor/embeds/embed-store";import type { EmbedDataStore } from "../editor/embeds/embed-data-store";import { loadMessages, saveMessages } from "../utils/chat-persistence";interface UseEmbedChatOptions {embedStore: EmbedStore | null;dataStore?: EmbedDataStore | null;/** Current embed src key (filename) */src: string;modelRef: React.RefObject<string>;userId: string;/*** Called when the agent picks a descriptive filename via createEmbed.* Parent is expected to update the htmlEmbed node's src attribute in* the doc and lift the new src into its own state. The hook already* moves the content in embedStore and migrates persisted messages.*/onRename?: (oldSrc: string, newSrc: string) => void;}/*** Slugify an arbitrary filename hint into a safe kebab-case slug.* Keeps ASCII letters/digits/dashes, collapses whitespace, lowercases.*/function slugify(raw: string): string {const base = raw.toLowerCase().replace(/\.html?$/i, "").normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);return base || "chart";}/*** Given a slug, find a unique .html filename in `embedStore`. If the* desired name is free, return it; otherwise append `-2`, `-3`, ...*/function ensureUniqueFilename(slug: string,embedStore: EmbedStore,currentSrc: string,): string {const base = `${slug}.html`;if (base === currentSrc) return base;if (!embedStore.has(base)) return base;let i = 2;while (embedStore.has(`${slug}-${i}.html`)) i++;return `${slug}-${i}.html`;}const MAX_EMBED_SIZE = 512_000;/*** Hard cap on the number of characters we inline when the agent reads* a data file. Above this, the tool returns a truncated preview with* a warning so the model doesn't blow past its context window on a* single tool call.*/const MAX_DATA_INLINE = 120_000;const transport = new DefaultChatTransport({ api: "/api/embed-chat" });1 unmodified linereturn `embed:${src}`;}export function useEmbedChat({ embedStore, dataStore, src, modelRef, userId, onRename }: UseEmbedChatOptions) {const [input, setInput] = useState("");// srcRef is the source of truth for the active embed filename. It// starts from the `src` prop but may change mid-session when the// agent renames the chart via createEmbed({ filename }). We do NOT// overwrite it from the prop on every render to avoid clobbering a// freshly-chosen name before the parent has caught up.const srcRef = useRef(src);// Sync srcRef whenever the incoming `src` prop changes from outside.// After an internal rename, we already set srcRef to the new name and// asked the parent to lift it; when the parent's state arrives here// the values match and this is a no-op.if (src !== srcRef.current) {srcRef.current = src;}const userIdRef = useRef(userId);userIdRef.current = userId;const onRenameRef = useRef(onRename);onRenameRef.current = onRename;// Guard: only allow sendAutomaticallyWhen AFTER the user has sent at// least one message in this session. Prevents auto-send on mount when2 unmodified linesconst getEmbedContext = useCallback(() => {if (!embedStore || !srcRef.current) return {};const currentSrc = srcRef.current;const embedHtml = embedStore.get(currentSrc);const isBanner = currentSrc === "banner.html";// A "scratch" file is a newly-created placeholder whose name is a// hash-based auto-generated slug (see SlashMenu). When the chart is// still empty under such a name, we explicitly ask the agent to// pick a descriptive filename on the first createEmbed call.const isScratch =!isBanner && !embedHtml && /^d3-chart-[a-z0-9]+\.html$/i.test(currentSrc);const dataFiles = dataStore? dataStore.list().map((m) => ({name: m.name,ext: m.ext,size: m.size,rowCount: m.rowCount,columns: m.columns,})): [];return {embedHtml: embedHtml || undefined,isBanner,isScratch,dataFiles,};}, [embedStore, dataStore]);const executeToolCall = useCallback((toolCall: { toolName: string; args: unknown; toolCallId: string }) => {3 unmodified linesswitch (toolCall.toolName) {case "createEmbed": {const { html, title, filename } = toolCall.args as {html: string;title?: string;source?: string;filename?: string;};if (!html?.trim()) return "ERROR: html cannot be empty";const stripped = html.trim();if (stripped.length > MAX_EMBED_SIZE) {return `ERROR: chart too large (${stripped.length} bytes, max ${MAX_EMBED_SIZE}). Simplify the code.`;}// Resolve the target src: if the agent proposed a filename// slug, slugify + ensure uniqueness. Never rename the banner// (its name is load-bearing for the article layout).let targetSrc = currentSrc;const isBanner = currentSrc === "banner.html";if (filename && !isBanner) {const slug = slugify(filename);const candidate = ensureUniqueFilename(slug, embedStore, currentSrc);if (candidate !== currentSrc) {targetSrc = candidate;}}if (targetSrc !== currentSrc) {// Write html under the new key and remove the old one atomically.embedStore.set(targetSrc, stripped);embedStore.remove(currentSrc);// Migrate persisted chat messages so the localStorage scope// tracks the new file name.try {const uid = userIdRef.current;const existing = loadMessages(uid, scopeKey(currentSrc));if (existing && existing.length > 0) {saveMessages(uid, scopeKey(targetSrc), existing);}saveMessages(uid, scopeKey(currentSrc), []);} catch {// Non-fatal: persistence is best-effort.}srcRef.current = targetSrc;// Let the parent update the htmlEmbed node's src attribute// in the ProseMirror doc and lift the new src into state.onRenameRef.current?.(currentSrc, targetSrc);} else {embedStore.set(currentSrc, stripped);}const lines = stripped.split("\n").length;const renamed = targetSrc !== currentSrc ? ` [renamed to ${targetSrc}]` : "";return `chart created (${lines} lines, ${stripped.length} chars)${title ? ` - "${title}"` : ""}${renamed}`;}case "patchEmbed": {28 unmodified linesreturn current;}case "listDataFiles": {if (!dataStore) return "(no data files - data store unavailable)";const files = dataStore.list();if (files.length === 0) return "(no data files attached)";return files.map((f) => {const cols = f.columns && f.columns.length > 0? ` columns=[${f.columns.join(", ")}]`: "";const rows = f.rowCount !== undefined ? ` rows=${f.rowCount}` : "";return `- ${f.name} (${f.ext}, ${f.size} bytes)${rows}${cols}`;}).join("\n");}case "readDataFile": {if (!dataStore) return "ERROR: data store unavailable";const { name } = toolCall.args as { name: string };if (!name) return "ERROR: missing file name";const file = dataStore.get(name);if (!file) return `ERROR: data file "${name}" not found`;const content = file.content;if (content.length <= MAX_DATA_INLINE) return content;return (content.slice(0, MAX_DATA_INLINE) +`\n\n[TRUNCATED - full file is ${content.length} chars, showing first ${MAX_DATA_INLINE}]`);}default:return `Unknown tool: ${toolCall.toolName}`;}},[embedStore, dataStore],);const { addToolOutput, setMessages: chatSetMessages, ...chat } = useChat({
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109import { useCallback, useEffect, useState } from "react";import type { EmbedDataFile, EmbedDataFileMeta, EmbedDataStore,} from "../editor/embeds/embed-data-store";import { MAX_DATA_FILE_SIZE, extFromName, inferDataShape, isAcceptedExt,} from "../utils/data-files";
interface UseEmbedDataOptions { dataStore: EmbedDataStore | null; userId: string;}
export interface UploadResult { ok: boolean; name?: string; error?: string;}
export function useEmbedData({ dataStore, userId }: UseEmbedDataOptions) { const [files, setFiles] = useState<EmbedDataFileMeta[]>(() => dataStore ? dataStore.list() : [], );
useEffect(() => { if (!dataStore) { setFiles([]); return; } setFiles(dataStore.list()); return dataStore.observe(() => { setFiles(dataStore.list()); }); }, [dataStore]);
const uploadFile = useCallback( async (file: File): Promise<UploadResult> => { if (!dataStore) return { ok: false, error: "Data store not ready" }; if (file.size > MAX_DATA_FILE_SIZE) { return { ok: false, error: `File too large (max ${(MAX_DATA_FILE_SIZE / (1024 * 1024)).toFixed(0)} MB)`, }; } const ext = extFromName(file.name); if (!isAcceptedExt(ext)) { return { ok: false, error: `Unsupported file type ".${ext}". Use CSV, TSV, JSON, NDJSON or TXT.`, }; }
const content = await file.text(); const shape = inferDataShape(ext, content); const record: EmbedDataFile = { meta: { name: file.name, ext, size: new Blob([content]).size, uploader: userId, addedAt: Date.now(), rowCount: shape.rowCount, columns: shape.columns, }, content, }; dataStore.set(record); return { ok: true, name: file.name }; }, [dataStore, userId], );
const uploadFiles = useCallback( async (fileList: FileList | File[]): Promise<UploadResult[]> => { const arr = Array.from(fileList); const results: UploadResult[] = []; for (const f of arr) { results.push(await uploadFile(f)); } return results; }, [uploadFile], );
const removeFile = useCallback( (name: string) => { dataStore?.remove(name); }, [dataStore], );
const getFile = useCallback( (name: string) => dataStore?.get(name), [dataStore], );
return { files, uploadFile, uploadFiles, removeFile, getFile, };}173 unmodified lines174175176177178179180181182183119 unmodified lines30330430530630730829 unmodified lines338339340173 unmodified linesborder-radius: 6px;color: var(--muted-color);margin-top: 4px;}.es-message__tool-name {font-weight: 600;}.es-message__tool-status--running {119 unmodified linesflex: 1;position: relative;overflow: hidden;}.es-hidden {29 unmodified linesword-break: break-all;color: var(--text-color);}173 unmodified lines174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204119 unmodified lines32432532632732832933033133233333433533633733833934034134234329 unmodified lines373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728173 unmodified linesborder-radius: 6px;color: var(--muted-color);margin-top: 4px;max-width: 100%;}.es-message__tool-name {font-weight: 600;white-space: nowrap;}.es-message__tool-subtitle {font-family: var(--font-mono);font-size: 10.5px;opacity: 0.75;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;max-width: 180px;}.es-message__tool--running {color: var(--primary-color);background: color-mix(in srgb, var(--primary-color) 12%, var(--code-bg));}.es-message__tool--done {color: var(--success-color, var(--muted-color));}.es-message__tool-status--running {119 unmodified linesflex: 1;position: relative;overflow: hidden;/* The iframe body is set to `background: transparent` by build-doc,so whatever sits behind the iframe is what actually shows. Pin thecontainer to --page-bg so the preview tracks the theme instead offalling through to the browser's default white. */background: var(--page-bg);}.es-preview__frame-container iframe {/* Some browsers paint a default white canvas on `srcdoc` iframesbefore the document's own <style> applies. Forcing the elementitself to transparent lets --page-bg show through, which keepsdark mode clean while the chart is (re)loading. */background: transparent;color-scheme: light dark;}.es-hidden {29 unmodified linesword-break: break-all;color: var(--text-color);}/* --- Files sidebar (far left) --- */.es-files {width: 240px;min-width: 220px;max-width: 260px;display: flex;flex-direction: column;border-right: 1px solid var(--border-color);background: var(--surface-bg);overflow-y: auto;}.es-files__section {display: flex;flex-direction: column;padding: 10px 12px 14px;border-bottom: 1px solid var(--border-color);}.es-files__section:last-child {border-bottom: none;}.es-files__section-title {display: flex;align-items: center;gap: 6px;text-transform: uppercase;font-size: 10.5px;font-weight: 700;letter-spacing: 0.06em;color: var(--muted-color);margin-bottom: 8px;}.es-files__count {margin-left: auto;font-size: 10.5px;font-weight: 600;color: var(--muted-color);background: var(--code-bg);padding: 1px 6px;border-radius: 10px;}.es-files__list {list-style: none;margin: 0 0 8px;padding: 0;display: flex;flex-direction: column;gap: 2px;}.es-files__empty {font-size: 11.5px;color: var(--muted-color);padding: 4px 0 6px;font-style: italic;}.es-files__item {display: flex;align-items: center;gap: 6px;padding: 5px 8px;border-radius: 6px;font-size: 12px;color: var(--text-color);min-width: 0;}.es-files__item--current {background: color-mix(in srgb, var(--primary-color) 14%, transparent);color: var(--text-color);}.es-files__item--data {padding: 0;overflow: hidden;}.es-files__item-main {flex: 1;display: flex;align-items: center;gap: 6px;background: transparent;border: none;padding: 5px 8px;font-size: 12px;color: inherit;cursor: pointer;text-align: left;min-width: 0;border-radius: 6px;}.es-files__item-main:hover {background: var(--code-bg);}.es-files__item--current .es-files__item-main:hover {background: color-mix(in srgb, var(--primary-color) 20%, transparent);}.es-files__name {flex: 1;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;min-width: 0;}.es-files__size {font-size: 10.5px;color: var(--muted-color);font-variant-numeric: tabular-nums;}.es-files__badge {font-size: 9.5px;text-transform: uppercase;letter-spacing: 0.06em;font-weight: 700;color: var(--primary-color);background: var(--page-bg);padding: 1px 5px;border-radius: 10px;}.es-files__item-remove {background: transparent;border: none;color: var(--muted-color);cursor: pointer;padding: 4px 8px;display: flex;align-items: center;opacity: 0;transition: opacity 120ms ease, color 120ms ease;}.es-files__item--data:hover .es-files__item-remove {opacity: 1;}.es-files__item-remove:hover {color: var(--danger-color, #e44);}.es-files__error {display: flex;align-items: center;gap: 6px;margin-top: 6px;padding: 6px 8px;font-size: 11.5px;color: var(--danger-color, #e44);background: color-mix(in srgb, var(--danger-color, #e44) 10%, transparent);border-radius: 6px;}/* --- Upload zone --- */.es-upload-zone {display: flex;align-items: center;justify-content: center;gap: 8px;padding: 14px 10px;margin-top: 4px;border: 1.5px dashed var(--border-color);border-radius: 8px;color: var(--muted-color);font-size: 12px;cursor: pointer;transition: background 120ms ease, border-color 120ms ease, color 120ms ease;text-align: center;flex-direction: column;}.es-upload-zone:hover,.es-upload-zone:focus-visible {border-color: var(--primary-color);color: var(--text-color);background: color-mix(in srgb, var(--primary-color) 6%, transparent);outline: none;}.es-upload-zone--active {border-color: var(--primary-color);background: color-mix(in srgb, var(--primary-color) 12%, transparent);color: var(--text-color);}.es-upload-zone--compact {flex-direction: row;padding: 8px 10px;font-size: 11.5px;}.es-upload-zone__text {display: flex;flex-direction: column;gap: 2px;align-items: center;}.es-upload-zone__text strong {color: var(--text-color);font-size: 12.5px;font-weight: 600;}.es-upload-zone__text span {font-size: 10.5px;color: var(--muted-color);}/* --- Data file viewer --- */.es-data-viewer {position: absolute;inset: 0;display: flex;flex-direction: column;background: var(--page-bg);z-index: 3;}.es-preview {position: relative;}.es-data-viewer__header {display: flex;align-items: center;gap: 12px;padding: 8px 12px;border-bottom: 1px solid var(--border-color);background: var(--surface-bg);flex-shrink: 0;}.es-data-viewer__title {display: flex;flex-direction: column;gap: 2px;min-width: 0;}.es-data-viewer__title strong {font-size: 13px;font-weight: 600;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}.es-data-viewer__meta {font-size: 11px;color: var(--muted-color);font-variant-numeric: tabular-nums;}.es-data-viewer__actions {margin-left: auto;display: flex;align-items: center;gap: 8px;}.es-data-viewer__tabs {display: flex;gap: 2px;}.es-data-viewer__body {flex: 1;overflow: auto;padding: 12px;min-height: 0;}.es-data-viewer__raw {margin: 0;padding: 12px 14px;background: var(--code-bg);border-radius: 6px;font-family: var(--font-mono);font-size: 12px;line-height: 1.6;color: var(--text-color);overflow-x: auto;white-space: pre;}.es-data-table-wrap {border: 1px solid var(--border-color);border-radius: 6px;overflow: auto;}.es-data-table {width: 100%;border-collapse: collapse;font-family: var(--font-mono);font-size: 11.5px;}.es-data-table th,.es-data-table td {padding: 6px 10px;border-right: 1px solid var(--border-color);border-bottom: 1px solid var(--border-color);text-align: left;vertical-align: top;max-width: 280px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}.es-data-table th:last-child,.es-data-table td:last-child {border-right: none;}.es-data-table thead th {position: sticky;top: 0;background: var(--surface-bg);font-weight: 600;color: var(--text-color);z-index: 1;}.es-data-table tbody tr:nth-child(even) {background: color-mix(in srgb, var(--border-color) 20%, transparent);}.es-data-table__footer {padding: 8px 12px;font-size: 11px;color: var(--muted-color);border-top: 1px solid var(--border-color);background: var(--surface-bg);font-style: italic;text-align: center;}
43 unmodified lines4445464748495051525354555657585943 unmodified linesborder: 1px solid var(--border-color);border-radius: 10px;padding: 0.35rem;min-width: 220px;box-shadow: var(--shadow-lg);overflow: hidden;}.slash-menu-item {display: flex;align-items: center;gap: 0.75rem;padding: 0.5rem 0.65rem;border-radius: 6px;cursor: pointer;transition: background 0.1s;43 unmodified lines444546474849505152535455565758596061626364656667686970717273747576777843 unmodified linesborder: 1px solid var(--border-color);border-radius: 10px;padding: 0.35rem;min-width: 280px;max-width: 340px;max-height: 360px;overflow-y: auto;box-shadow: var(--shadow-lg);}.slash-menu-group + .slash-menu-group {margin-top: 0.25rem;padding-top: 0.35rem;border-top: 1px solid var(--border-color);}.slash-menu-section {font-size: 0.65rem;font-weight: 600;letter-spacing: 0.06em;text-transform: uppercase;color: var(--muted-color);padding: 0.35rem 0.65rem 0.25rem;user-select: none;pointer-events: none;}.slash-menu-item {display: flex;align-items: center;gap: 0.75rem;padding: 0.45rem 0.6rem;border-radius: 6px;cursor: pointer;transition: background 0.1s;
12 unmodified lines13141516171815 unmodified lines3435363738394041424344456 unmodified lines52535455565712 unmodified linestoolName: string;/** "result" when the call has produced output, otherwise the in-flight state. */state: string;result?: unknown;}15 unmodified linesif (type === "tool-invocation") {const inv = anyPart.toolInvocation as| { toolName?: string; state?: string; result?: unknown }| undefined;if (!inv?.toolName) return null;return {toolName: inv.toolName,state: inv.state ?? "call",result: inv.result,};}6 unmodified linesreturn {toolName,state: normalized,result: anyPart.output,};}12 unmodified lines131415161718192015 unmodified lines363738394041424344454647486 unmodified lines5556575859606112 unmodified linestoolName: string;/** "result" when the call has produced output, otherwise the in-flight state. */state: string;/** Arguments passed to the tool (v5: part.toolInvocation.args, v6: part.input). */input?: unknown;result?: unknown;}15 unmodified linesif (type === "tool-invocation") {const inv = anyPart.toolInvocation as| { toolName?: string; state?: string; args?: unknown; result?: unknown }| undefined;if (!inv?.toolName) return null;return {toolName: inv.toolName,state: inv.state ?? "call",input: inv.args,result: inv.result,};}6 unmodified linesreturn {toolName,state: normalized,input: anyPart.input,result: anyPart.output,};}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145import type { EmbedDataFileMeta } from "../editor/embeds/embed-data-store";
/** * Light-weight client-side parsing of uploaded data files. Extracts * column names and row counts so the sidebar and agent system prompt * can preview dataset shape without shipping the full content every * time. * * Parsing is deliberately forgiving: it never throws on malformed * input, and returns `undefined` metadata fields when shape cannot be * inferred. */
export const ACCEPTED_DATA_EXTS = ["csv", "tsv", "json", "txt", "ndjson"] as const;export type AcceptedDataExt = (typeof ACCEPTED_DATA_EXTS)[number];
export const MAX_DATA_FILE_SIZE = 3 * 1024 * 1024;
export function extFromName(name: string): string { const match = name.toLowerCase().match(/\.([a-z0-9]+)$/); return match ? match[1] : "";}
export function isAcceptedExt(ext: string): ext is AcceptedDataExt { return (ACCEPTED_DATA_EXTS as readonly string[]).includes(ext);}
function splitCsvLine(line: string, delim: string): string[] { const out: string[] = []; let cur = ""; let inQuotes = false; for (let i = 0; i < line.length; i++) { const c = line[i]; if (inQuotes) { if (c === '"') { if (line[i + 1] === '"') { cur += '"'; i++; } else { inQuotes = false; } } else { cur += c; } } else if (c === '"') { inQuotes = true; } else if (c === delim) { out.push(cur); cur = ""; } else { cur += c; } } out.push(cur); return out;}
interface ParsedShape { rowCount?: number; columns?: string[];}
function parseDelimited(content: string, delim: string): ParsedShape { const lines = content .split(/\r\n|\n|\r/) .filter((l) => l.length > 0); if (lines.length === 0) return {}; const header = splitCsvLine(lines[0], delim).map((c) => c.trim()); return { columns: header, rowCount: Math.max(0, lines.length - 1), };}
function parseJson(content: string): ParsedShape { try { const parsed = JSON.parse(content); if (Array.isArray(parsed)) { const first = parsed.find((r) => r && typeof r === "object"); return { rowCount: parsed.length, columns: first ? Object.keys(first as Record<string, unknown>) : undefined, }; } if (parsed && typeof parsed === "object") { return { columns: Object.keys(parsed as Record<string, unknown>) }; } } catch { // swallow - return empty shape } return {};}
function parseNdjson(content: string): ParsedShape { const lines = content.split(/\r\n|\n|\r/).filter((l) => l.trim().length > 0); if (lines.length === 0) return {}; let columns: string[] | undefined; try { const first = JSON.parse(lines[0]); if (first && typeof first === "object" && !Array.isArray(first)) { columns = Object.keys(first as Record<string, unknown>); } } catch { // ignore } return { rowCount: lines.length, columns };}
export function inferDataShape(ext: string, content: string): ParsedShape { switch (ext) { case "csv": return parseDelimited(content, ","); case "tsv": return parseDelimited(content, "\t"); case "json": return parseJson(content); case "ndjson": return parseNdjson(content); default: return {}; }}
/** * Build a lightweight manifest line per file suitable for inclusion in * the agent system prompt. Keeps it to one line per file so many * datasets can coexist without exploding prompt size. */export function formatManifestLine(meta: EmbedDataFileMeta): string { const size = formatBytes(meta.size); const shape = meta.rowCount !== undefined ? ` - ${meta.rowCount} rows` : ""; const cols = meta.columns && meta.columns.length > 0 ? ` - columns: ${meta.columns.slice(0, 12).join(", ")}${meta.columns.length > 12 ? ", ..." : ""}` : ""; return `- ${meta.name} (${meta.ext.toUpperCase()}, ${size}${shape})${cols}`;}
export function formatBytes(bytes: number): string { if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;}