# Agent Comments Source: https://velt.dev/docs/ai/agent-comments Let your AI agents leave comments and findings directly in Velt by calling the Comments REST APIs. ## Overview Agent comments let your AI agents participate in collaboration the same way humans do: by leaving comments and findings anchored to a document. Instead of building a separate UI for agent output, your agent calls the same REST APIs that power the [Comments](/docs/async-collaboration/comments/overview) feature, and the findings render in the standard Velt comments experience. Any agent that can make an HTTP request can do this: a custom agent you create with the [Review Agents API](/docs/api-reference/rest-apis/v2/agents/create), or an external agent running in your own framework (LangChain, CrewAI, a cron job, etc.). ## How it works 1. **Your agent runs** and produces a finding (a spelling error, an accessibility issue, a code-review note, etc.). 2. **Your agent calls the [Add Comment Annotations API](/docs/api-reference/rest-apis/v2/comments-feature/comment-annotations/add-comment-annotations)** with an `agent` block attached to the root comment. 3. **The finding renders in Velt** as a [suggestion](/docs/async-collaboration/suggestions/overview) with **Accept** and **Reject** buttons that humans can review. 4. **Your app reacts to the outcome**: read agent comments back with the [Get Comment Annotations API](/docs/api-reference/rest-apis/v2/comments-feature/comment-annotations/get-comment-annotations-v2), or subscribe to the `suggestionAccepted` / `suggestionRejected` events in your frontend. ## Properties * An agent comment is a regular comment annotation with an `agent` block attached to its root comment. There is no separate agent-comments API or data store. You add, read, update, and delete agent comments with the same [Comment Annotations and Comments REST APIs](#backend-apis). * When you attach an `agent` block to the root comment (`commentData[0]`), the server stamps `sourceType: "agent"` on both that comment and the annotation, and generates the annotation-level `agent` block. When you attach it to a reply instead, only that comment is marked as agent-authored; the annotation root stays a normal comment. * Set the annotation `type` to `"suggestion"` so the finding is classified as an agent suggestion and renders with **Accept** / **Reject** buttons instead of as a regular comment. * Agent comments support two origins: `velt` (a built-in agent like `spell-check`, or a custom agent you create with the [Review Agents API](/docs/api-reference/rest-apis/v2/agents/create); the `agentId` is verified server-side) and `external` (an agent running in your own framework, where the `agentName` you supply is the source of truth). * When a reviewer accepts or rejects a finding, the outcome is emitted on the comment element as the `suggestionAccepted` / `suggestionRejected` events, so you can apply the change to your own data or trigger follow-up logic. ## APIs ### Backend APIs #### Add Agent Comments * Add an agent comment using the Add Comment Annotations REST API. Attach an `agent` block to the root comment (`commentData[0]`) and set the annotation `type` to `"suggestion"`. [Learn more](/docs/api-reference/rest-apis/v2/comments-feature/comment-annotations/add-comment-annotations) * See [The agent object](#the-agent-object) below for all the fields you can send. The most common path is an agent running in your own framework. Use `agentSource: "external"` and supply your own `agentName`: ```bash cURL expandable theme={null} curl -X POST 'https://api.velt.dev/v2/commentannotations/add' \ -H 'x-velt-api-key: YOUR_API_KEY' \ -H 'x-velt-auth-token: YOUR_AUTH_TOKEN' \ -H 'Content-Type: application/json' \ -d '{ "data": { "organizationId": "acme-corp", "documentId": "design-mockup-v2", "commentAnnotations": [ { "type": "suggestion", "commentData": [ { "commentText": "This button has insufficient color contrast.", "from": { "userId": "a11y-bot" }, "agent": { "agentSource": "external", "agentName": "Accessibility Bot", "agentId": "a11y-bot", "executionId": "run_8f21", "url": "https://example.com/design-mockup-v2", "reason": { "title": "Low color contrast", "description": "Contrast ratio is 2.1:1, below the 4.5:1 WCAG AA threshold.", "severity": "high", "findingType": "pin" } } } ] } ] } }' ``` ```javascript Node.js expandable theme={null} const response = await fetch('https://api.velt.dev/v2/commentannotations/add', { method: 'POST', headers: { 'x-velt-api-key': process.env.VELT_API_KEY, 'x-velt-auth-token': process.env.VELT_AUTH_TOKEN, 'Content-Type': 'application/json', }, body: JSON.stringify({ data: { organizationId: 'acme-corp', documentId: 'design-mockup-v2', commentAnnotations: [ { type: 'suggestion', commentData: [ { commentText: 'This button has insufficient color contrast.', from: { userId: 'a11y-bot' }, agent: { agentSource: 'external', agentName: 'Accessibility Bot', agentId: 'a11y-bot', executionId: 'run_8f21', url: 'https://example.com/design-mockup-v2', reason: { title: 'Low color contrast', description: 'Contrast ratio is 2.1:1, below the 4.5:1 WCAG AA threshold.', severity: 'high', findingType: 'pin', }, }, }, ], }, ], }, }), }); const result = await response.json(); ``` ```python Python expandable theme={null} import os import requests response = requests.post( "https://api.velt.dev/v2/commentannotations/add", headers={ "x-velt-api-key": os.environ["VELT_API_KEY"], "x-velt-auth-token": os.environ["VELT_AUTH_TOKEN"], "Content-Type": "application/json", }, json={ "data": { "organizationId": "acme-corp", "documentId": "design-mockup-v2", "commentAnnotations": [ { "type": "suggestion", "commentData": [ { "commentText": "This button has insufficient color contrast.", "from": {"userId": "a11y-bot"}, "agent": { "agentSource": "external", "agentName": "Accessibility Bot", "agentId": "a11y-bot", "executionId": "run_8f21", "url": "https://example.com/design-mockup-v2", "reason": { "title": "Low color contrast", "description": "Contrast ratio is 2.1:1, below the 4.5:1 WCAG AA threshold.", "severity": "high", "findingType": "pin", }, }, } ], } ], } }, ) result = response.json() ``` > [!TIP] > > For a built-in agent or a custom agent created with the [Review Agents API](/docs/api-reference/rest-apis/v2/agents/create), use `agentSource: "velt"` and pass its `agentId` instead. The agent's name is resolved server-side. #### Reply as an Agent * Add an agent-authored reply to an existing comment annotation using the Add Comments REST API with an `agent` block on the comment. [Learn more](/docs/api-reference/rest-apis/v2/comments-feature/comments/add-comments) * Annotation-level fields such as `type` are set when the annotation is created. They are not accepted on this endpoint. #### Get Agent Comments * Get agent comments using the Get Comment Annotations REST API with agent-specific filters. [Learn more](/docs/api-reference/rest-apis/v2/comments-feature/comment-annotations/get-comment-annotations-v2) * Only one agent filter may be supplied per request. | Filter | Description | | - | - | | `agentId` | Annotations created by a specific agent. | | `executionId` | Annotations from a specific agent run. Also returns comments from up to 29 earlier runs whose findings this run kept unchanged. | | `agentType` | Annotations of a given agent type: `built-in`, `custom`, or `external`. | | `agentSource` | `velt` or `external`. | | `agentSuggestions` | When `true`, returns only fresh (unaccepted) agent suggestions. | | `agentComments` | When `true`, returns all agent annotations regardless of status. | ```bash cURL theme={null} curl -X POST 'https://api.velt.dev/v2/commentannotations/get' \ -H 'x-velt-api-key: YOUR_API_KEY' \ -H 'x-velt-auth-token: YOUR_AUTH_TOKEN' \ -H 'Content-Type: application/json' \ -d '{ "data": { "organizationId": "acme-corp", "documentId": "design-mockup-v2", "agentId": "a11y-bot" } }' ``` * Agent annotations in the response carry `type: "suggestion"` and `sourceType: "agent"` at the annotation root, an annotation-root `agent` block, and an `agent` block on each agent-authored comment (`comments[].agent`). * To retrieve individual comments within a specific annotation, use the Get Comments REST API. [Learn more](/docs/api-reference/rest-apis/v2/comments-feature/comments/get-comments) #### Update Agent Comments * Update annotation-level fields (status, assignee, location, etc.) using the Update Comment Annotations REST API. [Learn more](/docs/api-reference/rest-apis/v2/comments-feature/comment-annotations/update-comment-annotations) * Update the content of individual comments within an annotation using the Update Comments REST API. [Learn more](/docs/api-reference/rest-apis/v2/comments-feature/comments/update-comments) #### Delete Agent Comments * Delete entire agent comment threads using the Delete Comment Annotations REST API. Filter by `annotationIds` or `userIds` (e.g. your agent's user ID), or use the combinable agent filters — `agentId`, `agentSuggestions`, and `agentUrls` — to delete e.g. one agent's still-pending suggestions for specific pages. [Learn more](/docs/api-reference/rest-apis/v2/comments-feature/comment-annotations/delete-comment-annotations) * Delete individual comments within a thread using the Delete Comments REST API. [Learn more](/docs/api-reference/rest-apis/v2/comments-feature/comments/delete-comments) ### Frontend APIs #### Handle Accept / Reject Events Because agent findings render with **Accept** and **Reject** buttons on the comment dialog, the outcome is emitted on the **comment element**. Subscribe to the [`suggestionAccepted` and `suggestionRejected` events](/docs/async-collaboration/comments/customize-behavior#event-subscription) to apply the change to your own data or trigger follow-up logic. The SDK records the outcome and persists the suggestion. Applying the change is your code's job. ```tsx React theme={null} import { useEffect } from 'react'; import { useCommentEventCallback } from '@veltdev/react'; export function AgentSuggestionListener() { const accepted = useCommentEventCallback('suggestionAccepted'); const rejected = useCommentEventCallback('suggestionRejected'); useEffect(() => { if (accepted) { // accepted.commentAnnotation contains the agent finding console.log('Suggestion accepted', accepted.commentAnnotation); } }, [accepted]); useEffect(() => { if (rejected) { console.log('Suggestion rejected', rejected.rejectReason); } }, [rejected]); return null; } ``` ```javascript Other Frameworks theme={null} const commentElement = Velt.getCommentElement(); commentElement.on('suggestionAccepted').subscribe(({ commentAnnotation }) => { // commentAnnotation contains the agent finding console.log('Suggestion accepted', commentAnnotation); }); commentElement.on('suggestionRejected').subscribe(({ commentAnnotation, rejectReason }) => { console.log('Suggestion rejected', rejectReason); }); ``` > [!TIP] > > For the full suggestion lifecycle (statuses, applying `newValue`, and the other suggestion-stream events), see the [Suggestions](/docs/async-collaboration/suggestions/overview) guide. ## The agent object Attach an `agent` object to the root comment (`commentData[0]`) when [adding an agent comment](#add-agent-comments), or to any comment when [replying as an agent](#reply-as-an-agent). It is discriminated on `agentSource`: | Field | Required | Description | | - | - | - | | `agentSource` | Yes | Origin of the agent. One of `velt` or `external`. | | `agentId` | Yes | The agent's ID. Must be non-empty. Verified server-side for `velt` agents; opaque (never validated) for `external` agents. | | `agentName` | Required for `external` | Display name for the agent. The only source of truth for an external agent's name. (For `velt` agents the name is resolved server-side.) | | `executionId` | No | Execution / run ID for this agent invocation. | | `url` | No | Page URL associated with the finding. | | `reason` | Yes | Finding details (`title`, `description`, `severity`, `findingType`, `confidence`, `suggestedFix`, etc.). Custom fields are preserved. | ### The reason object The `reason` object carries the finding's details. Here's each field with a description and an example value. | Field | Required | Type | Description | Example | | - | - | - | - | - | | `title` | Yes | string | Short finding title, used as a quick label for the issue. | `"Low color contrast"` | | `description` | Yes | string | Fuller explanation of what the agent found. | `"Contrast ratio is 2.1:1, below the 4.5:1 WCAG AA threshold."` | | `severity` | Yes | string | How serious the finding is. One of `critical`, `high`, `medium`, `low`, `info`. | `"high"` | | `findingId` | No | string | Your own unique ID for the finding, useful for dedup/tracking. | `"finding_a11y_0427"` | | `findingType` | No | string | What kind of target the finding is on. One of `text`, `pin`, `page`. | `"pin"` | | `issueType` | No | string | Custom classification you define for your own taxonomy. | `"accessibility"` | | `confidence` | No | number | How confident the agent is. Integer 0–100. | `92` | | `suggestion` | No | string | Suggested change in plain text (human-readable advice). | `"Darken the button background to at least #1A1A1A."` | | `suggestedFix` | No | string | The concrete fix value to apply. | `"#1A1A1A"` | | `htmlSnippet` | No | string | The relevant chunk of HTML where the issue lives. | `""` | | `htmlSelector` | No | string | CSS/HTML selector pointing to the finding's location. | `".cta-primary > button"` | | `source` | No | string | Where the triggering rule came from. One of `instructions`, `knowledge`. | `"knowledge"` | | `knowledgeSection` | No | string | Which knowledge section fired (pairs with `source: "knowledge"`). | `"brand-guidelines/accessibility"` | > [!NOTE] > > Don't conflate the two "fix" fields: `suggestion` is prose meant for a human to read in the comment, while `suggestedFix` is the actual replacement value your code applies. In the color-contrast example above, `suggestion` explains the change ("Darken the button background to at least #1A1A1A.") while `suggestedFix` is just the value itself (`"#1A1A1A"`). Putting it together, a fully-populated `reason` looks like: ```json theme={null} "reason": { "title": "Low color contrast", "description": "Contrast ratio is 2.1:1, below the 4.5:1 WCAG AA threshold.", "severity": "high", "findingId": "finding_a11y_0427", "findingType": "pin", "issueType": "accessibility", "confidence": 92, "suggestion": "Darken the button background to at least #1A1A1A.", "suggestedFix": "#1A1A1A", "htmlSnippet": "", "htmlSelector": ".cta-primary > button", "source": "knowledge", "knowledgeSection": "brand-guidelines/accessibility" } ``` Only the first three (`title`, `description`, `severity`) are required. Everything else is optional, and any extra custom fields you add beyond this list are preserved by the server. # Review Agents Source: https://velt.dev/docs/ai/agents/overview Build review agents for your product that review web pages, data, charts, and anything else you can surface via API or MCP, then create findings as comment annotations. ## What are review agents? Build review agents for your product. Point an agent at a URL, and it reviews the content and posts findings as comment annotations. Review agents can review anything you can surface: * **Web pages and sites**: text, screenshots, HTML, CSS, links, accessibility tree, Lighthouse. * **Your data**: pull any REST endpoint into the review with the `rest-api` strategy. * **Charts, dashboards, and more**: anything you can expose via an API or MCP server. You write a prompt and pick a few config options. The platform handles context gathering, LLM invocation, post-processing, deduplication, and annotation creation. You can also put agent creation in your users' hands: ship the [built-in agents](#built-in-agents) as defaults, and let users create custom agents in plain English from your UI. The [prompt tools](/docs/api-reference/rest-apis/v2/agents/prompt/enhance) turn a one-line instruction into a production agent config. ## What you get * **Built-in and custom agents.** Ready-made agents (Proofreader, Link Checker, Image Inspector, Mobile Inspector, Consistency Checker, PII, Lighthouse, accessibility, [and more](#built-in-agents)), or your own from a prompt. * **Plain-English agent builder.** Let your users describe a review in simple English; prompt tools ([enhance](/docs/api-reference/rest-apis/v2/agents/prompt/enhance), [validate](/docs/api-reference/rest-apis/v2/agents/prompt/validate), [refine](/docs/api-reference/rest-apis/v2/agents/prompt/refine)) check it, expand it into a full agent config, and iterate on feedback. `userContextFields` render typed inputs in your setup UI. * **Pluggable context gathering.** Stack strategies: page text, screenshots, HTML, CSS, links, accessibility tree, computed styles, robots.txt, sitemap, Lighthouse, live REST API data. * **Live REST API context.** The `rest-api` strategy fetches your endpoints at execution time and injects the responses into the prompt. Secrets are encrypted at rest and redacted on read. * **MCP tool use.** The `mcp-tools` strategy runs a multi-turn tool loop against your remote [MCP](https://modelcontextprotocol.io) servers. Works with Claude and Gemini. * **Versioned configurations.** Every behavioral edit creates a new version; one-click restore rolls back. * **Async execution.** `Run Execution` returns an `executionId` immediately; poll `Get Execution` until `status !== "running"`. * **Cross-page execution.** Set `crossPageExecute: true` to crawl the seed URL and review up to `maxUrlsToProcess` pages. * **Page lists.** Send `urls` to review exactly those pages, with no crawl. Use it for sites whose pages differ only by a query string. * **Several agents, one request.** Send `agentIds` to run up to 10 agents together, on one page or on a list of pages. Each agent still gets its own execution, and each page is loaded once for all of them. * **Focused rechecks.** Set `userContext.focusIssueTypes` to recheck only some [issue types](#issue-types), for example only blurry images. * **Per-run options.** Switch individual checks of a built-in agent off, or tune its thresholds, for one run. See [Per-run options](#per-run-options). * **Device emulation.** Run each execution as `"mobile"` or `"desktop"`. * **Re-run deduplication.** Re-running an agent replaces the prior run's suggestions instead of piling up duplicates. A focused recheck replaces only the suggestions of the issue types it rechecks. * **Token usage analytics.** Per-agent, per-model, per-month token usage via the Analytics endpoint. * **Agent groups.** Bundle related agents (e.g. "Brand QA") and filter lists by group. ## Use cases > [card] Brand consistency > > Verify brand colors, typography, and logo placement across your marketing pages. Re-run on every deploy. > [card] Pre-launch QA > > Run the Proofreader, Link Checker, and accessibility agents before a release. Findings land on the staging document. > [card] Content moderation > > Flag PII and profanity on user-generated pages. Pair with Review Workflow Builder for human review. > [card] Cross-page audit > > Set `crossPageExecute: true` and the crawler discovers internal links, then reviews each page. > [card] Data-enriched checks > > Pull live business data into the prompt with `rest-api`, e.g. validate on-page pricing against your billing API. > [card] Workflow integration > > Trigger an agent from a Review Workflow Builder workflow node and park the workflow on its findings. > [card] User-built agents > > Let your users create review agents in plain English from your UI. Ship built-in agents as defaults; prompt tools turn user instructions into custom ones. > [card] Docs accuracy > > Use `mcp-tools` to verify on-page code snippets live against your documentation MCP server. ## How it works 1. **Define the agent.** Call [Create Agent](/docs/api-reference/rest-apis/v2/agents/create) with a name, instructions, and config (context gathering, execution strategy, post-processing). 2. **Run an execution.** Call [Run Execution](/docs/api-reference/rest-apis/v2/agents/execution/run) with `agentId` and `url`, or with `agentIds` to run several agents on the same pages. Returns an `executionId` per agent immediately. 3. **Poll for results.** Call [Get Execution](/docs/api-reference/rest-apis/v2/agents/execution/get) until `status !== "running"`. Set `includeResults: true` for per-URL findings. 4. **Findings appear as annotations.** Each finding becomes a comment annotation on the document referenced by `organizationId` / `documentId` (on by default). ## Mental model | Concept | Meaning | | - | - | | **Agent** | Reusable review configuration: identity (`name`, `description`, `enabled`) plus behavior (instructions, context gathering, execution, post-processing). Behavioral edits create a new version. | | **Execution** | One run of an agent against a seed URL. Pins the agent `version` at dispatch, so in-flight runs ignore mid-run config changes. | | **Finding** | One issue on one URL: severity, category, target text, suggestion, HTML selector, confidence. Guardrails deduplicate and sanitize findings before annotations are created. | **Execution lifecycle:** ``` running → passed | failed | partial | error | skipped ``` ## Pipeline phases Each agent run executes sequential phases: | Phase | What happens | | - | - | | `validate` | Zod check on payload + input requirements + variable keys | | `extract` | All configured context gathering strategies run | | `execute` | LLM call (or registered service); results normalized to a finding array | | `postProcess` | Guardrails → delete previous suggestions → pin resolution → annotation creation → analytics | | `structureResponse` | Final response assembly with optional response adapter | ## Execution statuses | Status | Meaning | | - | - | | `running` | Execution is in progress | | `passed` | Completed successfully: all URLs processed cleanly, **no findings** | | `failed` | Completed with **findings**: all URLs processed cleanly | | `partial` | Mixed outcome: at least one URL succeeded and at least one URL failed ("passed with some failures") | | `error` | Every processed URL failed, or a fatal crawl/dispatch failure; nothing usable produced | | `skipped` | Execution was skipped (e.g. a precondition was not met) | **Terminal status precedence:** `error` > `partial` > `failed` > `passed`. A run that produced findings but had a single failing page surfaces as `partial` (not `error`). For `partial`/`error`, per-page failure detail is in `resultsSummary.urlsErrored` and `resultsSummary.erroredUrls`. ## Built-in agents Built-in agents are pre-registered for every workspace. Run one by its ID. | Agent ID | Name | Description | | - | - | - | | `spell-check` | Proofreader | Typos, doubled words ("the the"), punctuation slips (",," or a space before a full stop), brand names written with the wrong casing, a term cased two ways on one page, and leftover placeholder text such as lorem ipsum or "Insert headline here". Accepts British spellings and skips spelling on pages not written in English. It does not check grammar: use `grammar-check`. `aiConfig` does not apply to it. | | `grammar-check` | Grammar Check | Grammar checking | | `broken-links` | Link Checker | Every link, button, image, and form on the page: broken links and images, form submits that fail, buttons and links that do nothing when clicked, links to staging, preview, or local hosts, malformed links, a header logo not linked to the home page, phone numbers and emails that are not links, social icons that point at the wrong network, and links that open in the wrong kind of tab. | | `image-inspector` | Image Inspector | Images that do not show, blurry (upscaled) or stretched images, CSS background images included, empty or placeholder image slots, and images without alt text. An optional check for badly cropped photos (a head cut off) sends screenshots of the photos to an AI model, and is off unless you turn it on: see [Image Inspector](#image-inspector). | | `mobile-inspector` | Mobile Inspector | Opens the page at phone width (375 px by default) and tablet width (768 px), and flags a desktop layout shrunk to fit, sideways scrolling, content that runs off the screen, cut-off buttons and text, tap targets that are too small, button labels that wrap, content hidden under sticky bars, a menu button that opens nothing, and links or headings shown on desktop that a phone visitor cannot reach, with phone-width screenshots. To test the menu and sticky bars it taps the menu button and up to 2 same-page links: switch either off with [`skipChecks`](#mobile-inspector). Always runs as `"mobile"`. | | `consistency-checker` | Consistency Checker | Compares phone numbers, addresses, opening hours, emails, prices, and service and business names on the page with other key pages of the same site (6 by default), and flags values that differ: this part uses an AI model. Also flags terms capitalized differently from the rest of the site, on English pages, and buttons and links that look or behave differently from the others on the site, without a model. | | `ai-visibility` | AI Visibility | Scores whether AI answer engines can reach, read, understand, and correctly cite the page, with a fix for every failure. A visible date and author are asked for only on articles, such as blog posts and guides. A help page is asked for a list, table, or question heading. Home, pricing, product, collection, and landing pages, and news and press items, are not asked. See [AI Visibility](#ai-visibility) for its options. | | `migration-parity` | Migration Parity | Compares each page with the same page on your live or old site, and flags what the new page lost: team bios, reviews, FAQ questions, phone numbers, emails, street addresses, list items such as services, a page title, and a main heading. Reworded copy is never reported. Needs `userContext.liveSiteUrl`: see [Migration Parity](#migration-parity). No AI model. | | `content-request-list` | Content Request List | One checklist finding per page of what still waits on the client: empty sections, placeholder text and photos, "Coming soon" lines, short bios, and open comment threads that ask the client for content. See [Content Request List](#content-request-list). No AI model. | | `pii-detection` | PII Detection | PII (personal info) detection | | `profanity-filter` | Profanity Filter | Profanity detection | | `sensitive-data` | Sensitive Data | Sensitive data detection | | `lighthouse` | Lighthouse | Google Lighthouse performance/SEO/a11y audit | | `accessibility-checker` | Accessibility Checker | Accessibility (WCAG) audit | | `og-image-checker` | OG Image Checker | Open Graph image validation | | `lorem-ipsum` | Lorem Ipsum | Placeholder / lorem-ipsum text detection | When a finding comes with an exact correction, such as a corrected spelling or link, the agent puts it in `suggestedFix`. The comment annotation carries it as `agent.reason.suggestedFix`. > [!NOTE] > > Display names can change between releases. Identify agents by their ID. ## Issue types These built-in agents tag every finding with one of a fixed set of `issueType` values. Use them to filter findings, or pass some of them in `userContext.focusIssueTypes` on [Run Execution](/docs/api-reference/rest-apis/v2/agents/execution/run) to recheck only those issues. | Agent ID | Issue types | | - | - | | `spell-check` | `spelling`, `doubled-word`, `punctuation`, `placeholder`, `brand-casing`, `inconsistent-casing` | | `broken-links` | `broken-link`, `broken-image`, `dead-button`, `dead-form`, `staging-link`, `malformed-link`, `unlinked-logo`, `unlinked-phone`, `unlinked-email`, `unlinked-contact`, `social-link-mismatch`, `same-tab-link`, `new-tab-internal-link` | | `image-inspector` | `broken-image`, `empty-image`, `blurry-image`, `stretched-image`, `missing-alt`, `bad-crop` | | `mobile-inspector` | `desktop-layout-on-phone`, `horizontal-scroll`, `overflowing-element`, `overflowing-text`, `cut-off-button`, `cut-off-text`, `small-tap-target`, `wrapped-button-label`, `hidden-under-sticky-bar`, `broken-mobile-menu`, `missing-on-mobile` | | `consistency-checker` | `inconsistent-phone`, `inconsistent-address`, `inconsistent-hours`, `inconsistent-email`, `inconsistent-price`, `inconsistent-service-name`, `inconsistent-business-name`, `cross-page-casing`, `style-mismatch`, `missing-hover`, `hover-invisible` | | `migration-parity` | `missing-bio`, `missing-review`, `missing-faq`, `missing-phone`, `missing-email`, `missing-address`, `missing-list-item`, `missing-page-title`, `missing-main-heading` | | `content-request-list` | `content-requests` | A focused run also skips work that cannot produce the listed issue types. A Mobile Inspector run focused on `small-tap-target` taps neither the menu nor same-page links, and a Consistency Checker run focused only on `cross-page-casing` or the visual issue types (`style-mismatch`, `missing-hover`, `hover-invisible`) makes no model call. > [!TIP] > > To have the Link Checker report broken links only, run it with `userContext.focusIssueTypes` set to `["broken-link"]`. To stop it looking for a kind of problem at all, use its [per-run options](#link-checker). ## Per-run options The built-in agents below read options from the `userContext` of [Run Execution](/docs/api-reference/rest-apis/v2/agents/execution/run). Use them to switch a check off or tune a threshold for one run. Leave a key out to keep its default: the defaults are the agent's normal behavior. The agent ignores a value of the wrong type and applies the default. An empty string or `null` also keeps the default. `0` and `false` are values, not blanks. Each agent reads only its own keys, so a run with `agentIds` can carry options for several agents in one `userContext`: ```JSON theme={null} { "data": { "agentIds": ["broken-links", "spell-check"], "url": "https://example.com/pricing", "organizationId": "org_001", "documentId": "doc_001", "userContext": { "clickTest": false, "brandNames": ["AcmeCloud"], "skipChecks": ["placeholder"] } } } ``` ### Link Checker Options for `broken-links`. | Key | Type | Default | Effect | | - | - | - | - | | `clickTest` | boolean | `true` | Clicks links and buttons in a separate browser session to find controls that do nothing, and to tell a failing link from one the page handles itself. It blocks requests other than `GET`, `HEAD`, and `OPTIONS` and calls to analytics, advertising, and session-recording endpoints, and never clicks a control labeled as destructive or transactional. `false` skips the click test, so the run reports no `dead-button` findings. | | `pageLinkChecks` | boolean | `true` | `false` turns off `checkLogo`, `checkContacts`, `checkSocialIcons`, and `checkTabTargets` together. | | `checkLogo` | boolean | `true` | A header logo that does not link to the home page (`unlinked-logo`). | | `checkContacts` | boolean | `true` | Phone numbers and emails written as plain text (`unlinked-phone`, `unlinked-email`, `unlinked-contact`). | | `checkPhoneNumbers` | boolean | `true` | Phone numbers written as plain text (`unlinked-phone`). `false` keeps the check for plain-text emails only. Has no effect when `checkContacts` is `false`. | | `checkSocialIcons` | boolean | `true` | Social icons that link to a different network (`social-link-mismatch`). | | `checkTabTargets` | boolean | `true` | Links that open in the wrong kind of tab (`same-tab-link`, `new-tab-internal-link`). Any other domain is another site, even a sister brand or another domain you own, so a same-tab link to it is reported. A subdomain of the page's domain is the same site. A same-tab link whose label hands the visitor over to an app or a purchase, such as `Sign in`, `Book now`, or `Checkout`, is not reported. To count other domains as yours, use `ownDomains` or `sameNameIsOwnSite`. | | `ownDomains` | string\[] | `[]` | Your other domains, such as a sister brand or a careers site. A same-tab link to one, or to one of its subdomains, is not reported. Host names or URLs, at most 50. Public suffixes, such as `co.uk` or `vercel.app`, and IP addresses are ignored. | | `sameNameIsOwnSite` | boolean | `false` | `true` counts the same site name of 4 or more letters on another suffix (`brand.jobs` from `brand.com`) and the brand's status-page domain (`brandstatus.com`) as your own site. Never for government, school, or military domains. On by default before October 7, 2026. | | `reportOwnFilesInSameTab` | boolean | `false` | `true` also reports a document on your own site, such as a PDF, a spreadsheet, or an archive, that opens in the same tab (`same-tab-link`). A text file is never reported. | | `checkStagingLinks` | boolean | `true` | Links to staging, preview, or local hosts (`staging-link`). | | `checkMalformedLinks` | boolean | `true` | Links written in a way that cannot work (`malformed-link`). | | `checkImageUrls` | boolean | `true` | Image addresses (`broken-image`). | | `checkFormActions` | boolean | `true` | Form submit endpoints (`dead-form`). | | `checkInternalLinks` | boolean | `true` | Links to the same site. | | `checkExternalLinks` | boolean | `true` | Links to other sites. | | `maxLinksToCheck` | number | `500` | Most links checked per page. Whole number, clamped to 1 to 1000. | | `stagingNoindexSignal` | boolean | `true` | A same-site `dev.`, `qa.`, or `test.` link whose page answers with a `2xx` status and an `X-Robots-Tag: noindex` header counts as a staging link. Never for a link labeled as a sign-in. `false` lets only the words in the host decide. | | `stagingWords` | string\[] | `[]` | Words that mark a staging host wherever they appear in it, such as `beta` or `acc`, on top of the built-in ones (`staging`, `stage`, `stg`, `dev`, `preview`, `uat`, `qa`, `sandbox`, `test`, and a few more). | | `ambiguousStagingWords` | string\[] | `[]` | Words that mark a staging host in a subdomain only next to `www` or another staging word, as `dev` does. | | `notStagingWords` | string\[] | `[]` | Built-in staging words your site uses for something public, such as a public `preview.` subdomain. | | `ignoreOverlaySelectors` | string\[] | `[]` | CSS selectors of overlays your page embeds, such as a review toolbar or a chat widget. A change inside them never counts as the effect of a click. | | `skipClickLabels` | string\[] | `[]` | Labels the click test never clicks, on top of its built-in list of destructive and transactional words. Matched as whole words, in any case and any script. | The three staging word lists take single host words of 2 to 30 letters or digits, at most 50 per list. `ignoreOverlaySelectors` and `skipClickLabels` take at most 20 entries, of at most 200 and 60 characters. Other entries are ignored. During the click test, a click that opens a new tab, starts a download, or hands off to an app counts as working. A page that builds its content from data queries the test refuses, such as GraphQL, is not judged for dead controls. ### Proofreader Options for `spell-check`. The Proofreader finds candidates with a dictionary and rules, then asks a verification model to confirm the ones the rules are not certain of. If the model cannot answer, the run still reports the findings the rules are certain of, and its summary says what could not be checked. | Key | Type | Default | Effect | | - | - | - | - | | `rulesOnly` | boolean | `false` | Sends no page text to the verification model. Only findings the rules are certain of are reported. Spelling is not checked, and the run summary says so. | | `acceptedWords` | string\[] | `[]` | Words to accept as correctly spelled, in any case, on top of the built-in list. | | `brandNames` | string\[] | `[]` | Brand names and their exact casing, on top of the built-in list. Your casing wins over the built-in one. | | `skipChecks` | string\[] | `[]` | Issue types not to look for: any of `spelling`, `doubled-word`, `punctuation`, `placeholder`, `brand-casing`, `inconsistent-casing`. | | `keepAtOrAbove` | number | `0.75` | Lowest verification-model confidence at which a candidate the model checked is reported. Greater than 0 and at most 1. To get close to the behavior before October 7, 2026, send `0.6` with `nameChecks: false`. | | `nameChecks` | boolean | `true` | Before the Proofreader reports a spelling candidate, it asks the verification model whether the word is a name (a person, place, product, or brand). It skips this step when the word has a clear typo pattern, such as two swapped letters. `false` turns these name rules off. | | `nameAtOrAbove` | number | `0.75` | Lowest verification-model confidence that a word is a name at which a spelling candidate is dropped. A capitalized word that reads like a name is dropped at `0.5`, or at this value when it is lower. Greater than 0 and at most 1. Independent of `keepAtOrAbove`. | | `useGuidelines` | boolean | `true` | Reads extra accepted words and brand-name casing from the brand guidelines in your workspace's knowledge base. `false` skips that read for this run. | | `loremIpsumOnSamePages` | boolean | `false` | With `true`, lorem ipsum and pseudo-Latin filler are left to the `lorem-ipsum` agent, and the run summary says `Lorem ipsum is left to the Lorem Ipsum agent.` The Proofreader's other placeholder checks, such as "Insert headline here", still run. Ignored when you send `skipChecks`. | | `checkHiddenText` | boolean | `false` | Also proofreads text a visitor cannot see, such as an icon link's off-screen label or screen-reader-only text: what screen-reader users hear. | `acceptedWords` and `brandNames` take single words. The first 500 entries are read, and an entry longer than 64 characters is ignored. The verification model answers at most 20,000 questions per API key per UTC day, and a candidate takes one to three. Change detection's check of changed page text counts toward the same limit (see the run-control keys of [Run Execution](/docs/api-reference/rest-apis/v2/agents/execution/run)). Past that, the Proofreader reports only the findings its rules are certain of, and the run summary says `The daily spelling check limit was reached.` > [!TIP] > > The Proofreader also reports lorem ipsum. A run with `agentIds` that starts both `spell-check` and `lorem-ipsum` sets `loremIpsumOnSamePages: true` for you, so each lorem ipsum line is reported once, by the Lorem Ipsum agent. It does not when you send `skipChecks` or `loremIpsumOnSamePages` yourself. If you run the two agents on the same pages in separate requests, send `loremIpsumOnSamePages: true` to the Proofreader. The Proofreader cannot see whether the Lorem Ipsum execution succeeds. If that execution fails, lorem ipsum on those pages goes unreported. Send `loremIpsumOnSamePages: false` when you want both. A spelling finding names its correction in `suggestion` and `suggestedFix` when the verification model picks one of the dictionary's suggestions, or when there is only one. When there are several and none is picked, its `suggestion` is `Check the spelling.` and it has no `suggestedFix`. ### Consistency Checker Options for `consistency-checker`. Its keys start with `consistency` because a run with `agentIds` shares one `userContext` across every agent. | Key | Type | Default | Effect | | - | - | - | - | | `consistencyCasingCheck` | boolean | `true` | Runs the cross-page casing check (`cross-page-casing`). Brand names you give the Proofreader in `brandNames` are left to the Proofreader. | | `consistencyVisualCheck` | boolean | `true` | Runs the visual check, which uses no model: buttons and links styled differently from the site's usual style for their kind (`style-mismatch`), with no hover effect while the others have one (`missing-hover`), or whose text matches its background on hover (`hover-invisible`). | | `consistencyPeersOnly` | boolean | `true` | The visual check compares an element only with its peers. It reports no style difference for a component repeated on the page (unless the same component looks different on another page), for the colors of a promotion, for a button color that buttons on other pages also use (the site's accent color), or for a link colored like the text around it. The selected item of a tab or filter row is left out. `false` compares every element, as before October 7, 2026. | | `consistencyExactValues` | boolean | `true` | When this page's phone number or email is a one-character slip of the value the other pages agree on, names that value in the suggestion and in `suggestedFix`. | | `consistencyMaxPages` | number | `6` | Other pages of the site to compare with. Whole number, capped at 12. | | `consistencyMaxCharsPerPage` | number | `6000` | Characters of each other page's text given to the AI model. Whole number, capped at 20,000. | | `consistencyTextVisibility` | string | `"visible"` | `"visible"` compares only the text a visitor sees. `"all"` compares all rendered text, including text hidden with zero opacity. | | `consistencyIncludeScreenReaderText` | boolean | `false` | Counts screen-reader-only text, such as an icon link's label, as page text in the comparison and the casing check. | | `consistencyRawPagesAsEvidence` | boolean | not set | `true` reports a difference that rests only on pages read without a browser, such as a page that failed to render. A phone number is never reported this way. Not set, it is off when the run renders pages in a browser, which is the usual case. | A visual finding names the elements it groups in `metadata.labels`. A `style-mismatch` finding also lists what differs in `metadata.differences`, one entry per property: `{ property, value, dominant, dominantCount, css }`, where `css` is the declaration the rest of the site uses, such as `border-radius: 8px`. Its suggestion names the first declaration and counts the others. Read `metadata` on the findings of [Get Execution](/docs/api-reference/rest-apis/v2/agents/execution/get) with `includeResults: true`. ### Image Inspector Options for `image-inspector`. A value outside its range is ignored, and the default applies. | Key | Type | Default | Effect | | - | - | - | - | | `blurMinNaturalRatio` | number, 0.05 to 1 | `0.6` | An image is blurry when its file is narrower than this share of the CSS pixels it fills. | | `blurHighScale` | number, 1 to 20 | `2.5` | Enlargement from which a blurry image is `high` severity instead of `medium`. | | `blurMinRenderedWidthPx` | number, 0 to 4000 | `120` | Narrowest image, in CSS pixels, checked for blur. | | `stretchTolerance` | number, 0 to 1 | `0.08` | Aspect-ratio difference allowed before an image counts as stretched. | | `stretchMinWidthPx` | number, 0 to 4000 | `64` | Narrowest box, in CSS pixels, checked for stretching. | | `stretchMinHeightPx` | number, 0 to 4000 | `32` | Shortest box, in CSS pixels, checked for stretching. | | `emptyMinSidePx` | number, 0 to 4000 | `24` | Smallest image slot, in CSS pixels, reported as empty. | | `altMinSidePx` | number, 0 to 4000 | `48` | Smallest image, in CSS pixels, that needs alt text. | | `maxPerCategory` | whole number, 1 to 50 | `6` | Most findings pinned per issue type on a page. | | `linkCheckerOnSamePages` | boolean | `false` | With `true`, broken images the Link Checker also reports are left to it, so they are not reported twice. A one-page run with `agentIds` that starts `broken-links` sets it for you whenever the Link Checker checks images in that run. Set it yourself when you run the two agents on the same pages in separate requests, or in one `agentIds` run over several pages. A value you send always wins. | | `cropCheck` | boolean | not set | `true` turns on the bad-crop check (`bad-crop`): screenshots of up to 6 photos per page are sent to an AI model, which flags a head or main subject cut off at an edge. `false` keeps the check off whatever `aiConfig.modelChecks` says. Not set, the check runs only when the run's [`aiConfig.modelChecks`](/docs/api-reference/rest-apis/v2/agents/execution/run) lists `image-crop`. | Images without alt text are reported as one finding: pinned on the image when there is one, and page-level when there are several. The bad-crop check is the Image Inspector's only model call, and it is off unless turned on. A run focused on other issue types never runs it. When the model gives no usable answer, the run summary says `Photo crops could not be checked.` ### Mobile Inspector Options for `mobile-inspector`. A value outside its range is ignored, and the default applies. | Key | Type | Default | Effect | | - | - | - | - | | `phoneWidthPx` | whole number, 320 to 480 | `375` | Phone screen width, in CSS pixels, the page opens at. | | `minTapTargetPx` | number, 8 to 96 | `24` | Smallest tap target, in CSS pixels, that passes. The suggestion names this size. | | `maxScreenshots` | whole number, 0 to 10 | `7` | Screenshots per page, including the first screen. `0` turns screenshots off. | | `tabletWidthPx` | whole number, 600 to 1024, or `0` | `768` | Width, in CSS pixels, of the tablet layout pass. `0` turns the tablet pass off. | | `skipChecks` | string\[] | `[]` | Checks not to run, any of: `tablet` (the tablet layout pass), `sticky-bar` (content under fixed or sticky bars; it scrolls and taps same-page links), `wrapped-label` (button labels that wrap), `menu` (taps the menu button to see whether it opens anything), and `missing-on-mobile` (content shown on desktop that a phone visitor cannot reach). Unknown entries are ignored. | | `closeNotices` | boolean | `true` | Closes cookie and consent notices and small popups the way a visitor would before each width is measured, and leaves out the ones that stay. `false` leaves every notice alone and judges it as page content, so a button a cookie banner covers is reported as hidden under it. | The phone checks for sideways scrolling, overflow, cut-off content, and small tap targets always run. With `menu` skipped, the menu is not judged, and links that sit in a hidden phone menu are never reported as missing on phones. ### Migration Parity Options for `migration-parity`. `liveSiteUrl` is required. | Key | Type | Default | Effect | | - | - | - | - | | `liveSiteUrl` | string | none | Required. The live or old site to compare against: a full address or a bare domain, such as `old.example.com`. Only its origin is used. `liveUrl` is read as the same key when `liveSiteUrl` is absent. | | `maxFindings` | whole number, 1 to 20 | `6` | Most findings per page. A focused recheck (`focusIssueTypes`) caps only the issue types it asks for. | | `useSitemap` | boolean | `true` | When the same path does not exist on the live site, looks for the best match by address in the live site's sitemap. | A run without a usable `liveSiteUrl`, or whose live site is the site of the run's `url`, returns `INVALID_ARGUMENT` before any execution is created, with `Migration Parity needs the live site to compare against: send userContext.liveSiteUrl (a full address or a bare domain)` or `Migration Parity needs a live site other than the project site: userContext.liveSiteUrl names the same site as the run's url`. In a run with `agentIds`, Migration Parity is listed in `data.failed` and the other agents still start. For each page, the agent finds the same page on the live site and reports what the live page has that the new one lost. Names, numbers, and addresses are compared exactly; a phone number counts as kept in any written form. Contact details the live site shows only in its header or footer are compared once per run, on the run's first page. Live pages are read without your site access credentials, and only on public addresses. A page that was not compared gets no findings, keeps its earlier suggestions, and says why in the run summary: no matching live page, a live site that could not be read, a live page that timed out or refused the visit, too little text on either page, or a sign-in wall in front of either page. A page skipped for a sign-in wall is not billed. Each finding carries `livePageUrl` and `missing` (the missing items, at most 20) in `agent.reason`. Each page's result on [Get Execution](/docs/api-reference/rest-apis/v2/agents/execution/get) with `includeResults: true` carries `agentResult.report`: `livePageUrl`, `match` (`"same-path"`, `"sitemap"`, or `"none"`), `compared` (how many bios, reviews, FAQs, phone numbers, emails, addresses, and list items were compared), and `skipped` (`"gated"` or `"live-gated"` when a sign-in wall stood in front of the page or its live page). ### Content Request List Options for `content-request-list`. All are optional. | Key | Type | Default | Effect | | - | - | - | - | | `includeThreads` | boolean | `true` | Lists the document's open comment threads that ask for content or a confirmation. | | `maxItems` | whole number, 1 to 50 | `25` | Most checklist items per page. | | `minBioWords` | whole number, 1 to 100 | `10` | A team member's bio shorter than this is listed as short, when another member of the same team has a full bio. | | `clientUserIds` | string\[] | none | Up to 1,000 user IDs of the client. A thread the client opened is the client asking your team, so it is left out. Without this key or `clientEmailDomains`, every human ask counts. | | `clientEmailDomains` | string\[] | none | Up to 100 email domains of the client, subdomains included. Works as `clientUserIds` does, on the email of the thread's author. | | `audienceLabel` | string, 1 to 40 characters | `"the client"` | Who the checklist is for, as the finding names them, for example `3 things still need content from the owner`. Angle brackets are not allowed. | The agent posts one page-level finding per page, with issue type `content-requests`. The whole checklist is on the finding's `agent.reason.contentRequests` and on each page's `agentResult.report.contentRequests` in [Get Execution](/docs/api-reference/rest-apis/v2/agents/execution/get) results: items `{ kind, label, section?, text?, annotationId?, count? }`, where `kind` is `empty-section`, `placeholder-text`, `coming-soon`, `placeholder-image`, `thin-bio`, or `open-question`. It reads the run document's open comment threads and quotes one only when the run's audience can already see it: a public thread always, an organization-private thread only on a `"private"` run of that same organization, and a thread restricted to named users never. Threads an agent opened, and threads whose last human reply looks like the answer, are left out. It reads up to 2,000 annotations past the agents' own suggestions, and the summary says when older threads were not read. A page title alone in a banner, a "Coming soon" badge among real content, and stand-in lines in the header, navigation, or footer are not listed. A page behind a sign-in wall is skipped (`report.skipped: "gated"`), is not billed, and keeps its earlier checklist. ### AI Visibility Options for `ai-visibility`. | Key | Type | Default | Effect | | - | - | - | - | | `minVisibleWithoutJs` | number, 0 to 100 | `90` | The JavaScript check passes when at least this percent of the page's text is visible without running JavaScript. | | `failVisibleWithoutJs` | number, 0 to 100 | `60` | The JavaScript check fails below this percent. Between the two thresholds, it warns. | | `scoreAnswerShapeOnAllPages` | boolean | `false` | `true` scores the answer-shape check on every kind of page, as it was scored before October 2026: question headings, a list or table, a date, and an author on an article, and question headings and a list or table on other pages. A page with fewer than half of them fails. With `false`, the check asks only what the [`ai-visibility` row](#built-in-agents) describes, and a gap is a warning. | `0` is accepted as a threshold. Leave the key out, or send `null` or an empty string, to keep the default. A threshold outside 0 to 100 is ignored. Unlike the other options on this page, the two thresholds are declared fields of the agent, so a threshold that is not a number returns `INVALID_ARGUMENT`. ## Context gathering strategies Stack one or more strategies in the order you want them to run. | Strategy | What it returns | | - | - | | `web-page-text` | Visible text extracted via Puppeteer | | `web-page-screenshot` | Full-page screenshot as image (multimodal input) | | `web-page-html` | Cleaned HTML content | | `web-page-css` | Cleaned CSS content from stylesheets | | `web-page-links` | All hyperlinks on the page, classified internal/external | | `web-page-accessibility` | Accessibility issues (Pa11y / HTML_CodeSniffer) | | `computed-styles` | Browser-resolved computed CSS for specific selectors | | `robots-txt` | Fetched `robots.txt` | | `sitemap-data` | Discovered and parsed XML sitemaps | | `lighthouse` | Google Lighthouse audit (performance / a11y / best-practices / SEO) | | `rest-api` | Customer-configured REST endpoints fetched at runtime (SSRF-guarded, encrypted auth); injected via `{{restApiData}}` | | `none` | No context gathering (for service-only or text-only agents) | Per-strategy overrides are supplied under `contextGathering.strategyOptions[""]`. See [Create Agent](/docs/api-reference/rest-apis/v2/agents/create) for the `rest-api` endpoint configuration schema. ## Execution strategies | Strategy | Purpose | | - | - | | `ai` | LLM-driven analysis (default) | | `service` | Delegate to a registered built-in service (`serviceId` required) | | `service+ai` | Registered service, then AI analysis; `{{serviceResult}}` in the instructions resolves to the service output (`serviceId` required) | | `stagehand-agent` | Browser agent: the agent's model drives a live page with browser tools (`instructions` required) | | `mcp-tools` | Model-driven tool loop against remote MCP server(s) (`instructions` + `execution.mcpServers` required) | ## Knowledge (Memory-RAG) Agents can pull workspace knowledge from Velt Memory into the prompt via `execution.knowledge`: | Field | Type | Range | Description | | - | - | - | - | | `useMemory` | boolean | | When `true`, retrieves knowledge/patterns/activities from Memory and injects them as `{{memoryContext}}` | | `maxChunks` | number | 1–20 | Max knowledge chunks to retrieve | | `maxPatterns` | number | 1–20 | Max learned patterns to retrieve | | `maxActivities` | number | 1–20 | Max recent activities to retrieve | > [!NOTE] > > The `knowledge` block is strictly validated: only the four fields above are accepted. The legacy `sourceIds` field has been removed, and `maxChunks` is now capped at 20 (previously 50). Knowledge retrieval never fails an execution: if Memory is unavailable, the run continues in a degraded mode without knowledge context. ## Scope | Field | Bound to | | - | - | | `apiKey` | Workspace-wide (default; agents are per-workspace) | | `organizationId` | Annotations created on the named organization | | `documentId` | Annotations created on the named document | `organizationId` and `documentId` are required on Run Execution and control where annotations land. The document must already exist before you run an agent against it. ## Get started > [card] [Setup](/docs/ai/agents/setup) > > Create an agent, run it against a URL, and read the findings end-to-end. > [card] [API Reference](/docs/api-reference/rest-apis/v2/agents/create) > > All endpoints organized into Agents, Execution, Versioning, Prompt Tools, Analytics, and Groups. # Setup Source: https://velt.dev/docs/ai/agents/setup Build a review agent end to end: create, run, poll, and inspect findings. This guide walks through the steps to get a review agent running and surfacing findings as comment annotations. Each step links to the full API reference for request and response details. ## Step 1: (Optional) Refine your prompt If you have a one-line QA instruction and you're not sure it's specific enough to ship, run it through the prompt tools first. **Check completeness:** [Enhance Prompt](/docs/api-reference/rest-apis/v2/agents/prompt/enhance) returns either "your prompt is sufficient" or a specific clarification request (with suggested options for the user to pick from). **Expand into a structured task:** [Validate Prompt](/docs/api-reference/rest-apis/v2/agents/prompt/validate) takes a simple instruction and expands it into a comprehensive QA task with an analysis prompt, response descriptions, demo examples, and tool requirements. **Iterate on demo failures:** [Refine Prompt](/docs/api-reference/rest-apis/v2/agents/prompt/refine) takes an existing analysis prompt and a list of demo failures (with feedback) and produces a refined prompt. **Resolve optimal config:** [Resolve Config](/docs/api-reference/rest-apis/v2/agents/config/resolve) takes raw + processed instructions and recommends extraction strategies + execution strategy. These tools are optional. Skip straight to Step 2 if you already know what your agent should do. ## Step 2: Create the agent Call [Create Agent](/docs/api-reference/rest-apis/v2/agents/create) with a name, instructions, and a configuration block. The minimum viable agent is `name` + `description` + `enabled` + `instructions` + `contextGathering.strategies` + `execution` (send `{}` for the defaults): ```JSON theme={null} { "data": { "name": "Brand Color Checker", "description": "Verifies CTAs use the primary brand color", "enabled": true, "instructions": "Verify all CTAs use the primary brand color #1A73E8.", "contextGathering": { "strategies": ["web-page-text", "web-page-screenshot"] }, "execution": {} } } ``` The engine creates the agent's main document and writes version 1 to its versions subcollection. The response returns `{ agentId }`. For a complete walkthrough of every config block (`execution`, `response`, `postProcess`, `input`, `scope`, `setup`, `metadata`), see the [Create Agent](/docs/api-reference/rest-apis/v2/agents/create) reference. > [!NOTE] > > Built-in agents (`spell-check`, `broken-links`, etc.) are pre-registered for every workspace. You don't need to create them; skip straight to Step 3 with one of the [built-in agent IDs](/docs/ai/agents/overview#built-in-agents). ## Step 3: Run an execution Call [Run Execution](/docs/api-reference/rest-apis/v2/agents/execution/run) with `agentId`, `url`, `organizationId`, and `documentId`. All four are required: the document must already exist, and findings land on it as comment annotations. ```JSON theme={null} { "data": { "agentId": "abc123def456", "url": "https://example.com/pricing", "organizationId": "org_001", "documentId": "doc_001", "deviceType": "desktop", "ranBy": { "userId": "user_123", "name": "Jane Doe", "email": "jane@example.com" } } } ``` The response returns immediately with `{ executionId }`. The engine creates an execution document, dispatches a Cloud Task, and starts processing asynchronously. * **Cross-page execution:** Set `crossPageExecute: true` and the engine crawls the seed URL and processes up to `maxUrlsToProcess` pages (default 50). * **Page lists:** Send `urls` (max 500 absolute URLs or site-relative paths on the same host as `url`) and the engine reviews exactly those pages with no crawl. Use it when pages differ only by a query string and a crawl cannot find them. See [Run Execution](/docs/api-reference/rest-apis/v2/agents/execution/run) for the normalization rules. * **Several agents:** Send `agentIds` (up to 10) instead of `agentId`. Each agent gets its own execution, and the response lists one `executionId` per agent, plus any agent that could not start. It works on one page, or with `urls` or `crossPageExecute` on several, where each agent's execution covers every page. See [Run Execution](/docs/api-reference/rest-apis/v2/agents/execution/run#9-several-agents-on-one-page) and [several pages](/docs/api-reference/rest-apis/v2/agents/execution/run#11-several-agents-on-several-pages). * **Focused rechecks:** Set `userContext.focusIssueTypes` to report only the listed [issue types](/docs/ai/agents/overview#issue-types). The run replaces only the agent's earlier pending suggestions of those types. See [Run Execution](/docs/api-reference/rest-apis/v2/agents/execution/run#10-recheck-some-issue-types). * **Per-run options:** Switch a built-in agent's checks off, or tune its thresholds, through `userContext`. See [Per-run options](/docs/ai/agents/overview#per-run-options). * **Device emulation:** Set `deviceType: "mobile"` or `"desktop"` (default `"desktop"`) to control the viewport/user-agent used for context gathering and pin resolution. * **Workflow trigger:** Set `trigger: "workflow"` and pass `workflowExecutionId` when running an agent as part of a Review Workflow Builder workflow node. * **Annotation visibility:** Set `annotationVisibility` to choose who sees the comment annotations the execution creates. With `"public"`, anyone with access to the document sees the finding pins; the default, `"private"`, shows them to members and admins of the organization only. See [Run Execution](/docs/api-reference/rest-apis/v2/agents/execution/run) for both values. ## Step 4: Poll for results Call [Get Execution](/docs/api-reference/rest-apis/v2/agents/execution/get) with the `executionId` returned from Step 3. Poll until `execution.status !== "running"`. If you started several agents with `agentIds`, poll each `executionId` from `data.executions`. ```JSON theme={null} { "data": { "executionId": "exec_1711900000000_abc123def456" } } ``` Terminal statuses: | Status | Meaning | | - | - | | `passed` | Completed successfully: all URLs clean, no findings | | `failed` | Completed with findings: all URLs processed cleanly | | `partial` | Some URLs succeeded and some failed (see `resultsSummary.erroredUrls`) | | `error` | Every URL failed, or a fatal error (see `execution.error.code` and `retryable`) | | `skipped` | Execution was skipped (precondition unmet) | When the execution completes, `resultsSummary` contains aggregate counts: ```JSON theme={null} { "totalFindings": 7, "totalAnnotationsCreated": 7, "urlsProcessed": 12, "urlsWithFindings": 5 } ``` Re-runs use a per-URL **delete-and-recreate** model (`postProcess.deletePreviousSuggestions`, enabled by default): before writing a URL's new findings, the engine clears that URL's still-pending suggestions from the previous run, so annotations never pile up as duplicates. Suggestions a reviewer has already accepted, rejected, or resolved are left untouched. A focused recheck (`userContext.focusIssueTypes`) clears only the pending suggestions of the issue types it rechecks. ## Step 5: Fetch per-URL findings Set `includeResults: true` on Get Execution to fetch the full findings array per URL: ```JSON theme={null} { "data": { "executionId": "exec_1711900000000_abc123def456", "includeResults": true } } ``` The response includes a `results` array alongside `execution`. Each entry has the URL, the agent's output for it under `agentResult` (its findings are in `agentResult.findings`), and the URL's finding count: ```JSON theme={null} { "results": [ { "url": "https://example.com/pricing", "urlHash": "a1b2c3d4e5f6", "agentResult": { "status": "completed", "issueCount": 1, "findingsCount": 1, "findings": [ { "id": "finding-1", "title": "CTA uses non-brand color", "description": "The 'Buy now' button uses #FF5722 instead of #1A73E8", "severity": "high", "category": "color", "targetText": "Buy now", "suggestion": "Change background-color to #1A73E8", "htmlSelector": "a.cta-primary", "isPageLevel": false, "issueType": "brand-color", "confidence": 95, "evidence": { "selector": "a.cta-primary", "text": "Buy now" } } ], "error": null }, "findingCount": 1, "processedAt": 1711900050000 } ] } ``` Annotation counts are reported for the whole run only, in `resultsSummary.totalAnnotationsCreated`. See [Get Execution](/docs/api-reference/rest-apis/v2/agents/execution/get) for every field, including `evidence`. Findings are also written to the document as comment annotations (when `postProcess.annotations.enabled` is true, the default). Authors of these annotations are flagged with the system agent user. ## Listing and counting executions * **List executions** for an agent or document with pagination: [List Executions](/docs/api-reference/rest-apis/v2/agents/execution/list). * **Count executions** (e.g. a live "N running" counter) with [Count Executions](/docs/api-reference/rest-apis/v2/agents/execution/count). ## Iterating on the agent Behavioral edits create a new version. Identity edits do not. * **Edit identity (`name`, `description`, `enabled`):** [Update Agent](/docs/api-reference/rest-apis/v2/agents/update). No new version; the root doc is updated in place. * **Edit behavior (`instructions`, `contextGathering`, `execution`, `postProcess`, `input`, `scope`, `setup`):** [Update Agent Version](/docs/api-reference/rest-apis/v2/agents/version/update). Creates version `N+1` and bumps the agent's `version` pointer. In-flight executions stay pinned to whatever version they started on. * **List versions:** [List Versions](/docs/api-reference/rest-apis/v2/agents/versions/list). Each version contains the full behavioral snapshot. * **Roll back the most recent change:** [Restore Version](/docs/api-reference/rest-apis/v2/agents/versions/restore). Single-step undo; call repeatedly to walk backward. Cannot go below version 1. ## Organizing agents Use [Agent Groups](/docs/api-reference/rest-apis/v2/agents/groups/create) to bundle related agents together (e.g. "Brand QA"). Agents stay independent documents; groups just store an `agentIds` array. An agent can belong to multiple groups; deleting an agent removes it from every group automatically. When listing agents with [Get Agent(s)](/docs/api-reference/rest-apis/v2/agents/get), pass `groupId` to filter to a single group's members. ## Track usage [Get Agent Analytics](/docs/api-reference/rest-apis/v2/agents/analytics/get) returns per-agent, per-model, per-month token consumption plus execution counts. Filter by `agentId`, `year`, `month`, or `model`. ## Next steps > [card] [API Reference](/docs/api-reference/rest-apis/v2/agents/create) > > All endpoints organized into Agents, Execution, Versioning, Prompt Tools, Analytics, and Groups, with full request and response schemas. > [card] [Overview](/docs/ai/agents/overview) > > What agents are, the pipeline phases, built-in vs custom agents, and the full enum vocabulary. # Customize Behavior Source: https://velt.dev/docs/ai/approval-engine/customize-behavior Node config, edge routing, parallel groups, triggers, SLAs, linter rules, events, errors, and the object reference. This is the field reference. [Setup](/docs/ai/approval-engine/setup) covers the happy path, and [Patterns](/docs/ai/approval-engine/patterns) covers which option to pick. This page covers everything you reach for when you need precise control. ## Node configuration Every node has a `nodeId`, a `type`, and a `config` block. | Field | Type | Notes | | - | - | - | | `nodeId` | string | Required. 1 to 64 chars. Unique within the definition. | | `type` | enum | Required. `agent`, `human`, `notification`, or `webhook`. | | `config` | object | Required. Shape depends on `type`. See below. | | `slaMs` | integer | Deadline for the step, up to 7 days. See [SLA and breach handling](#sla-and-breach-handling). | | `requireNonEmptyOutput` | boolean | Sync webhook nodes only. Fails the step terminally with `webhook-node-empty-response` when the receiver returns an empty body. It has no effect in `mode: "async"`, because the step parks in `waiting` before the check runs. Accepted on the other node types, with no runtime effect. | | `name` | string | Cosmetic label, 1 to 200 chars. Echoed back, no runtime effect. | | `description` | string | Cosmetic, up to 2000 chars. Echoed back, no runtime effect. | `config` is validated strictly against the type. Unknown fields are rejected. ### Agent nodes An agent node runs a Velt agent against a URL, then routes on the result. The step parks in `waiting` while the agent runs and resumes on its own when the agent finishes, so you never have to poke it. | Field | Type | Notes | | - | - | - | | `agentId` | string | Required. A built-in or custom agent id. The reserved value `__mock__` returns a synthetic pass, for demos and tests only. | | `url` | string | A fixed absolute URL, up to 2000 chars. **Wins when both `url` and `urlPath` are set.** | | `urlPath` | string | A dot-path into `triggerContext` that resolves the URL from the trigger payload, up to 500 chars. | | `crossPageExecute` | boolean | Let the agent crawl beyond the seed URL. Defaults to `false`. | | `maxUrlsToProcess` | integer | Cap on URLs crawled per run, up to 500. | | `userContextMapping` | object | `{ field: dotPath }` map that builds the agent's `userContext` from `triggerContext`. | | `promptOverride` | string | Up to 8000 chars. | | `inputMapping` | object | Extra step inputs passed to the agent. | | `pollIntervalMs` | integer | 5000 to 60000. How often the engine checks the agent's status. Defaults to 15000. | | `agentMaxRuntimeMs` | integer | Hard ceiling, up to 24 hours. Defaults to 10 minutes. | | `aiConfig` | object | The AI provider and model for the agent run this node starts. Same fields and rules as `aiConfig` on [Run Execution](/docs/api-reference/rest-apis/v2/agents/execution/run). Omit it to use the provider and model the platform resolves for the agent. | **You must set `url` or `urlPath`.** Setting neither is rejected with `APPROVAL_AGENT_NODE_REQUIRES_URL_OR_URLPATH`. If `urlPath` resolves to nothing at run time and no static `url` is set, the step fails with `agent-url-unresolved`. A `urlPath` value with no scheme is normalized. Vercel's `payload.deployment.url` of `my-app.vercel.app` becomes `https://my-app.vercel.app`. Existing `http://` and `https://` values are left alone. ```json theme={null} { "nodeId": "brand-check", "type": "agent", "config": { "agentId": "brand-agent-v1", "urlPath": "documentUrl" }, "slaMs": 3600000 } ``` **Set the AI model for every run.** `aiConfig` applies to every run the node starts, including scheduled and triggered runs. It takes `provider`, `model`, `defaultModels`, and `maxToolTurns`, with the same validation as [Run Execution](/docs/api-reference/rest-apis/v2/agents/execution/run): at least one field set, unknown keys rejected, and models limited to the allowlist. The API rejects an invalid value with `INVALID_ARGUMENT` when you create or update the definition. If the allowlist later stops accepting a saved value, the step drops it when it starts the agent and the run uses the platform default. The step does not fail. ```json theme={null} { "nodeId": "nightly-audit", "type": "agent", "config": { "agentId": "broken-links", "url": "https://acme.com", "aiConfig": { "provider": "claude", "model": "claude-sonnet-5" } } } ``` The step output carries `agentExecutionStatus`, `agentResultsSummary`, `resolvedUrl`, `agentDurationMs`, and a `decision` of `approve` when the agent passed. Route on any of them with a [custom predicate](#custom-predicates). > [!WARNING] > > `blocking: true` requires a sibling `resolutionPolicy` to pass schema validation, and the pair is then rejected at run time with `agent-blocking-not-supported`, for every agent id including `__mock__`. To put a person in front of an agent's findings, place a `human` node downstream of the agent node instead. ### Human nodes A human node waits for reviewers to approve or reject. Set exactly one of `reviewers[]` or the legacy `reviewerIds[]`. | Field | Type | Notes | | - | - | - | | `reviewers` | array | Preferred. `[{ userId, mandatory }]`. Must include at least one `mandatory: true`. UserIds must be unique. | | `reviewerIds` | string\[] | Legacy. Every entry is treated as mandatory. | | `reviewerEmails` | string\[] | Up to 50 addresses. Surfaced on the step's `output.reviewerEmails` for your notification UI. | | `commentBody` | string | Up to 8000 chars. Stored on the step's output for your reviewer UI to render. | ```json theme={null} { "nodeId": "human-legal", "type": "human", "config": { "reviewers": [{ "userId": "u_legal_01", "mandatory": true }], "commentBody": "Please review for legal compliance." } } ``` The step resolves when every mandatory reviewer approves, or when any reviewer rejects. Record decisions with [Record Reviewer Decision](/docs/api-reference/rest-apis/v2/approval-engine/steps/record-reviewer-decision). > [!NOTE] > > A human node carries no rejection config. Its reject path is an outgoing `on: "reject"` edge, and every human node must have one, or the definition is rejected with `APPROVAL_HUMAN_NODE_REQUIRES_REJECT_PATH`. Group members are included in that rule. ### Notification nodes A notification node sends an email or Slack message built from the previous step's output. No extra cloud function needed. | Field | Type | Notes | | - | - | - | | `channel` | enum | Required. `email` or `slack`. | | `bodyTemplate` | string | Required. 1 to 16000 chars, with `{{dot.path}}` interpolation. | | `recipients` | string\[] | Required for `email`. 1 to 50 addresses. | | `subjectTemplate` | string | Email subject, up to 2000 chars. | | `slackTarget` | string | Required for `slack`. A channel id such as `C0123`, or an `https` incoming-webhook URL. | | `format` | enum | `text` (default), `html`, or `slack-blocks`. | ```json theme={null} { "nodeId": "notify-stakeholders", "type": "notification", "config": { "channel": "email", "recipients": ["lead@acme.dev", "pm@acme.dev"], "subjectTemplate": "Approval {{input.decision}} for {{execution.triggerContext.page.title}}", "bodyTemplate": "Findings: {{input.agentResultsSummary.summary}}", "format": "text" } } ``` **Templating** is dot-path substitution only. There is no code execution. Missing tokens render as an empty string, and objects and arrays are JSON-stringified. Three roots are available: | Root | Resolves to | | - | - | | `input.*` | The previous step's output. | | `execution.*` | `executionId`, `definitionId`, `correlationId`, and `triggerContext`. | | `step.*` | This step's metadata. | **Delivery notes.** Email goes through your workspace's SendGrid configuration. Delivering to at least one recipient completes the step; delivering to none fails it and retries. Slack delivery to a channel id needs a workspace bot token, and a webhook-URL target must be `https` on an allowed host. Slack config errors such as `channel_not_found` or `invalid_auth` are terminal and are not retried, while 5xx, network errors, and `rate_limited` are retried. `format: "slack-blocks"` means the rendered body must be a JSON array of Slack Block Kit blocks. It is valid only on the Slack channel and is rejected on email with `APPROVAL_NOTIFICATION_SLACK_BLOCKS_REQUIRES_SLACK`. ### Webhook nodes A webhook node calls your own HTTPS endpoint as a workflow step. | Field | Type | Notes | | - | - | - | | `url` | string | Required. `https` only, host-allowlisted, up to 2000 chars. | | `mode` | enum | `sync` (default) or `async`. | | `method` | enum | `GET` or `POST`. Defaults to `POST`. | | `authMode` | enum | `hmac` (default), `token`, or `none`. | | `authTokenHeader` | string | Required when `authMode: "token"`. The header the engine puts your token in. | | `timeoutMs` | integer | 1000 to 60000. Defaults to 10000. | | `expectedStatusCodes` | integer\[] | Up to 20 status codes to treat as success instead of the 2xx default. | | `bodyTemplate` | enum | `envelope` (default), `pass-through`, or `none`. `none` requires `method: "GET"`. | | `requestHeaders` | object | Extra headers. `x-velt-*` and reserved header names are rejected. | **`sync` mode** posts and waits for your response. A 2xx (or a listed `expectedStatusCodes` value) completes the step. A 4xx fails it terminally, because that is a configuration error on your side. A 5xx, timeout, or network error fails it with retry budget remaining. **`async` mode** posts the payload, then parks the step in `waiting`. With the default `bodyTemplate: "envelope"`, the body carries `callback.url`, `callback.token`, and `callback.tokenHeader`. With `bodyTemplate: "pass-through"`, the same three values are nested under `_velt` as `_velt.callbackUrl`, `_velt.callbackToken`, and `_velt.callbackTokenHeader`. To complete or fail the step, POST to that callback URL with the token in the `x-velt-callback-token` header and a body of `{ "status": "completed" | "failed", "output"?: {}, "error"?: {} }`. Async mode needs a `webhookSecret` on the execution to sign the callback token. With `authMode: "hmac"` the engine signs the outbound body with the execution's `webhookSecret` in `x-velt-signature`. With `authMode: "token"` it sends a static token, whose value is read at dispatch time from `triggerContext.webhookAuth[]` so the secret never lives in the definition. On success the step output carries `httpStatus`, allowlisted `responseHeaders`, `responseJson` when the response is JSON, and `responseText` capped at 64 KB. ## Edge model Every transition is one entry in `edges[]`: approve routing, reject routing, group fan-out and fan-in, and loop-backs. ```json theme={null} { "from": "human-review", "to": "rework-notice", "on": "reject" } ``` | Field | Type | Required | Notes | | - | - | - | - | | `from` | `EdgeEndpoint` | yes | Bare node-id string, `{ kind: "node", nodeId }`, or `{ kind: "group", groupId }`. | | `to` | `EdgeEndpoint` | yes | Same shape as `from`. | | `on` | enum | no, defaults to `always` | `approve`, `reject`, `always`, `exhausted`, or `custom`. `approve` and `reject` auto-compile their predicates. | | `when` | JSON-AST string | only with `on: "custom"` | Up to 1000 chars. Rejected on any other role. | | `loop` | `{ maxIterations }` | only on an `on: "reject"` back-edge | 1 to 20. Marks the edge as a loop-back. | Edges round-trip exactly. What you POST is what you read back. ### Reject, loop-back, and exhausted * **Reject route.** An outgoing `on: "reject"` edge from the rejecting node. ```json theme={null} { "from": "human-review", "to": "rework-notice", "on": "reject" } ``` * **Loop-back.** An `on: "reject"` edge whose `to` is an ancestor of `from`, marked with `loop`. The server derives the loop region from it. ```json theme={null} { "from": "human-review", "to": "agent-draft", "on": "reject", "loop": { "maxIterations": 3 } } ``` * **Exhausted route.** A sibling `on: "exhausted"` edge from the same `from`, fired when the loop hits its cap. Without one, an exhausted loop rolls the execution up to `failed`. ```json theme={null} { "from": "human-review", "to": "escalate", "on": "exhausted" } ``` ### Custom predicates Use `on: "custom"` with a `when` expression to gate an edge on the source step's output. `when` is a JSON-AST string. The engine parses it as JSON and evaluates it with a safe walker, never as JavaScript. ```json theme={null} { "from": "brand-check", "to": "legal-review", "on": "custom", "when": "{\"op\":\"eq\",\"args\":[{\"var\":\"output.passesBrandCheck\"},true]}" } ``` Common shapes: | Goal | `when` value | | - | - | | equality | `{"op":"eq","args":[{"var":"output.decision"},"approve"]}` | | numeric compare | `{"op":"gt","args":[{"var":"output.score"},0.8]}` | | boolean AND | `{"op":"and","args":[,]}` | | boolean OR | `{"op":"or","args":[,]}` | | negation | `{"op":"not","args":[]}` | | regex match | `{"op":"regex","args":[{"var":"output.body"},"^urgent"]}` | Supported operators: equality, comparison, boolean and/or/not, `regex`, `includes`, `startsWith`, `endsWith`, `length`, `isEmpty`. Path roots: | Root | Resolves to | | - | - | | `output.*` | The source step's terminal output. | | `step.*` | The source step's metadata: `stepId`, `nodeId`, `status`, `retryCount`. | | `execution.input.*` | The `triggerContext` you passed on dispatch. | An `on: "always"` edge, the default when `on` is omitted, fires whenever the source step reaches a fan-out-eligible status. ### Groups as edge sources A group can be an edge source (`from: { kind: "group", groupId }`), giving it one collective branch instead of one fan-out per member. * **`waitAll` as an edge source.** All members must terminate, then the group takes one branch by unanimity: `approve` if every member approved, otherwise `reject`. Provide both branches and exactly one fires. A routed collective reject is not a failed run: when the reject branch's successor completes, the execution rolls up to `completed`, and the rejecting member is `completed` with `output.decision: "reject"`, never `failed`. * **`cancelOnQuorum` and `joinOnQuorum` as edge sources.** They fire one collective approve-successor on approval quorum. A forward `on: "reject"` from either is rejected as a dead edge, because those policies only fan out on approval. * **Edges into a group** (`to: { kind: "group", groupId }`) expand to one edge per member, for every quorum policy. Successor step ids from a group are `group___to__`. Group-to-group edges are rejected. ### The compiled view Every `DefinitionView` returns a read-only `compiled` block next to your authored `edges`. `compiled.forwardEdges` is the runtime edge list with group endpoints expanded and `on` roles compiled to predicate ASTs. `compiled.loops` is the derived loop-region list. Render `compiled` directly instead of re-implementing the compiler in your client. See [Get Definition](/docs/api-reference/rest-apis/v2/approval-engine/definitions/get-definition#the-compiled-block). ## SLA and breach handling Set `slaMs` on any node to give the step a deadline, up to 7 days. If the step does not complete in time it becomes `breached` and emits `step.breached`. Declare an outgoing edge that routes on the breached status: either an `on: "always"` edge, which fires on the four fan-out-eligible statuses `completed`, `skipped`, `breached`, and `failed`, or an `on: "custom"` edge whose `when` tests for `breached`. A node that has outgoing edges but none that route on a breach is rejected with `missing-breach-edge`. A terminal node with no outgoing edges is accepted; if it breaches, the execution rolls up to `failed` and emits `execution.failed`. Agent nodes also have their own ceiling via `agentMaxRuntimeMs`, which defaults to 10 minutes. ## Parallel groups and quorum policies A parallel group declares member nodes that run in parallel and share an approval threshold. ```json theme={null} { "groupId": "parallel-review", "memberNodeIds": ["human-legal", "human-brand"], "expectedSteps": 2, "quorum": 2, "onQuorumMet": "waitAll" } ``` | Field | Type | Required | Description | | - | - | - | - | | `groupId` | string | yes | 1 to 64 chars. Stable identifier. | | `memberNodeIds` | string\[] | yes | 1 to 500 nodes. Each must be a declared node. A node belongs to at most one group. | | `expectedSteps` | integer | yes | 1 to 500. Members the group expects to terminate before it considers itself done. Set it equal to `memberNodeIds.length`; a higher value means the group never completes. | | `quorum` | integer | yes | 1 to `expectedSteps`. Approvals needed to fire the policy. | | `onQuorumMet` | enum | no | `waitAll` (default), `cancelOnQuorum`, or `joinOnQuorum`. | | `requiredNodeIds` | string\[] | no | Members whose approval is required. Each must be in `memberNodeIds`, and `length` must be at most `quorum`. | ### Quorum counts approvals, not completions A member counts toward quorum only when it ends `completed` with `output.decision === "approve"`. Rejections, failures, breaches, and cancellations advance the completion counter, never the approval counter. Two consequences follow: 1. **Agent nodes do count toward quorum.** An agent step ends `completed` with `output.decision: "approve"` when its run passes or is skipped, so it advances the approval counter exactly like a human approval. The one exception is an agent step that fails before dispatch: it takes the failure path, whose `output` is empty and carries no `decision`. See [Anti-patterns](/docs/ai/approval-engine/patterns#assuming-an-agent-in-a-quorum-group-never-counts). 2. **A reject does not block group completion.** It just stops the approval counter from advancing. Completion and quorum are tracked separately. ### `onQuorumMet` policies | Policy | What happens when approval quorum is first met | Per-member fan-out | | - | - | - | | `waitAll` (default) | Emits `group.quorum-met` and nothing else. As an edge source, waits for all members and fires one collective branch by unanimity. | Each member's edges fire on its own completion. Two members pointing at the same node create two downstream steps. | | `cancelOnQuorum` | Emits `group.quorum-met` and cancels every sibling still in `waiting`, with `actorId: "system:group-quorum"`. | Each completing member still fans out. Cancelled siblings do not. | | `joinOnQuorum` | Emits `group.quorum-met`, cancels waiting siblings, and fires a single group-owned successor per shared target. | Suppressed for members. The group owns fan-out, so each successor runs exactly once. | A `joinOnQuorum` successor's input is `{ groupOutputs, groupId, quorum, totalApproved }`. ### Requiring specific approvers By default quorum is anonymous: any N approvals out of M members fire the policy. To require specific people, list them in `requiredNodeIds`: ```json theme={null} { "groupId": "approver-group", "memberNodeIds": ["legal", "finance", "brand"], "expectedSteps": 3, "quorum": 2, "requiredNodeIds": ["legal", "finance"] } ``` Quorum now needs both conditions: every node in `requiredNodeIds` approved, **and** the numeric `quorum` reached. Here `brand` approving alone never satisfies quorum, even though `quorum: 2` could be met numerically. Omit `requiredNodeIds` to fall back to anonymous quorum. ## Loop regions A loop region lets a workflow re-enter an earlier node when a reviewer rejects, instead of failing outright. You do not declare loops directly. Mark an `on: "reject"` edge with `loop`, where the `to` is an ancestor of the `from`, and the server derives the region. Add a sibling `on: "exhausted"` edge to route when the cap is reached. ```json theme={null} { "from": "human-legal", "to": "agent-draft", "on": "reject", "loop": { "maxIterations": 5 } } { "from": "human-legal", "to": "human-escalate", "on": "exhausted" } ``` The derived region is surfaced read-only as `compiled.loops[]`: | Field | Type | Description | | - | - | - | | `loopId` | string | Server-assigned identifier. | | `entryNodeId` | string | Node re-entered on each iteration, the reject edge's `to`. | | `bodyNodeIds` | string\[] | Nodes inside the iteration scope, derived from the closure between `to` and `from`. | | `maxIterations` | integer | 1 to 20. Hard cap per execution. | | `onExhausted` | object or `null` | Target of the sibling `on: "exhausted"` edge. `null` rolls the execution up to `failed` at the cap. | The iteration predicate is `decision == 'reject' && rejectorMandatory == true`. Custom loop predicates are not supported: `loop` is valid only on an `on: "reject"` back-edge. ### Body-shape constraint The derived loop body must be one of two shapes: 1. **Single-terminal sequential.** Exactly one body node has edges leaving the body. That node is the iteration terminal. 2. **Group-bounded.** The exit-bearing body nodes are exactly the `memberNodeIds` of one `joinOnQuorum` group, every member is inside the body, and the group has `quorum === expectedSteps`. Other shapes are rejected with `loop-body-must-have-single-terminal`. ### Context threaded into the next iteration The entry step of iteration N+1 receives: ```ts theme={null} { iteration: number; // N+1 loopId: string; previousAttempts: Array<{ iteration: number; authorOutput: Record; // the body's iteration-terminal output rejectedBy: string; rejectorMandatory: boolean; rejectionReason: string | null; rejectedAt: number; }>; } ``` When a parallel group lives inside a loop body, each iteration gets fresh quorum state, so per-iteration quorum always starts from zero. ## Triggers Add a `triggers[]` entry to a definition and the engine starts runs for you, with no dispatch call. Each entry carries at most one mechanism: `inboundWebhook`, `schedule`, or `appTrigger`. Combining two on one entry is rejected. A definition may declare up to 50 entries, each using a different mechanism. | Field | Type | Required | Notes | | - | - | - | - | | `triggerId` | string | yes | 1 to 128 chars. Stable id, also the idempotency-key prefix. | | `eventName` | string | no | Up to 128 chars. Optional label. | | `filters` | object | no | Free-form match filters. | | `inboundWebhook` | object | no | See [Inbound webhook trigger](#inbound-webhook-trigger). | | `schedule` | object | no | See [Scheduled (cron) trigger](#scheduled-cron-trigger). | | `appTrigger` | object | no | See [App trigger](#app-trigger). | > [!NOTE] > > **Scope is inherited, always.** A triggered run carries the owning definition's `scope`. An organization- or document-scoped definition fires runs with the same `organizationId` and `documentId`. Org and document ids in a webhook body never set the run's scope. ### Inbound webhook trigger Declaring `inboundWebhook` exposes the definition at `POST /v2/workflow/webhook-inbound/trigger` so external systems can start runs. Velt's native contract verifies an HMAC or bearer signature, and provider presets let GitHub, Vercel, or a custom source sign with their own scheme. ```json theme={null} { "triggerId": "ci-build", "inboundWebhook": { "authMode": "hmac", "secret": "github-webhook-secret-...", "provider": "github", "allowedEvents": ["workflow_run", "push"], "idempotencyHeader": "x-github-delivery" } } ``` | Field | Type | Required | Notes | | - | - | - | - | | `authMode` | enum | yes | `hmac` verifies a body signature. `bearer` reads `Authorization: Bearer `, and is `velt`-only. | | `secret` | string | yes | 16 to 512 chars. The per-trigger secret, and the real authenticator. | | `provider` | enum | no | `velt` (default), `github`, `vercel`, or `custom`. | | `signatureHeader` | string | custom only | Header carrying the hex signature. | | `signatureAlgorithm` | enum | custom only | `sha1` or `sha256`. | | `signaturePrefix` | string | custom only | Prefix stripped before comparing, such as `sha256=`. | | `allowedEvents` | string\[] | no | 1 to 50 event names. Non-matching events return HTTP 200 with `event-ignored`. | | `eventNameHeader` | string | custom only | Header carrying the event name for `allowedEvents`. | | `idempotencyHeader` | string | no | Header to read the source event id from. | | `idempotencyBodyPath` | string | no | Dot-path in the body for the source event id, such as `event.id`. | | `payloadMapping` | enum | no | Applies to every provider. `pass-through` (default) sends the extracted payload as `triggerContext`; `wrap` nests it under `source`. | Presets resolve the signature header, algorithm, prefix, and event-name source for you: | `provider` | Signature header | Algorithm | Prefix | Event name from | | - | - | - | - | - | | `velt` (default) | `x-velt-signature` | HMAC-SHA256 | `sha256=` | body `type` | | `github` | `x-hub-signature-256` | HMAC-SHA256 | `sha256=` | `x-github-event` header | | `vercel` | `x-vercel-signature` | HMAC-SHA1 | none | `x-vercel-deployment-event` header, then body `type` | | `custom` | `signatureHeader` | `signatureAlgorithm` | `signaturePrefix` | `eventNameHeader` | Any provider other than `velt` requires `authMode: "hmac"`. **Request rules.** * **API key.** Send `x-velt-api-key`, or use the `?apiKey=` query param for providers that cannot set custom headers. The header wins if both are present. The Velt API key is a publishable client key, and the per-trigger `secret` is what actually authenticates the call. * **Identifiers.** Put `definitionId` and `triggerId` in the body for `velt`, or pass them as `?definitionId=` and `?triggerId=` query params. * **Body.** A JSON object up to 1 MB. For `velt`, shape it as `{ definitionId, triggerId, payload }` and `payload` becomes the `triggerContext`. For every other provider, the **entire body** becomes the `triggerContext`. * **Idempotency.** The source event id becomes the `idempotencyKey`, namespaced as `trig::` and deduplicated for 24 hours. Without one, the engine falls back to a per-request key. * **Responses.** Success returns `{ ok: true, code: "accepted", executionId, deduplicated }`. A filtered event returns HTTP 200 with `{ ok: false, code: "event-ignored" }`. An `allowedEvents` gate fails closed. If the event name cannot be resolved, the event is dropped. > [!NOTE] > > This endpoint takes **raw JSON**. Unlike the other REST endpoints, you do not wrap the payload in a `data` envelope, because external providers cannot reshape their outgoing bodies. Bodies over 1 MB are rejected with HTTP 413 and code `body-too-large`. This endpoint applies no per-source rate limiting, so add your own throttling in front of it if your source can burst. URL values inside the payload are not screened: the SSRF allowlist applies only to outbound destination URLs you configure on a definition, meaning the webhook node `url`, `webhookConfig.url`, the dispatch `webhookUrl`, and a URL-valued `slackTarget`. ### Scheduled (cron) trigger Declaring `schedule` starts runs on a cron cadence, for example a nightly audit. ```json theme={null} { "triggerId": "nightly-audit", "schedule": { "cron": "0 2 * * *", "timezone": "America/Los_Angeles", "enabled": true, "payloadTemplate": { "source": "nightly" } } } ``` | Field | Type | Required | Notes | | - | - | - | - | | `cron` | string | yes | Standard 5-field cron expression. Validated at write time (`APPROVAL_SCHEDULE_CRON_INVALID`). | | `timezone` | string | yes | An IANA zone such as `America/Los_Angeles`. Validated at write time (`APPROVAL_SCHEDULE_TIMEZONE_INVALID`). DST is handled for you. | | `enabled` | boolean | yes | Only enabled schedules fire. Setting `false` removes the schedule. | | `payloadTemplate` | object | no | A static object merged into `triggerContext` under `schedule.payload`. | The dispatched run's `triggerContext.schedule` carries `{ triggerId, scheduledAt, payload }`. A schedule fires at most once per scheduled instant, and missed runs are not replayed. ### App trigger Install the Velt **GitHub App** or **Vercel Integration** once, and matching events route to your workflows automatically. There is no per-repo or per-project webhook to configure, and no secret on the trigger: deliveries are authenticated app-wide against the provider's signature. Three steps: 1. **Connect the installation once** from your Velt dashboard. This returns an `installationRef`: the GitHub `installation.id`, or the Vercel `configuration.id`. 2. **Add an `appTrigger`** to a definition, referencing that `installationRef`. 3. **Events fire automatically.** Every matching event starts a run. ```json theme={null} { "triggerId": "gh-deploy-review", "appTrigger": { "provider": "github", "installationRef": "41234567", "repoFilter": ["acme/website"], "allowedEvents": ["push", "pull_request"] } } ``` | Field | Type | Required | Notes | | - | - | - | - | | `provider` | enum | yes | `github` or `vercel`. | | `installationRef` | string | yes | 1 to 256 chars. Must already be connected to your workspace, or the request fails with `FAILED_PRECONDITION`. | | `repoFilter` | string\[] | no | GitHub `org/repo` allowlist, up to 200 entries. Omit for every repo. | | `projectFilter` | string\[] | no | Vercel project id or name allowlist, up to 200 entries. Omit for every project. | | `allowedEvents` | string\[] | no | 1 to 50 event names, such as `push` or `deployment.succeeded`. Omit for all events. | | `payloadFilters` | array | no | Up to 20 entries of `{ path, in }`. The binding fires only when every filter matches a value in its `in` list. | Each delivery is deduplicated on the provider's delivery id, so duplicate deliveries never re-run a workflow. Events are matched by `(provider, installationRef)`, then narrowed by your filters. > [!NOTE] > > App triggers are available on Superflow-platform workspaces. Creating a definition with an `appTrigger` from another workspace returns `FAILED_PRECONDITION` with `APPROVAL_APP_PLATFORM_NOT_SUPPORTED`. **Example: scan every Vercel production deploy for broken links, then email the result.** ```json theme={null} { "definitionId": "vercel-broken-links-scan", "name": "Vercel deploy scan", "nodes": [ { "nodeId": "scan", "type": "agent", "config": { "agentId": "broken-links", "urlPath": "payload.deployment.url", "maxUrlsToProcess": 50 } }, { "nodeId": "notify", "type": "notification", "config": { "channel": "email", "recipients": ["web-team@acme.com"], "subjectTemplate": "Broken-link scan for {{execution.triggerContext.payload.deployment.url}}", "bodyTemplate": "Found {{input.agentResultsSummary.totalFindings}} broken link(s).", "format": "text" } } ], "edges": [{ "from": "scan", "to": "notify", "on": "always" }], "triggers": [ { "triggerId": "vercel-prod-deploys", "appTrigger": { "provider": "vercel", "installationRef": "icfg_AbC123xyz", "projectFilter": ["my-marketing-site"], "allowedEvents": ["deployment.succeeded"] } } ] } ``` `urlPath` resolves the just-deployed URL from the Vercel payload. It arrives without a scheme, so the engine normalizes it to `https://`. ## Cancelling and overriding | Goal | Endpoint | | - | - | | Stop a whole run and all its in-flight steps | [Cancel Execution](/docs/api-reference/rest-apis/v2/approval-engine/executions/cancel-execution) | | Stop one step, leaving its siblings running | [Cancel Step](/docs/api-reference/rest-apis/v2/approval-engine/steps/cancel-step) | | Force a parked step to a decision | [Resolve Step](/docs/api-reference/rest-apis/v2/approval-engine/steps/resolve-step) | Cancelling a run is a no-op on a run that already reached a terminal status. Successors of a cancelled step are never scheduled. Resolve Step has two flavors. `force-approve`, `force-reject`, `force-complete`, and `force-fail` are admin overrides for hung steps. `reviewer-approve` and `reviewer-reject` are reviewer actions, and they additionally require `actorId` to be one of the step's declared reviewers, or the call is rejected with `PERMISSION_DENIED`. For every approve or reject action the engine computes `decision`, `approved`, and `approvalReply` itself and writes them as authoritative. A caller-supplied `output` carrying those keys cannot override them, so you cannot record a rejection in the audit log while routing downstream edges as an approval. Other keys in `output` still pass through. ## Webhook delivery Set a receiver in one of two places: | Where | Applies to | Fields | | - | - | - | | `webhookConfig` on the definition | Every run of that definition | `{ url, secret, eventTypes? }` | | `webhookUrl` + `webhookSecret` on dispatch | That one run | Overrides `webhookConfig` | `secret` is 16 to 512 chars. Optional `eventTypes` narrows delivery to up to 50 event types. Both forms are `https`-only and SSRF-guarded at write time and again at delivery time. ### Retry policy | Attempt | Delay before retry | | - | - | | 1 (initial) | n/a | | 2 | 2 s | | 3 | 8 s | | 4 | 32 s | | 5 | 2 min | | 6 | 8 min, then dead-letter | After the final retry the payload goes to a dead-letter queue. Recover missed events with [Get Execution Events](/docs/api-reference/rest-apis/v2/approval-engine/executions/get-execution-events) and `sinceSeq`. **Delivery is at-least-once.** The same `eventId` and `seq` appear on retries, so make your receiver idempotent on `(executionId, seq)`. For signature verification and receiver setup, see [Setup, Step 4](/docs/ai/approval-engine/setup#step-4-get-the-outcome). ## Events ### Event reference Events delivered by webhook and returned from [Get Execution Events](/docs/api-reference/rest-apis/v2/approval-engine/executions/get-execution-events): | Event type | When emitted | `data` highlights | | - | - | - | | `execution.dispatched` | Run created and first steps scheduled. | `{ definitionId, definitionVersion, rootStepIds }` | | `execution.completed` | All steps terminal, no unhandled failure. | null | | `execution.failed` | A blocking step failed or breached with no recovery edge. | null | | `execution.cancelled` | Run cancelled, or fully rolled back. | `{ reason? }` | | `step.awaiting-approval` | A step entered `waiting`: a human step, a running agent step, or an async webhook step. | Human steps: `{ waitingForReviewers, mandatoryCount, resumeKey }`. Agent steps: `{ agentId, agentExecutionId, pollIntervalMs }`. | | `step.completed` | Step transitioned to `completed`. | Human steps: `{ aggregatorStatus, nodeType, decision }`. Agent steps: `{ agentExecutionId, agentExecutionStatus, decision, source }`. | | `step.failed` | Step failed after its retry budget ran out, or failed terminally when retries cannot help. | Varies by node type. Human steps: `{ reason }` (`no-reviewers`, `no-mandatory-reviewers`, `duplicate-reviewer-user-ids`, `exception`). Webhook steps: `{ httpStatus, latencyMs, retryClass }`. Notification steps: `{ channel, retryClass }`, which is also the shape Slack config errors such as `channel_not_found` use. Config-validation failures on either type emit `{ reason }` instead, including the `webhook-node-empty-response` path. Agent resumes: `{ agentExecutionId, agentExecutionStatus, decision, source }`. | | `step.breached` | Step passed its SLA before completing. | `{ reason }` | | `step.cancelled` | Step cancelled directly or by a quorum side effect. | `{ actorId, reason }` | | `group.quorum-met` | A group's approval threshold was first satisfied. | `{ groupId, total, quorum, completedTotal, expectedSteps }` | | `loop.iteration-started` | A rejected iteration spawned the next one below the cap. | `{ loopId, iteration, triggeredBy: 'rejection' }` | | `loop.exhausted` | The loop hit `maxIterations`. | `{ loopId, iteration, lastRejectedBy?, lastRejectionReason? }` | A step using the reserved `__mock__` agent id completes inline and emits `{ agentId, synthetic, decision }` instead, so a receiver you tested against `__mock__` sees different `data` keys in production. The `{ code, message }` error object is not part of the event `data`. It lives on the step's `error` field, which you read with [Get Execution](/docs/api-reference/rest-apis/v2/approval-engine/executions/get-execution) as `steps[].error`. Route on `event.type`, then fetch the step for the detail. > [!NOTE] > > Internal events such as `step.scheduled`, `step.started`, `step.retried`, and `step.overridden` consume `seq` numbers but are not delivered externally. Your stream may have gaps in `seq`, which is expected. ### Cancellation reasons `step.cancelled` carries a `data.reason` string. This is an open set, so switch on `event.type` for control flow, not on `data.reason`. | Reason | Source | Meaning | | - | - | - | | `group-quorum-met` | system | The parent group met quorum under `cancelOnQuorum` or `joinOnQuorum`. Audit shows `actorId: "system:group-quorum"`. | | `loop-restart` | system | A [loop region](#loop-regions) started the next iteration while a step from the previous one was still running. Audit shows `actorId: "system:loop-restart"`. | | (admin-supplied) | admin | Free-form reason passed to [Cancel Step](/docs/api-reference/rest-apis/v2/approval-engine/steps/cancel-step). | ## Linter rules Definitions are validated on create and update. Any violation returns `INVALID_ARGUMENT` with the code in the message. | Code | Meaning | | - | - | | `duplicate-node-id` | Two nodes share the same `nodeId`. | | `dangling-edge` | An edge references a node or group that is not declared. | | `cycle-detected` | The graph has a cycle. Only marked reject loop-backs may revisit a node. | | `unreachable-node` | A node has no path from any root. | | `node-missing-config` | A node has no `config` block. | | `missing-breach-edge` | A node sets `slaMs` and has outgoing edges, but none routes on a breach. | | `group-duplicate-id` | Two groups share the same `groupId`. | | `group-members-empty` | `memberNodeIds` is empty. | | `group-member-missing` | A member references an unknown node. | | `group-expected-steps-invalid` | `expectedSteps` is below 1. | | `group-quorum-invalid` | `quorum` is below 1 or above `expectedSteps`. | | `group-cancelonquorum-requires-quorum-lt-expected` | `cancelOnQuorum` requires `quorum < expectedSteps`. | | `group-joinonquorum-members-must-share-successors` | `joinOnQuorum` requires every member to have the same set of outgoing targets. | | `group-required-not-in-members` | An entry in `requiredNodeIds` is not in `memberNodeIds`. | | `group-required-exceeds-quorum` | `requiredNodeIds.length` is greater than `quorum`. | | `group-node-in-multiple-groups` | A node is a member of two or more groups. | | `loop-node-in-multiple-loops` | Two or more reject back-edges derive loop regions with overlapping bodies. Use one group-source back-edge instead. See [Anti-patterns](/docs/ai/approval-engine/patterns#one-reject-back-edge-per-parallel-reviewer). | | `loop-body-must-have-single-terminal` | The derived loop body is neither single-terminal sequential nor group-bounded. See [Body-shape constraint](#body-shape-constraint). | | `loop-group-bounded-quorum-must-equal-expected` | A group-bounded loop body needs `quorum === expectedSteps`, so the iteration terminal coincides with all members finishing. | ### Edge validation errors | Error key | Cause | | - | - | | `APPROVAL_EDGE_CUSTOM_REQUIRES_WHEN` | `on: "custom"` without a non-empty `when`. | | `APPROVAL_EDGE_WHEN_ONLY_FOR_CUSTOM` | `when` supplied on a non-custom edge. | | `APPROVAL_EDGE_LOOP_REQUIRES_REJECT` | `loop` on an edge that is not `on: "reject"`. | | `APPROVAL_EDGE_LOOP_REQUIRES_BACK_EDGE` | A reject loop-back whose `to` is not an ancestor of `from`. | | `APPROVAL_EDGE_REJECT_CYCLE_REQUIRES_LOOP` | `on: "reject"` to an ancestor without `loop`. | | `APPROVAL_EDGE_EXHAUSTED_REQUIRES_LOOP_SIBLING` | `on: "exhausted"` with no sibling reject loop-back from the same `from`. | | `APPROVAL_HUMAN_NODE_REQUIRES_REJECT_PATH` | A human node has no outgoing `on: "reject"` edge. | | `APPROVAL_AGENT_NODE_REQUIRES_URL_OR_URLPATH` | An agent node sets neither `url` nor `urlPath`. | | `APPROVAL_EDGE_GROUP_TO_GROUP_FORBIDDEN` | Both endpoints are group containers. | | `APPROVAL_GROUP_FROM_REJECT_REQUIRES_LOOP` | Forward `on: "reject"` from a `joinOnQuorum` or `cancelOnQuorum` group. | | `APPROVAL_GROUP_FROM_LOOP_REQUIRES_JOINONQUORUM` | A reject loop-back from a group that is not `joinOnQuorum`. | | `APPROVAL_APP_TRIGGER_EXCLUSIVE` | One trigger entry declares more than one of `inboundWebhook`, `schedule`, `appTrigger`. | ## Errors All errors follow the standard envelope: ```json theme={null} { "error": { "message": "...", "status": "INVALID_ARGUMENT", "details": {} } } ``` ### Canonical codes | Code | Meaning | Typical cause | | - | - | - | | `INVALID_ARGUMENT` | Schema or graph validation failed, or `x-velt-auth-token` is missing. | Missing field, wrong type, out-of-range value, edge contract violation, linter rule, absent auth token. | | `PERMISSION_DENIED` | The `x-velt-auth-token` is not one of the workspace's registered tokens, or the actor is not allowed to take the action. | An unregistered auth token, or a `reviewer-*` resolve action whose `actorId` is not on the step's reviewer list. | | `NOT_FOUND` | Target does not exist. | Unknown `executionId`, `definitionId`, or `stepId`. | | `ALREADY_EXISTS` | Conflicting create. | An active definition already uses that `definitionId`. | | `FAILED_PRECONDITION` | Optimistic lock or state-machine violation. | `ifVersion` mismatch, cancelling a terminal step, deleting a definition with in-flight runs. | | `RESOURCE_EXHAUSTED` | Rate limit exceeded. | Per-IP or per-API-key quota. | | `DEADLINE_EXCEEDED` | Internal timeout. | Retry with an idempotency key. | ### Schema validation messages These are the literal `message` strings returned in the error envelope. The `APPROVAL_*` names used elsewhere on this page are internal rule identifiers, not values you will find in a response body. | Message | Trigger | | - | - | | `webhookUrl and webhookSecret must be provided together` | Dispatch supplied one but not the other. | | `webhookUrl must use https scheme` | Non-HTTPS scheme. | | `webhookUrl host resolves to a private, loopback, or link-local address` | Private IP, `localhost`, `metadata.google.internal`, or `*.internal`. | | `at least one of reviewerIds or reviewers must be provided` | Human node with no reviewers. | | `cannot set both reviewerIds and reviewers, use one` | Both populated. Use `reviewers[]`. | | `reviewer userIds must be unique` | Duplicate `userId` in `reviewers[]`. | | `reviewers must include at least one mandatory reviewer` | Every reviewer has `mandatory: false`. | | `notification node with channel="email" requires a non-empty recipients array` | `channel: "email"` with no `recipients`. | | `notification node with channel="slack" requires a slackTarget (channel id or incoming-webhook URL)` | `channel: "slack"` with no `slackTarget`. | | `webhook node with authMode="token" requires authTokenHeader to be set` | `authMode: "token"` with no `authTokenHeader`. | | `inboundWebhook provider="github"/"vercel"/"custom" requires authMode="hmac"` | A non-`velt` provider using `authMode: "bearer"`. | | `inboundWebhook with provider="custom" and authMode="hmac" requires signatureHeader and signatureAlgorithm` | `provider: "custom"` with `hmac` but no `signatureHeader` or `signatureAlgorithm`. | | `schedule.cron must be a valid 5-field cron expression` | `cron` is not a parseable 5-field expression. | | `schedule.timezone must be a valid IANA timezone name (e.g. America/Los_Angeles)` | `timezone` is not a valid IANA zone. | ## Rate limiting Rate limits apply per API key, with extra per-endpoint tiers on high-volume routes. A `RESOURCE_EXHAUSTED` error means you should back off and retry with exponential delay. Dispatch retries are safe to replay with an `idempotencyKey`. ## Object reference ```typescript theme={null} interface ExecutionView { executionId: string; status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'; startedAt: number; // epoch ms completedAt: number | null; cancelledAt: number | null; definitionId: string; definitionVersion: number; correlationId: string; idempotencyKey: string; documentId?: string; // dispatch documentId; omitted when not passed organizationId?: string; // dispatch organizationId; omitted when not passed failureReason: { code: string; message: string } | null; steps: StepView[]; } interface StepView { stepId: string; nodeId: string; nodeType: 'agent' | 'human' | 'notification' | 'webhook'; status: 'pending' | 'running' | 'waiting' | 'completed' | 'failed' | 'skipped' | 'cancelled' | 'breached'; groupId: string | null; startedAt: number | null; completedAt: number | null; output: Record; error: { code: string; message: string } | null; } interface DefinitionView { definitionId: string; name: string; description: string | null; version: number; scope: { level: 'apiKey' | 'organization' | 'document'; organizationId: string | null; documentId: string | null }; nodes: NodeView[]; edges: EdgeView[]; groups: ParallelGroupDef[] | null; compiled: CompiledGraph; triggers: WorkflowTriggerConfig[] | null; tags: string[] | null; custom: Record | null; createdAt: number; updatedAt: number; status: 'active' | 'tombstoned'; } type JsonAst = Record; interface CompiledGraph { forwardEdges: CompiledForwardEdge[]; loops: CompiledLoopRegion[]; } interface CompiledForwardEdge { from: string; to: string; role: 'approve' | 'reject' | 'always' | 'exhausted' | 'custom'; when: JsonAst | null; fromGroupId?: string; toGroupId?: string; } interface CompiledLoopRegion { loopId: string; entryNodeId: string; bodyNodeIds: string[]; maxIterations: number; onExhausted: { routeToNodeId: string } | null; } interface ApprovalEventView { eventId: string; seq: number; // monotonic per execution type: string; // external event type, see Event reference stepId: string | null; timestamp: number; // epoch ms correlationId: string; data?: Record; } ``` ### Step ids Step ids are deterministic, so retries land on the same record: | Step | Id shape | | - | - | | Root step, no incoming edges | `step___` | | Per-edge fan-out | `__to__` | | `joinOnQuorum` fan-out | `group___to__` | ### Human step output After a human step resumes, `output` carries the aggregator rollup: ```typescript theme={null} { reviewers: Array<{ userId: string; mandatory: boolean }>; reviewerIds: string[]; reviewerEmails: string[]; commentBody: string | null; aggregatorStatus: 'resolved' | 'rejected'; approveCount: number; rejectCount: number; totalResponses: number; mandatoryCount: number; mandatoryApproveCount: number; decision: 'approve' | 'reject'; approved: boolean; resumedAt: number; resumeKey: string; } ``` ### `joinOnQuorum` successor input ```typescript theme={null} { groupOutputs: Record /* member's output */>; groupId: string; quorum: number; totalApproved: number; } ``` # Review Workflow Builder (Beta) Source: https://velt.dev/docs/ai/approval-engine/overview Run multi-step review and approval workflows where AI agents and people sign off together. ## What is the Review Workflow Builder? The Review Workflow Builder runs review and approval processes for you. You describe the process once as a **definition**, a graph of steps. Whenever something in your app needs review, you start a **run** against it. The engine walks the graph: it runs AI agents, waits for human approvals, evaluates branching rules, enforces deadlines, sends notifications, and tells you when the run finishes. You never build the runtime. No state machine, no retry logic, no concurrent-reviewer bookkeeping. ## How it works 1. **Author a definition.** Nodes are the steps. Edges connect them. The engine validates the graph when you save it. 2. **Start a run.** Call the dispatch API, or let a webhook, cron schedule, or connected GitHub / Vercel app start it for you. 3. **The engine executes.** Agent, notification, and sync webhook steps finish without your involvement. Human steps wait for a decision. 4. **Record decisions.** Post each reviewer's approve or reject. Matching edges fire and the run advances. 5. **Consume the outcome.** Receive signed webhooks in real time, or poll the event stream. ## A minimal workflow One reviewer approves. If they reject, the work goes back to an agent for rework. ```json theme={null} { "definitionId": "doc-signoff", "name": "Document sign-off", "nodes": [ { "nodeId": "manager-approval", "type": "human", "config": { "reviewers": [{ "userId": "u_manager_01", "mandatory": true }] } }, { "nodeId": "rework-notice", "type": "agent", "config": { "agentId": "rework-agent-v1", "urlPath": "documentUrl" } } ], "edges": [ { "from": "manager-approval", "to": "rework-notice", "on": "reject" } ] } ``` That is a complete, valid workflow. [Run it end to end in Setup](/docs/ai/approval-engine/setup). ## Building blocks | Term | What it is | | - | - | | **Definition** | The blueprint: `nodes` + `edges` + optional `groups`. You give it a stable `definitionId`. | | **Node** | One step. Four types: `agent`, `human`, `notification`, `webhook`. | | **Edge** | "When this node finishes, start that one." Carries an `on` role such as `approve` or `reject`. | | **Group** | A set of nodes that run in parallel and share an approval quorum. | | **Execution** | One live run of a definition. Has an `executionId` and a `steps[]` array. | | **Step** | One runtime instance of a node inside an execution. | Definitions are **versioned**. Editing one creates a new version, and runs already in flight finish on the version they started with. Old versions are not readable and there is no rollback, so see [Versioning](/docs/ai/approval-engine/patterns#versioning-and-what-it-does-not-do) before you rely on it. The graph is a DAG. Revision loops are the one exception: a `reject` edge pointing back to an earlier node creates a bounded retry loop. A definition holds up to 100 nodes and 500 edges. ### Node types | Type | What it does | Parks in `waiting`? | | - | - | - | | `agent` | Runs a Velt agent against a URL, then routes on the result. | Yes, while the agent runs. Resumes on its own. | | `human` | Waits for reviewers to approve or reject. | Yes, until you record decisions. | | `notification` | Sends an email or Slack message built from the previous step's output. | No. | | `webhook` | Calls your own HTTPS endpoint. | Only in `async` mode, until your callback. | Full config for each type is in [Customize Behavior](/docs/ai/approval-engine/customize-behavior#node-configuration). ### Lifecycles ``` Execution: pending → running → completed | failed | cancelled Step: pending → running → (waiting) → completed | failed | skipped | cancelled | breached ``` `waiting` means the step is parked. Agent steps resume on their own when the agent finishes. Human and async webhook steps stay parked until you send a decision or a callback. ## Four ways to start a run | Trigger | How it starts | Setup | | - | - | - | | **Dispatch API** | Your backend calls `/executions/dispatch`. | [Setup](/docs/ai/approval-engine/setup#step-2-dispatch-an-execution) | | **Inbound webhook** | An external system POSTs to the engine. Supports GitHub, Vercel, and custom signature presets. | [Inbound webhook trigger](/docs/ai/approval-engine/customize-behavior#inbound-webhook-trigger) | | **Cron schedule** | A cron expression starts a run on a cadence, such as a nightly audit. | [Scheduled trigger](/docs/ai/approval-engine/customize-behavior#scheduled-cron-trigger) | | **Installed app** | Connect the Velt GitHub App or Vercel Integration once, then GitHub and Vercel events route to your workflows. | [App trigger](/docs/ai/approval-engine/customize-behavior#app-trigger) | ## Scope Pick the level that matches how your product is structured. Scope does not select between definitions: you always dispatch a specific `definitionId`, and `definitions/list` returns every level. Scope sets the `organizationId` and `documentId` that trigger-started runs inherit. | Level | Bound to | | - | - | | `apiKey` | Workspace-wide. This is the default. | | `organization` | One `organizationId`. | | `document` | One `documentId` under an organization. | > [!NOTE] > > Review Workflow Builder state is partitioned per tenant. Each tenant's definitions, executions, and events live in that tenant's own database. ## What the engine handles for you * **Parallel review with quorum.** Wait for everyone, advance once N approve, or require specific people. * **Idempotent dispatch.** The same `idempotencyKey` always returns the same `executionId`. Retries never duplicate a run. * **SLA deadlines.** Set `slaMs` on a step. On breach the step becomes `breached` and routes down your escalation edge. * **Signed webhooks.** Every state change is POSTed with an HMAC-SHA256 signature and retried with backoff. * **Recoverable events.** Every event has a monotonic `seq`. Poll with `sinceSeq` to catch up after an outage. * **Write-time validation.** Cycles, dangling edges, unreachable nodes, and bad quorum settings are rejected before you dispatch. ## Limitations in beta * You author definitions as JSON. There is no visual builder yet. * You host the reviewer UI. Render the waiting step and call `recordReviewerDecision`. * Setting `blocking: true` on an agent node is rejected at runtime. Put a `human` node downstream of the agent instead. * Editing a definition only affects new runs. In-flight runs are not migrated. ## Get started > [card] [Setup](/docs/ai/approval-engine/setup) > > Author a definition, start a run, record a decision, and get the outcome. > [card] [Customize Behavior](/docs/ai/approval-engine/customize-behavior) > > Node config, edge routing, quorum policies, triggers, SLAs, events, and errors. > [card] [Patterns](/docs/ai/approval-engine/patterns) > > Which option to pick, and the mistakes that look reasonable but break. > [card] [REST API Reference](/docs/api-reference/rest-apis/v2/approval-engine/definitions/create-definition) > > Every endpoint with full request and response schemas. > [card] [Review Agents](/docs/ai/agents/overview) > > The AI agents your `agent` nodes run. # Patterns Source: https://velt.dev/docs/ai/approval-engine/patterns Which feature to reach for, and the mistakes that look reasonable but break. [Customize Behavior](/docs/ai/approval-engine/customize-behavior) tells you what every field does. This page tells you which one to pick. ## I want X, use Y | You want to model | Use | | - | - | | One reviewer. On reject, retry up to N times, then escalate. | An `on: "reject"` back-edge with `loop.maxIterations`, plus a sibling `on: "exhausted"` edge. | | One reviewer. On reject, hand off to a different team. | An `on: "reject"` forward edge. | | Three reviewers in parallel, all must approve, any rejection rewinds the stage as a unit. | A `joinOnQuorum` group with `quorum === expectedSteps`, plus one group-source `on: "reject"` back-edge. | | Two of three approvals is enough, stop bothering the third. | `cancelOnQuorum`. | | Two of three approvals is enough, then run "publish" exactly once. | `joinOnQuorum`. | | Everyone must finish, then take one collective approve or reject path. | A `waitAll` group as an edge source, carrying both an `on: "approve"` and an `on: "reject"` branch. | | Specific people must approve, regardless of the count. | `requiredNodeIds` on the group. | | An agent's findings need human sign-off. | An `agent` node with a `human` node downstream of it. | | A reviewer must respond within 24 hours, or escalate. | `slaMs` on the node, plus an `on: "always"` edge or an `on: "custom"` edge whose `when` tests for `breached`. | | Real-time notification on every state change. | `webhookUrl` + `webhookSecret` on dispatch. | | The same receiver for every run of a definition. | `webhookConfig` on the definition. | | Catch up after a missed webhook. | `/executions/getEvents` with `sinceSeq`. | | A workflow step calls your API and continues based on the response. | A `webhook` node with `mode: "sync"`. | | A workflow step hands off to a slow external system and waits. | A `webhook` node with `mode: "async"`. | | An external system starts a run. | A trigger with `inboundWebhook`. | | A run on a schedule, such as a nightly audit. | A trigger with `schedule`. | | GitHub or Vercel events start runs, with no per-repo setup. | A trigger with `appTrigger`. | | Email or Slack sent from inside the workflow. | A `notification` node. | | An admin acts on a reviewer's behalf, distinguishable in the audit log. | `/steps/resolve` with `reviewer-approve` or `reviewer-reject`. | | An admin force-completes a step that has no approve or reject concept. | `/steps/resolve` with `force-complete` or `force-fail`. | ## Duplicating a workflow There is no duplicate endpoint. A definition supports five operations: create, update, delete, get, and list. Copying is not one of them, so you do it by hand. It is four steps. **1. Fetch the original** Call [Get Definition](/docs/api-reference/rest-apis/v2/approval-engine/definitions/get-definition). The response carries `definitionId`, `name`, `description`, `scope`, `nodes`, `edges`, `groups`, `triggers`, `tags`, and `custom`, plus the server-owned `version`, `createdAt`, `updatedAt`, `status`, and `compiled`. It does not carry `webhookConfig`. **2. Change the id and the name** `definitionId` is the workflow's permanent handle, and two active definitions cannot share one. Turn `marketing-page-approval` into `marketing-page-approval-eu`. Give the copy a name a human can tell apart too. **3. Strip the server-owned fields and the explicit nulls** A read response carries bookkeeping that is not yours to set: `version`, `createdAt`, `updatedAt`, `status`, and `compiled`. Delete all five before sending. Then delete every key whose value is `null`. Every optional field you never set comes back that way: `description`, `groups`, `triggers`, `tags`, `custom`, and `organizationId` / `documentId` inside `scope`. Create takes each of those as absent or as a real value, never as `null`, so a leftover `null` is rejected. Create rejects unknown fields outright too, so leaving even one of either kind in fails the whole request with `INVALID_ARGUMENT`. That is the good outcome: you get a loud error, never a silently mangled copy. **4. Send it to create** POST the trimmed object to [Create Definition](/docs/api-reference/rest-apis/v2/approval-engine/definitions/create-definition). You now have a second workflow, starting at `version: 1`. > [!WARNING] > > **Triggers are what bite people.** If the original runs every night at 2am, the copy now runs every night at 2am too, and you have two nightly runs. > > Before you create the copy, either drop `triggers` entirely and re-add them deliberately, or give the copy fresh `triggerId` values. > [!NOTE] > > `webhookConfig` is write-only. Create Definition and Update Definition accept it, but Get Definition does not return it. The copy therefore starts with no per-definition webhook target. Re-send `webhookConfig`, with its own fresh secret, on the create call if the copy needs one. Dispatch-level `webhookUrl` + `webhookSecret` are a separate path, so a run dispatched with that pair still pushes every lifecycle event. Supplying both on dispatch replaces the definition's `webhookConfig` for that run rather than adding a second target, and it clears any `eventTypes` filter. > > Updates hit the same gap. Update is a full replace, and the object you fetched carries no `webhookConfig`, so a get, edit, update round trip nulls the existing `webhookConfig` on the original definition. Re-send it on every update of a definition that has one. Everything the read response carries copies safely. Your `edges` come back exactly as you authored them, byte for byte with no reformatting, so the round trip cannot quietly change routing. `scope` echoes the organization and document ids you originally sent, not internal ones, so it is safe to copy or edit as-is. ## Versioning, and what it does not do Every update bumps the version (`v1` to `v2` to `v3`) and stores a complete copy of the previous content. Nothing is overwritten in place. Three things follow, and they are the useful part: * **You cannot clobber a coworker's edit.** Update requires `ifVersion`, your claim about which version you are editing. If someone pushed `v5` while you were working from `v4`, your update is rejected with `FAILED_PRECONDITION` and a message like `Version conflict: expected 4, current 5`, instead of silently overwriting them. * **Editing never disturbs runs already in progress.** A run locks onto the version that was current when it started and finishes on that version. If a request is sitting in someone's queue on `v3` and you publish `v4` adding a reviewer, that request does not change shape under the reviewer. It completes as `v3`. Only new runs pick up `v4`. * **Delete and recreate resets the counter.** Recreating a deleted `definitionId` purges the old snapshots and starts again at `v1`. The version line is not continuous across a delete. ### What versioning does not give you This is where expectations usually outrun reality. Old versions are stored, but **you cannot read them**. There is no endpoint to list history or fetch what `v2` looked like. The snapshots exist for audit and recovery; they are not part of the public API. All you can see is the current version number. Which means **there is no rollback**. If `v5` was a mistake, you cannot ask for `v4` back. You need your own copy of `v4`'s content, which you resubmit as an update, producing a `v6` that contains `v4`'s content. You move forward to go back. Without a copy, you are reconstructing it by hand. There is also no draft versus live distinction, no way to mark a version as the stable one, and no way to run a specific version. New runs always get the latest. > [!TIP] > > Keep your definitions in source control and treat the API as the deployment target. That single habit gives you the history, the diffs, and the rollback path the API does not. ## Choosing a parallel-review policy Pick by what should happen the moment quorum is met. | You want | Use | What happens | | - | - | - | | Everyone signs off. Nobody is freed early. | `waitAll` (default) | The engine waits for every member to terminate. Each member's edges fire on its own completion. | | Once 2 of 3 approve, stop bothering the third. Each approver still triggers its own downstream work. | `cancelOnQuorum` | The third reviewer's waiting step is cancelled by the system. The two approvers still fan out per edge. | | After quorum, run the next step exactly once, not once per approver. | `joinOnQuorum` | Same cancellation as `cancelOnQuorum`, and per-member fan-out is suppressed. The group fires one shared successor carrying every member's output. | **Groups can branch collectively.** Set `from: { kind: "group", groupId }` and the group fires one successor instead of one per member. `waitAll` waits for everyone and decides by unanimity, approving only if every member approved, so it can carry both an `on: "approve"` and an `on: "reject"` branch. `joinOnQuorum` and `cancelOnQuorum` fire on approval quorum only, so a forward `on: "reject"` from either is rejected as a dead edge. > [!WARNING] > > A per-member `on: "reject"` edge on a `joinOnQuorum` member is unreachable at runtime. The policy suppresses per-member fan-out, so the rejecter's edge never fires. It still satisfies the reject-path rule, but it is dead code. For per-rejecter routing, use `waitAll` or `cancelOnQuorum`, which keep per-member fan-out. ## Choosing a rejection strategy Every `human` node needs a reject route. There are three shapes. **Send it back to me.** One reviewer, one retry counter. The work returns to an earlier node, up to N times, then escalates. ```json theme={null} { "from": "human-boss", "to": "agent-publish", "on": "approve" }, { "from": "human-boss", "to": "agent-draft", "on": "reject", "loop": { "maxIterations": 3 } }, { "from": "human-boss", "to": "human-skip-level-mgr", "on": "exhausted" } ``` **Send it somewhere else.** No retry, just routing. A different team picks it up. ```json theme={null} { "from": "human-boss", "to": "agent-publish", "on": "approve" }, { "from": "human-boss", "to": "human-rework-team", "on": "reject" } ``` **Rewind the whole stage.** Several reviewers work in parallel, all must approve, and any single rejection sends the entire stage back with one shared retry counter. ```json theme={null} { "groups": [ { "groupId": "compliance-review", "memberNodeIds": ["human-legal", "human-brand", "human-finance"], "expectedSteps": 3, "quorum": 3, "onQuorumMet": "joinOnQuorum" } ], "edges": [ { "from": { "kind": "group", "groupId": "compliance-review" }, "to": "agent-publish", "on": "approve" }, { "from": { "kind": "group", "groupId": "compliance-review" }, "to": "agent-draft", "on": "reject", "loop": { "maxIterations": 3 } }, { "from": { "kind": "group", "groupId": "compliance-review" }, "to": "human-cco", "on": "exhausted" } ] } ``` A group-source reject back-edge is `joinOnQuorum`-only, because that is the case where one shared counter makes sense. Forward collective fan-out works for any policy. If rejection should simply end the run, say so explicitly with a reject edge to a terminal node. The engine will not let you leave it implicit. ## Choosing SLA and breach handling Set `slaMs` when a step is time-critical. On breach the step becomes `breached`, which is terminal. The catch: a reject edge fires on `decision == 'reject'`, never on a breach. So `slaMs` plus only a reject edge is rejected at write time with `missing-breach-edge`. Add one of: * An `on: "always"` edge, which fires on every terminal status including `breached`. * An `on: "custom"` edge whose `when` tests for the breached status. ## Webhooks or polling They are complementary, not alternatives. | You want | Use | | - | - | | Push notification the moment state changes. | `webhookUrl` + `webhookSecret` on dispatch, or `webhookConfig` on the definition. | | Recovery after your receiver was down. | `/executions/getEvents` with `sinceSeq`. | | A read-only tool that should not host an HTTPS receiver. | Polling alone. | In production use both: webhooks for liveness, polling for recovery. `seq` is monotonic per execution, so catch-up is deterministic. ## Anti-patterns These look reasonable. They are not. ### One reject back-edge per parallel reviewer ```json theme={null} // Rejected: loop-node-in-multiple-loops "edges": [ { "from": "human-legal", "to": "agent-draft", "on": "reject", "loop": { "maxIterations": 3 } }, { "from": "human-brand", "to": "agent-draft", "on": "reject", "loop": { "maxIterations": 3 } }, { "from": "human-finance", "to": "agent-draft", "on": "reject", "loop": { "maxIterations": 3 } } ] ``` Each back-edge derives its own loop region, and the bodies overlap. Use one `joinOnQuorum` group with a single group-source reject back-edge, as in "Rewind the whole stage" above. ### `slaMs` with only a reject edge ```json theme={null} // Rejected: missing-breach-edge "nodes": [{ "nodeId": "human-review", "type": "human", "slaMs": 86400000, "config": { "reviewers": [{ "userId": "u_1", "mandatory": true }] } }], "edges": [{ "from": "human-review", "to": "human-rework", "on": "reject" }] ``` The reject edge never fires on a breach, so the breach would dead-end. Add a breach route. ### A final human node with no reject edge ```json theme={null} // Rejected: APPROVAL_HUMAN_NODE_REQUIRES_REJECT_PATH "nodes": [{ "nodeId": "human-final-approver", "type": "human", "config": { "reviewers": [{ "userId": "u_1", "mandatory": true }] } }] ``` Even the last approver needs somewhere to send a rejection. If rejection should end the run, route it to a terminal node explicitly. ### Assuming an agent in a quorum group never counts ```json theme={null} // Accepted, and the agent does count toward the quorum "groups": [{ "groupId": "x", "memberNodeIds": ["agent-summarize", "human-legal"], "expectedSteps": 2, "quorum": 2, "onQuorumMet": "joinOnQuorum" }] ``` An agent step ends `completed` with `output.decision` set to `approve` when its agent run passes or is skipped, and `failed` when it does not. Quorum counts every member that completes with a `decision` of `approve`, whatever the node type. So a passing `agent-summarize` plus an approving `human-legal` meets `quorum: 2`, and the group fires. Failure is the real constraint here, not node type. A failed agent step never counts toward the approval counter, whatever shape its output takes. If the agent run finishes unsuccessfully, the step carries `output.decision` set to `reject`. If the step fails before the run starts, its `output` is empty and carries no `decision` at all: a missing `agentId`, neither `url` nor `urlPath`, `blocking: true`, or a failed dispatch call. Other failure paths carry an `output` with neither a `decision` nor an approval. None of them advance the approval counter, only the completion counter. With `quorum` equal to `expectedSteps`, one agent failure keeps the group from firing, exactly as one human rejection would. > [!NOTE] > > Marking the agent `blocking: true` is not available: blocking agent nodes are rejected at runtime with `agent-blocking-not-supported`. To get human review of an agent's findings, put a `human` node downstream of the agent node. ### `when` written as JavaScript ```json theme={null} // Rejected: the expression fails to compile { "from": "x", "to": "y", "on": "custom", "when": "output.decision == 'approve'" } ``` `when` is a JSON-AST string, not an expression language: ```json theme={null} { "from": "x", "to": "y", "on": "custom", "when": "{\"op\":\"eq\",\"args\":[{\"var\":\"output.decision\"},\"approve\"]}" } ``` You only write this for `on: "custom"`. The `approve`, `reject`, `always`, and `exhausted` roles compile their own predicates. ### An `on: "exhausted"` target that is reachable another way This is accepted, and it will surprise you. Dispatch never seeds an exhausted-route node as a root: it drops any node that has an incoming edge, and separately drops any node named by a loop's `onExhausted.routeToNodeId`. The duplicate shows up later. If your escalation node is also the target of a normal edge, its predecessor's fan-out spawns it when that predecessor completes, and the loop spawns a second copy when the cap is hit. The two steps get different ids, so neither one deduplicates the other. Both run. Keep `on: "exhausted"` targets as leaves with no other incoming edges. Chain anything else off them. ## Next steps > [card] [Customize Behavior](/docs/ai/approval-engine/customize-behavior) > > The field reference behind every choice on this page. > [card] [Setup](/docs/ai/approval-engine/setup) > > Build and run a workflow end to end. # Setup Source: https://velt.dev/docs/ai/approval-engine/setup Build a workflow end to end: author a definition, start a run, record a decision, and get the outcome. By the end of this page you will have authored a workflow, started a run, recorded a human decision, and received the result. > [!NOTE] > > New here? Read the [Overview](/docs/ai/approval-engine/overview) first for the mental model. [Customize Behavior](/docs/ai/approval-engine/customize-behavior) is the field reference. ## Before you start All endpoints are under `https://api.velt.dev/v2/`. Every request needs three headers: | Header | Value | | - | - | | `x-velt-api-key` | Your workspace API key. | | `x-velt-auth-token` | A short-lived auth token. See [Auth Tokens](/docs/security/auth-tokens). | | `content-type` | `application/json` | Never put `apiKey` or `authToken` in the body. They are read from the headers. Wrap your payload in `data`. Success comes back under `result`, errors under `error`: ```json theme={null} // request { "data": { /* endpoint fields */ } } // success { "result": { /* payload */ } } // error { "error": { "message": "...", "status": "INVALID_ARGUMENT", "details": {} } } ``` Export your credentials once so the examples below run as written: ```bash theme={null} export VELT_API_KEY="ak_live_..." export VELT_AUTH_TOKEN="at_..." ``` ## Build your first workflow You will build the smallest workflow that exercises the whole engine: one human approval. Approving finishes the run. Rejecting routes to a follow-up step. ```mermaid theme={null} flowchart LR Start([Dispatch]) --> M["manager-approval
(human)"] M -->|approve| Done([Run complete]) M -->|"on: reject"| RW["rework-notice
(agent)"] RW --> Done ``` ### Step 1: Create the definition Every `human` node needs a reject path, so give it an outgoing `on: "reject"` edge. Approving has no outgoing edge here, so the run completes after the approval. The follow-up node uses the reserved `__mock__` agent id so you can run this end to end without registering a real agent. Use a real `agentId` in production. ```bash theme={null} curl -X POST https://api.velt.dev/v2/workflow/definitions/create \ -H "x-velt-api-key: $VELT_API_KEY" \ -H "x-velt-auth-token: $VELT_AUTH_TOKEN" \ -H "content-type: application/json" \ -d '{ "data": { "definitionId": "doc-signoff", "name": "Document sign-off", "scope": { "level": "apiKey" }, "nodes": [ { "nodeId": "manager-approval", "type": "human", "config": { "reviewers": [{ "userId": "u_manager_01", "mandatory": true }], "commentBody": "Please review and approve this document." } }, { "nodeId": "rework-notice", "type": "agent", "config": { "agentId": "__mock__", "urlPath": "documentUrl" } } ], "edges": [ { "from": "manager-approval", "to": "rework-notice", "on": "reject" } ] } }' ``` A successful create returns a `DefinitionView` with `version: 1` and `status: "active"`. The engine validates the graph at write time. Schema errors, edge-contract errors, cycles, dangling edges, unreachable nodes, and bad quorum settings all fail here rather than at run time. A rejected definition returns `INVALID_ARGUMENT`. The `message` is the human-readable rule text, for example `every human node must have at least one outgoing edge with on="reject" (a forward reject route or a reject back-edge): manager-approval`. Linter failures put everything in `error.message` too: the text `Definition linter failed:` followed by a JSON array whose entries each carry a `code` such as `missing-breach-edge`. Parse `error.message` to read those codes, because `error.details` is not set on a linter failure. Only schema failures populate `error.details`, with an `issues` array of Zod `{ code, path, message }` entries. Match on the linter `code`; the `APPROVAL_*` names are internal rule identifiers and never appear in a response. > [!TIP] > > Two rules catch most first-time authors. A `human` node needs an outgoing `on: "reject"` edge (`APPROVAL_HUMAN_NODE_REQUIRES_REJECT_PATH`). An `agent` node needs either `url` or `urlPath` (`APPROVAL_AGENT_NODE_REQUIRES_URL_OR_URLPATH`). Those two names are internal rule identifiers. The response carries the rule text, not the name. Full request shape: [Create Definition](/docs/api-reference/rest-apis/v2/approval-engine/definitions/create-definition). ### Step 2: Dispatch an execution Dispatch starts a run against one work item. Write the definition once and reuse it across many dispatches. `triggerContext` is free-form data your nodes and edge conditions read as `execution.input.*`. Pass an `idempotencyKey` so retries never spawn duplicates. ```bash theme={null} curl -X POST https://api.velt.dev/v2/workflow/executions/dispatch \ -H "x-velt-api-key: $VELT_API_KEY" \ -H "x-velt-auth-token: $VELT_AUTH_TOKEN" \ -H "content-type: application/json" \ -d '{ "data": { "definitionId": "doc-signoff", "idempotencyKey": "doc-123-signoff", "triggerContext": { "documentUrl": "https://app.acme.com/docs/123" } } }' ``` ```json theme={null} { "result": { "executionId": "exec_1777374504255_xzy43k9q", "correlationId": "corr_...", "deduplicated": false } } ``` Keep the `executionId`. It is the handle for everything that follows. `deduplicated: true` means you replayed an earlier dispatch with the same `idempotencyKey` and got the original run back. Full request shape: [Dispatch Execution](/docs/api-reference/rest-apis/v2/approval-engine/executions/dispatch-execution). ### Step 3: Record a decision Fetch the execution to find the step waiting on a human: ```bash theme={null} curl -X POST https://api.velt.dev/v2/workflow/executions/get \ -H "x-velt-api-key: $VELT_API_KEY" \ -H "x-velt-auth-token: $VELT_AUTH_TOKEN" \ -H "content-type: application/json" \ -d '{ "data": { "executionId": "exec_1777374504255_xzy43k9q" } }' ``` Look for a step with `"status": "waiting"` and `"nodeType": "human"`, then grab its `stepId`. You own the reviewer UI in beta. Render the waiting step to your user, and when they click approve or reject, call `recordReviewerDecision`: ```bash theme={null} curl -X POST https://api.velt.dev/v2/workflow/steps/recordReviewerDecision \ -H "x-velt-api-key: $VELT_API_KEY" \ -H "x-velt-auth-token: $VELT_AUTH_TOKEN" \ -H "content-type: application/json" \ -d '{ "data": { "executionId": "exec_1777374504255_xzy43k9q", "stepId": "step_manager-approval_..._lwofay", "reviewerId": "u_manager_01", "decision": "approve", "reason": "Looks good for launch." } }' ``` ```json theme={null} { "result": { "recorded": true, "aggregatorStatus": "resolved", "resumeScheduled": true } } ``` `reviewerId` must match a `userId` declared on the node. The step resolves and the workflow advances when every mandatory reviewer approves, or when any reviewer rejects. Recording the same reviewer's decision twice is idempotent and returns `recorded: false`. Full request shape: [Record Reviewer Decision](/docs/api-reference/rest-apis/v2/approval-engine/steps/record-reviewer-decision). ### Step 4: Get the outcome You have two ways to learn how the run ends. Use both in production: webhooks for liveness, polling for recovery. #### A. Webhooks, for real time Pass `webhookUrl` and `webhookSecret` on dispatch. The engine POSTs every externally-visible event to you, signed with HMAC-SHA256: ```json theme={null} // add to the dispatch "data" "webhookUrl": "https://hooks.acme.com/velt/approvals", "webhookSecret": "whsec_...at-least-16-chars..." ``` Each delivery is a POST with a 10s timeout and no redirects. Your receiver sees: | Header | What it is | | - | - | | `x-velt-signature` | `sha256=`. HMAC-SHA256 of the raw request body. | | `x-velt-event-id` | Stable event id, unchanged across retries. | | `x-velt-attempt` | 0-based attempt counter. | Verify the signature against the raw request body bytes. Do not re-serialize the parsed JSON: ```js theme={null} const crypto = require('crypto'); function verifyVeltSignature(rawBody, headerValue, secret) { const [scheme, hex] = String(headerValue).split('='); if (scheme !== 'sha256' || !hex) return false; const computed = crypto.createHmac('sha256', secret).update(rawBody, 'utf8').digest('hex'); const a = Buffer.from(hex, 'hex'); const b = Buffer.from(computed, 'hex'); return a.length === b.length && crypto.timingSafeEqual(a, b); } ``` Delivery is at-least-once, retried at `2s → 8s → 32s → 2m → 8m` before dead-lettering. The same `eventId` and `seq` appear on retries, so **make your receiver idempotent**: dedupe on `eventId` or `(executionId, seq)`. > [!WARNING] > > `webhookUrl` must use `https`. Loopback, private (RFC 1918), and link-local hosts are rejected, as are `localhost`, `metadata.google.internal`, `metadata`, and any `*.internal` hostname. DNS is re-resolved at delivery time, and redirects are never followed. To send the same events to one receiver for every run of a definition, set `webhookConfig` on the definition instead. See [Webhook delivery](/docs/ai/approval-engine/customize-behavior#webhook-delivery). #### B. Event polling, for catch-up You can read the event stream directly whether or not you use webhooks. Pass the highest `seq` you have durably stored as `sinceSeq` to get only what is new: ```bash theme={null} curl -X POST https://api.velt.dev/v2/workflow/executions/getEvents \ -H "x-velt-api-key: $VELT_API_KEY" \ -H "x-velt-auth-token: $VELT_AUTH_TOKEN" \ -H "content-type: application/json" \ -d '{ "data": { "executionId": "exec_1777374504255_xzy43k9q", "sinceSeq": 0 } }' ``` `seq` is monotonic per execution. Only external event types are returned, so your stream may have gaps in `seq`. That is normal. When you see `execution.completed` or `execution.failed`, the run is done. Full request shape: [Get Execution Events](/docs/api-reference/rest-apis/v2/approval-engine/executions/get-execution-events). ## Events you will receive | Event | When | | - | - | | `execution.dispatched` | Run created and the first steps scheduled. | | `step.awaiting-approval` | A step entered `waiting`: a human step, a running agent step, or an async webhook step. | | `step.completed` | A step finished successfully. Human resumes include `decision`. | | `step.failed` | A step failed after exhausting its retry budget. | | `step.breached` | A step missed its SLA deadline. | | `step.cancelled` | A step was cancelled directly or by a quorum side effect. | | `group.quorum-met` | A parallel group's approval threshold was first met. | | `loop.iteration-started` | A revision loop started another iteration. | | `loop.exhausted` | A revision loop hit its `maxIterations` cap. | | `execution.completed` | All steps terminal, no unhandled failure. | | `execution.failed` | A blocking step failed or breached with no recovery edge. | | `execution.cancelled` | The run was cancelled. | Payload shapes are in the [Event reference](/docs/ai/approval-engine/customize-behavior#event-reference). ## A realistic workflow Once the basics click, you compose richer graphs. Here an agent drafts, legal and brand review in parallel, and a single publish step fires once both approve: ```json theme={null} { "data": { "definitionId": "marketing-copy-approval", "name": "Marketing copy approval", "scope": { "level": "apiKey" }, "nodes": [ { "nodeId": "agent-draft", "type": "agent", "config": { "agentId": "copy-agent-v1", "urlPath": "documentUrl" } }, { "nodeId": "human-legal", "type": "human", "config": { "reviewers": [{ "userId": "u_legal_01", "mandatory": true }] } }, { "nodeId": "human-brand", "type": "human", "config": { "reviewers": [{ "userId": "u_brand_01", "mandatory": true }] } }, { "nodeId": "agent-publish", "type": "agent", "config": { "agentId": "publish-agent-v1", "urlPath": "documentUrl" } } ], "edges": [ { "from": "agent-draft", "to": "human-legal" }, { "from": "agent-draft", "to": "human-brand" }, { "from": "human-legal", "to": "agent-publish" }, { "from": "human-brand", "to": "agent-publish" }, { "from": { "kind": "group", "groupId": "parallel-review" }, "to": "agent-draft", "on": "reject", "loop": { "maxIterations": 3 } } ], "groups": [{ "groupId": "parallel-review", "memberNodeIds": ["human-legal", "human-brand"], "expectedSteps": 2, "quorum": 2, "onQuorumMet": "joinOnQuorum" }] } } ``` `agent-draft` runs first and fans out to both reviewers. Because the group uses `joinOnQuorum` with `quorum: 2`, `agent-publish` runs exactly once after both approve, not once per approver. The reject back-edge from the group is required, not decorative. Every `human` node needs a reject route, including group members. It also makes the workflow useful: if either reviewer rejects, the work loops back to `agent-draft` for up to 3 revisions. See [Parallel groups](/docs/ai/approval-engine/customize-behavior#parallel-groups-and-quorum-policies). > [accordion] How the events play out > > ``` > 1. Create Definition > → definition with parallel-review group, onQuorumMet: joinOnQuorum > > 2. Dispatch Execution > → executionId returned, status=running > execution.dispatched > step.completed (agent-draft) > step.awaiting-approval (human-legal) > step.awaiting-approval (human-brand) > > 3. Record Reviewer Decision (u_legal_01, approve) > step.completed (human-legal) > > 4. Record Reviewer Decision (u_brand_01, approve) > step.completed (human-brand) > group.quorum-met (parallel-review) > step.completed (agent-publish, single instance) > execution.completed > ``` > [accordion] Stopping reviewers early with cancelOnQuorum > > A group of 3 reviewers with `quorum: 2` and `onQuorumMet: "cancelOnQuorum"`: > > ``` > 2 of 3 approve → engine fires: > group.quorum-met (parallel-review) > step.cancelled (third-reviewer-step) > data: { actorId: "system:group-quorum", reason: "group-quorum-met" } > ``` > > The two approvers' downstream paths still fan out. The cancelled reviewer's edges do not fire. ## Start runs without calling dispatch You do not have to call the dispatch API. Add a `triggers[]` entry to a definition and the engine starts runs for you: * **[Inbound webhook](/docs/ai/approval-engine/customize-behavior#inbound-webhook-trigger):** an external system POSTs to the engine. GitHub, Vercel, and custom signature presets are built in. * **[Cron schedule](/docs/ai/approval-engine/customize-behavior#scheduled-cron-trigger):** a cron expression starts a run on a cadence. * **[Installed app](/docs/ai/approval-engine/customize-behavior#app-trigger):** connect the Velt GitHub App or Vercel Integration once, then events route to your workflows automatically. ## Common errors | Code | Meaning | | - | - | | `INVALID_ARGUMENT` | The request failed schema or graph validation, or `x-velt-auth-token` is missing. Graph failures and rule-based schema failures name the rule in the message. A plain missing or mistyped field returns the bare Zod message, such as `Required`. A missing auth token returns the flat message `Auth token is required`. | | `PERMISSION_DENIED` | The `x-velt-auth-token` is not one of the workspace's registered tokens. The `steps/resolve` endpoint also returns it when a `reviewer-approve` or `reviewer-reject` action passes an `actorId` that is not on the step's reviewer list. `recordReviewerDecision` has no reviewer-list check of its own: an undeclared `reviewerId` comes back as `recorded: false`. | | `NOT_FOUND` | Unknown `executionId`, `definitionId`, or `stepId`. | | `ALREADY_EXISTS` | An active definition already uses that `definitionId`. | | `FAILED_PRECONDITION` | State violation, such as resolving a step that is not `waiting`. | | `RESOURCE_EXHAUSTED` | Rate limited. Back off and retry, which is safe with an `idempotencyKey`. | The four most common reasons the engine rejects a definition: * **A human node has no outgoing `on: "reject"` edge.** The message is `every human node must have at least one outgoing edge with on="reject" (a forward reject route or a reject back-edge)`, then a colon and the offending `nodeId`. * **An agent node has neither `url` nor `urlPath`.** The message is `agent node requires either a static "url" or a "urlPath"`. * **A node sets `slaMs` but nothing routes on a breach.** The linter rejects it with the `code` `missing-breach-edge`. * **`when` written as JavaScript.** It must be a JSON-AST string, not `"output.decision == 'approve'"`. Linter failures arrive inside `error.message` as `Definition linter failed:` plus a JSON array, and every entry carries a `code`. Parse the message to read them, because `error.details` stays empty on a linter failure. Match on that `code` rather than on the surrounding message text. See [Linter rules](/docs/ai/approval-engine/customize-behavior#linter-rules) for the full list, and [Anti-patterns](/docs/ai/approval-engine/patterns#anti-patterns) for the mistakes that trigger them. ## Next steps > [card] [Customize Behavior](/docs/ai/approval-engine/customize-behavior) > > Node config, edge routing, triggers, quorum, SLAs, events, and errors. > [card] [REST API Reference](/docs/api-reference/rest-apis/v2/approval-engine/definitions/create-definition) > > Definitions, Executions, and Steps with full schemas. # Chat SDK Adapter Source: https://velt.dev/docs/ai/chat-sdk-adapter Build a bot that reads and responds to Velt comment threads using the Chat SDK and @veltdev/chat-sdk-adapter. [Chat SDK](https://chat-sdk.dev) lets you build cross-platform bots whose logic stays platform-agnostic. The [`@veltdev/chat-sdk-adapter`](https://www.npmjs.com/package/@veltdev/chat-sdk-adapter) connects a Chat SDK bot to **Velt comment threads**, so the same bot can run on Velt, Slack, Discord, and every other Chat SDK adapter. When a user @-mentions your bot or reacts in a comment thread, Velt sends a webhook to your app and the bot responds by replying in the thread, following the conversation, and reacting to events. > [!TIP] > > **Try it live:** open the [tiptap comments demo](https://sample-apps-tiptap-comments-demo.vercel.app), > leave a comment, and @-mention **Velt Bot**, and it streams an AI reply back into the > thread. Source: the [`nextjs-velt-ai-bot`](https://github.com/velt-js/velt-chat-sdk-adapter/tree/main/examples/nextjs-velt-ai-bot) sample app. ## How it maps | Chat SDK | Velt | | - | - | | Thread | Comment annotation inside a document | | Message | Comment | | Channel | Document | | `onNewMention` | A comment that @-mentions the bot | | `onReaction` | A reaction added to / removed from a comment | | `thread.post()` | A reply added to the comment thread | ## Quickstart **1. Install the adapter and Chat SDK** ```bash theme={null} npm install @veltdev/chat-sdk-adapter chat @chat-adapter/state-memory ``` **2. Add your environment variables** Create a `.env.local` file with your Velt API key, the bot's auth token, and the webhook secret. You'll get the webhook secret in the final step. ```env .env.local theme={null} VELT_API_KEY="your-velt-api-key" VELT_AUTH_TOKEN="" VELT_WEBHOOK_SECRET="whsec_..." VELT_ORGANIZATION_ID="your-organization-id" ``` `VELT_AUTH_TOKEN` is optional; if omitted, the adapter generates a bot token from your API key, scoped to `VELT_ORGANIZATION_ID`. **3. Create a user database** The `resolveUsers` function converts Velt user ids into display names. ```tsx app/database.ts theme={null} export const BOT_USER_ID = "velt-bot"; export const BOT_USER_NAME = "Velt Bot"; const USERS = [ { userId: "user-1", name: "Charlie Layne" }, { userId: "user-2", name: "Mislav Abha" }, { userId: BOT_USER_ID, name: BOT_USER_NAME }, ]; export function getUser(userId: string) { const user = USERS.find((u) => u.userId === userId); return user ? { name: user.name } : undefined; } export function resolveUsers({ userIds }: { userIds: string[] }) { return userIds.map((id) => getUser(id)); } ``` **4. Create the bot instance** Create a Chat instance with the Velt adapter and register handlers for mentions and reactions. ```tsx app/bot.ts theme={null} import { Chat } from "chat"; import { createMemoryState } from "@chat-adapter/state-memory"; import { createVeltAdapter, type VeltAdapter } from "@veltdev/chat-sdk-adapter"; import { BOT_USER_ID, BOT_USER_NAME, resolveUsers } from "./database"; let chatSingleton: Chat<{ velt: VeltAdapter }> | null = null; export function getChat() { if (chatSingleton) return chatSingleton; const chat = new Chat<{ velt: VeltAdapter }>({ userName: BOT_USER_NAME, adapters: { velt: createVeltAdapter({ botUserId: BOT_USER_ID, botUserName: BOT_USER_NAME, organizationId: process.env.VELT_ORGANIZATION_ID, resolveUsers, }), }, state: createMemoryState(), }); // Reply when a user @-mentions the bot. chat.onNewMention(async (thread, message) => { await thread.subscribe(); await thread.post(`Hi ${message.author.fullName}! How can I help?`); }); // React to reactions (read-only on the managed backend). chat.onReaction(async (event) => { console.log( `${event.user.fullName} ${event.added ? "added" : "removed"} ${event.emoji}`, ); }); chatSingleton = chat; return chat; } ``` > [!NOTE] > > The bot is created lazily so importing the module doesn't require > credentials at build time. Credentials are read on the first webhook > request. **5. Create the webhook endpoint** The bot processes incoming comments and reactions through this route. It must run on the Node.js runtime because signature verification needs the raw body and Node's `crypto`. ```tsx app/api/webhooks/velt/route.ts theme={null} import { after } from "next/server"; import { getChat } from "../../../bot"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; export async function POST(request: Request) { return getChat().webhooks.velt(request, { waitUntil: (p) => after(() => p) }); } ``` On Vercel, use `waitUntil` from `@vercel/functions` instead of `after`. **6. Set up the Velt webhook** 1. Expose your endpoint publicly (e.g. with a tunnel during development). 2. In the Velt Console → **Configurations → Webhook Service**, set the endpoint URL and enable these events: * `comment.add` * `comment_annotation.add` * `comment.reaction_add` * `comment.reaction_delete` 3. Copy your **webhook secret** (`whsec_...`) into `VELT_WEBHOOK_SECRET`. You can also configure the webhook via [`POST /v2/workspace/webhookconfig/update`](/docs/api-reference/rest-apis/v2/workspace/webhookconfig-update). Now when users @-mention your bot or react to messages in comment threads, your bot responds automatically. ## Webhook versions The adapter supports both Velt webhook systems: * **Advanced (v2):** verified with Svix-style HMAC-SHA256 using the `whsec_...` secret. This is the default. * **Basic (v1):** verified against the `Authorization: Basic ` header. Set `webhookVersion: "v1"` and pass that token as `webhookSecret`. ## Reactions Reading reactions (`onReaction`) works on all Velt plans. > [!WARNING] > > **Writing** reactions (`addReaction` / `removeReaction`) is not supported on > the managed Velt backend, because there is no managed REST endpoint to add a > reaction as a user, so these methods throw a clear error. To enable reaction writes, > pass a `selfHostingConfig.reactionsService` (a self-hosted reactions service > backed by your own database) and the adapter delegates to it. ## What to read next * [Live demo: tiptap comments](https://sample-apps-tiptap-comments-demo.vercel.app) (@-mention **Velt Bot**) * Sample apps: [AI streaming bot](https://github.com/velt-js/velt-chat-sdk-adapter/tree/main/examples/nextjs-velt-ai-bot) · [greeting bot](https://github.com/velt-js/velt-chat-sdk-adapter/tree/main/examples/nextjs-velt-bot) * [Chat SDK documentation](https://chat-sdk.dev) * [`@veltdev/chat-sdk-adapter` on npm](https://www.npmjs.com/package/@veltdev/chat-sdk-adapter) * [Velt Webhooks](/docs/webhooks/advanced) * [Velt REST API: Comments](/docs/api-reference/rest-apis/v2/comments-feature/comments/add-comments) # Memory (Beta) Source: https://velt.dev/docs/ai/memory/overview Memory turns the review decisions your users make in your app into a searchable knowledge base. Query it over REST to search past decisions, ask questions, and get grounded suggestions. Your users comment on and review work inside your app. Memory records every one of those decisions, plus the ones your AI agents make. Add your own guidelines on top, then query all of it over REST. ## How it works **1. Reviews become judgments** Every review decision your users make in your app is recorded as a **judgment**: the decision, the reasoning, who decided, and what they decided on. This happens automatically. There is no "create judgment" endpoint. **2. You add knowledge** Ingest your guidelines, standards, and policy docs. Memory converts each file to markdown, extracts rules, and embeds it. **3. You query both** Use `search` for raw decision records, `ask` for a written answer with citations, and `suggest` for a recommendation on a new item. **4. Memory derives insights** Reviewer profiles, decision patterns, stats, and alerts build up from those judgments over time. > [!NOTE] > > A new workspace starts empty. `ask` returns an empty `answer` with `confidence: 0` until enough review history exists. Memory returns nothing rather than inventing an answer. ## Quickstart Every endpoint is a `POST` under `https://api.velt.dev/v2/`. The examples below read your API key and [Auth Token](/docs/security/auth-tokens) from `$VELT_API_KEY` and `$VELT_AUTH_TOKEN`. ### 1. Add a knowledge source Base64-encode a file and send it. Ingestion runs in the background and returns a `sourceId`. ```bash theme={null} curl -X POST https://api.velt.dev/v2/memory/knowledge/ingest \ -H "x-velt-api-key: $VELT_API_KEY" \ -H "x-velt-auth-token: $VELT_AUTH_TOKEN" \ -H "content-type: application/json" \ -d '{ "data": { "source": "inline", "file": { "base64": "'"$(base64 -w0 brand-guidelines.pdf)"'", "mimeType": "application/pdf", "fileName": "brand-guidelines.pdf", "fileSize": 184320 } } }' # -> { "result": { "status": "processing", "sourceId": "src_9a8...", "message": "Knowledge ingestion task enqueued." } } ``` Poll with that `sourceId` until `status` is `completed` or `failed`: ```bash theme={null} curl -X POST https://api.velt.dev/v2/memory/knowledge/ingest-status \ -H "x-velt-api-key: $VELT_API_KEY" \ -H "x-velt-auth-token: $VELT_AUTH_TOKEN" \ -H "content-type: application/json" \ -d '{ "data": { "sourceId": "src_9a8..." } }' # -> { "result": { "status": "completed", "extractedRulesCount": 7 } } ``` Files up to 5 MB go inline. For files up to 30 MB, call [Get Upload URL](/docs/api-reference/rest-apis/v2/memory/knowledge/upload-url), `PUT` the bytes to the returned `uploadUrl`, then ingest with `{ "source": "fileRef", "fileRef": "", "mimeType": "..." }`. ### 2. Ask a question You get a written answer, the records it drew on, and a confidence score. ```bash theme={null} curl -X POST https://api.velt.dev/v2/memory/ask \ -H "x-velt-api-key: $VELT_API_KEY" \ -H "x-velt-auth-token: $VELT_AUTH_TOKEN" \ -H "content-type: application/json" \ -d '{ "data": { "question": "How do we handle copy that makes medical claims?" } }' ``` ```json theme={null} { "result": { "answer": "Reviewers reject copy that makes medical claims without a citation...", "citations": [ { "recordId": "act_8f3...", "snippet": "Claim 'clinically proven' lacks a citation." } ], "confidence": 0.74, "recordsSearched": 18 } } ``` ### 3. Search past decisions Use `search` when you want the underlying records instead of a written answer. ```bash theme={null} curl -X POST https://api.velt.dev/v2/memory/search \ -H "x-velt-api-key: $VELT_API_KEY" \ -H "x-velt-auth-token: $VELT_AUTH_TOKEN" \ -H "content-type: application/json" \ -d '{ "data": { "query": "unsupported medical claim", "limit": 5, "filters": { "decision": "rejected" } } }' ``` Each result carries the `reasoning`, `decision`, `confidence`, who decided (`actionUser`), and a `similarity` score. ### 4. Get a suggestion Ask what Memory would recommend for a new item, based on precedent. ```bash theme={null} curl -X POST https://api.velt.dev/v2/memory/suggest \ -H "x-velt-api-key: $VELT_API_KEY" \ -H "x-velt-auth-token: $VELT_AUTH_TOKEN" \ -H "content-type: application/json" \ -d '{ "data": { "query": "Ad copy: clinically proven to reduce wrinkles" } }' ``` ```json theme={null} { "result": { "primary": { "recommendation": "reject", "confidence": 0.78, "basedOn": 12, "topReasons": ["Unsupported medical claim"], "caveats": [] }, "conflict": null } } ``` `primary` is the best-grounded recommendation. `conflict` is filled in when the evidence is split, so you can show that reviewers disagree. ## Narrow your results Add these fields to `search` and `ask` to control what Memory reads. | Field | What it does | | - | - | | `organizationId` | Limits the read to one organization. | | `documentId` | Limits the read to one document. Applied only when you also send `organizationId`; without it the field is ignored and the read stays workspace-wide. | | `documentIds` | Limits the read to a set of documents, 1 to 25 ids. Same rules as `documentId`: applied only when you also send `organizationId`, and ignored when you send `documentId` too. `judgments/query` accepts it as well. | | `limit` | `search` only. Caps results. 1 to 50, defaults to 10. `ask` sizes its own retrieval and ignores this field. | | `filters` | Narrows by `decision`, `judgeType` (`human` or `agent`), `contentType`, `reviewerId`, or `dateRange`. `decision` matches the stored value exactly: `comment`, `resolve`, `approved`, `rejected`, `in_progress`, `agree`, `disagree`, `endorse`, `document_approved`, or `document_rejected`. `dateRange` is `{ start, end }` as either ISO-8601 strings or epoch milliseconds. `excludeDocumentIds` leaves out judgments from up to 20 named documents. | | `filters.annotationId` | Reads one comment thread in chronological order. Requires `organizationId`. | | `recencyDays` | Returns the last N complete UTC days of activity instead of a semantic match. 1 to 365. Good for digests. | ## All endpoints > [card] Search and Ask > > [Search Judgments](/docs/api-reference/rest-apis/v2/memory/search) · [Ask Memory](/docs/api-reference/rest-apis/v2/memory/ask) · [Suggest Decision](/docs/api-reference/rest-apis/v2/memory/suggest) · [Query Judgments](/docs/api-reference/rest-apis/v2/memory/judgments/query) > [card] Knowledge > > [Ingest](/docs/api-reference/rest-apis/v2/memory/knowledge/ingest) · [Ingest Status](/docs/api-reference/rest-apis/v2/memory/knowledge/ingest-status) · [Upload URL](/docs/api-reference/rest-apis/v2/memory/knowledge/upload-url) · [Search](/docs/api-reference/rest-apis/v2/memory/knowledge/search) · [List](/docs/api-reference/rest-apis/v2/memory/knowledge/list) · [Rules](/docs/api-reference/rest-apis/v2/memory/knowledge/rules) · [Update](/docs/api-reference/rest-apis/v2/memory/knowledge/update) · [Download](/docs/api-reference/rest-apis/v2/memory/knowledge/download) · [Delete](/docs/api-reference/rest-apis/v2/memory/knowledge/delete) > [card] Insights > > [Reviewer Profile](/docs/api-reference/rest-apis/v2/memory/profiles/get) · [Patterns](/docs/api-reference/rest-apis/v2/memory/patterns/get) · [Stats](/docs/api-reference/rest-apis/v2/memory/stats/get) > [card] Alerts > > [List](/docs/api-reference/rest-apis/v2/memory/alerts/list) · [Dismiss](/docs/api-reference/rest-apis/v2/memory/alerts/dismiss) · [Mark Actioned](/docs/api-reference/rest-apis/v2/memory/alerts/action) · [Get Config](/docs/api-reference/rest-apis/v2/memory/alerts/config/get) · [Update Config](/docs/api-reference/rest-apis/v2/memory/alerts/config/update) > [!TIP] > > There are two searches, and they read different things. [Search Judgments](/docs/api-reference/rest-apis/v2/memory/search) reads past decisions. [Search Knowledge Base](/docs/api-reference/rest-apis/v2/memory/knowledge/search) reads the content of the files you ingested. Pass `includeRules: true` on the second one to search extracted rules too. ## Good to know * **Judgments are read-only.** They come from your users' review activity, so a new workspace has none until people start reviewing. Comments from older SDK clients are enriched into Memory too, including a one-time backfill of historical data. * **Ingestion is asynchronous.** `ingest` returns `processing`. Poll `ingest-status` until it is `completed` or `failed`. * **Supported file types:** PDF, CSV, Excel (`.xlsx`), and plain text. * **File limits:** 5 MB inline, 30 MB by reference. * **Duplicate uploads** report the original source's status, so a duplicate can stay `processing` until the original finishes. `completed` always means safe to download. * **Knowledge rate limits**, per API key per minute: `knowledge/ingest-status` 600, `knowledge/search` 120, `knowledge/upload-url` 100, `knowledge/ingest` 30, `knowledge/delete` 30. Going over returns `RESOURCE_EXHAUSTED`, so keep bulk imports and status polling under those ceilings. ## Errors | Status | Meaning | | - | - | | `INVALID_ARGUMENT` | The request failed validation, or the `x-velt-auth-token` header is missing. | | `PERMISSION_DENIED` | The `x-velt-auth-token` is not valid for this API key. | | `NOT_FOUND` | Unknown `sourceId`, or an `x-velt-api-key` that does not resolve to a workspace. `knowledge/download` is the exception: an unknown `sourceId` there returns `null` with a `200`. | | `ABORTED` | Deleting a source that is still processing, or one that duplicate uploads point at. Poll `ingest-status` until the status is terminal, or delete the duplicates first. | | `FAILED_PRECONDITION` | The signed upload URL expired before you called `ingest`, or you called `knowledge/update` on a source that is not rule-based. | | `RESOURCE_EXHAUSTED` | Rate limited. Back off and retry. | On a validation error, every memory endpoint returns `details.issues` alongside `message` and `status`, listing each failing field. The most common `INVALID_ARGUMENT` causes: * `filters.annotationId` without `organizationId`. * A `documentIds` list that is empty, holds more than 25 ids, or holds an empty id. * `documentId` without `organizationId` on `knowledge/ingest` or `knowledge/upload-url`. * A `dateRange` whose `start` is after its `end`. * An unsupported file type, or an inline file over 5 MB. Use [Get Upload URL](/docs/api-reference/rest-apis/v2/memory/knowledge/upload-url) for larger files. * An unrecognized field on `knowledge/ingest`, `knowledge/upload-url`, `knowledge/ingest-status`, `knowledge/delete`, or `knowledge/search`. These five reject unknown keys, so a typo like `bas64` fails instead of being ignored. `knowledge/search` is workspace-wide and rejects `organizationId` and `documentId`. # Customize Behavior Source: https://velt.dev/docs/ai/rewriter/customize-behavior # addComment Create a comment annotation anchored to the text range from a [`TextSelectedEvent`](/docs/api-reference/sdk/models/data-models#textselectedevent). * **Params:** [`RewriterAddCommentRequest`](/docs/api-reference/sdk/models/data-models#rewriteraddcommentrequest) * **Returns:** `Promise<`[`RewriterAddCommentResponse`](/docs/api-reference/sdk/models/data-models#rewriteraddcommentresponse)`>` > [tab] React / Next.js > > ```js theme={null} > const rewriterElement = client.getRewriterElement(); > > const result = await rewriterElement.addComment({ text: 'Consider simplifying this.', event }); > > if (result.success) { > console.log('Created annotation:', result.annotationId); > } > ``` > [tab] Other Frameworks > > ```js theme={null} > const rewriterElement = Velt.getRewriterElement(); > > const result = await rewriterElement.addComment({ text: 'Consider simplifying this.', event }); > > if (result.success) { > console.log('Created annotation:', result.annotationId); > } > ``` # askAi Send a text-generation prompt to any AI model via Velt's proxy. The provider is resolved automatically from the model name prefix (`gpt-*`/`o1-*`/`o3-*`/`o4-*` → OpenAI, `claude-*` → Anthropic, `gemini-*` → Gemini). * **Params:** [`RewriterAskAiRequest`](/docs/api-reference/sdk/models/data-models#rewriteraskairequest) * **Returns:** `Promise<`[`RewriterAskAiResponse`](/docs/api-reference/sdk/models/data-models#rewriteraskairesponse)`>` > [tab] React / Next.js > > ```js theme={null} > const rewriterElement = client.getRewriterElement(); > > const response = await rewriterElement.askAi({ > model: 'gemini-2.5-flash', > prompt: 'Make it more formal', > selectedText: event.text, > }); > > if (response.success) { > console.log('AI output:', response.text); > } > ``` > [tab] Other Frameworks > > ```js theme={null} > const rewriterElement = Velt.getRewriterElement(); > > const response = await rewriterElement.askAi({ > model: 'gemini-2.5-flash', > prompt: 'Make it more formal', > selectedText: event.text, > }); > > if (response.success) { > console.log('AI output:', response.text); > } > ``` # enableRewriter > [tab] React / Next.js > > ```js theme={null} > const rewriterElement = client.getRewriterElement(); > rewriterElement.enableRewriter(); > rewriterElement.disableRewriter(); //to disable > > ``` > [tab] Other Frameworks > > ```js theme={null} > if (Velt) { > const rewriterElement = Velt.getRewriterElement(); > rewriterElement.enableRewriter(); > rewriterElement.disableRewriter(); //to disable > } > ``` # on Subscribe to Rewriter events. Supports `'textSelected'` to receive a [`TextSelectedEvent`](/docs/api-reference/sdk/models/data-models#textselectedevent) whenever a user selects text in a Rewriter-enabled region. * **Params:** `action: 'textSelected'` * **Returns:** `Observable<`[`TextSelectedEvent`](/docs/api-reference/sdk/models/data-models#textselectedevent)`>` > [tab] React / Next.js > > ```js theme={null} > const rewriterElement = client.getRewriterElement(); > > rewriterElement.on('textSelected').subscribe((event) => { > console.log('Selected text:', event.text); > }); > ``` > [tab] Other Frameworks > > ```js theme={null} > const rewriterElement = Velt.getRewriterElement(); > > rewriterElement.on('textSelected').subscribe((event) => { > console.log('Selected text:', event.text); > }); > ``` # replaceText Replace the DOM text identified by a [`TextSelectedEvent`](/docs/api-reference/sdk/models/data-models#textselectedevent) with new text. * **Params:** [`RewriterReplaceTextRequest`](/docs/api-reference/sdk/models/data-models#rewriterreplacetextrequest) * **Returns:** `Promise<`[`RewriterReplaceTextResponse`](/docs/api-reference/sdk/models/data-models#rewriterreplacetextresponse)`>` > [tab] React / Next.js > > ```js theme={null} > const rewriterElement = client.getRewriterElement(); > > const result = await rewriterElement.replaceText({ text: 'Replacement text', event }); > > if (result.success) { > console.log('Replaced:', result.originalText, '→', result.replacedText); > } > ``` > [tab] Other Frameworks > > ```js theme={null} > const rewriterElement = Velt.getRewriterElement(); > > const result = await rewriterElement.replaceText({ text: 'Replacement text', event }); > > if (result.success) { > console.log('Replaced:', result.originalText, '→', result.replacedText); > } > ``` > [!NOTE] > > `textSelected` does not fire, and `replaceText()` returns `success: false`, for a selection inside TipTap or another ProseMirror-based editor. # enableDefaultUI Show or hide the built-in Velt rewriter toolbar. Calling `disableDefaultUI()` suppresses the toolbar on text selection while keeping all rewriter events active, so you can render a fully custom UI. Call `enableDefaultUI()` to restore the default toolbar. * **Returns:** `void` > [tab] React / Next.js > > ```js theme={null} > const rewriterElement = client.getRewriterElement(); > > // Show the default Velt toolbar on text selection (default state) > rewriterElement.enableDefaultUI(); > > // Hide the default Velt toolbar; handle UI yourself > rewriterElement.disableDefaultUI(); > ``` > [tab] Other Frameworks > > ```js theme={null} > const rewriterElement = Velt.getRewriterElement(); > > // Show the default Velt toolbar on text selection (default state) > rewriterElement.enableDefaultUI(); > > // Hide the default Velt toolbar; handle UI yourself > rewriterElement.disableDefaultUI(); > ``` # Rewriter Source: https://velt.dev/docs/ai/rewriter/overview Let users select text on your website and use AI to rewrite, improve, or comment on it — powered by any major LLM provider. [https://landing-page-demo-velt.vercel.app/?feature=rewriter](https://landing-page-demo-velt.vercel.app/?feature=rewriter) [Open in larger window](https://landing-page-demo-velt.vercel.app/?feature=rewriter) ## What is the Rewriter? The Rewriter lets your users select any text on your website and send it to an AI model for rewriting, then apply the result directly to the page. You can also anchor collaborative comments to any selected text range. Velt handles the AI API, text selection tracking, and DOM replacement — you control the prompts, model choice, and UX. ## Key capabilities * **Multi-model AI API** — Route prompts to OpenAI (`gpt-*`, `o1-*`, `o3-*`, `o4-*`), Anthropic (`claude-*`), or Google (`gemini-*`) through Velt's api with no additional backend setup. * **Text selection tracking** — Subscribe to `textSelected` events to know exactly which text a user highlighted, including its DOM position. * **In-place text replacement** — Replace the selected DOM text with AI-generated output in one API call. * **Comment anchoring** — Attach collaborative comment threads to specific text ranges for review workflows. ## Use cases > [card] Content editing tools > > Let writers and editors select a paragraph and ask AI to adjust tone, simplify language, fix grammar, or expand on an idea — all without leaving the page. > [card] Collaborative document review > > Reviewers select text and leave AI-assisted feedback as anchored comments. Combine `askAi` for suggested rewrites with `addComment` to capture discussion around each change. > [card] CMS and website builders > > Give non-technical users an AI rewrite button inside your CMS. They highlight a heading or product description, pick a prompt like "Make it shorter" or "Add a call to action," and see the update instantly. > [card] Education and writing platforms > > Students select their draft text and get AI-powered suggestions to improve clarity, fix citations, or rephrase for a different audience — with before-and-after visibility. > [card] Localization and translation > > Users highlight text and prompt the AI to translate it into another language or adapt it for a regional audience, then apply the result directly to the page. > [card] Customer support knowledge bases > > Support teams review help articles and use AI to simplify technical jargon, adjust tone for end users, or flag outdated content with anchored comments. ## How it works 1. **Enable the Rewriter** on any page or section of your app. 2. **Listen for text selections** — when a user highlights text, you receive a `TextSelectedEvent` with the selected content and DOM context. 3. **Send an AI prompt** — call `askAi` with the selected text, a prompt, and your preferred model. Velt routes the request through its api. 4. **Apply the result** — call `replaceText` to swap the original text with the AI output in the DOM. 5. **Optionally add a comment** — call `addComment` to anchor a collaborative comment thread to the text range. ## Supported AI models | Provider | Model prefixes | | - | - | | OpenAI | `gpt-*`, `o1-*`, `o3-*`, `o4-*` | | Anthropic | `claude-*` | | Google | `gemini-*` | > [!NOTE] > > You can use your own LLM API keys by configuring them in the [Velt Console](https://console.velt.dev/). This gives you full control over billing, rate limits, and model access. If no custom key is configured, Velt's built-in API handles authentication by default. ## Get started > [card] [Setup](/docs/ai/rewriter/setup) > > Step-by-step guide to enable the Rewriter, subscribe to events, and wire up AI-powered text replacement. > [card] [Customize Behavior](/docs/ai/rewriter/customize-behavior) > > API reference for all Rewriter methods — enable/disable, text events, AI prompts, replacement, and comments. # Setup Source: https://velt.dev/docs/ai/rewriter/setup ## Setup #### Step 1: Enable Rewriter > [tab] React / Next.js > > ```js theme={null} > const rewriterElement = client.getRewriterElement(); > rewriterElement.enableRewriter(); > rewriterElement.disableRewriter(); //to disable > > ``` > [tab] Other Frameworks > > ```js theme={null} > if (Velt) { > const rewriterElement = Velt.getRewriterElement(); > rewriterElement.enableRewriter(); > rewriterElement.disableRewriter(); //to disable > } > ``` #### Step 2: Subscribe to text selection events Subscribe to Rewriter events. Supports `'textSelected'` to receive a [`TextSelectedEvent`](/docs/api-reference/sdk/models/data-models#textselectedevent) whenever a user selects text in a Rewriter-enabled region. * **Params:** `action: 'textSelected'` * **Returns:** `Observable<`[`TextSelectedEvent`](/docs/api-reference/sdk/models/data-models#textselectedevent)`>` > [tab] React / Next.js > > ```js theme={null} > const rewriterElement = client.getRewriterElement(); > > rewriterElement.on('textSelected').subscribe((event) => { > console.log('Selected text:', event.text); > }); > ``` > [tab] Other Frameworks > > ```js theme={null} > const rewriterElement = Velt.getRewriterElement(); > > rewriterElement.on('textSelected').subscribe((event) => { > console.log('Selected text:', event.text); > }); > ``` #### Step 3: Send a prompt to AI Send a text-generation prompt to any AI model via Velt's api. The provider is resolved automatically from the model name prefix (`gpt-*`/`o1-*`/`o3-*`/`o4-*` → OpenAI, `claude-*` → Anthropic, `gemini-*` → Gemini). * **Params:** [`RewriterAskAiRequest`](/docs/api-reference/sdk/models/data-models#rewriteraskairequest) * **Returns:** `Promise<`[`RewriterAskAiResponse`](/docs/api-reference/sdk/models/data-models#rewriteraskairesponse)`>` > [tab] React / Next.js > > ```js theme={null} > const rewriterElement = client.getRewriterElement(); > > const response = await rewriterElement.askAi({ > model: 'gemini-2.5-flash', > prompt: 'Make it more formal', > selectedText: event.text, > }); > > if (response.success) { > console.log('AI output:', response.text); > } > ``` > [tab] Other Frameworks > > ```js theme={null} > const rewriterElement = Velt.getRewriterElement(); > > const response = await rewriterElement.askAi({ > model: 'gemini-2.5-flash', > prompt: 'Make it more formal', > selectedText: event.text, > }); > > if (response.success) { > console.log('AI output:', response.text); > } > ``` #### Step 4: Take action on the returned result Once you have the AI response, you can either replace the selected text in the DOM or anchor a comment to it. Choose the option that fits your use case, or combine both. > [tab] Option A: Replace selected text > > Replace the DOM text identified by a [`TextSelectedEvent`](/docs/api-reference/sdk/models/data-models#textselectedevent) with new text. > > * **Params:** [`RewriterReplaceTextRequest`](/docs/api-reference/sdk/models/data-models#rewriterreplacetextrequest) > > * **Returns:** `Promise<`[`RewriterReplaceTextResponse`](/docs/api-reference/sdk/models/data-models#rewriterreplacetextresponse)`>` > > > [tab] React / Next.js > > > > ```js theme={null} > > const rewriterElement = client.getRewriterElement(); > > > > const result = await rewriterElement.replaceText({ text: aiResponse.text, event }); > > > > if (result.success) { > > console.log('Replaced:', result.originalText, '→', result.replacedText); > > } > > ``` > > > [tab] Other Frameworks > > > > ```js theme={null} > > const rewriterElement = Velt.getRewriterElement(); > > > > const result = await rewriterElement.replaceText({ text: aiResponse.text, event }); > > > > if (result.success) { > > console.log('Replaced:', result.originalText, '→', result.replacedText); > > } > > ``` > [tab] Option B: Add a comment to selected text > > Create a comment annotation anchored to the text range from a [`TextSelectedEvent`](/docs/api-reference/sdk/models/data-models#textselectedevent). > > * **Params:** [`RewriterAddCommentRequest`](/docs/api-reference/sdk/models/data-models#rewriteraddcommentrequest) > > * **Returns:** `Promise<`[`RewriterAddCommentResponse`](/docs/api-reference/sdk/models/data-models#rewriteraddcommentresponse)`>` > > > [tab] React / Next.js > > > > ```js theme={null} > > const rewriterElement = client.getRewriterElement(); > > > > const result = await rewriterElement.addComment({ text: aiResponse.text, event }); > > > > if (result.success) { > > console.log('Created annotation:', result.annotationId); > > } > > ``` > > > [tab] Other Frameworks > > > > ```js theme={null} > > const rewriterElement = Velt.getRewriterElement(); > > > > const result = await rewriterElement.addComment({ text: aiResponse.text, event }); > > > > if (result.success) { > > console.log('Created annotation:', result.annotationId); > > } > > ``` ## Complete Example > [tab] React / Next.js > > ```js theme={null} > const rewriterElement = client.getRewriterElement(); > rewriterElement.enableRewriter(); > > rewriterElement.on('textSelected').subscribe(async (event) => { > const aiResponse = await rewriterElement.askAi({ > model: 'gemini-2.5-flash', > prompt: 'Make it more formal', > selectedText: event.text, > }); > if (aiResponse.success) { > await rewriterElement.replaceText({ text: aiResponse.text, event }); > } > }); > ``` > [tab] Other Frameworks > > ```js theme={null} > const rewriterElement = Velt.getRewriterElement(); > rewriterElement.enableRewriter(); > > rewriterElement.on('textSelected').subscribe(async (event) => { > const aiResponse = await rewriterElement.askAi({ > model: 'gemini-2.5-flash', > prompt: 'Make it more formal', > selectedText: event.text, > }); > if (aiResponse.success) { > await rewriterElement.replaceText({ text: aiResponse.text, event }); > } > }); > ``` # Generate Token Source: https://velt.dev/docs/api-reference/rest-apis/v1/auth/generate-token POST https://api.velt.dev/v1/auth/token/get Use this API to generate a JWT token used by your client to authenticate with Velt. The token encodes user information and optional properties such as organization and admin status. > [!NOTE] > > * JWT token expires in 48 hours. > * For v1, `apiKey` and `authToken` are provided in the request body (not headers). # Endpoint `POST https://api.velt.dev/v1/auth/token/get` # Headers **Content-Type** `string` *required* application/json # Body #### Params **data** `object` *required* **properties** **apiKey** `string` *required* Your Velt API Key. **authToken** `string` *required* Your Auth Token from the Velt console. See [Auth Tokens](/docs/security/auth-tokens). **userId** `string` *required* Unique identifier for the user. **userProperties** `object` **properties** **organizationId** `string` *required* Organization ID. Should match the `organizationId` used in the `identify` call. **isAdmin** `boolean` Whether the user has admin privileges. This is the only supported way to set a user as admin. Do not set this in the `identify` call. **email** `string` User email. If provided, it is validated against the email used in the `identify` call. ## **Example Requests** #### Generate token with organization and admin ```JSON theme={null} { "data": { "apiKey": "YOUR_API_KEY", "authToken": "YOUR_AUTH_TOKEN", "userId": "yourUserId", "userProperties": { "isAdmin": true, "organizationId": "YOUR_ORGANIZATION_ID", "email": "user@example.com" } } } ``` #### Minimal token request ```JSON theme={null} { "data": { "apiKey": "YOUR_API_KEY", "authToken": "YOUR_AUTH_TOKEN", "userId": "yourUserId", "userProperties": { "organizationId": "YOUR_ORGANIZATION_ID" } } } ``` # Response > [!WARNING] > > Generate the JWT token on your server, not your client, to keep your secrets secure. #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Token generated successfully.", "data": { "token": "YOUR_JWT_TOKEN" } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "Auth token not found.", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Token generated successfully.", "data": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } } } ``` # Add Comment Annotations Source: https://velt.dev/docs/api-reference/rest-apis/v1/comments-feature/comment-annotations/add-comment-annotations POST https://api.velt.dev/v1/commentannotations/add Use this API to add comment annotations to a document within an organization. * You can add comments on an elemement, text or page. * You can provide HTML or text content. * Additional filters can be applied using location IDs. # Endpoint `POST https://api.velt.dev/v1/commentannotations/add` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `Object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` *required* Document ID **commentAnnotations** `Object[]` *required* **properties** **annotationId** `string` Custom Annotation ID. If not provided, Velt will generate a unique ID for the annotation. **location** `Object` **properties** **id** `string` *required* Location ID **locationName** `string` Location Name **targetElement** `Object` Target Element **properties** **elementId** `string` Element DOM Id **targetText** `string` Target Text. Provide this if you want to add comment annotation on the provided text content. **occurrence** `number` Occurrence. Provide this if you want to add comment annotation on a text content. **selectAllContent** `boolean` Select All Content. Provide this if you want to select and add comment annotation on the entire text content of the target elementId. **commentData** `Object[]` *required* Array of Comment Data **properties** **commentId** `number` Custom Comment ID. If not provided, Velt will generate a unique ID for the comment. **commentText** `string` Comment content in plain text string **commentHtml** `string` Comment content in HTML string **isCommentResolverUsed** `boolean` Use this for self-hosting comments data. Set this as true if you are comments resolver data provider in the SDK. **isCommentTextAvailable** `boolean` Use this for self-hosting comments data. Set this as true if this comment will have text content. Sometimes, comments might only have attachments and in that case, set this as false. **from** `User` *required* User object from whom the comment is added **createdAt** `number` Created At timestamp (in milliseconds since epoch). **lastUpdated** `number` Last Updated timestamp (in milliseconds since epoch). **taggedUserContacts** `Object[]` Array of tagged user contacts **properties** **text** `string` *required* Display text of the tagged user (e.g. "@Username") **userId** `string` *required* User ID of the tagged user **contact** `Object` *required* **properties** **email** `string` *required* Email of the tagged user **name** `string` *required* Name of the tagged user **userId** `string` *required* User ID of the tagged user **status** `Status` Status **properties** **id** `string` *required* Status ID **name** `string` *required* Status Name **type** `'default' | 'ongoing' | 'terminal'` *required* Type. **color** `string` *required* Text and comment pin color **lightColor** `string` *required* Background color on the status indicator **svg** `string` Raw SVG of the icon. Either `svg` or `iconUrl` is required. **iconUrl** `string` Icon URL. Either `svg` or `iconUrl` is required. **assignedTo** `User` User object to whom the comment is assigned **context** `Object` Custom key/value metadata object **createdAt** `number` Created At timestamp (in milliseconds since epoch). **lastUpdated** `number` Last Updated timestamp (in milliseconds since epoch). **priority** `Object` Priority **properties** **id** `string` *required* Priority ID **color** `string` *required* Priority Color **name** `string` *required* Priority Name **lightColor** `string` *required* Priority Light Color ## **Example Requests** #### Add comment annotation by organizationId, documentId and location ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "commentAnnotations": [ { "location": { "id": "yourLocationId", "locationName": "yourLocationName" }, "targetElement": { "elementId": "yourElementId", "targetText": "Your Target Text", "occurrence": 1, "selectAllContent": false }, "commentData": [ { "commentText": "Sample Comment", "commentHtml": "
Sample Comment
", "from": { "userId": "yourUserId", "name": "yourUserName", "email": "yourUserEmail", } } ] } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Comment Annotation(s) added successfully.", "data": { "-O0mpUziLcBwzREvZKs6": { "success": true, "annotationId": "-O0mpUziLcBwzREvZKs6", "commentIds": [ 126535 ], "message": "Added Successfully" } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Comment Annotation(s) added successfully.", "data": { "-O0mpUziLcBwzREvZKs6": { "success": true, "annotationId": "-O0mpUziLcBwzREvZKs6", "commentIds": [ 126535 ], "message": "Added Successfully" } } } } ``` # Delete Comment Annotations Source: https://velt.dev/docs/api-reference/rest-apis/v1/comments-feature/comment-annotations/delete-comment-annotations POST https://api.velt.dev/v1/commentannotations/delete Use this API to delete comment annotations from a document within an organization. Additional filters can be applied using location IDs, annotation IDs, or user IDs. # Endpoint `POST https://api.velt.dev/v1/commentannotations/delete` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` Organization ID **documentId** `string` *required* Document ID **locationIds** `string[]` Array of Location IDs **annotationIds** `string[]` Array of Annotation IDs **userIds** `string[]` Array of User IDs ## **Example Requests** #### 1. Delete annotations by organizationId and documentId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId" } } ``` #### 2. Delete annotations by organizationId, documentId and locationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationIds": [ "locationx" ] } } ``` #### 3. Delete annotations by organizationId, documentId, locationIds and userIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationIds": [ "locationx" ], "userIds": [ "yourUserId" ] } } ``` #### 4. Delete annotations by organizationId, documentId and userIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "userIds": [ "yourUserId" ] } } ``` #### 5. Delete annotations by organizationId, documentId and annotationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "annotationIds": [ "yourAnnotationId1", "yourAnnotationId2" ] } } ``` #### 6. Delete annotations by organizationId, documentId, locationIds and annotationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationIds": [ "locationx" ], "annotationIds": [ "yourAnnotationId1", "yourAnnotationId2" ] } } ``` #### 7. Delete annotations by documentId. This will work if the document was created without an organization. ```JSON theme={null} { "data": { "documentId": "yourDocumentId" } } ``` #### 8. Delete annotations by documentId and locationIds. This will work if the document was created without an organization. ```JSON theme={null} { "data": { "documentId": "yourDocumentId", "locationIds": [ "locationx" ] } } ``` #### 9. Delete annotations by documentId and userIds. This will work if the document was created without an organization. ```JSON theme={null} { "data": { "documentId": "yourDocumentId", "userIds": [ "yourUserId" ] } } ``` #### 10. Delete annotations by documentId and annotationIds. This will work if the document was created without an organization. ```JSON theme={null} { "data": { "documentId": "yourDocumentId", "annotationIds": [ "yourAnnotationId1", "yourAnnotationId2" ] } } ``` #### 11. Delete annotations by documentId, locationIds, and userIds. This will work if the document was created without an organization. ```JSON theme={null} { "data": { "documentId": "yourDocumentId", "locationIds": [ "locationx" ], "userIds": [ "yourUserId" ] } } ``` #### 12. Delete annotations by documentId, locationIds, and annotationIds. This will work if the document was created without an organization. ```JSON theme={null} { "data": { "documentId": "yourDocumentId", "locationIds": [ "locationx" ], "annotationIds": [ "yourAnnotationId1", "yourAnnotationId2" ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Annotations deleted successfully.", "data": { "yourAnnotationId1": { "success": true, "id": "yourAnnotationId", "message": "Deleted Successfully" }, "yourAnnotationId2": { "success": false, "id": "yourAnnotationId2", "message": "Annotation not found." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Annotations deleted successfully.", "data": { "yourAnnotationId": { "success": true, "id": "yourAnnotationId", "message": "Deleted Successfully" } } } } ``` # Get Comment Annotations Source: https://velt.dev/docs/api-reference/rest-apis/v1/comments-feature/comment-annotations/get-comment-annotations POST https://api.velt.dev/v1/commentannotations/get Use this API to retrieve comment annotations from a document within an organization. Additional filters can be applied using location IDs, annotation IDs, or user IDs. > [!WARNING] > > Use this for SDK v3 or prior versions. # Endpoint `POST https://api.velt.dev/v1/commentannotations/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` *required* Document ID **locationIds** `string[]` Array of Location IDs. Limit: Only 30 IDs can be passed at a time. **annotationIds** `string[]` Array of Annotation IDs. Limit: Only 30 IDs can be passed at a time. **userIds** `string[]` Array of User IDs. Limit: Only 30 IDs can be passed at a time. ## **Example Requests** #### 1. Get annotations by organizationId and documentId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", } } ``` #### 2. Get annotations by organizationId, documentId, and locationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationIds": [ "locationx" ], } } ``` #### 3. Get annotations by organizationId, documentId, locationIds, and userIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationIds": [ "locationx" ], "userIds": [ "yourUserId" ], } } ``` #### 4. Get annotations by organizationId, documentId, and userIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "userIds": [ "yourUserId" ], } } ``` #### 5. Get annotations by organizationId, documentId, and annotationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "annotationIds": [ "yourAnnotationId1", "yourAnnotationId2" ], } } ``` #### 6. Get annotations by organizationId, documentId, locationIds, and annotationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationIds": [ "locationx" ], "annotationIds": [ "yourAnnotationId1", "yourAnnotationId2" ], } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Annotations fetched successfully.", "data": [ { "annotationId": "yourAnnotationId", "comments": [ { "commentId": 123456, "commentText": "This is a sample comment text.", "commentHtml": "

This is a sample comment text.

", "from": { "userId": "user123", "name": "John Doe", "email": "john.doe@example.com" }, "lastUpdated": "2023-06-15T10:30:00Z" } ], "from": { "userId": "user123", "name": "John Doe", "email": "john.doe@example.com" }, "color": "#00FF00", "createdAt": "2023-06-15T10:30:00Z", "lastUpdated": "2023-06-15T10:30:00Z", "status": { "id": "OPEN", "name": "Open", "color": "#0000FF", "type": "default" } }, null // null is returned only if you provided an annotationId that doesn't exist ] } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Annotations fetched successfully.", "data": [ { "annotationId": "yourAnnotationId", "comments": [ { "commentId": 123456, "commentText": "This is a sample comment text.", "commentHtml": "

This is a sample comment text.

", "from": { "userId": "user123", "name": "John Doe", "email": "john.doe@example.com" }, "lastUpdated": "2023-06-15T10:30:00Z", "type": "text", } ], "from": { "userId": "user123", "name": "John Doe", "email": "john.doe@example.com" }, "color": "#00FF00", "createdAt": "2023-06-15T10:30:00Z", "lastUpdated": "2023-06-15T10:30:00Z", "status": { "id": "OPEN", "name": "Open", "color": "#0000FF", "type": "default" } }, null // null is returned only if you provided an annotationId that doesn't exist ] } } ``` # Get Comment Annotations Count Source: https://velt.dev/docs/api-reference/rest-apis/v1/comments-feature/comment-annotations/get-comment-annotations-count POST https://api.velt.dev/v1/commentannotations/count/get Use this API to retrieve the count of comment annotations for specified documents, including both total and unread counts. > [!WARNING] > > Prior to using this API, you must: > > * Enable advanced queries option in [the console](https://console.velt.dev/dashboard/config/appconfig) > * Deploy v4 series of the Velt SDK. # Endpoint `POST https://api.velt.dev/v1/commentannotations/count/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentIds** `string[]` *required* Array of document IDs to get comment annotation counts for. Limit: Only 30 IDs can be passed at a time. **userId** `string` *required* ID of the user requesting the counts **statusIds** `string[]` Array of status IDs to filter comments by (e.g., "OPEN", "IN_PROGRESS") #### **Example Request** ```JSON theme={null} { "data": { "organizationId": "ORG_ID", "documentIds": ["DOC_1", "DOC_2"], "userId": "1.1", "statusIds": ["OPEN", "IN_PROGRESS"] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Comment count retrieved successfully.", "data": { "DOC_1": { "total": 4, "unread": 2 }, "DOC_2": { "total": 2, "unread": 0 } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```JSON theme={null} { "result": { "status": "success", "message": "Comment count retrieved successfully.", "data": { "DOC_1": { "total": 4, "unread": 2 }, "DOC_2": { "total": 2, "unread": 0 } } } } ``` # Update Comment Annotations Source: https://velt.dev/docs/api-reference/rest-apis/v1/comments-feature/comment-annotations/update-comment-annotations POST https://api.velt.dev/v1/commentannotations/update Use this API to update comment annotations in a document within an organization. Additional filters can be applied using location IDs, annotation IDs, or user IDs. # Endpoint `POST https://api.velt.dev/v1/commentannotations/update` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` *required* Document ID **locationIds** `string[]` Array of Location IDs **userIds** `string[]` Array of User IDs. These are the users who created the comment annotation. **annotationIds** `string[]` Array of Annotation IDs **updatedData** `Object[]` **properties** **location** `Object` **properties** **id** `string` *required* Location ID **locationName** `string` Location Name **targetElement** `Object` Target Element **properties** **elementId** `string` Element DOM Id **targetText** `string` Target Text. Provide this if you want to add comment annotation on the provided text content. **occurrence** `number` Occurrence. Provide this if you want to add comment annotation on a text content. **selectAllContent** `boolean` Select All Content. Provide this if you want to select and add comment annotation on the entire text content of the target elementId. **from** `User` User object from whom the Comment Annotation is added **status** `Status` Status **properties** **id** `string` *required* Status ID **name** `string` *required* Status Name **type** `'default' | 'ongoing' | 'terminal'` *required* Type. **color** `string` Text and comment pin color **lightColor** `string` Background color on the status indicator **svg** `string` Raw SVG of the icon. **iconUrl** `string` Icon URL. **assignedTo** `User` User object to whom the comment is assigned **context** `Object` Custom key/value metadata object **priority** `Object` Priority **properties** **id** `string` *required* Priority ID **name** `string` *required* Priority Name **color** `string` Priority Color **lightColor** `string` Priority Light Color **updateUsers** `Object[]` **properties** **oldUser** `User` *required* **properties** **userId** `string` *required* Old user's ID **name** `string` Old user's name **email** `string` Old user's email **newUser** `User` *required* **properties** **userId** `string` *required* New user's ID **name** `string` New user's name **email** `string` New user's email ## **Example Requests** #### 1. Update all comment annotations by organizationId and documentId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "updatedData" : { "status": { "type": "ongoing" } } } } ``` #### 2. Update comment annotations by organizationId, documentId and locationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationIds": [ "locationx" ], "updatedData" : { "status": { "type": "ongoing" } } } } ``` #### 3. Update annotations by organizationId, documentId, locationIds and userIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationIds": [ "locationx" ], "userIds": [ "yourUserId" ], "updatedData" : { "status": { "type": "ongoing" } } } } ``` #### 4. Update comment annotations by organizationId, documentId and userIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "userIds": [ "yourUserId" ], "updatedData" : { "status": { "type": "ongoing" } } } } ``` #### 5. Update comment annotations by organizationId, documentId and annotationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "annotationIds": [ "yourAnnotationId1", "yourAnnotationId2" ], "updatedData" : { "status": { "type": "ongoing" } } } } ``` #### 6. Update comment annotations by organizationId, documentId, locationIds and annotationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationIds": [ "locationx" ], "annotationIds": [ "yourAnnotationId1", "yourAnnotationId2" ], "updatedData" : { "status": { "type": "ongoing" } } } } ``` #### 7. Update Users in existing comment annotations ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "annotationIds": [ "yourAnnotationId1", "yourAnnotationId2" ], "updateUsers" : [ { "oldUser": { "userId": "oldUserId", }, "newUser": { "userId": "newUserId", "name": "newUserName", "email": "newUserEmail" } } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Annotations updated successfully.", "data": { "yourAnnotationId1": { "success": true, "id": "yourAnnotationId1", "message": "Annotations updated successfully" } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Annotations updated successfully.", "data": { "yourAnnotationId1": { "success": true, "id": "yourAnnotationId1", "message": "Annotations updated successfully" } } } } ``` # Add Comments Source: https://velt.dev/docs/api-reference/rest-apis/v1/comments-feature/comments/add-comments POST https://api.velt.dev/v1/commentannotations/comments/add Use this API to add comments within a specific CommentAnnotation. # Endpoint `POST https://api.velt.dev/v1/commentannotations/comments/add` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` *required* Document ID **annotationId** `string` *required* Comment Annotation ID **commentData** `Comment[]` *required* Array of Comment Data **properties** **commentId** `number` Custom Comment ID. If not provided, Velt will generate a unique ID for the comment. **commentText** `string` Comment content in plain text string **commentHtml** `string` Comment content in HTML string **isCommentResolverUsed** `boolean` Use this for self-hosting comments data. Set this as true if you are comments resolver data provider in the SDK. **isCommentTextAvailable** `boolean` Use this for self-hosting comments data. Set this as true if this comment will have text content. Sometimes, comments might only have attachments and in that case, set this as false. **from** `User` *required* User object from whom the comment is added **createdAt** `number` Created At timestamp (in milliseconds since epoch). **lastUpdated** `number` Last Updated timestamp (in milliseconds since epoch). **taggedUserContacts** `Object[]` Array of tagged user contacts **properties** **text** `string` *required* Display text of the tagged user (e.g. "@Username") **userId** `string` *required* User ID of the tagged user **contact** `Object` *required* **properties** **email** `string` *required* Email of the tagged user **name** `string` *required* Name of the tagged user **userId** `string` *required* User ID of the tagged user ## **Example Requests** #### 1. Add comment in a CommentAnnotation by organizationId, documentId, and annotationId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "annotationId": "yourAnnotationId", "commentData": [ { "commentText": "Sample Comment", "commentHtml": "
Hello
", "from": { "userId": "yourUserId" } } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Comment(s) added successfully.", "data": [ 778115 ] } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Comment(s) added successfully.", "data": [ 778115 ] } } ``` # Delete Comments Source: https://velt.dev/docs/api-reference/rest-apis/v1/comments-feature/comments/delete-comments POST https://api.velt.dev/v1/commentannotations/comments/delete Use this API to delete comments within a specific CommentAnnotation. Additional filters can be applied using comment IDs. # Endpoint `POST https://api.velt.dev/v1/commentannotations/comments/delete` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` *required* Document ID **annotationId** `string` *required* Comment Annotation ID **commentIds** `number[]` Array of Comment IDs ## **Example Requests** #### 1. Delete all comments of a CommentAnnotation by organizationId, documentId, and annotationId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "annotationId": "yourAnnotationId" } } ``` #### 2. Delete specific comments of a CommentAnnotation by organizationId, documentId, annotationId and commentIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "annotationId": "yourAnnotationId", "commentIds": [ 153783, 607395 ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Comments(s) deleted successfully.", "data": { "153783": { "success": true, "id": 153783, "message": "Deleted successfully" }, "607395": { "success": false, "id": 607395, "message": "Not found" } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Comments(s) deleted successfully.", "data": { "153783": { "success": true, "id": 153783, "message": "Deleted successfully" } } } } ``` # Get Comments Source: https://velt.dev/docs/api-reference/rest-apis/v1/comments-feature/comments/get-comments POST https://api.velt.dev/v1/commentannotations/comments/get Use this API to retrieve comments in a specific CommentAnnotation. Additional filters can be applied using comment IDs. > [!WARNING] > > Prior to using this API, you must: > > * Enable advanced queries option in [the console](https://console.velt.dev/dashboard/config/appconfig) > * Deploy v4 series of the Velt SDK. # Endpoint `POST https://api.velt.dev/v1/commentannotations/comments/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` *required* Document ID **annotationId** `string` *required* Comment Annotation ID **userIds** `string[]` *required* User IDs **commentIds** `number[]` Array of Comment IDs ## **Example Requests** #### 1. Get all comments with a CommentAnnotation by organizationId, documentId, and annotationId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "annotationId": "yourAnnotationId" } } ``` #### 2. Get specific comments of a CommentAnnotation by organizationId, documentId, annotationId and commentIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "annotationId": "yourAnnotationId", "commentIds": [ 153783, 607395 ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Comments(s) retrieved successfully.", "data": [ { "commentHtml": "
Hello Updated 2
", "commentId": 153783, "commentText": "Sample Comment Text", "from": { "email": "user@example.com", "name": "User Name", "userId": "yourUserId" }, "lastUpdated": "2024-06-20T09:53:42.258Z", "status": "added", "type": "text" }, null // If comment not found ] } } ``` ```js theme={null} { "result": { "status": "success", "message": "Comments(s) retrieved successfully.", "data": [ { "commentHtml": "
Hello Updated 2
", "commentId": 153783, "commentText": "Sample Comment Text", "from": { "email": "user@example.com", "name": "User Name", "userId": "yourUserId" }, "lastUpdated": "2024-06-20T09:53:42.258Z", "status": "added", "type": "text" } ] } } ``` # Update Comments Source: https://velt.dev/docs/api-reference/rest-apis/v1/comments-feature/comments/update-comments POST https://api.velt.dev/v1/commentannotations/comments/update Use this API to update comments within a specific CommentAnnotation. # Endpoint `POST https://api.velt.dev/v1/commentannotations/comments/update` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` *required* Document ID **annotationId** `string` *required* Comment Annotation ID **commentIds** `number[]` *required* Comment IDs **updatedData** `Object` *required* Comment data **properties** **commentText** `string` Comment content in plain text string **commentHtml** `string` Comment content in HTML string **isCommentResolverUsed** `boolean` Use this for self-hosting comments data. Set this as true if you are comments resolver data provider in the SDK. **isCommentTextAvailable** `boolean` Use this for self-hosting comments data. Set this as true if this comment will have text content. Sometimes, comments might only have attachments and in that case, set this as false. **from** `User` *required* User object from whom the comment is added **taggedUserContacts** `Object[]` Array of tagged user contacts **properties** **text** `string` *required* Display text of the tagged user (e.g. "@Username") **userId** `string` *required* User ID of the tagged user **contact** `Object` *required* **properties** **email** `string` *required* Email of the tagged user **name** `string` *required* Name of the tagged user **userId** `string` *required* User ID of the tagged user ## **Example Requests** #### Update comment in a CommentAnnotation by organizationId, documentId, annotationId and commentId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "annotationId": "yourAnnotationId", "commentIds": [ 153783, 607395 ], "updatedData": { "commentText": "Sample Updated Comment", "commentHtml": "
Hello Updated
" } } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Comment updated successfully.", "data": { "607395": { "success": true, "id": 607395, "message": "Updated successfully" } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Comment updated successfully.", "data": { "607395": { "success": true, "id": 607395, "message": "Updated successfully" } } } } ``` # Add Documents Source: https://velt.dev/docs/api-reference/rest-apis/v1/documents/add-documents POST https://api.velt.dev/v1/organizations/documents/add Use this API to add documents with metadata to an organization. # Endpoint `POST https://api.velt.dev/v1/organizations/documents/add` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documents** `Document[]` *required* Array of Document objects **folderId** `string` *required* Folder ID to add the documents to. ## **Example Requests** #### 1. Create new documents ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documents": [ { "documentId": "yourDocumentId", "documentName": "Your Document Name" } ] } } ``` #### 2. Create new documents in a specific folder ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documents": [ { "documentId": "yourDocumentId", "documentName": "Your Document Name" } ], "folderId": "yourFolderId" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Document(s) added successfully.", "data": { "yourDocumentId": { "success": true, "id": "8121657101517513", "message": "Added Successfully" } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Document(s) added successfully.", "data": { "yourDocumentId": { "success": true, "id": "8121657101517513", "message": "Added Successfully" } } } } ``` # Delete Documents Source: https://velt.dev/docs/api-reference/rest-apis/v1/documents/delete-documents POST https://api.velt.dev/v1/organizations/documents/delete Use this API to delete specific documents from an organization. # Endpoint `POST https://api.velt.dev/v1/organizations/documents/delete` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentIds** `string[]` *required* Array of Document IDs ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentIds": ["yourDocumentId1", "yourDocumentId2"] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Document(s) deleted successfully.", "data": { "yourDocumentId1": { "success": true, "id": "6737987049068973", "message": "Deleted Successfully" }, "yourDocumentId2": { "success": false, "id": "yourDocumentId2", "message": "Document does not exist", "code": "not-found" } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` #### Per-Item Failures This endpoint returns HTTP `200` even when individual documents fail. Check `success` on each entry rather than the HTTP status. **code** `string` Why this particular item failed. Present on every entry with `"success": false`. | Value | Meaning | Safe to retry? | | - | - | - | | `not-found` | The document does not exist. | No | | `internal` | A genuine server-side failure. | Yes | ```JSON theme={null} { "result": { "status": "success", "message": "Document(s) deleted successfully.", "data": { "yourDocumentId1": { "success": true, "id": "6737987049068973", "message": "Deleted Successfully" }, "yourDocumentId2": { "success": false, "id": "yourDocumentId2", "message": "Document does not exist", "code": "not-found" } } } } ``` ```js theme={null} { "result": { "status": "success", "message": "Document(s) deleted successfully.", "data": { "yourDocumentId1": { "success": true, "id": "6737987049068973", "message": "Deleted Successfully" } } } } ``` # Get Documents Source: https://velt.dev/docs/api-reference/rest-apis/v1/documents/get-documents POST https://api.velt.dev/v1/organizations/documents/get Use this API to retrieve specific documents or all documents from an organization. > [!WARNING] > > Use this for SDK v3 or prior versions. # Endpoint `POST https://api.velt.dev/v1/organizations/documents/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentIds** `string[]` Array of Document IDs. Limit: Only 30 IDs can be passed at a time. ## **Example Requests** #### 1. Get all documents from organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", } } ``` #### 2. Get specific documents from organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentIds": ["yourDocumentId1", "yourDocumentId2"], } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Document(s) retrieved successfully.", "data": [ { "documentName": "yourDocumentName", "disabled": false, "accessType": "public", "id": "yourDocumentId", } ] } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Document(s) retrieved successfully.", "data": [ { "documentName": "yourDocumentName", "disabled": false, "accessType": "public", "id": "yourDocumentId", } ] } } ``` # Move Documents Source: https://velt.dev/docs/api-reference/rest-apis/v1/documents/move-documents POST https://api.velt.dev/v1/organizations/documents/move Use this API to move documents to a different folder within an organization. # Endpoint `POST https://api.velt.dev/v1/organizations/documents/move` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentIds** `string[]` *required* Array of Document IDs. Limit: Only 30 IDs can be passed at a time. **folderId** `string` *required* ID of the folder where documents will be moved ## **Example Requests** #### Move documents to a folder ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentIds": ["yourDocumentId1", "yourDocumentId2"], "folderId": "targetFolderId" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Documents moved successfully." } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Documents moved successfully." } } ``` # Update Access for Documents Source: https://velt.dev/docs/api-reference/rest-apis/v1/documents/update-document-access POST https://api.velt.dev/v1/organizations/documents/access/update Use this API to update the access type for a single or multiple documents at once. > [!TIP] > > You can update the default access type for all the documents associated with your API Key in [console](https://console.velt.dev/dashboard/config/appconfig). # Endpoint `https://api.velt.dev/v1/organizations/documents/access/update` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentIds** `string[]` *required* Array of Document IDs **accessType** `string` *required* (default: public) Access type for the documents. Allowed values: `organizationPrivate`, `restricted`, `public`. [Learn more](/docs/key-concepts/overview#access-control). ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentIds": ["yourDocumentId1, yourDocumentId2"], "accessType": "organizationPrivate" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Updated access for documents successfully.", "data": { "yourDocumentId": { "success": true, "accessType": "organizationPrivate", "message": "Document access type updated." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Updated access for documents successfully.", "data": { "yourDocumentId": { "success": true, "accessType": "organizationPrivate", "message": "Document access type updated." } } } } ``` # Update Disabled State for Documents Source: https://velt.dev/docs/api-reference/rest-apis/v1/documents/update-document-disable-state POST https://api.velt.dev/v1/organizations/documents/access/disablestate/update Use this API to enable or disable both read and write access for all users. > [!NOTE] > > Let's say your customer's trial or subscription has ended and you want to disable their access to the Velt data, you could use this to diable access to specific documents. # Endpoint `https://api.velt.dev/v1/organizations/documents/access/disablestate/update` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentIds** `string[]` *required* Array of Document IDs **disabled** `boolean` *required* (default: false) Whether to disable read and write access to the specified documents. Allowed values: `true`, `false` ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentIds": ["yourDocumentId"], "disabled": true } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Updated disable state for documents successfully.", "data": { "yourDocumentId": { "success": true, "disabled": true, "message": "Document disabled state updated." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Updated disable state for documents successfully.", "data": { "yourDocumentId": { "success": true, "disabled": true, "message": "Document disabled state updated." } } } } ``` # Update Documents Source: https://velt.dev/docs/api-reference/rest-apis/v1/documents/update-documents POST https://api.velt.dev/v1/organizations/documents/update Use this API to update metadata of documents within an organization. # Endpoint `POST https://api.velt.dev/v1/organizations/documents/update` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documents** `Document[]` *required* Array of Document objects ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documents": [ { "documentId": "yourDocumentId", "documentName": "Your Document Name" } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Document(s) updated successfully.", "data": { "yourDocumentId": { "success": true, "id": "8121657101517513", "message": "Updated Successfully" } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` #### Per-Item Failures This endpoint returns HTTP `200` even when individual documents fail. Check `success` on each entry rather than the HTTP status. **code** `string` Why this particular item failed. Present on every entry with `"success": false`. | Value | Meaning | Safe to retry? | | - | - | - | | `not-found` | The document does not exist. | No | | `internal` | A genuine server-side failure. | Yes | ```JSON theme={null} { "result": { "status": "success", "message": "Document(s) updated successfully.", "data": { "yourDocumentId1": { "success": true, "id": "6737987049068973", "message": "Updated Successfully" }, "yourDocumentId2": { "success": false, "id": "yourDocumentId2", "message": "Document does not exist", "code": "not-found" } } } } ``` ```js theme={null} { "result": { "status": "success", "message": "Document(s) updated successfully.", "data": { "yourDocumentId": { "success": true, "id": "8121657101517513", "message": "Updated Successfully" } } } } ``` # Add Folder Source: https://velt.dev/docs/api-reference/rest-apis/v1/folders/add-folder POST https://api.velt.dev/v1/organizations/folders/add Use this API to create a new folder in an organization. > [!WARNING] > > Prior to using this API, you must: > > * Enable advanced queries option in [the console](https://console.velt.dev/dashboard/config/appconfig) > * Deploy v4 series of the Velt SDK. # Endpoint `POST https://api.velt.dev/v1/organizations/folders/add` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **folders** `Folders[]` *required* **properties** **folderId** `string` *required* Unique identifier for the new folder **folderName** `string` Name of the folder **parentFolderId** `string` ID of the parent folder ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "folders": [ { "folderId": "yourFolderId", "folderName": "yourFolderName", "parentFolderId": "yourParentFolderId" } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Folder created successfully.", "data": { "yourFolderId": { "success": true, "id": "yourFolderId", "message": "Folder added." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Folder created successfully.", "data": { "yourFolderId": { "success": true, "id": "yourFolderId", "message": "Folder added." } } } } ``` # Get Folders Source: https://velt.dev/docs/api-reference/rest-apis/v1/folders/get-folders POST https://api.velt.dev/v1/organizations/folders/get Use this API to retrieve the given folder's metadata and its subfolders. > [!WARNING] > > Prior to using this API, you must: > > * Enable advanced queries option in [the console](https://console.velt.dev/dashboard/config/appconfig) > * Deploy v4 series of the Velt SDK. # Endpoint `POST https://api.velt.dev/v1/organizations/folders/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **folderId** `string` Folder ID to retrieve a specific folder and its subfolders. If not provided, all folders in the organization will be retrieved. ## **Example Requests** #### 1. Get all folders in organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId" } } ``` #### 2. Get specific folder in an organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "folderId": "yourFolderId" } } ``` # Response #### Success Response for All Folders ```JSON theme={null} { "result": { "status": "success", "message": "Folders retrieved successfully.", "data": [ { "folderId": "folderId1", "folderName": "Folder 1", "organizationId": "yourOrganizationId", "parentFolderId": "root", "createdAt": 1738695615706, "lastUpdated": 1738696287859 }, { "folderId": "folderId2", "folderName": "Folder 2", "organizationId": "yourOrganizationId", "parentFolderId": "root", "createdAt": 1738695077691, "lastUpdated": 1738695077691 } ] } } ``` #### Success Response for Specific Folder ```JSON theme={null} { "result": { "status": "success", "message": "Folders retrieved successfully.", "data": [ { "folderId": "folderId1", "folderName": "Folder 1", "organizationId": "yourOrganizationId", "parentFolderId": "root", "createdAt": 1738695077691, "lastUpdated": 1738695077691, "subFolders": [ { "folderId": "childFolderId1", "folderName": "Child Folder 1", "organizationId": "yourOrganizationId", "parentFolderId": "folderId1", "createdAt": 1738695615706, "lastUpdated": 1738698727591 } ] } ] } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Folders retrieved successfully.", "data": [ { "folderId": "folderId1", "folderName": "Folder 1", "organizationId": "yourOrganizationId", "parentFolderId": "root", "createdAt": 1738695077691, "lastUpdated": 1738695077691, "subFolders": [ { "folderId": "childFolderId1", "folderName": "Child Folder 1", "organizationId": "yourOrganizationId", "parentFolderId": "folderId1", "createdAt": 1738695615706, "lastUpdated": 1738698727591 } ] } ] } } ``` # Update Folder Source: https://velt.dev/docs/api-reference/rest-apis/v1/folders/update-folder POST https://api.velt.dev/v1/organizations/folders/update Use this API to: 1. update metadata of a folder within an organization. 2. move a folder and its contents to a different parent folder. > [!WARNING] > > Prior to using this API, you must: > > * Enable advanced queries option in [the console](https://console.velt.dev/dashboard/config/appconfig) > * Deploy v4 series of the Velt SDK. # Endpoint `POST https://api.velt.dev/v1/organizations/folders/update` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **folders** `Folders[]` *required* **properties** **folderId** `string` *required* Unique identifier for the new folder **folderName** `string` Name of the folder **parentFolderId** `string` ID of the parent folder ## **Example Request** ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "folders": [ { "folderId": "yourFolderId", "folderName": "yourFolderName", "parentFolderId": "yourParentFolderId" } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Folder Updated successfully.", "data": { "yourFolderId": { "success": true, "id": "yourFolderId", "message": "Folder Updated." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Folder Updated successfully.", "data": { "yourFolderId": { "success": true, "id": "yourFolderId", "message": "Folder Updated." } } } } ``` # Update Access for Folders Source: https://velt.dev/docs/api-reference/rest-apis/v1/folders/update-folder-access POST https://api.velt.dev/v1/organizations/folders/access/update Use this API to update the access type for a single or multiple folders at once. > [!TIP] > > You can update the default access type for all the folders associated with your API Key in [console](https://console.velt.dev/dashboard/config/appconfig). # Endpoint `https://api.velt.dev/v1/organizations/folders/access/update` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **folderIds** `string[]` *required* Array of Folder IDs **accessType** `string` *required* (default: public) Access type for the folders. Allowed values: `organizationPrivate`, `restricted`, `public`. [Learn more](/docs/key-concepts/overview#access-control). ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "folderIds": ["yourFolderId1, yourFolderId2"], "accessType": "organizationPrivate" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Updated access for folders successfully.", "data": { "yourFolderId": { "success": true, "accessType": "organizationPrivate", "message": "Folder access type updated." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Updated access for folders successfully.", "data": { "yourFolderId": { "success": true, "accessType": "organizationPrivate", "message": "Folder access type updated." } } } } ``` # Delete All User Data Source: https://velt.dev/docs/api-reference/rest-apis/v1/gdpr/delete-all-user-data-gdpr POST https://api.velt.dev/v1/users/data/delete Remove All User data from Velt. Use this API to remove all user data from Velt. This will: * remove their access from all the documents and data in the organization. * remove them from @mention contact dropdown list. * remove them from @mentions where they were tagged. * remove all feature data created by the user. eg: comments, reactions etc. > [!WARNING] > > * This API may take up to 5 minutes to return a 202 response since it runs an asynchronous job to delete user data across the system. > * To speed up this process, you can optionally provide the organizationIds where the user belongs. > * The actual deletion of data can take upto 24 hours to complete. # Endpoint `POST https://api.velt.dev/v1/users/data/delete` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **userIds** `string[]` *required* Array of user Ids. **organizationIds** `string[]` Array of organization Ids. These are the organizations that the user is part of. ## **Example Request** ```JSON theme={null} { "data": { "userIds": [ "yourUserId1", "yourUserId2" ], "organizationIds": [ "yourOrganizationId1", "yourOrganizationId2" ] } } ``` # Response #### Success Response ```JSON theme={null} { "status": "success", "message": "Data deletion process has been initiated.", "data": { "jobId": "dsQuvPmIynANgPLLEhCm", "tasksCount": 5 }, "statusCode": 202 } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "status": "success", "message": "Data deletion process has been initiated.", "data": { "jobId": "dsQuvPmIynANgPLLEhCm", "tasksCount": 5 }, "statusCode": 202 } ``` # Get All User Data Source: https://velt.dev/docs/api-reference/rest-apis/v1/gdpr/get-all-user-data-gdpr POST https://api.velt.dev/v1/users/data/get Get all feature data for a user stored in Velt. Use this API to get all feature data for a user stored in Velt. * The data will be paginated and returned in chunks of 100 items per feature data. * You can use the `nextPageToken` returned in the response to fetch the next chunk of data. * If there are no more items to fetch, the `nextPageToken` will not be returned. * Here is the data that will be included: * **User profile data:** If they were added to any organization, document or folder. * **Comments data:** All the comments created by the user or where they were involved in. * **Reactions data:** All the reactions created by the user. * **Notifications data:** All the notifications where the user was involved in. * **Recordings data:** All the recordings created by the user. > [!WARNING] > > This API may take a few seconds to return a response depending on the dataset size. # Endpoint `POST https://api.velt.dev/v1/users/data/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* The organization Id of the organization that the user is part of. **userId** `string` *required* The user Id of the user you want to get the data for. **pageToken** `string` Page token retrieved from previous API call. ## **Example Request** ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "userId": "yourUserId", "pageToken": "yourPageToken" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Data fetched successfully.", "data": { "comments": [..], //Upto 100 items. Empty array if no items are found. "reactions": [..], //Upto 100 items. Empty array if no items are found. "recordings": [..], //Upto 100 items. Empty array if no items are found. "notifications": [..] //Upto 100 items. Empty array if no items are found. }, "nextPageToken": "bhdwdqwjs298e39e479ddkeuw==329" // This will be null if there are no more items to fetch. } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT", "code": 500 } } ``` ```js theme={null} { "result": { "status": "success", "message": "Data fetched successfully.", "data": { "comments": [..], //Upto 100 items. Empty array if no items are found. "reactions": [..], //Upto 100 items. Empty array if no items are found. "recordings": [..], //Upto 100 items. Empty array if no items are found. "notifications": [..] //Upto 100 items. Empty array if no items are found. }, "nextPageToken": "bhdwdqwjs298e39e479ddkeuw==329" //This will be null if there are no more items to fetch. } } ``` # Get Delete All User Data Status Source: https://velt.dev/docs/api-reference/rest-apis/v1/gdpr/get-delete-user-data-status-gdpr POST https://api.velt.dev/v1/users/data/delete/status Get the status of the data deletion process for a user. Use this API to get the status of the data deletion process for a user. > [!WARNING] > > This API may take a few seconds to return a response depending on the dataset size. # Endpoint `POST https://api.velt.dev/v1/users/data/delete/status` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **jobId** `string` *required* The job Id of the data deletion process. ## **Example Request** ```JSON theme={null} { "data": { "jobId": "yourJobId" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Data fetched successfully.", "data": { "isDeleteCompleted": true, "tasksLeft": 0, "lastTaskCompletedTime": 1748972106739 } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT", "code": 500 } } ``` ```js theme={null} { "result": { "status": "success", "message": "Data fetched successfully.", "data": { "isDeleteCompleted": true, "tasksLeft": 0, "lastTaskCompletedTime": 1748972106739 } } } ``` # Broadcast Event Source: https://velt.dev/docs/api-reference/rest-apis/v1/livestate/broadcast-event POST https://api.velt.dev/v1/livestate/broadcast Use this API to broadcast live state events to any document. Use it with the [Live State](/docs/realtime-collaboration/live-state-sync/setup#get-live-data) feature. # Endpoint `POST https://api.velt.dev/v1/livestate/broadcast` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body Parameters **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID where the document belongs **documentId** `string` *required* Document ID to broadcast the event to **liveStateDataId** `string` *required* Unique identifier for the live state data **data** `Object` *required* The data to broadcast. Can be any valid serializable JSON object. **merge** `boolean` (default: false) If true, merges the new data with existing data instead of replacing it ## Example Request ```JSON theme={null} { "organizationId": "YOUR_ORGANIZATION_ID", "documentId": "YOUR_DOCUMENT_ID", "liveStateDataId": "sample_live_state_data_id", "data": { "status": "active", "message": "Hello World", "customField": "custom value" }, "merge": true } ``` # Response ## Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Event broadcasted successfully.", "data": { "success": true } } } ``` ## Error Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "ERROR_CODE" } } ``` ```json theme={null} { "result": { "status": "success", "message": "Event broadcasted successfully.", "data": { "success": true } } } ``` # Delete Data by Location Source: https://velt.dev/docs/api-reference/rest-apis/v1/locations/delete-data-by-location POST https://api.velt.dev/v1/organizations/documents/locations/data/delete Delete all data associated with a specific location Use this API to delete all data (comments, recordings, or any other feature data) associated with a specific location. # Endpoint `POST https://api.velt.dev/v1/organizations/documents/locations/data/delete` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **apiKey** `string` *required* Your API key **authToken** `string` *required* Your Auth Token **documentId** `string` *required* Document ID **location** `object` *required* The location object containing the data to be deleted ## **Example Request** ```JSON theme={null} { "data": { "apiKey": "YOUR_API_KEY", "authToken": "YOUR_AUTH_TOKEN", "documentId": "YOUR_DOCUMENT_ID", "location": { "id": "scene_1", "locationName": "White scene" } } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Data deleted successfully.", "data": null } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Data deleted successfully.", "data": null } } ``` # Update Location Source: https://velt.dev/docs/api-reference/rest-apis/v1/locations/update-location POST https://api.velt.dev/v1/organizations/documents/locations/update Update a Location's metadata Use this API to update a Location's metadata. # Endpoint `POST https://api.velt.dev/v1/organizations/documents/locations/update` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **apiKey** `string` *required* Your API key **authToken** `string` *required* Your Auth Token **organizationId** `string` Organization ID. Provide the organizationId if you are using Organizations feature. **documentId** `string` *required* Document ID **migrate** `object` *required* **properties** **oldLocation** `object` *required* The current location object **newLocation** `object` *required* The updated location object **merge** `boolean` When true, merges new location fields with existing ones. When false, completely replaces the old location object. Default: false ## **Example Request** ```JSON theme={null} { "data": { "apiKey": "YOUR_API_KEY", "authToken": "YOUR_AUTH_TOKEN", "documentId": "YOUR_DOCUMENT_ID", "migrate": { "oldLocation": { "id": "scene_1", "locationName": "Untitled scene" }, "newLocation": { "id": "scene_1", "locationName": "White scene" } }, "merge": true } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Location updated.", "data": null } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Location updated.", "data": null } } ``` # Add Notifications Source: https://velt.dev/docs/api-reference/rest-apis/v1/notifications/add-notifications POST https://api.velt.dev/v1/notifications/add Use this API to add notifications. # Endpoint `POST https://api.velt.dev/v1/notifications/add` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` *required* Document ID **actionUser** `User` *required* User who took the action **notificationId** `string` Notification ID. If not provided, Velt will generate a random ID. Use this if you want more control on the ID being set and prevent duplicate notifications. Only the special characters `_`, `-` are allowed. **displayHeadlineMessageTemplate** `string` *required* Display Headline Message Template **displayHeadlineMessageTemplateData** `object` Display Headline Message Template Data (Optional) **properties** **actionUser** `User` User who took the action **recipientUser** `string` User who was directly affected by the action **yourCustomField** `string` Any custom field with string value **displayBodyMessage** `string` *required* Display Body Message **notifyUsers** `User[]` *required* Array of Notify Users **notifyAll** `boolean` Default is true. If set to true, the notification will be sent to all users in the organization. If set to false, the notification will be sent to only the users specified in the `notifyUsers` array. **notificationSourceData** `object` Any custom object to be stored with the notification. When the user clicks on the notification, this data will be sent in the callback. **createDocument** `boolean` If set to true, a new document will be created before the notification is created. **createOrganization** `boolean` If set to true, a new organization will be created (if it doesn't exist) before the notification is created. ## **Example Request** ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "actionUser": { "userId": "yourUserId", "name": "User Name", "email": "user@example.com" }, "displayHeadlineMessageTemplate": "This is main template, you can pass variables using curly brackets like this: {actionUser}, {recipientUser}, {yourCustomVariableWithStringValue}", "displayHeadlineMessageTemplateData": { "actionUser": { "userId": "yourUserId", "name": "User Name", "email": "user@example.com" }, "recipientUser": { "userId": "recipientUserId", "name": "Recipient Name", "email": "recipient@example.com" }, "yourCustomField": "Variable will be replaced with this text" }, "displayBodyMessage": "This is body message (Secondary message)", "notifyUsers": [ { "email": "test@example.com", "userId": "testingUserId" }, { "userId": "yourUserId", "name": "User Name", "email": "user@example.com" } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Notification added successfully.", "data": { "success": true, "message": "Notification added successfully." } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Notification added successfully.", "data": { "success": true, "message": "Notification added successfully." } } } ``` # Delete Notifications Source: https://velt.dev/docs/api-reference/rest-apis/v1/notifications/delete-notifications POST https://api.velt.dev/v1/notifications/delete Use this API to delete notifications. # Endpoint `POST https://api.velt.dev/v1/notifications/delete` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` Document ID (Optional) **locationId** `string` Location ID (Optional) **userId** `string` User ID (Optional) **notificationIds** `string[]` Array of Notification IDs (Optional) ## **Example Requests** #### 1. Delete by organizationId and documentId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId" } } ``` #### 2. Delete by organizationId, documentId and notificationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "notificationIds": [ "yourNotificationId" ] } } ``` #### 3. Delete by organizationId and userId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "userId": "yourUserId" } } ``` #### 4. Delete by organizationId, userId and notificationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "userId": "yourUserId", "notificationIds": [ "yourNotificationId" ] } } ``` #### 5. Delete by organizationId, documentId and userId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "userId": "yourUserId" } } ``` #### 6. Delete by organizationId, documentId, userId and notificationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "userId": "yourUserId", "notificationIds": [ "yourNotificationId" ] } } ``` #### 7.Delete by organizationId, documentId and locationId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationId": "yourLocationId" } } ``` #### 8. Delete by organizationId, documentId, locationId and notificationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationId": "yourLocationId", "notificationIds": [ "yourNotificationId" ] } } ``` #### 9. Delete by organizationId, locationId and userId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "locationId": "yourLocationId", "userId": "yourUserId", } } ``` #### 10. Delete by organizationId, locationId, userId, and notificationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "locationId": "yourLocationId", "userId": "yourUserId", "notificationIds": [ "yourNotificationId" ] } } ``` #### 11. Delete by organizationId, documentId, locationId and userId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationId": "yourLocationId", "userId": "yourUserId", } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Notification(s) deleted successfully.", "data": { "8955243231506071": { "success": true, "message": "Notification deleted." } } } } ``` #### When some notifications are not found ```JSON theme={null} { "result": { "status": "success", "message": "Notification(s) deleted successfully.", "data": { "89552432315060712": { "success": false, "message": "Failed to delete notification." }, "8955243231506071": { "success": true, "message": "Notification deleted." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Notification(s) deleted successfully.", "data": { "8955243231506071": { "success": true, "message": "Notification deleted." } } } } ``` # Get Config Source: https://velt.dev/docs/api-reference/rest-apis/v1/notifications/get-config POST https://api.velt.dev/v1/notifications/config/get > [!WARNING] > > To use this API, you must have the this feature enabled in [Velt console](https://console.velt.dev/dashboard/config/notification) Use this API to set the notifications config for users. # Endpoint `POST https://api.velt.dev/v1/notifications/config/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* The ID of the organization. **documentIds** `string[]` *required* An array of document IDs. The notification configuration will be fetched for these documents for the specified user. Max 30 documents can be fetched at a time. **userId** `string` *required* The ID of the user. ## **Example Request** ```JSON theme={null} { "data": { "organizationId": "org1", "documentIds": ["doc1"], "userId":"USER_ID1" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "User config fetched successfully.", "data": [ { "config": { "inbox": "ALL", "email": "ALL" }, "metadata": { "organizationId": "org1", "apiKey": "API_KEY", "documentId": "doc1", "userId": "USER_ID1" } } ] } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "User config fetched successfully.", "data": [ { "config": { "inbox": "ALL", "email": "ALL" }, "metadata": { "organizationId": "org1", "apiKey": "API_KEY", "documentId": "doc1", "userId": "USER_ID1" } } ] } } ``` # Get Notifications Source: https://velt.dev/docs/api-reference/rest-apis/v1/notifications/get-notifications POST https://api.velt.dev/v1/notifications/get Use this API to retrieve notifications. > [!WARNING] > > Use this for SDK v3 or prior versions. # Endpoint `POST https://api.velt.dev/v1/notifications/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` Document ID **locationId** `string` Location ID **userId** `string` User ID **notificationIds** `string[]` Array of Notification IDs. Limit: Only 30 items can be passed at a time. ## **Example Requests** #### 1. Get by organizationId, documentId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId" } } ``` #### 2. Get by organizationId, documentId and notificationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "notificationIds": [ "yourNotificationId" ] } } ``` #### 3. Get by organizationId, documentId and locationId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationId": "yourLocationId" } } ``` #### 4. Get by organizationId, documentId, locationId and notificationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationId": "yourLocationId", "notificationIds": [ "yourNotificationId" ] } } ``` #### 5. Get by organizationId and userId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "userId": "yourUserId" } } ``` #### 6. Get by organizationId, userId and notificationIds ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "userId": "yourUserId", "notificationIds": [ "yourNotificationId" ] } } ``` #### 7. Get by organizationId, documentId and userId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "userId": "yourUserId" } } ``` #### 8. Get by organizationId, locationId and userId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "userId": "yourUserId", "locationId": "yourLocationId" } } ``` #### 9. Get by organizationId, documentId, locationId, and userId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "userId": "yourUserId", "locationId": "yourLocationId" } } ``` # Response > [!NOTE] > > Velt filters results by comment visibility. A notification for a private comment reaches only users who can see that comment. This check runs in addition to any Access Context filtering. #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Notification(s) retrieved successfully.", "data": [ { "id": "notificationId", "notificationSource": "custom", "notificationSourceData": {}, //The data of the notification source. e.g., CommentAnnotation "actionUser": { "email": "user@example.com", "name": "User Name", "userId": "yourUserId" }, "displayBodyMessage": "This is body message (Secondary message)", "displayHeadlineMessageTemplate": "This is main template, you can pass variables using curly brackets like this: {actionUser}, {recipientUser}, {yourCustomVariableWithStringValue}", "displayHeadlineMessageTemplateData": { "actionUser": { "email": "user@example.com", "name": "User Name", "userId": "yourUserId" }, "recipientUser": { "email": "recipient@example.com", "name": "Recipient Name", "userId": "recipientUserId" }, "yourCustomVariableWithStringValue": "Variable will be replaced with this text" }, "metadata": { "apiKey": "yourApiKey", "documentId": "yourDocumentId", "organizationId": "yourOrganizationId" }, "notifyUsers": { "yourNotifyUserId": true }, "notifyUsersByUserId": { "yourNotifyUserById": true }, "timestamp": 1722409519944 } ] } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Notification(s) retrieved successfully.", "data": [ { "id": "notificationId", "notificationSource": "custom", "notificationSourceData": {}, //The data of the notification source. e.g., CommentAnnotation "actionUser": { "email": "user@example.com", "name": "User Name", "userId": "yourUserId" }, "displayBodyMessage": "This is body message (Secondary message)", "displayHeadlineMessageTemplate": "This is main template, you can pass variables using curly brackets like this: {actionUser}, {recipientUser}, {yourCustomVariableWithStringValue}", "displayHeadlineMessageTemplateData": { "actionUser": { "email": "user@example.com", "name": "User Name", "userId": "yourUserId" }, "recipientUser": { "email": "recipient@example.com", "name": "Recipient Name", "userId": "recipientUserId" }, "yourCustomVariableWithStringValue": "Variable will be replaced with this text" }, "metadata": { "apiKey": "yourApiKey", "documentId": "yourDocumentId", "organizationId": "yourOrganizationId" }, "notifyUsers": { "yourNotifyUserId": true }, "notifyUsersByUserId": { "yourNotifyUserById": true }, "timestamp": 1722409519944 } ] } } ``` # Set Config Source: https://velt.dev/docs/api-reference/rest-apis/v1/notifications/set-config POST https://api.velt.dev/v1/notifications/config/set > [!WARNING] > > To use this API, you must have the this feature enabled in [Velt console](https://console.velt.dev/dashboard/config/notification) Use this API to set the notifications config for users. # Endpoint `POST https://api.velt.dev/v1/notifications/config/set` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* The ID of the organization. **documentIds** `string[]` *required* An array of document IDs. The notification configuration will be applied to these documents for the specified users. **userIds** `string[]` *required* An array of user IDs. The notification configuration will be set for these users. **config** `object` *required* Object containing the notification preferences. **properties** **inbox** `string` In-app inbox notification preference. Valid values:
  • `ALL`: User receives all notifications in their inbox.
  • `MINE`: User receives notifications in their inbox only for activities directly involving them (e.g., mentions, replies).
  • `NONE`: User receives no notifications in their inbox.
Optional. **email** `string` Email notification preference. Valid values:
  • `ALL`: User receives email notifications for all activities.
  • `MINE`: User receives email notifications only for activities directly involving them.
  • `NONE`: User receives no email notifications.
Optional. **slack** `string` Slack notification preference (requires Slack integration to be effective). Valid values:
  • `ALL`: User receives Slack notifications for all activities.
  • `MINE`: User receives Slack notifications only for activities directly involving them.
  • `NONE`: User receives no Slack notifications.
Optional. ## **Example Request** ```JSON theme={null} { "data": { "organizationId": "org1", "documentIds": ["doc1"], "userIds":["USER_ID1"], "config":{ "inbox": "ALL", // ALL | MINE | NONE "email": "ALL" // ALL | MINE | NONE } } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "User config set successfully.", "data": { "USER_ID1": { "success": true, "userId": "USER_ID1", "documentId": "doc1", "message": "User config set successfully." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "User config set successfully.", "data": { "USER_ID1": { "success": true, "userId": "USER_ID1", "documentId": "doc1", "message": "User config set successfully." } } } } ``` # Update Notifications Source: https://velt.dev/docs/api-reference/rest-apis/v1/notifications/update-notifications POST https://api.velt.dev/v1/notifications/update Use this API to update notifications. # Endpoint `POST https://api.velt.dev/v1/notifications/update` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` Document ID (Optional) **locationId** `string` Location ID **userId** `string` User ID (Optional) **notifications** `object` Notifications object **properties** **id** `string` Notification ID **actionUser** `User` User who took the action **displayHeadlineMessageTemplate** `string` Display Headline Message Template **displayHeadlineMessageTemplateData** `object` Display Headline Message Template Data **properties** **actionUser** `User` User who took the action **recipientUser** `string` User who was directly affected by the action **yourCustomField** `string` Any custom field with string value **displayBodyMessage** `string` Display Body Message **notificationSourceData** `object` Any custom object to be stored with the notification. When the user clicks on the notification, this data will be sent to in the callback. **readByUserIds** `string[]` Array of user ids that you want to mark the notification as read. **persistReadForUsers** `boolean` Use this with the `readByUserIds` param. If `true`, the read notifications will be not be removed from the "For You" tab. ## **Example Requests** #### 1. Update by organizationId and documentId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "notifications": [ { "id": "yourNotificationId", "displayBodyMessage": "This is body message (Secondary message)", } ] } } ``` #### 2. Update by organizationId, documentId and locationId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "locationId": "yourLocationId", "notifications": [ { "id": "yourNotificationId", "displayBodyMessage": "This is body message (Secondary message)", } ] } } ``` #### 3. Update by organizationId, documentId and userId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "userId": "yourUserId", "notifications": [ { "id": "yourNotificationId", "displayBodyMessage": "This is body message (Secondary message)", } ] } } ``` #### 4. Update by organizationId and userId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "userId": "yourUserId", "notifications": [ { "id": "yourNotificationId", "displayBodyMessage": "This is body message (Secondary message)", } ] } } ``` #### 5. Update by organizationId, documentId, locationId and userId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "userId": "yourUserId", "locationId": "yourLocationId", "notifications": [ { "id": "yourNotificationId", "displayBodyMessage": "This is body message (Secondary message)", } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Notification(s) updated successfully.", "data": { "5471488637912692": { "success": true, "message": "Notification updated." } } } } ``` #### When some notifications are not found ```JSON theme={null} { "result": { "status": "success", "message": "Notification(s) updated successfully.", "data": { "5471488637912692": { "success": false, "message": "Failed to update notification." }, "5471488637912693": { "success": true, "message": "Notification updated." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Notification(s) updated successfully.", "data": { "5471488637912692": { "success": true, "message": "Notification updated." } } } } ``` # Add Organizations Source: https://velt.dev/docs/api-reference/rest-apis/v1/organizations/add-organizations POST https://api.velt.dev/v1/organizations/add Use this API to add new organizations and its metadata. # Endpoint `POST https://api.velt.dev/v1/organizations/add` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizations** `Organization[]` *required* Array of Organization objects ## **Example Requests** #### Add organization ```JSON theme={null} { "data": { "organizations": [ { "organizationId": "yourOrganizationId", "organizationName": "Your Organization Name" } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Organization(s) added successfully.", "data": { "yourOrganizationId": { "success": true, "id": "02cf91e5e7a5f4c0b600c84cf248384b", "message": "Added Successfully" } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Organization(s) added successfully.", "data": { "yourOrganizationId": { "success": true, "id": "02cf91e5e7a5f4c0b600c84cf248384b", "message": "Added Successfully" } } } } ``` # Delete Organizations Source: https://velt.dev/docs/api-reference/rest-apis/v1/organizations/delete-organizations POST https://api.velt.dev/v1/organizations/delete Use this API to delete specific organization(s) data by their IDs. # Endpoint `POST https://api.velt.dev/v1/organizations/delete` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationIds** `string[]` *required* Array of Organization IDs ## **Example Requests** #### Delete specific organization ```JSON theme={null} { "data": { "organizationIds": [ "yourOrganizationId1", "yourOrganizationId2" ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Organization(s) deleted successfully.", "data": { "yourOrganizationId1": { "success": true, "id": "02cf91e5e7a5f4c0b600c84cf248384b", "message": "Deleted Successfully" }, { "yourOrganizationId2": { "success": false, "id": "02cf91e5e7a5f4c0b600c84cf248384b", "message": "Organization does not exist" } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Organization(s) deleted successfully.", "data": { "yourOrganizationId": { "success": true, "id": "02cf91e5e7a5f4c0b600c84cf248384b", "message": "Deleted Successfully" } } } } ``` # Get Organizations Source: https://velt.dev/docs/api-reference/rest-apis/v1/organizations/get-organizations POST https://api.velt.dev/v1/organizations/get Use this API to retrieve specific organizations by organization IDs. > [!WARNING] > > Use this for SDK v3 or prior versions. # Endpoint `POST https://api.velt.dev/v1/organizations/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationIds** `string[]` Array of Organization IDs (Optional). Limit: Only 30 IDs can be passed at a time. If this is not provided, all organizations will be returned. ## **Example Requests** ```JSON theme={null} { "data": { "organizationIds": [ "yourOrganizationId" ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Organization(s) retrieved successfully.", "data": [ { "id": "yourOrganizationId", "organizationName": "Your Organization Name", "disabled": false, // other metadata fields may be included here } // ... more organizations if multiple were retrieved ] } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Organization(s) retrieved successfully.", "data": [ { "id": "yourOrganizationId", "organizationName": "Your Organization Name", "disabled": false, // other metadata fields may be included here } // ... more organizations if multiple were retrieved ] } } ``` # Update Disabled State for Organizations Source: https://velt.dev/docs/api-reference/rest-apis/v1/organizations/update-organization-disable-state POST https://api.velt.dev/v1/organizations/access/disablestate/update Use this API to enable or disable both read and write access for all documents for all users. > [!NOTE] > > Let's say your customer's trial or subscription has ended and you want to disable their access to the Velt data, you could use this to disable access to the entire organization data. > [!NOTE] > > If organization does not exist, it will be created. # Endpoint `POST https://api.velt.dev/v1/organizations/access/disablestate/update` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationIds** `string[]` *required* Array of Organization IDs **disabled** `boolean` *required* Whether to disable read and write access to the specified organizations. Allowed values: `true`, `false`. ## **Example Requests** ```JSON theme={null} { "data": { "organizationIds": ["yourOrganizationId1","yourOrganizationId2"], "disabled": true } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Updated disable state for Organization(s) successfully.", "data": { "yourOrganizationId1": { "success": true, "id": "02cf91e5e7a5f4c0b600c84cf248384b", "message": "Updated disable state for organization Successfully" }, "yourOrganizationId2": { "success": false, "id": "44e0132f4c6b0d453f18df42d2263b4e", "message": "Organization does not exist" } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Updated disable state for Organization(s) successfully.", "data": { "yourOrganizationId": { "success": true, "id": "02cf91e5e7a5f4c0b600c84cf248384b", "message": "Updated disable state for organization Successfully" } } } } ``` # Update Organizations Source: https://velt.dev/docs/api-reference/rest-apis/v1/organizations/update-organizations POST https://api.velt.dev/v1/organizations/update Use this API to update existing organization(s) metadata. # Endpoint `POST https://api.velt.dev/v1/organizations/update` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizations** `Organization[]` *required* Array of Organization objects ## **Example Requests** ```JSON theme={null} { "data": { "organizations": [ { "organizationId": "yourOrganizationId", "organizationName": "Your Updated Organization Name" } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Organization(s) updated successfully.", "data": { "yourOrganizationId": { "success": true, "id": "02cf91e5e7a5f4c0b600c84cf248384b", "message": "Updated Successfully" } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Organization(s) updated successfully.", "data": { "yourOrganizationId": { "success": true, "id": "02cf91e5e7a5f4c0b600c84cf248384b", "message": "Updated Successfully" } } } } ``` # Add User Groups Source: https://velt.dev/docs/api-reference/rest-apis/v1/user-groups/add-groups POST https://api.velt.dev/v1/organizations/usergroups/add Use this API to add organization user groups to a specific organization. # Endpoint `POST https://api.velt.dev/v1/organizations/usergroups/add` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **organizationUserGroups** `OrganizationUserGroup[]` *required* Array of Organization User Group objects ## **Example Request** #### Add organization user group in a specific organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "organizationUserGroups": [ { "groupId": "engineering", "groupName": "Engineering" } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Organization User Groups added successfully.", "data": { "yourGroupId": { "success": true, "id": "77ab6767b022ad0323ba39c24f12cc95", "message": "Organization user group added." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Organization User Groups added successfully.", "data": { "yourGroupId": { "success": true, "id": "77ab6767b022ad0323ba39c24f12cc95", "message": "Organization user group added." } } } } ``` # Add Users to Groups Source: https://velt.dev/docs/api-reference/rest-apis/v1/user-groups/add-users-to-group POST https://api.velt.dev/v1/organizations/usergroups/users/add Use this API to add users to a specific organization user group. # Endpoint `POST https://api.velt.dev/v1/organizations/usergroups/users/add` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **organizationUserGroupId** `string` *required* Organization User Group ID **userIds** `string[]` *required* Array of User IDs ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "organizationUserGroupId": "yourGroupId", "userIds": ["yourUserId1"] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Added organization users to group successfully.", "data": { "yourUserId1": { "success": true, "organizationUserGroupId": "yourGroupId", "message": "User added to organization user group." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Added organization users to group successfully.", "data": { "yourUserId1": { "success": true, "organizationUserGroupId": "yourGroupId", "message": "User added to organization user group." } } } } ``` # Delete Users from Groups Source: https://velt.dev/docs/api-reference/rest-apis/v1/user-groups/delete-users-from-group POST https://api.velt.dev/v1/organizations/usergroups/users/delete Use this API to delete users from a specific organization user group. # Endpoint `POST https://api.velt.dev/v1/organizations/usergroups/users/delete` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **organizationUserGroupId** `string` *required* Organization User Group ID **userIds** `string[]` *required* Array of User IDs **deleteAll** `boolean` *required* If true, all users in the group will be deleted. ## **Example Requests** #### Delete specific users from group ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "organizationUserGroupId": "yourGroupId", "userIds": ["yourUserId1"] } } ``` #### Delete all users from group ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "organizationUserGroupId": "yourGroupId", "deleteAll": true } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Deleted users from group successfully.", "data": { "yourUserId1": { "success": true, "organizationUserGroupId": "yourGroupId", "message": "User deleted from organization user group." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Deleted users from group successfully.", "data": { "yourUserId1": { "success": true, "organizationUserGroupId": "yourGroupId", "message": "User deleted from organization user group." } } } } ``` # Add Users Source: https://velt.dev/docs/api-reference/rest-apis/v1/users/add-users POST https://api.velt.dev/v1/users/add Use this API to add Users to: 1. **Organization:** This will provide them access to all the documents in the organization unless the document has `restricted` access type. It will also show users in the contact list of the organization. 2. **Folder:** This will provide them access to all the documents in the folder. If you pass the `folderId`, then the users will be added to the folder and not the organization. 3. **Document:** This will provide them access to the specified document. It will also show users in the contact list of the document. If you pass the `documentId`, then the users will be added to the document and not the organization or folder. > [!NOTE] > > * If organization does not exist, it will be created. > * If you provide documentId or folderId, then the users will only be added at that level and not at the organization level. To also add users at the organization level, you will need to call this API again with only the organizationId. > * If User's `initial` is not provided in the User object, then it will be automatically created using the name field. # Endpoint `POST https://api.velt.dev/v1/users/add` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` Document ID. Provide this if you want to add users to a specific document. **folderId** `string` Folder ID. Provide this if you want to add users to a specific folder. Either provide `documentId` or `folderId`. **users** `User[]` *required* Array of [User](/docs/api-reference/sdk/models/data-models#user) objects. ## **Example Requests** #### 1. Add users to a specific organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "users": [ { "userId": "yourUserId1", "name": "User Name", "email": "user@email.com" } ] } } ``` #### 2. Add users to a specific document within an organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "users": [ { "userId": "yourUserId1", "name": "User Name", "email": "user@email.com" } ] } } ``` #### 3. Add users to a specific folder within an organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "folderId": "yourFolderId", "users": [ { "userId": "yourUserId1", "name": "User Name", "email": "user@email.com" } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "User(s) processed successfully.", "data": { "yourUserId1": { "success": true, "id": "4c250058149d6c9fb8c894c9ef29c790", "message": "User added." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "User(s) processed successfully.", "data": { "yourUserId1": { "success": true, "id": "4c250058149d6c9fb8c894c9ef29c790", "message": "User added." } } } } ``` # Delete Users Source: https://velt.dev/docs/api-reference/rest-apis/v1/users/delete-users POST https://api.velt.dev/v1/users/delete Remove Users from an Organization or a Document. Use this API to remove Users from: 1. **Organization:** This will remove their access from all the documents and data in the organization. It will also remove these users from the contact list of the organization. 2. **Document:** This will remove their access from the specified document. It will also remove these users from the contact list of the document. If you pass the `documentId`, then the users will be removed from the document. # Endpoint `POST https://api.velt.dev/v1/users/delete` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` Document IDs. Provide this if you want to delete users from a specific document. **folderId** `string` Folder ID. Either provide `documentId` or `folderId`. **userIds** `string[]` *required* Array of user Ids. ## **Example Requests** #### 1. Delete users in a specific organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "userIds": [ "yourUserId1" ] } } ``` #### 2. Delete users in a specific document within an organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "userIds": [ "yourUserId1" ] } } ``` #### 3. Delete users in a specific folder within an organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "folderId": "yourFolderId", "userIds": [ "yourUserId1" ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "User(s) deleted successfully.", "data": { "yourUserId1": { "success": true, "message": "User removed." } } } } ``` #### User(s) Not Found ```JSON theme={null} { "result": { "status": "success", "message": "User(s) deleted successfully.", "data": { "yourUserId1": { "success": true, "message": "User removed." }, { "yourUserId2": { "success": false, "message": "User does not exist." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "User(s) deleted successfully.", "data": { "yourUserId1": { "success": true, "message": "User removed." } } } } ``` # Get Users Source: https://velt.dev/docs/api-reference/rest-apis/v1/users/get-users POST https://api.velt.dev/v1/users/get Use this API to retrieve users based on various filters such as organization ID, document ID, organization user group IDs or user IDs. You can use these filters in various combinations to get the desired users. Some examples are shown below. > [!WARNING] > > Use this for SDK v3 or prior versions. # Endpoint `POST https://api.velt.dev/v1/users/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### **Params** **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` Document ID **userIds** `string[]` Array of User IDs. Limit: Only 30 items can be passed at a time. **organizationUserGroupIds** `string[]` Array of Organization User Group IDs. Only 30 items can be passed at a time. ## **Example Requests** #### 1. Get users by organizationId ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId" } } ``` #### 2. Get users by documentId within an organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId" } } ``` #### 3. Get users by specific user IDs in an organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "userIds": [ "yourUserId1", "yourUserId2" ] } } ``` #### 4. Get users by specific user IDs in the given organization and document ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "userIds": [ "yourUserId1", "yourUserId2" ] } } ``` #### 5. Get users by organization and organization user group IDs ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "organizationUserGroupIds": [ "yourOrganizationUserGroupId" ] } } ``` #### 6. Get users by organization, organization user group IDs and user IDs ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "userIds": [ "yourUserId1", "yourUserId2" ], "organizationUserGroupIds": [ "yourOrganizationUserGroupId" ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "User(s) retrieved successfully.", "data": [ { "email": "userEmail@domain.com", "name": "userName", "userId": "yourUserId" } ] } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "Error retrieving user(s).", "status": "ERROR_CODE" } } ``` ```js theme={null} { "result": { "status": "success", "message": "User(s) retrieved successfully.", "data": [ { "email": "userEmail@domain.com", "name": "userName", "userId": "yourUserId" } ] } } ``` # Update Users Source: https://velt.dev/docs/api-reference/rest-apis/v1/users/update-users POST https://api.velt.dev/v1/users/update Use this API to update user metadata based on various filters such as organization ID, document ID, folder ID and user IDs. You can use these filters in various combinations to get the desired results. The user metadata such as name, email etc can be updated. # Endpoint `POST https://api.velt.dev/v1/users/update` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### **Params** **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` Document ID **folderId** `string` Folder ID. Either provide `documentId` or `folderId`. **users** `User[]` *required* Array of [User](/docs/api-reference/sdk/models/data-models#user) objects. ## **Example Requests** #### 1. Update users in a specific organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "users": [ { "userId": "yourUserId1", "name": "User Name", "email": "user@email.com" } ] } } ``` #### 2. Update users in a specific document within an organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "documentId": "yourDocumentId", "users": [ { "userId": "yourUserId1", "name": "User Name", "email": "user@email.com" } ] } } ``` #### 3. Update users in a specific folder within an organization ```JSON theme={null} { "data": { "organizationId": "yourOrganizationId", "folderId": "yourFolderId", "users": [ { "userId": "yourUserId1", "name": "User Name", "email": "user@email.com" } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "User(s) processed successfully.", "data": { "yourUserId1": { "success": true, "id": "7d87015b055a168b098cf05b870e40ff", "message": "User updated." } } } } ``` #### Some User(s) Not Found ```JSON theme={null} { "result": { "status": "success", "message": "User(s) processed successfully.", "data": { "yourUserId1": { "success": true, "id": "7d87015b055a168b098cf05b870e40ff", "message": "User updated." }, "yourUserId2": { "success": false, "id": "ad22d93b49ad990d2b3d582d08d7768a", "message": "User does not exist." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "User(s) processed successfully.", "data": { "yourUserId1": { "success": true, "id": "7d87015b055a168b098cf05b870e40ff", "message": "User updated." } } } } ``` # Add Domains Source: https://velt.dev/docs/api-reference/rest-apis/v1/workspace/add-domain POST https://api.velt.dev/v1/workspace/domains/add Use this API to add new organizations and its metadata. # Endpoint `POST https://api.velt.dev/v1/workspace/domains/add` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **domains** `string[]` *required* Array of domains # Example Request ```JSON theme={null} { "data": { "domains" : [ "https://www.google.com", "https://*.firebase.com" ] } } ``` # Example Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Domain(s) added successfully to allowed domains.", "data": { "domainsAdded": [ "google.com", "*.firebase.com" ] } } } ``` #### Failure Response ##### If some domains are already in the allowed domains ```JSON theme={null} { "error": { "details": { "domainsAdded": [ "velt.dev" ], "skippedDomains": [ "google.com" ] }, "message": "Domain(s) added successfully to allowed domains. Skipped existing domains.", "status": "INTERNAL" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Domain(s) added successfully to allowed domains.", "data": { "domainsAdded": [ "google.com", "*.firebase.com" ] } } } ``` # Delete Domains Source: https://velt.dev/docs/api-reference/rest-apis/v1/workspace/delete-domain POST https://api.velt.dev/v1/workspace/domains/delete Use this API to add new organizations and its metadata. # Endpoint `POST https://api.velt.dev/v1/workspace/domains/delete` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **domains** `string[]` *required* Array of domains # Example Request ```JSON theme={null} { "data": { "domains" : [ "https://www.google.com", "https://*.firebase.com" ] } } ``` # Example Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Domain(s) removed successfully from allowed domains.", "data": { "domainsRemoved": [ "google.com", "*.firebase.com" ] } } } ``` #### Failure Response ##### If some domains are not in the allowed domains ```JSON theme={null} { "error": { "details": { "domainsRemoved": [ "velt.dev" ], "skippedDomains": [ "google.com" ] }, "message": "Domain(s) removed successfully from allowed domains. Skipped non-existing domains.", "status": "INTERNAL" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Domain(s) removed successfully from allowed domains.", "data": { "domainsRemoved": [ "google.com", "*.firebase.com" ] } } } ``` # Add Activity Logs Source: https://velt.dev/docs/api-reference/rest-apis/v2/activities/add-activities POST https://api.velt.dev/v2/activities/add Use this API to create activity log records for a document within an organization. > [!NOTE] > > Adding activity logs via the REST API requires `activityServiceConfig` to be enabled at the workspace level in the [Velt Console](https://console.velt.dev). # Endpoint `POST https://api.velt.dev/v2/activities/add` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` *required* Document ID **activities** `object[]` *required* Array of activity log objects to create. **properties** **id** `string` Optional Firestore document ID for the activity record. Use this to control the ID for idempotent writes — if an activity with this ID already exists it will be overwritten. **featureType** `string` *required* Feature that generated the activity log. Must be one of: `"comment"`, `"reaction"`, `"recorder"`, `"crdt"`, `"custom"`. **actionType** `string` *required* Specific action performed (e.g., `"comment.add"`). **actionUser** `User` *required* User who performed the action. **targetEntityId** `string` ID of the primary entity the activity log targets (e.g., annotation ID). Required when `featureType` is `"custom"`; optional for all other feature types. **targetSubEntityId** `string` ID of a sub-entity within the target (e.g., a specific comment ID). **changes** `object` Map of field names to `{ from, to }` objects describing what changed. **entityData** `any` Snapshot of the entity at the time of the action. **entityTargetData** `any` Snapshot of the target entity at the time of the action. **displayMessageTemplate** `string` Message template string. Use `{{variable}}` syntax for dynamic values. **displayMessageTemplateData** `object` Key-value data to populate `displayMessageTemplate` variables. **actionIcon** `string` URL or identifier for the icon representing this action. **isActivityResolverUsed** `boolean` Use this for self-hosting activity data. Set to `true` if you are using the activity resolver data provider in the SDK. When `true`, indicates that PII has been stripped from the activity record and the record is pending resolver re-hydration. ## **Example Requests** #### Add a single activity log (non-custom featureType, targetEntityId optional) ```JSON theme={null} { "data": { "organizationId": "org-123", "documentId": "doc-456", "activities": [ { "featureType": "comment", "actionType": "comment.add", "actionUser": { "userId": "user-1", "email": "user@example.com", "name": "User Name" }, "displayMessageTemplate": "{{user}} added a comment" } ] } } ``` #### Add an activity log with a custom ID (idempotent write) ```JSON theme={null} { "data": { "organizationId": "org-123", "documentId": "doc-456", "activities": [ { "id": "my-custom-activity-id", "featureType": "comment", "actionType": "comment.add", "actionUser": { "userId": "user-1", "email": "user@example.com", "name": "User Name" }, "targetEntityId": "annotation-789", "displayMessageTemplate": "{{user}} added a comment" } ] } } ``` #### Add a custom featureType activity (targetEntityId required) ```JSON theme={null} { "data": { "organizationId": "org-123", "documentId": "doc-456", "activities": [ { "featureType": "custom", "actionType": "statusChanged", "actionUser": { "userId": "user-1", "email": "user@example.com", "name": "User Name" }, "targetEntityId": "entity-456", "displayMessageTemplate": "{{user}} changed the status" } ] } } ``` #### Add an activity log with changes and template data ```JSON theme={null} { "data": { "organizationId": "org-123", "documentId": "doc-456", "activities": [ { "featureType": "comment", "actionType": "comment.update", "actionUser": { "userId": "user-1", "email": "user@example.com", "name": "User Name" }, "targetEntityId": "annotation-789", "targetSubEntityId": "comment-001", "changes": { "commentText": { "from": "Original text", "to": "Updated text" } }, "displayMessageTemplate": "{{user}} updated a comment", "displayMessageTemplateData": { "user": { "userId": "user-1", "name": "User Name" } } } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Activity(s) added successfully.", "data": { "success": true, "message": "Activity(s) added successfully." } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Activity(s) added successfully.", "data": { "success": true, "message": "Activity(s) added successfully." } } } ``` # Delete Activity Logs Source: https://velt.dev/docs/api-reference/rest-apis/v2/activities/delete-activities POST https://api.velt.dev/v2/activities/delete Use this API to delete activity log records. At least one of `documentId`, `targetEntityId`, or `activityIds` is required. # Endpoint `POST https://api.velt.dev/v2/activities/delete` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` Delete all activity logs associated with this document ID. **activityIds** `string[]` Delete specific activity logs by ID. **targetEntityId** `string` Delete all activity logs associated with this entity ID. > [!WARNING] > > At least one of `documentId`, `targetEntityId`, or `activityIds` must be provided. ## **Example Requests** #### 1. Delete by activityIds ```JSON theme={null} { "data": { "organizationId": "org-123", "activityIds": ["activity-001", "activity-002"] } } ``` #### 2. Delete all activities for a document ```JSON theme={null} { "data": { "organizationId": "org-123", "documentId": "doc-456" } } ``` #### 3. Delete all activities for a target entity ```JSON theme={null} { "data": { "organizationId": "org-123", "targetEntityId": "annotation-789" } } ``` #### 4. Delete by documentId and targetEntityId ```JSON theme={null} { "data": { "organizationId": "org-123", "documentId": "doc-456", "targetEntityId": "annotation-789" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Activity(s) deleted successfully.", "data": { "activity-001": { "success": true, "message": "Activity deleted." } } } } ``` #### When some activities are not found ```JSON theme={null} { "result": { "status": "success", "message": "Activity(s) deleted successfully.", "data": { "activity-001": { "success": false, "message": "Failed to delete activity." }, "activity-002": { "success": true, "message": "Activity deleted." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Activity(s) deleted successfully.", "data": { "activity-001": { "success": true, "message": "Activity deleted." } } } } ``` # Get Activity Logs Source: https://velt.dev/docs/api-reference/rest-apis/v2/activities/get-activities POST https://api.velt.dev/v2/activities/get Use this API to retrieve activity log records for a document or organization. # Endpoint `POST https://api.velt.dev/v2/activities/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **documentId** `string` Document ID. Filter activities to a specific document. **targetEntityId** `string` Target entity ID. Filter activities to a specific entity (e.g., annotation ID). **featureTypes** `string[]` Filter by feature type. Must be one or more of: `"comment"`, `"reaction"`, `"recorder"`, `"crdt"`, `"custom"`. **actionTypes** `string[]` Filter by action type (e.g., `["comment.add"]`). **userId** `string` Filter activities by the acting user's ID. **activityIds** `string[]` Fetch specific activities by ID. **order** `string` Order results by timestamp. Must be `asc` or `desc`. Default: `desc`. **pageSize** `number` Number of items to retrieve per page. Default: 1000. Minimum: 1. **pageToken** `string` Encrypted pagination token retrieved from a previous API response. ## **Example Requests** #### 1. Get by organizationId and documentId ```JSON theme={null} { "data": { "organizationId": "org-123", "documentId": "doc-456", "order": "desc", "pageSize": 50 } } ``` #### 2. Get by organizationId, documentId and featureTypes ```JSON theme={null} { "data": { "organizationId": "org-123", "documentId": "doc-456", "featureTypes": ["comment"], "order": "desc", "pageSize": 50 } } ``` #### 3. Get specific activity logs by activityIds ```JSON theme={null} { "data": { "organizationId": "org-123", "activityIds": ["activity-001", "activity-002"] } } ``` #### 4. Get by targetEntityId with pagination ```JSON theme={null} { "data": { "organizationId": "org-123", "documentId": "doc-456", "targetEntityId": "annotation-789", "pageSize": 20, "pageToken": "encryptedPageToken" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Activity(s) retrieved successfully.", "data": [ { "id": "activity-001", "featureType": "comment", "actionType": "comment.add", "actionUser": { "userId": "user-1", "email": "user@example.com", "name": "User Name" }, "targetEntityId": "annotation-789", "displayMessageTemplate": "{{user}} added a comment", "displayMessageTemplateData": { "user": { "userId": "user-1", "name": "User Name" } }, "metadata": { "apiKey": "yourApiKey", "documentId": "doc-456", "organizationId": "org-123" }, "timestamp": 1722409519944 } ], "pageToken": "nextPageToken" } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Activity(s) retrieved successfully.", "data": [ { "id": "activity-001", "featureType": "comment", "actionType": "comment.add", "actionUser": { "userId": "user-1", "email": "user@example.com", "name": "User Name" }, "targetEntityId": "annotation-789", "displayMessageTemplate": "{{user}} added a comment", "displayMessageTemplateData": { "user": { "userId": "user-1", "name": "User Name" } }, "metadata": { "apiKey": "yourApiKey", "documentId": "doc-456", "organizationId": "org-123" }, "timestamp": 1722409519944 } ], "pageToken": "nextPageToken" } } ``` # Update Activity Logs Source: https://velt.dev/docs/api-reference/rest-apis/v2/activities/update-activities POST https://api.velt.dev/v2/activities/update Use this API to update existing activity log records within an organization. # Endpoint `POST https://api.velt.dev/v2/activities/update` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* Organization ID **activities** `object[]` *required* Array of activity log objects to update. Each must include the activity log `id`. **properties** **id** `string` *required* Activity log ID to update. **changes** `object` Map of field names to `{ from, to }` objects describing what changed. **entityData** `any` Updated snapshot of the entity. **entityTargetData** `any` Updated snapshot of the target entity. **displayMessageTemplate** `string` Updated message template string. Use `{{variable}}` syntax for dynamic values. **displayMessageTemplateData** `object` Updated key-value data to populate `displayMessageTemplate` variables. **actionIcon** `string` Updated URL or identifier for the action icon. ## **Example Requests** #### Update a single activity log's display message ```JSON theme={null} { "data": { "organizationId": "org-123", "activities": [ { "id": "activity-001", "displayMessageTemplate": "{{user}} updated the comment" } ] } } ``` #### Update multiple activities ```JSON theme={null} { "data": { "organizationId": "org-123", "activities": [ { "id": "activity-001", "displayMessageTemplate": "{{user}} updated the comment", "displayMessageTemplateData": { "user": { "userId": "user-1", "name": "User Name" } } }, { "id": "activity-002", "actionIcon": "https://example.com/icons/edit.svg" } ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Activity(s) updated successfully.", "data": { "activity-001": { "success": true, "message": "Activity updated." } } } } ``` #### When some activities are not found ```JSON theme={null} { "result": { "status": "success", "message": "Activity(s) updated successfully.", "data": { "activity-001": { "success": false, "message": "Failed to update activity." }, "activity-002": { "success": true, "message": "Activity updated." } } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` ```js theme={null} { "result": { "status": "success", "message": "Activity(s) updated successfully.", "data": { "activity-001": { "success": true, "message": "Activity updated." } } } } ``` # Get Agent Analytics Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/analytics/get POST https://api.velt.dev/v2/agents/analytics/get Use this API to fetch AI token usage analytics and execution counts. Data is aggregated from per-workspace Firestore usage documents. Filter by `agentId`, `year`, `month`, and/or `model`. # Endpoint `POST https://api.velt.dev/v2/agents/analytics/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **agentId** `string` Min 1 char. Agent ID. Omit for aggregate analytics across all agents. **year** `string` 4-digit year string (regex `^\d{4}$`), e.g. `"2026"`. **month** `string` Two-digit month `"01"`–`"12"` (regex `^(0[1-9]|1[0-2])$`). **model** `string` Filter by model. Use the full provider-prefixed model id (e.g. `"gemini/gemini-3.6-flash"`). This narrows `byModel` only; `allTime`, `yearly`, and `monthly` are unaffected. A value that matches no stored key returns `byModel: {}`. ## **Example Requests** #### 1. Aggregate analytics (all agents) ```JSON theme={null} { "data": {} } ``` #### 2. Single agent analytics ```JSON theme={null} { "data": { "agentId": "abc123def456" } } ``` #### 3. Filtered by year and month ```JSON theme={null} { "data": { "agentId": "abc123def456", "year": "2026", "month": "03" } } ``` #### 4. Filtered by model ```JSON theme={null} { "data": { "model": "gemini/gemini-3.6-flash" } } ``` # Response The `analytics` object maps to the `AgentAnalyticsResponse` interface. Model keys are formatted as `provider_model` (e.g. `"claude_claude-sonnet-5"`). Dots and slashes in the provider or model id are replaced with underscores, so `gemini/gemini-3.6-flash` is keyed as `"gemini_gemini-3_6-flash"`. #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Analytics fetched successfully", "data": { "analytics": { "tokenUsage": { "allTime": { "requestCount": 1250, "promptTokens": 2500000, "completionTokens": 750000, "thoughtsTokens": 50000, "totalTokens": 3300000 }, "yearly": { "2026": { "claude_claude-sonnet-5": { "requestCount": 350, "promptTokens": 700000, "completionTokens": 210000, "thoughtsTokens": 20000, "totalTokens": 930000 }, "gemini_gemini-3_6-flash": { "requestCount": 500, "promptTokens": 1000000, "completionTokens": 300000, "thoughtsTokens": 10000, "totalTokens": 1310000 } } }, "monthly": { "03": { "claude_claude-sonnet-5": { "requestCount": 120, "promptTokens": 240000, "completionTokens": 72000, "thoughtsTokens": 5000, "totalTokens": 317000 } } }, "byModel": { "claude_claude-sonnet-5": { "requestCount": 500, "promptTokens": 1000000, "completionTokens": 300000, "thoughtsTokens": 50000, "totalTokens": 1350000 }, "gemini_gemini-3_6-flash": { "requestCount": 750, "promptTokens": 1500000, "completionTokens": 450000, "thoughtsTokens": 0, "totalTokens": 1950000 } } }, "executionCounts": { "abc123def456": { "executionCount": 45, "lastExecutedAt": 1711900000000 }, "spell-check": { "executionCount": 142, "lastExecutedAt": 1711900000000 } } } } } } ``` **`TokenUsageSummary` fields (repeated in every breakdown):** | Field | Type | Description | | - | - | - | | `requestCount` | number | Total number of LLM API requests. | | `promptTokens` | number | Total input tokens consumed. | | `completionTokens` | number | Total output tokens generated. | | `thoughtsTokens` | number | Thinking/reasoning tokens (model-dependent; 0 for Gemini). | | `totalTokens` | number | Total tokens consumed. | **`tokenUsage` breakdown keys:** | Key | Type | Present When | Description | | - | - | - | - | | `allTime` | `TokenUsageSummary` | always | Aggregate across all time. | | `yearly` | `Record>` | yearly usage recorded | Keyed by year string, then by model key. | | `monthly` | `Record>` | request includes `year` | Keyed by month (`"01"` to `"12"`), then by model key. | | `byModel` | `Record` | usage recorded | Cross-year aggregate keyed by model. | > [!NOTE] > > Only `tokenUsage.allTime` and `executionCounts` are guaranteed. Read the rest defensively rather than assuming the keys exist. > > `monthly` is returned only when the request includes a `year`. It is the per-month breakdown of that year, and `month` narrows it further. Without `year`, the `monthly` key is absent no matter how much monthly usage exists, so `month` on its own has no effect. > > `yearly` and `byModel` are omitted when the workspace has no recorded usage to report for them. **`executionCounts` map:** Keyed by `agentId`. When you pass an `agentId` filter, the map is narrowed to that single agent, or returned as `{}` when that agent has no recorded executions. | Field | Type | Description | | - | - | - | | `executionCount` | number | Total executions for this agent. | | `lastExecutedAt` | number \| null | Epoch ms of last execution. Null if never. | #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` **Errors:** `INVALID_ARGUMENT` (invalid `year` or `month` format). ```js theme={null} { "result": { "status": "success", "message": "Analytics fetched successfully", "data": { "analytics": { "tokenUsage": { "allTime": { "requestCount": 0, "promptTokens": 0, "completionTokens": 0, "thoughtsTokens": 0, "totalTokens": 0 } }, "executionCounts": {} } } } } ``` # Get Capture Focus Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/capture-focus/get POST https://api.velt.dev/v2/agents/checks/capture-focus/get Use this API to find where a check's comment sits on its captured screenshot. It returns the site version, the page, the device, the element's box, the pages to walk through, and the comment's row with its thumbnail. Use it to open a screenshot zoomed on the problem. The comment must carry a check: an agent comment the engine keyed, or a person's comment attached to a check. See [Checks Overview](/docs/api-reference/rest-apis/v2/agents/checks/overview). # Endpoint `POST https://api.velt.dev/v2/agents/checks/capture-focus/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **annotationId** `string` *required* The comment annotation id. 1 to 512 characters, no `/`, and not `.` or `..`. The schema uses `.strict()`: unknown fields are rejected. ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "annotationId": "K7mQ2xR9vB4wLdT1sYpN" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Capture focus retrieved", "data": { "versionId": null, "urlHash": "a41c9e07", "device": "desktop", "rect": { "x": 812, "y": 4120, "width": 96, "height": 20, "viewportWidth": 1440 }, "pages": [ "https://www.example.com/", "https://www.example.com/pricing", "https://www.example.com/about" ], "comment": { "annotationId": "K7mQ2xR9vB4wLdT1sYpN", "ruleKey": "link-broken", "pageUrl": "https://www.example.com/", "pagePath": "/", "scope": "site", "pageCount": 14, "locationType": "element", "evidenceLabel": "footer a[href=\"/careers\"]", "statusKind": "open", "pendingVerify": false, "thumbnailUrl": "https://storage.example.com/thumbs/a41c9e07.png", "isAgent": true } } } } ``` The `comment` above is shortened. It has every field of a [List Check Comments](/docs/api-reference/rest-apis/v2/agents/checks/comments/list) row. | Field | Type | Description | | - | - | - | | `data.versionId` | string \| null | The site version of a page comment. `null` for a site comment, or when unknown. | | `data.urlHash` | string \| null | Hash of the comment's page. | | `data.device` | string | `"desktop"` or `"mobile"`. | | `data.rect` | object \| null | The element's box on the full-page capture, in CSS pixels: `x`, `y`, `width`, `height` and the capture's `viewportWidth`. `null` when no box was measured, for example for a `source` or `none` comment. | | `data.pages` | string\[] | The comment's pages. One entry for a page comment. | | `data.comment` | object | The comment's row, with its thumbnail. | #### Failure Response ```JSON theme={null} { "error": { "message": "This comment was not written by a check", "status": "FAILED_PRECONDITION", "details": { "reason": "CHECKS_NOT_A_CHECK_COMMENT" } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a missing or malformed `annotationId`, or an unknown field) / `NOT_FOUND` with `CHECKS_COMMENT_NOT_FOUND` (no such comment in the project) or `CHECKS_WORKSPACE_NOT_FOUND` (the workspace has no store database) / `FAILED_PRECONDITION` with `CHECKS_NOT_A_CHECK_COMMENT` (the comment carries no check). ```js theme={null} { "result": { "status": "success", "message": "Capture focus retrieved", "data": { "versionId": "ver_20261026a", "urlHash": "c82f1b5e", "device": "mobile", "rect": null, "pages": ["https://www.example.com/pricing"], "comment": { "annotationId": "P2nW8tY4kQ6mZcV3hJxL", "ruleKey": "image-broken", "scope": "page", "statusKind": "open" } } } } ``` # Attach Comment Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/comments/attach POST https://api.velt.dev/v2/agents/checks/comments/attach Use this API to attach a comment a person wrote to a check. The attached comment counts in the check's open count and pages, lists under the check in [List Check Comments](/docs/api-reference/rest-apis/v2/agents/checks/comments/list), and resolves and verifies with it. Attaching a comment that is already attached to another check moves it. Only a person's comment can be attached. An agent comment already belongs to its check and is refused. The engine never attaches a comment on its own. See [Checks Overview](/docs/api-reference/rest-apis/v2/agents/checks/overview#comment). # Endpoint `POST https://api.velt.dev/v2/agents/checks/comments/attach` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **annotationId** `string` *required* The person's comment annotation id. 1 to 512 characters, no `/`, and not `.` or `..`. **ruleKey** `string` *required* The check. `[a-z0-9:-]`, at most 120 characters. **userId** `string` *required* 1 to 512 characters. Recorded as the person who attached the comment. The schema uses `.strict()`: unknown fields are rejected. ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "annotationId": "H3vN6pQ1zT8kWmB5xYcR", "ruleKey": "link-broken", "userId": "user_sam" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Comment attached", "data": { "attached": true, "ruleKey": "link-broken" } } } ``` | Field | Type | Description | | - | - | - | | `data.attached` | boolean | Always `true`. | | `data.ruleKey` | string | The check the comment is now attached to. | The comment's [`checkInfo`](/docs/api-reference/sdk/models/data-models#checkinfo) now holds `attached: true` and `attachedRuleKey`. #### Failure Response ```JSON theme={null} { "error": { "message": "An agent comment cannot be attached to or detached from a check", "status": "FAILED_PRECONDITION", "details": { "reason": "CHECKS_AGENT_COMMENT_NOT_ATTACHABLE" } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a missing or malformed `annotationId` or `ruleKey`, a missing `userId`, or an unknown field) / `NOT_FOUND` with `CHECKS_COMMENT_NOT_FOUND` (no such comment in the project) or `CHECKS_WORKSPACE_NOT_FOUND` (the workspace has no store database) / `FAILED_PRECONDITION` with `CHECKS_AGENT_COMMENT_NOT_ATTACHABLE` (an agent comment). ```js theme={null} { "result": { "status": "success", "message": "Comment attached", "data": { "attached": true, "ruleKey": "link-broken" } } } ``` # Detach Comment Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/comments/detach POST https://api.velt.dev/v2/agents/checks/comments/detach Use this API to detach a person's comment from the check it was [attached](/docs/api-reference/rest-apis/v2/agents/checks/comments/attach) to. The engine removes the comment's `checkInfo` and updates the check's counts. The comment itself, its status and its replies stay the same. # Endpoint `POST https://api.velt.dev/v2/agents/checks/comments/detach` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **annotationId** `string` *required* The attached comment's annotation id. 1 to 512 characters, no `/`, and not `.` or `..`. **userId** `string` *required* 1 to 512 characters. The person who detaches the comment. The schema uses `.strict()`: unknown fields are rejected. ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "annotationId": "H3vN6pQ1zT8kWmB5xYcR", "userId": "user_sam" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Comment detached", "data": { "detached": true } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "This comment is not attached to a check", "status": "FAILED_PRECONDITION", "details": { "reason": "CHECKS_COMMENT_NOT_ATTACHED" } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a missing or malformed `annotationId`, a missing `userId`, or an unknown field) / `NOT_FOUND` with `CHECKS_COMMENT_NOT_FOUND` (no such comment in the project) or `CHECKS_WORKSPACE_NOT_FOUND` (the workspace has no store database) / `FAILED_PRECONDITION` with `CHECKS_AGENT_COMMENT_NOT_ATTACHABLE` (an agent comment) or `CHECKS_COMMENT_NOT_ATTACHED` (the comment is not attached to a check). ```js theme={null} { "result": { "status": "success", "message": "Comment detached", "data": { "detached": true } } } ``` # List Check Comments Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/comments/list POST https://api.velt.dev/v2/agents/checks/comments/list Use this API to list one check's comments in one status, a page at a time. Each row says whether the comment is a page comment or a site comment, where it is, its status and whether it waits for a verify. See [Checks Overview](/docs/api-reference/rest-apis/v2/agents/checks/overview). Comments people [attached](/docs/api-reference/rest-apis/v2/agents/checks/comments/attach) to the check come on the first page, with `attached: true` and `isAgent: false`. # Endpoint `POST https://api.velt.dev/v2/agents/checks/comments/list` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **ruleKey** `string` *required* The check. `[a-z0-9:-]`, at most 120 characters. **status** `string` *required* `"open"` (Open and In progress, never a rejected comment), `"resolved"` (never a rejected comment) or `"rejected"` (the check's [rejected](/docs/api-reference/rest-apis/v2/agents/checks/comments/reject) comments, whatever their status). **cursor** `string` The `nextCursor` of the previous page. `[A-Za-z0-9_-]`, 1 to 200 characters. **limit** `number` Comments per page. Whole number, 1 to 100. Default: `50`. **versionId** `string` A site version id. Returns the page comments last seen on this version, and the site comments with a page last seen on it. `[A-Za-z0-9_-]`, 1 to 200 characters. **runId** `string` An agent execution id. Returns the comments this run first or last saw. `[A-Za-z0-9_-]`, 1 to 200 characters. The schema uses `.strict()`: unknown fields are rejected. ## **Example Requests** #### 1. First page of open comments ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "ruleKey": "link-broken", "status": "open", "limit": 20 } } ``` #### 2. Next page ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "ruleKey": "link-broken", "status": "open", "limit": 20, "cursor": "K7mQ2xR9vB4wLdT1sYpN" } } ``` #### 3. Comments one run found ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "ruleKey": "link-broken", "status": "open", "runId": "exec_8Hk2Lm4Qp9" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Check comments retrieved", "data": { "comments": [ { "annotationId": "K7mQ2xR9vB4wLdT1sYpN", "ruleKey": "link-broken", "pageUrl": "https://www.example.com/", "pagePath": "/", "scope": "site", "pages": [ "https://www.example.com/", "https://www.example.com/pricing", "https://www.example.com/about" ], "pageCount": 14, "pageVersions": { "https://www.example.com/": "ver_20261026a", "https://www.example.com/pricing": "ver_20261026a", "https://www.example.com/about": "ver_20261025b" }, "locationType": "element", "evidence": "footer a[href=\"/careers\"]#h:3f9a1c0b7d2e", "evidenceLabel": "footer a[href=\"/careers\"]", "confidence": 96, "statusId": "OPEN", "statusType": "default", "statusKind": "open", "pendingVerify": false, "createdAt": 1761379200000, "verifiedAt": null, "reopenedCount": 0, "versionId": null, "urlHash": "a41c9e07", "thumbnailUrl": "https://storage.example.com/thumbs/a41c9e07.png", "deepLink": "https://app.example.com/review?commentId=K7mQ2xR9vB4wLdT1sYpN", "title": "Broken link to /careers", "suggestedFix": "Point the link at /jobs, or remove it.", "firstSeenRunId": "exec_8Hk2Lm4Qp9", "lastSeenRunId": "exec_9Jn3Pq5Rs1", "isAgent": true } ], "nextCursor": null } } } ``` | Field | Type | Description | | - | - | - | | `data.comments` | object\[] | The comments of this page. | | `comments[].annotationId` | string | The comment annotation id. | | `comments[].ruleKey` | string | The check. | | `comments[].pageUrl` | string | The page the comment was written on. | | `comments[].pagePath` | string | That page's path. | | `comments[].scope` | string | `"page"` or `"site"`. | | `comments[].pages` | string\[] | Site comments: the pages it is on (at most 1,000 stored). | | `comments[].pageCount` | number | Site comments: the true number of pages. | | `comments[].allPagesMatched` | boolean | Site comments: `true` when `pageCount` is more than `pages` holds. | | `comments[].pageVersions` | object | Site comments: the version each stored page was last seen on, by page. | | `comments[].locationType` | string | `"element"`, `"source"` or `"none"`. | | `comments[].evidence` | string | The exact spot, as the engine keys it. Element evidence ends with `#h:` and a hash of the element. | | `comments[].evidenceLabel` | string | The evidence to show a person, without the hash. | | `comments[].confidence` | number | 0 to 100, from the latest sighting. `0` on an attached comment. | | `comments[].statusId` | string | The comment's status id. | | `comments[].statusType` | string | `"default"`, `"ongoing"` or `"terminal"`. | | `comments[].statusKind` | string | What the status means: `"open"`, `"in_progress"`, `"resolved"`, or `"rejected"` (a person rejected it, whatever its status). | | `comments[].rejectReason` | string | Rejected comments: one of the four reasons, `excluded` (rejected by [Exclude Check](/docs/api-reference/rest-apis/v2/agents/checks/exclude)), or the person's own words. Absent when the reject named no reason. | | `comments[].pendingVerify` | boolean | `true` when the comment is Resolved and waits for the scan that verifies it. | | `comments[].createdAt` | number | When the comment was written (epoch ms). | | `comments[].resolvedAt` | number | When it was resolved (epoch ms). | | `comments[].timeToResolveMs` | number | `resolvedAt` minus `createdAt`. | | `comments[].verifiedAt` | number \| null | When a scan verified it (epoch ms). Only a scan sets it. | | `comments[].resolvedBy` | string | `"scan"`, `"user"`, `"mcp"` or `"suggestion"` (an accepted suggestion). | | `comments[].reopenedCount` | number | Times the comment was reopened. | | `comments[].versionId` | string \| null | Page comments: the site version it was last seen on. `null` for site comments. | | `comments[].urlHash` | string \| null | Hash of `pageUrl`. | | `comments[].thumbnailUrl` | string \| null | A screenshot thumbnail of the page, when one is captured. | | `comments[].deepLink` | string | A link that opens the comment. | | `comments[].title` | string | The comment's title. | | `comments[].suggestedFix` | string | How to fix it, when the agent suggested one. | | `comments[].firstSeenRunId` | string \| null | The run that first found it. `null` on an attached comment. | | `comments[].lastSeenRunId` | string \| null | The run that last found it. `null` on an attached comment. | | `comments[].attached` | boolean | `true` on a person's comment attached to the check. | | `comments[].isAgent` | boolean | `false` on an attached comment. | | `data.nextCursor` | string \| null | Pass as `cursor` for the next page. `null` when there is no more. | > [!NOTE] > > `limit` counts agent comments. The attached comments on the first page come on top of it. A page can also hold fewer than `limit` comments while `nextCursor` is set, so keep reading until `nextCursor` is `null`. #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT", "details": { "issues": [ { "code": "invalid_enum_value", "path": ["status"], "message": "Invalid enum value. Expected 'open' | 'resolved' | 'rejected', received 'closed'" } ] } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a missing `ruleKey` or `status`, a malformed `ruleKey`, `cursor`, `versionId` or `runId`, a `limit` outside `1..100`, or an unknown field) / `NOT_FOUND` with `CHECKS_WORKSPACE_NOT_FOUND` (the workspace has no store database). ```js theme={null} { "result": { "status": "success", "message": "Check comments retrieved", "data": { "comments": [], "nextCursor": null } } } ``` # Reject Comment Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/comments/reject POST https://api.velt.dev/v2/agents/checks/comments/reject Use this API to reject one comment of a check, with one of the four [reject reasons](/docs/api-reference/rest-apis/v2/agents/checks/overview#reject-reasons). It writes the same shape as the Velt SDK's [`rejectSuggestion()`](/docs/api-reference/sdk/api/api-methods#rejectsuggestion). The comment's `suggestion.status` becomes `rejected`, with `suggestion.rejectReason` (the person's words when given, else the reason), `suggestion.resolvedBy` and `suggestion.resolvedAt`. The annotation becomes a regular comment. The comment's status does not change: an Open comment stays Open, with its pin, and a Resolved one stays Resolved. A resolve that was waiting for its verify rescan stops waiting. Like the SDK, it rejects only a suggestion that is still pending (or a comment with no suggestion) that no scan verified. It refuses an accepted suggestion with `CHECKS_SUGGESTION_SETTLED` and a verified comment with `CHECKS_ALREADY_VERIFIED`. A comment rejected only by [Exclude Check](/docs/api-reference/rest-apis/v2/agents/checks/exclude) takes the person's reject instead. A rejected comment counts nowhere: not in the check's open count, never makes a check failing, and not in the score. When an agent finds the same problem again, the comment stays rejected as it is: no scan reopens, resolves, verifies or rewrites it. Reject is idempotent: a comment that is already rejected is left as it is. The comment must be an agent comment. A person's comment is refused, attached to a check or not: [detach](/docs/api-reference/rest-apis/v2/agents/checks/comments/detach) it instead. # Endpoint `POST https://api.velt.dev/v2/agents/checks/comments/reject` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **annotationId** `string` *required* The comment annotation id. 1 to 512 characters, no `/`, and not `.` or `..`. **reason** `string` *required* `"wrong"`, `"not_important"`, `"not_applicable"` or `"cannot_tell"`. **userId** `string` *required* 1 to 512 characters. Recorded as the person who rejected the comment. **feedbackReason** `string` At most 2,000 characters. The person's own words, stored as `suggestion.rejectReason` and sent with the reason to the agent's feedback. The schema uses `.strict()`: unknown fields are rejected. ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "annotationId": "K7mQ2xR9vB4wLdT1sYpN", "reason": "not_applicable", "userId": "user_sam", "feedbackReason": "This link is behind a login on purpose." } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Comment rejected", "data": { "rejected": true } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "Only an agent comment can be resolved, rejected or reopened here", "status": "FAILED_PRECONDITION", "details": { "reason": "CHECKS_NOT_AGENT_COMMENT" } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a missing `annotationId` or `userId`, a `reason` outside the four (`excluded`, which a row can show, is the engine's own and refused here), a `feedbackReason` over 2,000 characters, or an unknown field) / `NOT_FOUND` with `CHECKS_COMMENT_NOT_FOUND` (no such comment in the project) / `FAILED_PRECONDITION` with `CHECKS_NOT_AGENT_COMMENT` (a person's comment), `CHECKS_SUGGESTION_SETTLED` (an accepted suggestion) or `CHECKS_ALREADY_VERIFIED` (a comment a scan verified). ```js theme={null} { "result": { "status": "success", "message": "Comment rejected", "data": { "rejected": true } } } ``` # Reopen Comment Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/comments/reopen POST https://api.velt.dev/v2/agents/checks/comments/reopen Use this API to put a Resolved comment of a check back to Open (verified or not). The resolve and verify fields are cleared, so a later resolve is verified again. A [rejected](/docs/api-reference/rest-apis/v2/agents/checks/comments/reject) comment is not reopened: it stays rejected, and the call still answers `{ reopened: true }`. A person's reject cannot be undone over the API; an excluded check's rejects are undone by [Include Check](/docs/api-reference/rest-apis/v2/agents/checks/include). Reopen is idempotent: a comment that is already Open or In progress keeps its status. The comment can be an agent comment, or a person's comment [attached](/docs/api-reference/rest-apis/v2/agents/checks/comments/attach) to a check. A person's comment that is not attached to a check is refused. See [Statuses](/docs/api-reference/rest-apis/v2/agents/checks/overview#statuses). # Endpoint `POST https://api.velt.dev/v2/agents/checks/comments/reopen` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **annotationId** `string` *required* The comment annotation id. 1 to 512 characters, no `/`, and not `.` or `..`. **userId** `string` *required* 1 to 512 characters. Recorded as the person who reopened the comment. The schema uses `.strict()`: unknown fields are rejected. ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "annotationId": "K7mQ2xR9vB4wLdT1sYpN", "userId": "user_sam" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Comment reopened", "data": { "reopened": true } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "Comment not found", "status": "NOT_FOUND", "details": { "reason": "CHECKS_COMMENT_NOT_FOUND" } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a missing `annotationId` or `userId`, or an unknown field) / `NOT_FOUND` with `CHECKS_COMMENT_NOT_FOUND` (no such comment in the project) / `FAILED_PRECONDITION` with `CHECKS_NOT_AGENT_COMMENT` (a person's comment not attached to a check). ```js theme={null} { "result": { "status": "success", "message": "Comment reopened", "data": { "reopened": true } } } ``` # Resolve Comment Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/comments/resolve POST https://api.velt.dev/v2/agents/checks/comments/resolve Use this API to resolve one comment of a check, for a person (`by: "user"`) or an MCP client (`by: "mcp"`). The comment becomes Resolved and waits for the scan that verifies it (`pendingVerify: true`). Only a scan verifies: see [Statuses](/docs/api-reference/rest-apis/v2/agents/checks/overview#statuses). The resolve starts a verify rescan, which uses AI credits at the flat rescan rate. Resolves on one project within 15 seconds share one rescan per agent, so a fresh resolve answers `queued: true` with no run id yet. Resolve is idempotent. Resolving a comment that already waits for its rescan answers `alreadyPending: true`, starts nothing and charges nothing. A comment a scan already verified is refused: [reopen](/docs/api-reference/rest-apis/v2/agents/checks/comments/reopen) it first. A [rejected](/docs/api-reference/rest-apis/v2/agents/checks/comments/reject) comment takes the Resolved status and nothing else: no verify rescan, no charge, no `pendingVerify`. It answers `{ rescanExecutionId: null, queued: false, alreadyPending: false }` and stays rejected (`statusKind: "rejected"`), so it still counts nowhere. The comment can be an agent comment, or a person's comment [attached](/docs/api-reference/rest-apis/v2/agents/checks/comments/attach) to a check. An agent comment written before the checks engine, with no check, is Resolved and its agent scans its page once, charged like any one-page scan. A person's comment that is not attached to a check is refused. # Endpoint `POST https://api.velt.dev/v2/agents/checks/comments/resolve` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **annotationId** `string` *required* The comment annotation id. 1 to 512 characters, no `/`, and not `.` or `..`. **by** `string` *required* Who resolves: `"user"` (a person) or `"mcp"` (an MCP client). Any other value is rejected. **userId** `string` *required* 1 to 512 characters. Recorded as the person who resolved the comment. **userName** `string` At most 512 characters. The person's name, for the verify rescan's run. **userEmail** `string` At most 512 characters. The person's email, for the verify rescan's run. The schema uses `.strict()`: unknown fields are rejected. ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "annotationId": "K7mQ2xR9vB4wLdT1sYpN", "by": "user", "userId": "user_jordan", "userName": "Jordan Lee", "userEmail": "jordan@example.com" } } ``` # Response #### Success Response (fresh resolve) ```JSON theme={null} { "result": { "status": "success", "message": "Comment resolved", "data": { "rescanExecutionId": null, "queued": true, "alreadyPending": false } } } ``` #### Success Response (already waiting) ```JSON theme={null} { "result": { "status": "success", "message": "Comment resolved", "data": { "rescanExecutionId": "exec_4Wq7Zx2Np8", "queued": false, "alreadyPending": true } } } ``` | Field | Type | Description | | - | - | - | | `data.rescanExecutionId` | string \| null | The verify rescan's execution id, once it has started. `null` while the resolve waits in its 15-second window. | | `data.queued` | boolean | `true` when the comment waits for a rescan that has no run id yet. | | `data.alreadyPending` | boolean | `true` when the comment already waited for its rescan: nothing new started. | All three are `false` / `null` when no verify rescan is involved: the workspace has no store database, the comment has no check, or the rescan could not be queued. In the last case, the next scan of the comment's pages verifies or reopens it. #### Failure Response ```JSON theme={null} { "error": { "message": "This comment was already verified by a scan", "status": "FAILED_PRECONDITION", "details": { "reason": "CHECKS_ALREADY_VERIFIED" } } } ``` **Errors:** * `INVALID_ARGUMENT` for a body outside the schema: a missing `annotationId`, `by` or `userId`, a `by` other than `"user"` or `"mcp"`, or an unknown field; * `NOT_FOUND` with `CHECKS_COMMENT_NOT_FOUND` (no such comment in the project); * `FAILED_PRECONDITION` with `CHECKS_ALREADY_VERIFIED` (a scan already verified the comment: reopen it first) or `CHECKS_NOT_AGENT_COMMENT` (a person's comment not attached to a check). ```js theme={null} { "result": { "status": "success", "message": "Comment resolved", "data": { "rescanExecutionId": null, "queued": true, "alreadyPending": false } } } ``` # Exclude Check Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/exclude POST https://api.velt.dev/v2/agents/checks/exclude Use this API to exclude a check for a project, with one of the four [reject reasons](/docs/api-reference/rest-apis/v2/agents/checks/overview#reject-reasons). The check's state becomes `excluded`: * it leaves the score (its `scoreImpact` is `0`) and counts none of its comments (its `openCount` and `pageCount` are `0`); * its open agent comments are [rejected](/docs/api-reference/rest-apis/v2/agents/checks/comments/reject) with the reason `excluded`. Their status does not change. A person's comment [attached](/docs/api-reference/rest-apis/v2/agents/checks/comments/attach) to the check, and an accepted suggestion, stay as they are; * its findings write no comment. The agent still runs. [Include Check](/docs/api-reference/rest-apis/v2/agents/checks/include) undoes it. # Endpoint `POST https://api.velt.dev/v2/agents/checks/exclude` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **ruleKey** `string` *required* The check. `[a-z0-9:-]`, at most 120 characters. **reason** `string` *required* `"wrong"`, `"not_important"`, `"not_applicable"` or `"cannot_tell"`. **userId** `string` *required* 1 to 512 characters. Recorded as the person who excluded the check. The schema uses `.strict()`: unknown fields are rejected. ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "ruleKey": "link-unlinked-email", "reason": "not_important", "userId": "user_sam" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Check excluded", "data": { "excluded": true } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "Workspace not found or has no store database for the checks engine", "status": "NOT_FOUND", "details": { "reason": "CHECKS_WORKSPACE_NOT_FOUND" } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a missing or malformed `ruleKey`, a `reason` outside the four, a missing `userId`, or an unknown field) / `NOT_FOUND` with `CHECKS_WORKSPACE_NOT_FOUND` (the workspace has no store database). ```js theme={null} { "result": { "status": "success", "message": "Check excluded", "data": { "excluded": true } } } ``` # Include Check Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/include POST https://api.velt.dev/v2/agents/checks/include Use this API to include a check that was [excluded](/docs/api-reference/rest-apis/v2/agents/checks/exclude). The comments the exclusion rejected are pending suggestions again, the check counts in the score again, and the next run writes comments from its findings again. A comment a person [rejected](/docs/api-reference/rest-apis/v2/agents/checks/comments/reject) on its own stays rejected. # Endpoint `POST https://api.velt.dev/v2/agents/checks/include` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **ruleKey** `string` *required* The check. `[a-z0-9:-]`, at most 120 characters. **userId** `string` *required* 1 to 512 characters. Recorded as the person who reopened the comments. The schema uses `.strict()`: unknown fields are rejected. ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "ruleKey": "link-unlinked-email", "userId": "user_sam" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Check included", "data": { "included": true } } } ``` #### Failure Response ```JSON theme={null} { "error": { "message": "Workspace not found or has no store database for the checks engine", "status": "NOT_FOUND", "details": { "reason": "CHECKS_WORKSPACE_NOT_FOUND" } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a missing or malformed `ruleKey`, a missing `userId`, or an unknown field) / `NOT_FOUND` with `CHECKS_WORKSPACE_NOT_FOUND` (the workspace has no store database). ```js theme={null} { "result": { "status": "success", "message": "Check included", "data": { "included": true } } } ``` # List Checks Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/list POST https://api.velt.dev/v2/agents/checks/list Use this API to list a project's [checks](/docs/api-reference/rest-apis/v2/agents/checks/overview), most severe first. Each row carries the check's counts, score impact, state and owner. Filter by agent, severity, owner or state. # Endpoint `POST https://api.velt.dev/v2/agents/checks/list` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **filters** `object` Optional filters. Every filter given must match. | Key | Type | Description | | - | - | - | | `agentId` | string | 1 to 512 characters. Checks this agent produces. | | `severity` | string | `"critical"`, `"high"`, `"medium"` or `"low"`. | | `ownerMemberId` | string | 1 to 512 characters. Checks whose owner override or effective owner is this user. | | `state` | string | `"failing"`, `"excluded"` or `"passing"`. | The schema uses `.strict()`: unknown fields, in `data` or in `filters`, are rejected. ## **Example Requests** #### 1. List every check ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site" } } ``` #### 2. List the failing critical checks ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "filters": { "severity": "critical", "state": "failing" } } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Checks retrieved", "data": { "checks": [ { "ruleKey": "link-broken", "title": "Broken link", "description": "A link on the page returns an error or does not resolve.", "severity": "critical", "responsibility": "dev", "agentIds": ["broken-links"], "openCount": 2, "pageCount": 14, "scoreImpact": 4.2, "state": "failing", "ownerMemberId": null, "effectiveOwner": { "userId": "user_jordan", "name": "Jordan Lee", "email": "jordan@example.com" }, "lastSeenAt": 1761465600000, "failingSince": 1761379200000 }, { "ruleKey": "link-unlinked-email", "title": "Email address is not linked", "description": "An email address cannot be clicked to write.", "severity": "low", "responsibility": "content", "agentIds": ["broken-links"], "openCount": 0, "pageCount": 0, "scoreImpact": 0, "state": "excluded", "ownerMemberId": null, "effectiveOwner": null, "lastSeenAt": 1761206400000, "ignoredReason": "not_important", "ignoredBy": "user_sam", "ignoredAt": 1761292800000 } ], "excludedCount": 1, "runEndInProgress": false, "writesPending": false } } } ``` | Field | Type | Description | | - | - | - | | `data.checks` | object\[] | The checks, most severe first, then by score impact. | | `checks[].ruleKey` | string | The check's key. | | `checks[].title` | string | The check's name. | | `checks[].description` | string | What the check finds. | | `checks[].severity` | string | `"critical"`, `"high"`, `"medium"` or `"low"`. | | `checks[].responsibility` | string | Who fixes it: `"content"`, `"design"` or `"dev"`. | | `checks[].fixGuide` | string | How to fix it. Present when the check has one. | | `checks[].agentIds` | string\[] | The agents that produce the check. | | `checks[].openCount` | number | Open comments, attached comments included. `0` for an excluded check. | | `checks[].pageCount` | number | Pages with an open comment. `0` for an excluded check. | | `checks[].scoreImpact` | number | Points the check takes off the site score. `0` for an excluded check. | | `checks[].state` | string | `"failing"`, `"passing"` or `"excluded"`. | | `checks[].ownerMemberId` | string \| null | The owner set with [Set Check Owner](/docs/api-reference/rest-apis/v2/agents/checks/owner/set), or `null`. | | `checks[].effectiveOwner` | object \| null | The owner that applies: the override, else the default owner for the check's responsibility, else the project admin. `{ userId, name?, email? }`. | | `checks[].lastSeenAt` | number \| null | When a run last found the check (epoch ms). | | `checks[].ignoredReason` | string | Excluded checks: the reason given to [Exclude Check](/docs/api-reference/rest-apis/v2/agents/checks/exclude). | | `checks[].ignoredBy` | string | Excluded checks: who excluded it. | | `checks[].ignoredAt` | number | Excluded checks: when (epoch ms). | | `checks[].failingSince` | number | Failing checks: when the check last went from passing to failing (epoch ms). | | `data.excludedCount` | number | Checks excluded for the project. | | `data.runEndInProgress` | boolean | `true` while a run's comments are being grouped and written. The list may change in a few seconds. | | `data.writesPending` | boolean | `true` when a run's writes failed and wait for the next run. | #### Failure Response ```JSON theme={null} { "error": { "message": "Workspace not found or has no store database for the checks engine", "status": "NOT_FOUND", "details": { "reason": "CHECKS_WORKSPACE_NOT_FOUND" } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a missing `organizationId` or `documentId`, a `filters` value outside its list, or an unknown field) / `NOT_FOUND` with `CHECKS_WORKSPACE_NOT_FOUND` (the workspace has no store database). ```js theme={null} { "result": { "status": "success", "message": "Checks retrieved", "data": { "checks": [], "excludedCount": 0, "runEndInProgress": false, "writesPending": false } } } ``` # Checks Overview Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/overview How agent comments are grouped into checks, and how a resolve is verified by a scan. The checks engine groups the comments your [agents](/docs/ai/agents/overview) write into **checks**. Use the Checks APIs to read a project's checks, its comments and its score, and to resolve, reject, reopen, exclude, assign and attach. # Concepts ## Project A project is one Velt document of one organization: the pair `organizationId` and `documentId`. Every Checks endpoint takes both, and both are required. The same `documentId` in two organizations is two projects. ## Check A check is one kind of problem, named by its `ruleKey`, for example `link-broken` (a link that returns an error) or `image-broken`. Rule keys are lowercase letters, digits, `:` and `-`, at most 120 characters. A custom agent's checks have keys like `custom:{agentId}:{type}`. Each check has a title, a description, a severity, a responsibility (`content`, `design` or `dev`), an owner, the number of open comments and pages, its impact on the score, and a state: | State | Meaning | | - | - | | `failing` | The check has open comments. | | `passing` | The check has no open comments. | | `excluded` | The check is excluded for the project. It leaves the score and its findings write no comment. The agent still runs. | ## Comment A comment is one problem at one spot. It is a regular Velt comment annotation, written by the agent, with the engine's metadata in [`checkInfo`](/docs/api-reference/sdk/models/data-models#checkinfo). A finding seen again on a later run updates the same comment: it never writes a duplicate. * **Page comment**: a problem on one page (`scope: "page"`). * **Site comment**: the same problem at the same spot on two or more pages, for example a broken link in a shared footer. It is one comment for every page (`scope: "site"`), with its `pages` and its true `pageCount`. The engine stores a site comment on the `velt-site` location with [`isDocumentLevel: true`](/docs/api-reference/sdk/models/data-models#commentannotation). Velt lists it on every page of the document and draws its pin only where its target is found. * **Attached comment**: a comment a person wrote and then [attached](/docs/api-reference/rest-apis/v2/agents/checks/comments/attach) to a check. It counts in the check's open count and pages, lists under the check, and resolves and verifies with it. Each comment has a location type: `element` (pinned to an element on the page), `source` (a line in the page's stored HTML) or `none` (the evidence only). ## Statuses | Status | Meaning | | - | - | | Open | The problem is there. A comment In progress also counts as open. | | Resolved | Someone resolved it, or a scan found it fixed. | **Verified** means Resolved by a scan. Only a scan verifies: a scan sets `verifiedAt` and nothing else does. **Rejected** is not a status. A person who disagrees with the agent rejects its comment, in the same shape as the Velt SDK's [`rejectSuggestion()`](/docs/api-reference/sdk/api/api-methods#rejectsuggestion). `suggestion.status` becomes `rejected`. `suggestion.rejectReason` holds one of the four reasons below, the person's own words, `excluded` (an [excluded check](/docs/api-reference/rest-apis/v2/agents/checks/exclude)) or nothing. The comment keeps its status (an Open comment stays Open with its pin). A rejected comment counts nowhere (open counts, failing checks, the score). When an agent finds it again, it stays rejected as it is. When a person or an MCP client resolves a comment, it is Resolved and waits for the scan that verifies it (`pendingVerify: true`). The resolve queues a verify rescan: * The problem is gone: the comment is verified, with one reply such as "Verified. Fixed on all 12 pages. Time to resolve: 2 hours 14 minutes." * The problem is still there: the comment is reopened, with one reply such as "Still on 3 pages". * The rescan could not check its pages: it is tried again, up to 3 times, at no extra charge. After that the comment gets the reply "Could not verify yet." and stays Resolved and unverified until the next scan of its pages. A scan also resolves on its own: a comment its agent no longer finds on a page it checked is Resolved and verified by that scan. ## Severities | Severity | Weight | | - | - | | `critical` | 10 | | `high` | 7 | | `medium` | 3 | | `low` | 1 | The severity is also stored as the comment's `priority`. Checks are listed most severe first. ## Score Each page has a score from 0 to 100: the weighted share of the checks that apply to the page and pass on it. A check applies to a page when one of its agents checked the page in the last 30 days. The site score is the mean over the pages checked in the last 30 days. An excluded check is left out of the score. ## Reject reasons Rejecting a comment and excluding a check take one of the same four reasons. `excluded` is the engine's own reason for an excluded check's comments and is refused as input: | Reason | Meaning | | - | - | | `wrong` | The finding is wrong. | | `not_important` | The finding is right but does not matter. | | `not_applicable` | The finding does not apply here. | | `cannot_tell` | The person cannot tell. | # Resolves and credits A resolve through [Resolve Comment](/docs/api-reference/rest-apis/v2/agents/checks/comments/resolve) or [Resolve Check](/docs/api-reference/rest-apis/v2/agents/checks/resolve) starts a verify rescan, which uses AI credits at the flat rescan rate. Resolves on one project within 15 seconds share one rescan per agent. Resolve is idempotent: resolving a comment that already waits for its rescan starts nothing and charges nothing. When the agent is busy or the workspace has no credits, no rescan runs: the comment stays Resolved and the next scan of its pages verifies or reopens it. Resolve takes `by`: `"user"` for a person, `"mcp"` for an MCP client. Nothing else is accepted. # Status changes made in a Velt client A status a person changes in any Velt client (the Velt comment UI, or your own UI calling the SDK) reaches the checks engine on its own, about 10 seconds later: * Resolved: resolved by that user, then verified by a scan. A rejected comment takes the status only, with no verify. * Back to Open from Resolved: reopened. A rejected comment stays rejected. * A suggestion accepted in a Velt UI: resolved by `suggestion`, then verified by a scan. * A suggestion rejected in a Velt UI: the SDK's own reject. The engine records it (the agent's feedback, the counts) without changing the reject. A status changed with the [Update Comment Annotations](/docs/api-reference/rest-apis/v2/comments-feature/comment-annotations/update-comment-annotations) API does not reach the engine. Use [Resolve Comment](/docs/api-reference/rest-apis/v2/agents/checks/comments/resolve), [Reject Comment](/docs/api-reference/rest-apis/v2/agents/checks/comments/reject) and [Reopen Comment](/docs/api-reference/rest-apis/v2/agents/checks/comments/reopen) instead. # Requests Every Checks endpoint is a `POST` with the `x-velt-api-key` and `x-velt-auth-token` headers and a `{ "data": { ... } }` body. Every body takes `organizationId` and `documentId` (both required, 1 to 512 characters each). Every body uses `.strict()`: a field that is not on the endpoint's page is rejected with `INVALID_ARGUMENT`, never ignored. The decisions record the `userId` you send as the person who made them. The auth token proves the caller is the workspace, so send the id of the person acting. The same endpoints are also served under `/v1/agents/checks/...` with the same body and the same response. ## Workspaces without a store database The checks engine needs the workspace's Firestore store database. Without one, the reads and the check-level decisions return `NOT_FOUND` with the reason `CHECKS_WORKSPACE_NOT_FOUND`. Resolve, reject and reopen still change the comment, with no verify and no scan. # Errors A body outside the schema returns `INVALID_ARGUMENT`, with every failing field in `details.issues`. Every other refusal carries its reason in `details.reason`. Branch on the reason, never on the message. ```JSON theme={null} { "error": { "message": "This comment was already verified by a scan", "status": "FAILED_PRECONDITION", "details": { "reason": "CHECKS_ALREADY_VERIFIED" } } } ``` | `details.reason` | Status | When | | - | - | - | | `CHECKS_WORKSPACE_NOT_FOUND` | `NOT_FOUND` | The workspace has no store database for the checks engine. | | `CHECKS_COMMENT_NOT_FOUND` | `NOT_FOUND` | No comment with this `annotationId` in the project. | | `CHECKS_NOT_AGENT_COMMENT` | `FAILED_PRECONDITION` | Resolve or reopen of a person's comment that is not attached to a check, or a reject of any person's comment. | | `CHECKS_ALREADY_VERIFIED` | `FAILED_PRECONDITION` | Resolve or reject of a comment a scan already verified. Reopen it first. | | `CHECKS_SUGGESTION_SETTLED` | `FAILED_PRECONDITION` | Reject of an accepted suggestion. A suggestion is accepted or rejected once. | | `CHECKS_NOT_A_CHECK_COMMENT` | `FAILED_PRECONDITION` | The comment carries no check (capture focus, source location). | | `CHECKS_SOURCE_LOCATION_UNAVAILABLE` | `FAILED_PRECONDITION` | Source location of a comment whose location type is not `source`. | | `CHECKS_AGENT_COMMENT_NOT_ATTACHABLE` | `FAILED_PRECONDITION` | Attach or detach of an agent comment. | | `CHECKS_COMMENT_NOT_ATTACHED` | `FAILED_PRECONDITION` | Detach of a comment that is not attached to a check. | | `CHECKS_INVALID_PAGES_CURSOR` | `INVALID_ARGUMENT` | `pagesCursor` is not a page of the previous read. | | `CHECKS_INVALID_PAGE_URL` | `INVALID_ARGUMENT` | `pageUrl` is not an `http(s)` page of the comment, or `versionId` is malformed (source location). | | `CHECKS_INVALID_PAGES` | `INVALID_ARGUMENT` | A `pages` entry is not an `http(s)` URL (rescan agents). | The engine also checks rule keys, cursors, filters, reasons and settings itself (`CHECKS_INVALID_RULE_KEY`, `CHECKS_INVALID_CURSOR`, `CHECKS_INVALID_VERSION_FILTER`, `CHECKS_INVALID_REJECT_REASON`, `CHECKS_INVALID_RESOLVER`, `CHECKS_INVALID_SETTINGS`, `CHECKS_INVALID_PAGE_SIZE`), but over REST the schema refuses these values first, with `INVALID_ARGUMENT` and `details.issues`. # Endpoints | Endpoint | Does | | - | - | | [List Checks](/docs/api-reference/rest-apis/v2/agents/checks/list) | The project's checks. | | [List Check Comments](/docs/api-reference/rest-apis/v2/agents/checks/comments/list) | One check's comments in one status. | | [Get Site Score](/docs/api-reference/rest-apis/v2/agents/checks/score/get) | The site score, the last runs and the pages. | | [Get Capture Focus](/docs/api-reference/rest-apis/v2/agents/checks/capture-focus/get) | Where a comment sits on its captured screenshot. | | [Get Source Location](/docs/api-reference/rest-apis/v2/agents/checks/source-location/get) | Where a source comment sits in the stored HTML. | | [Resolve Comment](/docs/api-reference/rest-apis/v2/agents/checks/comments/resolve) | Resolve one comment and queue its verify rescan. | | [Resolve Check](/docs/api-reference/rest-apis/v2/agents/checks/resolve) | Resolve every open comment of a check. | | [Reject Comment](/docs/api-reference/rest-apis/v2/agents/checks/comments/reject) | Reject a comment with a reason. | | [Reopen Comment](/docs/api-reference/rest-apis/v2/agents/checks/comments/reopen) | Put a Resolved comment back to Open. | | [Exclude Check](/docs/api-reference/rest-apis/v2/agents/checks/exclude) | Take a check out of the project. | | [Include Check](/docs/api-reference/rest-apis/v2/agents/checks/include) | Bring an excluded check back. | | [Set Check Owner](/docs/api-reference/rest-apis/v2/agents/checks/owner/set) | Set or clear a check's owner. | | [Get Check Settings](/docs/api-reference/rest-apis/v2/agents/checks/settings/get) | The settings the engine applies. | | [Update Check Settings](/docs/api-reference/rest-apis/v2/agents/checks/settings/update) | Change the confidence floor, flags and default owners. | | [Attach Comment](/docs/api-reference/rest-apis/v2/agents/checks/comments/attach) | Attach a person's comment to a check. | | [Detach Comment](/docs/api-reference/rest-apis/v2/agents/checks/comments/detach) | Detach a person's comment from its check. | | [List Rescan Agents](/docs/api-reference/rest-apis/v2/agents/checks/rescan-agents/list) | The agents to run to rescan the site. | # Set Check Owner Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/owner/set POST https://api.velt.dev/v2/agents/checks/owner/set Use this API to set a check's owner for a project, or to clear it with `null`. Without an owner set here, the check's owner is the default owner for its responsibility, else the project admin (see [Update Check Settings](/docs/api-reference/rest-apis/v2/agents/checks/settings/update)). [List Checks](/docs/api-reference/rest-apis/v2/agents/checks/list) returns both: `ownerMemberId` (set here) and `effectiveOwner` (the one that applies). # Endpoint `POST https://api.velt.dev/v2/agents/checks/owner/set` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **ruleKey** `string` *required* The check. `[a-z0-9:-]`, at most 120 characters. **ownerMemberId** `string | null` *required* The owner's user id (1 to 512 characters), or `null` to clear the owner. The field must be present. **owner** `object | null` The owner's name and email, so they show without a lookup: `{ userId, name?, email? }`, `name` and `email` at most 512 characters each. Kept only when `owner.userId` equals `ownerMemberId`. The schema uses `.strict()`: unknown fields, in `data` or in `owner`, are rejected. ## **Example Requests** #### 1. Set the owner ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "ruleKey": "link-broken", "ownerMemberId": "user_jordan", "owner": { "userId": "user_jordan", "name": "Jordan Lee", "email": "jordan@example.com" } } } ``` #### 2. Clear the owner ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "ruleKey": "link-broken", "ownerMemberId": null } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Check owner set", "data": { "ownerMemberId": "user_jordan" } } } ``` | Field | Type | Description | | - | - | - | | `data.ownerMemberId` | string \| null | The owner now set, or `null` when cleared. | #### Failure Response ```JSON theme={null} { "error": { "message": "Workspace not found or has no store database for the checks engine", "status": "NOT_FOUND", "details": { "reason": "CHECKS_WORKSPACE_NOT_FOUND" } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a missing or malformed `ruleKey`, a missing `ownerMemberId`, an `owner` without `userId`, or an unknown field) / `NOT_FOUND` with `CHECKS_WORKSPACE_NOT_FOUND` (the workspace has no store database). ```js theme={null} { "result": { "status": "success", "message": "Check owner set", "data": { "ownerMemberId": null } } } ``` # List Rescan Agents Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/rescan-agents/list POST https://api.velt.dev/v2/agents/checks/rescan-agents/list Use this API to list the agents to run to rescan a project's site: the agents of its checks and of its runs in the last 30 days. A site whose agents found nothing still names them. With `pages`, it returns only the agents that checked one of those pages. When no agent checked any of them, every agent of the site is returned. Run the agents with [Run Execution](/docs/api-reference/rest-apis/v2/agents/execution/run). This endpoint starts nothing and charges nothing. # Endpoint `POST https://api.velt.dev/v2/agents/checks/rescan-agents/list` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **pages** `string[]` At most 1,000 absolute `http(s)` page URLs, each at most 2,048 characters. Without it, the agents of the whole site. The schema uses `.strict()`: unknown fields are rejected. ## **Example Requests** #### 1. The whole site ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site" } } ``` #### 2. Some pages ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "pages": [ "https://www.example.com/pricing", "https://www.example.com/about" ] } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Rescan agents retrieved", "data": { "agentIds": ["broken-links", "spell-check"] } } } ``` | Field | Type | Description | | - | - | - | | `data.agentIds` | string\[] | The agent ids, sorted. Empty when no agent has checked the site. | #### Failure Response ```JSON theme={null} { "error": { "message": "pages must be a list of page URLs", "status": "INVALID_ARGUMENT", "details": { "reason": "CHECKS_INVALID_PAGES" } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a `pages` entry that is not a URL, more than 1,000 `pages`, or an unknown field; or `CHECKS_INVALID_PAGES` for a `pages` entry that is not `http(s)`) / `NOT_FOUND` with `CHECKS_WORKSPACE_NOT_FOUND` (the workspace has no store database). ```js theme={null} { "result": { "status": "success", "message": "Rescan agents retrieved", "data": { "agentIds": ["broken-links"] } } } ``` # Resolve Check Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/resolve POST https://api.velt.dev/v2/agents/checks/resolve Use this API to resolve every open agent comment of one check in one call, for a person (`by: "user"`) or an MCP client (`by: "mcp"`). Each comment is resolved as [Resolve Comment](/docs/api-reference/rest-apis/v2/agents/checks/comments/resolve) does: Resolved, and waiting for the scan that verifies it. All of them share one verify window, so each of the check's agents rescans once. The resolve starts a verify rescan, which uses AI credits at the flat rescan rate. It is idempotent: a comment that already waits for its rescan is counted in `alreadyPending`, not resolved again, and not charged again. At most 5,000 open comments are resolved in one call. Attached comments are not included. See [Checks Overview](/docs/api-reference/rest-apis/v2/agents/checks/overview). # Endpoint `POST https://api.velt.dev/v2/agents/checks/resolve` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **ruleKey** `string` *required* The check. `[a-z0-9:-]`, at most 120 characters. **by** `string` *required* Who resolves: `"user"` (a person) or `"mcp"` (an MCP client). Any other value is rejected. **userId** `string` *required* 1 to 512 characters. Recorded as the person who resolved the comments. **userName** `string` At most 512 characters. The person's name, for the verify rescans. **userEmail** `string` At most 512 characters. The person's email, for the verify rescans. The schema uses `.strict()`: unknown fields are rejected. ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "ruleKey": "link-broken", "by": "mcp", "userId": "user_jordan" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Check resolved", "data": { "resolved": 3, "alreadyPending": 1, "rescanExecutionIds": ["exec_4Wq7Zx2Np8"], "truncated": false } } } ``` | Field | Type | Description | | - | - | - | | `data.resolved` | number | Comments this call resolved. | | `data.alreadyPending` | number | Comments that already waited for their verify rescan: nothing new started, nothing charged. | | `data.rescanExecutionIds` | string\[] | The verify runs of the comments that already waited, when they have started. The comments resolved now are queued and have no run id yet. | | `data.truncated` | boolean | `true` when the check had more than 5,000 open comments. The rest stay open: call again. | #### Failure Response ```JSON theme={null} { "error": { "message": "Workspace not found or has no store database for the checks engine", "status": "NOT_FOUND", "details": { "reason": "CHECKS_WORKSPACE_NOT_FOUND" } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a missing or malformed `ruleKey`, a missing `userId`, a `by` other than `"user"` or `"mcp"`, or an unknown field) / `NOT_FOUND` with `CHECKS_WORKSPACE_NOT_FOUND` (the workspace has no store database). ```js theme={null} { "result": { "status": "success", "message": "Check resolved", "data": { "resolved": 0, "alreadyPending": 0, "rescanExecutionIds": [], "truncated": false } } } ``` # Get Site Score Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/score/get POST https://api.velt.dev/v2/agents/checks/score/get Use this API to get a project's site score, its last runs and its pages with their scores, lowest score first. The pages come a page at a time. See [Score](/docs/api-reference/rest-apis/v2/agents/checks/overview#score). # Endpoint `POST https://api.velt.dev/v2/agents/checks/score/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **pagesCursor** `string` The `nextPagesCursor` of the previous read, passed back exactly as it came. It is opaque: do not build or edit one. At most 4,096 characters. **pageSize** `number` Pages per read. Whole number, 1 to 1,000. Default: `500`. The schema uses `.strict()`: unknown fields are rejected. ## **Example Requests** #### 1. First read ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "pageSize": 100 } } ``` #### 2. Next read ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "pageSize": 100, "pagesCursor": "p1WzgzLjMsImh0dHBzOi8vZXhhbXBsZS5jb20vcHJpY2luZyIsImM4MmYxYjVlIl0" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Site score retrieved", "data": { "siteScore": 94.8, "recentRuns": [ { "runId": "exec_9Jn3Pq5Rs1", "siteScore": 94.8, "at": 1761465600000, "trigger": "standalone", "agentId": "broken-links" } ], "pages": [ { "url": "https://www.example.com/pricing", "urlHash": "c82f1b5e", "score": 91.5, "openCount": 2, "lastCheckedAt": 1761465600000 }, { "url": "https://www.example.com/", "urlHash": "a41c9e07", "score": 95, "openCount": 1, "lastCheckedAt": 1761465600000 } ], "nextPagesCursor": null, "totalPages": 2, "excludedCount": 1, "nextScanAt": null } } } ``` | Field | Type | Description | | - | - | - | | `data.siteScore` | number \| null | The site score, 0 to 100. `null` before the first run. | | `data.recentRuns` | object\[] | The last runs (at most 30), newest first: `runId`, the `siteScore` after it, `at` (epoch ms), the run's `trigger` (for example `"standalone"`, or `"resolve"` for a verify rescan), and the `agentId` that ran. | | `data.pages` | object\[] | One page of the pages, lowest score first. | | `pages[].url` | string | The page. | | `pages[].urlHash` | string | Hash of `url`. | | `pages[].score` | number \| null | The page's score, 0 to 100. `null` when no check applies to it. | | `pages[].openCount` | number | Open comments on the page. An excluded check's comments are not counted. | | `pages[].lastCheckedAt` | number \| null | When an agent last checked the page (epoch ms). | | `data.nextPagesCursor` | string \| null | Pass as `pagesCursor` for the next read. It marks a place in the order (lowest score first, then URL), not a page, so a page marked gone or rescored since never fails the next read. `null` at the end. | | `data.totalPages` | number | Pages across every read. | | `data.excludedCount` | number | Checks excluded for the project. | | `data.nextScanAt` | null | Reserved. Always `null` today. | #### Failure Response ```JSON theme={null} { "error": { "message": "The pages cursor is not the nextPagesCursor of a previous read", "status": "INVALID_ARGUMENT", "details": { "reason": "CHECKS_INVALID_PAGES_CURSOR" } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a malformed `pagesCursor`, a `pageSize` outside `1..1000`, or an unknown field; or `CHECKS_INVALID_PAGES_CURSOR` when `pagesCursor` does not decode to a position in the list) / `NOT_FOUND` with `CHECKS_WORKSPACE_NOT_FOUND` (the workspace has no store database). ```js theme={null} { "result": { "status": "success", "message": "Site score retrieved", "data": { "siteScore": null, "recentRuns": [], "pages": [], "nextPagesCursor": null, "totalPages": 0, "excludedCount": 0, "nextScanAt": null } } } ``` # Get Check Settings Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/settings/get POST https://api.velt.dev/v2/agents/checks/settings/get Use this API to get the checks settings the engine applies to a project: the confidence floor, your own flags and the default owners, and where they came from. Change them with [Update Check Settings](/docs/api-reference/rest-apis/v2/agents/checks/settings/update). # Endpoint `POST https://api.velt.dev/v2/agents/checks/settings/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. The schema uses `.strict()`: unknown fields are rejected. ## **Example Requests** ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Check settings retrieved", "data": { "confidenceFloor": 60, "hostFlags": { "weeklyDigest": true }, "owners": { "dev": { "userId": "user_jordan", "name": "Jordan Lee", "email": "jordan@example.com" }, "admin": { "userId": "user_sam" } }, "source": "mirror", "updatedAt": 1761465600000 } } } ``` | Field | Type | Description | | - | - | - | | `data.confidenceFloor` | number | 0 to 100. A finding under it writes no comment. Default: `50`. | | `data.hostFlags` | object | Your own boolean flags. Stored and returned, never read by the engine. | | `data.owners` | object | The default owner of a check by its responsibility (`content`, `design`, `dev`) and the fallback (`admin`), each `{ userId, name?, email? }`. Only the owners set with Update Check Settings are present. | | `data.source` | string | Where the settings came from: `"mirror"` (set with Update Check Settings), `"host"` (the embedding product's own) or `"default"`. | | `data.updatedAt` | number \| null | When the settings were last updated (epoch ms), or `null` when never set. | #### Failure Response ```JSON theme={null} { "error": { "message": "Workspace not found or has no store database for the checks engine", "status": "NOT_FOUND", "details": { "reason": "CHECKS_WORKSPACE_NOT_FOUND" } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a missing `organizationId` or `documentId`, or an unknown field) / `NOT_FOUND` with `CHECKS_WORKSPACE_NOT_FOUND` (the workspace has no store database). ```js theme={null} { "result": { "status": "success", "message": "Check settings retrieved", "data": { "confidenceFloor": 50, "hostFlags": {}, "owners": {}, "source": "default", "updatedAt": null } } } ``` # Update Check Settings Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/settings/update POST https://api.velt.dev/v2/agents/checks/settings/update Use this API to update a project's checks settings: the confidence floor, your own flags and the default owners. A field set to `null` is cleared. A field left out is kept. The response is the settings the engine now applies, as [Get Check Settings](/docs/api-reference/rest-apis/v2/agents/checks/settings/get) returns them. # Endpoint `POST https://api.velt.dev/v2/agents/checks/settings/update` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **settings** `object` *required* The settings to change. Every key is optional; `null` clears it. | Key | Type | Description | | - | - | - | | `confidenceFloor` | number \| null | 0 to 100. A finding under it writes no comment. Default: `50`. | | `hostFlags` | object \| null | Your own boolean flags, by name (1 to 120 characters). Stored and returned, never read by the engine. A flag set to `null` is removed; `hostFlags: null` removes them all. | | `owners` | object \| null | `{ content?, design?, dev?, admin? }`, each `{ userId, name?, email? }` or `null`. The default owner of a check by its responsibility; `admin` is the fallback. An owner set to `null` is removed; `owners: null` removes them all. | The schema uses `.strict()`: unknown fields, in `data`, `settings`, `owners` or an owner, are rejected. ## **Example Requests** #### 1. Raise the floor and set the dev owner ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "settings": { "confidenceFloor": 60, "owners": { "dev": { "userId": "user_jordan", "name": "Jordan Lee", "email": "jordan@example.com" } } } } } ``` #### 2. Set a flag and clear the floor ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "settings": { "confidenceFloor": null, "hostFlags": { "weeklyDigest": true } } } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Check settings updated", "data": { "confidenceFloor": 60, "hostFlags": {}, "owners": { "dev": { "userId": "user_jordan", "name": "Jordan Lee", "email": "jordan@example.com" } }, "source": "mirror", "updatedAt": 1761465600000 } } } ``` See [Get Check Settings](/docs/api-reference/rest-apis/v2/agents/checks/settings/get) for the fields. #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT", "details": { "issues": [ { "code": "too_big", "path": ["settings", "confidenceFloor"], "message": "Number must be less than or equal to 100" } ] } } } ``` **Errors:** `INVALID_ARGUMENT` (a body outside the schema: a missing `settings`, a `confidenceFloor` outside `0..100`, a flag that is not a boolean or `null`, an owner without `userId`, or an unknown field) / `NOT_FOUND` with `CHECKS_WORKSPACE_NOT_FOUND` (the workspace has no store database). ```js theme={null} { "result": { "status": "success", "message": "Check settings updated", "data": { "confidenceFloor": 50, "hostFlags": { "weeklyDigest": true }, "owners": {}, "source": "mirror", "updatedAt": 1761465600000 } } } ``` # Get Source Location Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/checks/source-location/get POST https://api.velt.dev/v2/agents/checks/source-location/get Use this API to find where a `source` comment's evidence sits in a page's stored HTML: the line number, the line, and the evidence's offsets in it. Use it for a "Show in source" view. Render the answer as it comes: do not repeat the matching. The comment must be a `source` comment (its `locationType` is `"source"`). The HTML is the page's capture in the site version asked for. See [Checks Overview](/docs/api-reference/rest-apis/v2/agents/checks/overview). # Endpoint `POST https://api.velt.dev/v2/agents/checks/source-location/get` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **organizationId** `string` *required* 1 to 512 characters. The organization of the project. **documentId** `string` *required* 1 to 512 characters. The document of the project. **annotationId** `string` *required* The comment annotation id. 1 to 512 characters, no `/`, and not `.` or `..`. **pageUrl** `string` One of the comment's pages: an absolute `http(s)` URL on the comment's site, at most 2,048 characters. Default: the comment's own page. **versionId** `string` A version of that page. `[A-Za-z0-9_-]`, 1 to 200 characters. Default: the version the comment last saw the page on. The schema uses `.strict()`: unknown fields are rejected. ## **Example Requests** #### 1. The comment's own page ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "annotationId": "R5tB1nM8wQ3xKzL7cVdF" } } ``` #### 2. Another page and version of a site comment ```JSON theme={null} { "data": { "organizationId": "org_acme", "documentId": "acme-marketing-site", "annotationId": "R5tB1nM8wQ3xKzL7cVdF", "pageUrl": "https://www.example.com/about", "versionId": "ver_20261025b" } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Source location retrieved", "data": { "versionId": "ver_20261026a", "urlHash": "a41c9e07", "pageUrl": "https://www.example.com/", "lineNumber": 42, "line": " ", "lineOffset": 0, "matchStart": 4, "matchEnd": 43 } } } ``` | Field | Type | Description | | - | - | - | | `data.versionId` | string \| null | The version read. | | `data.urlHash` | string \| null | Hash of the page read. | | `data.pageUrl` | string \| null | The page read, or `null` when none could be. | | `data.lineNumber` | number \| null | 1-based line of the stored HTML that holds the evidence, or `null` when it was not found. | | `data.line` | string | The line that holds the evidence. A very long line (minified HTML) is cut around the match. When the stored HTML could not be read, the evidence itself. | | `data.lineOffset` | number | Where `line` starts in the stored line. `0` unless a long line was cut. | | `data.matchStart` | number \| null | Where the evidence starts in `line`, or `null` when it was not found there. | | `data.matchEnd` | number \| null | Where the evidence ends in `line` (exclusive), or `null`. | > [!NOTE] > > The stored HTML is read up to 8 MB and within about 8 seconds. When the page has no capture for the version, or the read does not finish in time, the answer is the evidence with no offsets. #### Failure Response ```JSON theme={null} { "error": { "message": "This comment has no line in the stored page", "status": "FAILED_PRECONDITION", "details": { "reason": "CHECKS_SOURCE_LOCATION_UNAVAILABLE" } } } ``` **Errors:** * `INVALID_ARGUMENT` for a body outside the schema (a missing or malformed `annotationId`, a `pageUrl` that is not a URL, a malformed `versionId`, or an unknown field), or with `CHECKS_INVALID_PAGE_URL` for a `pageUrl` that is not `http(s)`, not on the comment's site, or not one of its pages; * `NOT_FOUND` with `CHECKS_COMMENT_NOT_FOUND` (no such comment in the project) or `CHECKS_WORKSPACE_NOT_FOUND` (the workspace has no store database); * `FAILED_PRECONDITION` with `CHECKS_NOT_A_CHECK_COMMENT` (the comment carries no check) or `CHECKS_SOURCE_LOCATION_UNAVAILABLE` (the comment is not a `source` comment). ```js theme={null} { "result": { "status": "success", "message": "Source location retrieved", "data": { "versionId": null, "urlHash": "a41c9e07", "pageUrl": "https://www.example.com/", "lineNumber": null, "line": "", "lineOffset": 0, "matchStart": null, "matchEnd": null } } } ``` # Resolve Config Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/config/resolve POST https://api.velt.dev/v2/agents/config/resolve Use this API to resolve optimal extraction strategies and execution strategy for an agent based on its instructions. The engine analyzes the (optional `rawInstructions` plus the processed `instructions`) and returns: * A recommended set of `contextGathering.strategies` * A recommended `executionStrategy` (`ai`, `service`, `service+ai`, or `stagehand-agent`) * Per-strategy options where a recommended strategy needs them * Reasoning for each recommendation Use this as a starting point when creating a new agent; the response can be passed straight into [Create Agent](/docs/api-reference/rest-apis/v2/agents/create) under the `contextGathering` and `execution` blocks. # Endpoint `POST https://api.velt.dev/v2/agents/config/resolve` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **instructions** `string` *required* Min 1 char. The processed/enhanced agent instructions. **rawInstructions** `string` Verbatim user prompt. When provided, the resolver also uses it to detect navigation/interaction intent (e.g. "click the menu, then check…") and may recommend `stagehand-agent` execution. **provider** `string` LLM provider override: `"gemini"`, `"claude"`, or `"openai"`. Any other value is accepted by the request schema, but the resolver then fails internally and returns its hardcoded default recommendation under a `success` status. Omit the field to use the platform default. ## **Example Requests** #### 1. Resolve a static analysis agent ```JSON theme={null} { "data": { "instructions": "Verify all CTAs use the primary brand color #1A73E8 and the heading font 'Inter'." } } ``` #### 2. Resolve an interactive agent ```JSON theme={null} { "data": { "rawInstructions": "Open the navigation menu, click 'Pricing', and check that the page title contains 'Pricing'.", "instructions": "Open the navigation menu, click the Pricing link, and verify the resulting page title contains 'Pricing'." } } ``` # Response #### Success Response ```JSON theme={null} { "result": { "status": "success", "message": "Config resolved successfully", "data": { "resolvedConfig": { "extraction_strategies": ["web-page-text", "web-page-screenshot", "computed-styles"], "execution_strategy": "ai", "reasoning": "The instructions describe a static visual + textual check (brand colors and fonts). Screenshots support color verification; computed styles resolve the rendered font on the heading elements. AI execution is sufficient; no service delegation needed.", "strategy_options": { "computed-styles": { "selectors": ["h1", ".cta"] } } } } } } ``` | Field | Type | Description | | - | - | - | | `data.resolvedConfig.extraction_strategies` | string\[] | Recommended `contextGathering.strategies` values. | | `data.resolvedConfig.execution_strategy` | string | Recommended `execution.executionStrategy` value. | | `data.resolvedConfig.reasoning` | string | Explanation for the recommendations. | | `data.resolvedConfig.strategy_options` | object | Per-strategy config the resolver derived from the prompt. Today the only key emitted is `computed-styles` (`{ selectors, properties? }`). Maps to `contextGathering.strategyOptions`. Omitted when no recommended strategy needs options. | > [!WARNING] > > Carry `strategy_options` across to Create Agent along with `extraction_strategies`. Some strategies are inert without it: `computed-styles` requires a `selectors` list, and dropping the resolver's options silently produces an agent that gathers nothing for that strategy. Mapping the response onto [Create Agent](/docs/api-reference/rest-apis/v2/agents/create): | Resolver field | Create Agent field | | - | - | | `extraction_strategies` | `contextGathering.strategies` | | `strategy_options` | `contextGathering.strategyOptions` | | `execution_strategy` | `execution.executionStrategy` | #### Failure Response ```JSON theme={null} { "error": { "message": "ERROR_MESSAGE", "status": "INVALID_ARGUMENT" } } ``` **Errors:** `INVALID_ARGUMENT` (missing or empty `instructions`). > [!WARNING] > > The resolver never surfaces an AI failure as an error. If the model call fails for any reason, the endpoint still returns `200` with `"status": "success"` and a hardcoded fallback recommendation: `extraction_strategies` of `["web-page-text", "web-page-html", "web-page-screenshot"]`, `execution_strategy` of `"ai"`, and `reasoning` of `"Default configuration applied"`. Check for that exact `reasoning` string before treating a response as tailored to your instructions. ```js theme={null} { "result": { "status": "success", "message": "Config resolved successfully", "data": { "resolvedConfig": { "extraction_strategies": ["web-page-text"], "execution_strategy": "ai", "reasoning": "..." } } } } ``` # Create Agent Source: https://velt.dev/docs/api-reference/rest-apis/v2/agents/create POST https://api.velt.dev/v2/agents/create Use this API to create a new custom agent configuration. The engine stores the agent in Firestore and writes version 1 to the agent's versions subcollection. The schema uses `.passthrough()`, so any additional behavioral fields are forwarded to the service layer. # Endpoint `POST https://api.velt.dev/v2/agents/create` # Headers **x-velt-api-key** `string` *required* Your API key. **x-velt-auth-token** `string` *required* Your [Auth Token](/docs/security/auth-tokens). # Body #### Params **data** `object` *required* **properties** **name** `string` *required* Min 1 char. Agent display name. **description** `string` *required* Min 1 char. Human-readable description of what the agent does. **rawInstructions** `string` Original user-provided instructions (before enhancement). **instructions** `string` Processed/enhanced instructions used by the AI execution. Required whenever the execution strategy consumes a prompt — `"ai"` (the default), `"service+ai"`, `"stagehand-agent"`, and `"mcp-tools"`. Only pure `"service"` agents may omit it. **enabled** `boolean` *required* Whether the agent is active. **phaseTimeoutMs** `number` Per-phase timeout in milliseconds. Positive integer, no upper bound. Omit to use the platform default. **metadata** `object` Arbitrary client metadata. Use your own keys (e.g. `{ "team": "growth", "owner": "jane" }`). **contextGathering** `object` *required* Context gathering configuration. | Field | Type | Required | Description | | - | - | - | - | | `strategies` | string\[] | yes | Min 1 strategy. See [context gathering strategies](#context-gathering-strategies). | | `strategyOptions` | object | no | Per-strategy option overrides, keyed by strategy name ([see below](#context-gathering-strategy-options)). When `strategies` includes `"rest-api"`, `strategyOptions["rest-api"]` is required ([see below](#rest-api-strategy-options)). | | `aiConfig` | object | no | AI provider/model override for the gather phase ([see below](#ai-config-provider--model)). | **execution** `object` *required* Execution configuration. Send `{}` to accept the defaults (the `"ai"` strategy). | Field | Type | Required | Description | | - | - | - | - | | `executionStrategy` | string | no | `"ai"` (default), `"service"`, `"service+ai"`, `"stagehand-agent"`, or `"mcp-tools"`. | | `serviceId` | string | no | Required when `executionStrategy` is `"service"` or `"service+ai"`. Values: `"broken-links"`, `"crawler"`, `"screenshot"`, `"accessibility-checker"`, `"og-image-checker"`. | | `aiConfig` | object | no | AI provider/model override for the execute phase ([see below](#ai-config-provider--model)). | | `mcpServers` | object\[] | no | Required (≥1) when `executionStrategy` is `"mcp-tools"`. Remote MCP servers the model may call during the tool loop ([see below](#mcp-servers-mcp-tools-strategy)). | | `responseDescriptions` | object | no | Per-field descriptions guiding AI response shaping ([see below](#response-descriptions)). | | `strategyOptions` | object | no | Per-strategy option overrides. See [execution strategy options](#execution-strategy-options). | | `knowledge` | object | no | Memory-RAG knowledge integration ([see below](#knowledge-memory-rag)). | **response** `object` Response formatting configuration. | Field | Type | Required | Description | | - | - | - | - | | `useAiFormatting` | boolean | no | Whether to use AI for response formatting. | | `formattingPrompt` | string | no | Custom prompt for AI formatting. | | `responseAdapter` | string | no | Adapter name: `"broken-links-response"`, `"crawler-response"`, `"screenshot-response"`, `"accessibility-checker-response"`, `"og-image-checker-response"`. | | `aiConfig` | object | no | Accepted and stored, but not consumed. See the note below. | > [!NOTE] > > AI response formatting is not implemented yet. `useAiFormatting`, `formattingPrompt`, and `response.aiConfig` are accepted and stored, but nothing reads them at runtime, so setting them has no effect on the agent's output. **postProcess** `object` Post-processing pipeline configuration. All stages default to **enabled** when omitted or when `enabled` is not explicitly `false`. | Field | Type | Required | Description | | - | - | - | - | | `guardrails` | object | no | `{ enabled?: boolean }`: finding quality pipeline — deduplicates findings (identical source URL + target text + occurrence + issue type) and sanitizes HTML/XSS from all text fields. | | `deletePreviousSuggestions` | object | no | `{ enabled?: boolean }`: per-URL delete-and-recreate that clears the prior run's suggestions for the URL before writing the new ones. This is the active dedup mechanism. | | `annotations` | object | no | `{ enabled?: boolean, strategy?: string }`: strategy is `"findings"`, `"word-level"`, `"page-level"`, or `"none"`. | | `analytics` | object | no | `{ enabled?: boolean }`: analytics event tracking. | | `matchAndMerge` | object | no | **Deprecated / ignored.** `{ enabled?: boolean }`: replaced by `deletePreviousSuggestions`. Still accepted for backward compatibility but has no effect. | | `customProcessors` | string\[] | no | Custom post-processor names. | | `findingEnrichment` | object | no | `{ commentFormat?: "plain" \| "legacy" }`: the layout of the comment each finding posts. Default for custom agents: `"legacy"`. See [Comment format](#comment-format). | Unknown keys inside `postProcess` are rejected. Pin resolution (anchoring visual findings to element coordinates) always runs as part of the pipeline and is not configurable via this field. **input** `object` Input declaration configuration. | Field | Type | Required | Description | | - | - | - | - | | `variableKeys` | string\[] | no | Variable names the agent expects in `payload.variables`. | | `userContextFields` | object\[] | no | User-context field definitions (`{ id, title, type, required?, example?, defaultValue? }`). | | `inputRequirements` | object | no | `{ requires?: string[], requiresOneOf?: string[] }`. | Each `userContextFields[]` entry: `id` (min 1), `title` (min 1), `type` (`"string"` / `"number"` / `"boolean"`), optional `required` (boolean), optional `example` (string; sample value surfaced in setup UIs), optional `defaultValue` (string / number / boolean). At run time, a field that is missing, `null`, or an empty string takes its `defaultValue` and then satisfies `required`. An `id` cannot be one of the reserved keys every agent honors: the run-scope keys `focusIssueTypes`, `sourceAnnotationId`, `sourcePageUrl`, and `sourceElementXpath`, or the run-control keys `forceFullRun` and `changeDetection` (see [Run Execution](/docs/api-reference/rest-apis/v2/agents/execution/run)). The request returns `INVALID_ARGUMENT` with `This userContextFields id is reserved for run scope or run control (focusIssueTypes, sourceAnnotationId, sourcePageUrl, sourceElementXpath, forceFullRun, changeDetection); give the field another id`. The key names are case-sensitive. > [!NOTE] > > `input.supportedVariables` is **response-only**. It lists the template variables the agent's prompt can reference (e.g. `{{restApiData}}`, `{{memoryContext}}`) and is server-computed from `contextGathering.strategies` and `input.variableKeys`. On create, anything you send in this field is discarded. On a [version update](/docs/api-reference/rest-apis/v2/agents/version/update) it is recomputed only when those inputs change. **scope** `object` Scope and targeting configuration. | Field | Type | Required | Description | | - | - | - | - | | `pageScope` | string\[] | no | URL glob patterns the agent runs on. | | `pageScopeExclude` | string\[] | no | URL glob patterns to exclude. | | `contentTypes` | string\[] | no | Content types the agent handles. | | `crossPage` | object | no | Cross-page execution config. See below. | `crossPage` is optional, but when present these three fields are **required**; omitting any of them fails validation. | Field | Type | Required | Description | | - | - | - | - | | `enabled` | boolean | yes | Whether cross-page evaluation is on. | | `targetProperty` | string | yes | The property being compared across pages. | | `pageDiscovery` | string | yes | `"auto"` (crawl to discover pages) or `"manual"` (use `pages[]`). | | `pages` | string\[] | no | Explicit page list. Pair with `pageDiscovery: "manual"`. | | `sourceOfTruthKnowledgeSourceId` | string | no | Knowledge source to treat as the reference for the comparison. | **setup** `object` Tooling metadata for the setup assistant and checklist-to-agent converter. Not consumed by the agent pipeline at runtime. | Field | Type | Required | Description | | - | - | - | - | | `setupSamples` | object\[] | no | Sample content plus the findings the agent should produce on it. | | `checklistOrigin` | object | no | Provenance for an agent generated from a checklist. | Each `setupSamples[]` entry: | Field | Type | Required | Description | | - | - | - | - | | `content` | string | yes | The sample content the agent is evaluated against. | | `source` | string | yes | `"synthetic"` or `"user-provided"`. | | `findings` | object\[] | yes | Expected findings, each `{ message (required), elementSelector?, isCorrect? }`. | | `pmVerdict` | string | no | Reviewer verdict: `"correct"` or `"incorrect"`. | | `pmNotes` | string | no | Free-text reviewer notes. | `checklistOrigin`: | Field | Type | Required | Description | | - | - | - | - | | `checklistId` | string | yes | Source checklist ID. | | `checklistVersion` | number | yes | Source checklist version. Integer ≥ 0. | | `sectionRefs` | string\[] | yes | Checklist sections this agent covers. | | `memoryRuleIds` | string\[] | yes | Knowledge rules this agent was derived from. | | `deduplicatedFrom` | number | no | Count of source rules collapsed into this agent. Integer ≥ 0. | #### Context gathering strategies | Strategy | What it returns | | - | - | | `web-page-text` | Visible text extracted via Puppeteer | | `web-page-screenshot` | Full-page screenshot as image (multimodal input) | | `web-page-html` | Cleaned HTML content | | `web-page-css` | Cleaned CSS content from stylesheets | | `web-page-links` | All hyperlinks, classified internal/external | | `web-page-accessibility` | Accessibility issues (Pa11y / HTML_CodeSniffer) | | `computed-styles` | Browser-resolved computed CSS for specific selectors | | `robots-txt` | Fetched `robots.txt` | | `sitemap-data` | Discovered and parsed XML sitemaps | | `lighthouse` | Google Lighthouse audit (performance / a11y / best-practices / SEO) | | `rest-api` | Customer-configured REST endpoints fetched at runtime ([see below](#rest-api-strategy-options)) | | `none` | No context gathering (for service-only or text-only agents) | #### Context gathering strategy options Per-strategy overrides are supplied under `contextGathering.strategyOptions[""]`. All are optional unless noted. | Strategy | Option | Type | Description | | - | - | - | - | | `web-page-text` | `deviceType` | string | `"mobile"` / `"desktop"` (default `"desktop"`). | | | `excludeIframes` | boolean | Exclude iframe content. Default `false`. | | `web-page-screenshot` | `scrollBeforeCapture` | boolean | Scroll the full page before capture. | | | `maxPageHeightPx` | number | Cap the captured page height. | | | `waitUntil` | string | Puppeteer wait condition. | | | `deviceType` | string | `"mobile"` / `"desktop"`. | | `web-page-html` | `includeHead` | boolean | Include ``. Default `true`. | | | `includeBody` | boolean | Include ``. Default `true`. | | | `excludeIframes` | boolean | Default `false`. | | | `waitUntil` | string | Puppeteer wait condition. | | `web-page-css` | `includeInlineStyles` | boolean | Include inline ` > > ``` > [tab] Other Frameworks > > ```jsx theme={null} >
> >
> >
>
> > > ``` # Inline Comments Section #### sortBy and sortOrder * Change the default sorting order of Comments in the Inline Comments Section. * Params: * `sortBy`: The field to sort by. Currently supports `createdAt` and `lastUpdated`. Default: `lastUpdated` for multithread and `createdAt` for single thread. * `sortOrder`: The order to sort by. It can be `asc` or `desc`. Default: `desc` for multithread and `asc` for single thread. > [tab] React / Next.js > > ```jsx theme={null} > > ``` > [tab] Other Frameworks > > ```html theme={null} > sort-by="createdAt" > sort-order="desc" > > > ``` #### multiThread * By default [inline comment section](/docs/async-collaboration/comments/setup/inline-comments) is multithreaded. * You can make it single threaded by setting `multiThread` prop to `false`. * Default: `true` > [tab] React / Next.js > > ```jsx theme={null} > > ``` > [tab] Other Frameworks > > ```html theme={null} > > ``` #### commentPlaceholder, replyPlaceholder, composerPlaceholder * Customize placeholder text for different input fields in the inline comments section. * Props: * `commentPlaceholder`: Placeholder text for the main comment input field. * `replyPlaceholder`: Placeholder text for the reply input field. * `composerPlaceholder`: Placeholder text for the composer input field. > [tab] React / Next.js > > ```jsx theme={null} > commentPlaceholder="ABC Placeholder" > replyPlaceholder="ABC Reply Placeholder" > composerPlaceholder="ABC Composer Placeholder" > /> > ``` > [tab] Other Frameworks > > ```html theme={null} > comment-placeholder="ABC Placeholder" > reply-placeholder="ABC Reply Placeholder" > composer-placeholder="ABC Composer Placeholder" > > > ``` To customize placeholder text shown when **editing** an existing comment or reply, use `editPlaceholder`, `editCommentPlaceholder`, and `editReplyPlaceholder`. See [`VeltInlineCommentsSectionProps`](/docs/api-reference/sdk/models/data-models#veltinlinecommentssectionprops) for details. #### composerPosition * Change the position of the comment composer in the inline comments section to `top` or `bottom`. * Default: `bottom` > [tab] React / Next.js > > ```jsx theme={null} > > ``` > [tab] Other Frameworks > > ```html theme={null} > > ``` #### context * Pass a custom context object to the Inline Comments Section component. * The provided context will be added to any comments created in the inline comments section, allowing you to associate custom metadata with those comments. * Additionally, the component will filter and display only the comments that match the provided context object. * This dual behavior makes it easy to scope comments to specific areas of your application (e.g., specific cells in a table, dashboard widgets, or data segments). > [tab] React / Next.js > > ```jsx theme={null} > context={{ > department: "marketing", > quarter: "Q1", > category: "paid-ads", > }} > /> > ``` > [tab] Other Frameworks > > ```html theme={null} > > ``` #### contextOptions * Configure the matching behavior for the context object when filtering comments. * By default, comments must fully match all key-value pairs in the provided context. * Set `partialMatch: true` to enable flexible matching where comments match if they contain all the specified context fields (extra fields in the comment's context are ignored). * See [`Context` Matching](#context-matching) for detailed explanation and examples. > [tab] React / Next.js > > ```jsx theme={null} > {/* Full match (default) - comment must have exact context */} > context={{ department: "marketing", quarter: "Q1" }} > /> > > {/* Partial match - comment matches if it contains these fields */} > > context={{ department: "marketing" }} > contextOptions={{ partialMatch: true }} > /> > ``` > [tab] Other Frameworks > > ```html theme={null} > > context='{"department": "marketing", "quarter": "Q1"}'> > > > > > context='{"department": "marketing"}' > context-options='{"partialMatch": true}'> > > > ``` #### readOnly Control read-only mode at the component level. When enabled, users can view comments but cannot reply, edit, or add new comments in the Inline Comments Section. The local component prop takes precedence over global settings when explicitly set. Default: `false` > [tab] React / Next.js > > ```jsx theme={null} > targetElementId="my-element" > readOnly={true} > /> > ``` > [tab] Other Frameworks > > ```html theme={null} > target-element-id="my-element" > read-only="true"> > > ``` # Popover Comments #### enableDialogOnTargetElementClick ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/hover-cell-comment.gif?s=092f6241ef57b96231d6f837b6ab9743) Whether the comment dialog opens when target element is clicked. This is relevant only for Popover mode. `Default: true` > [tab] React / Next.js > > ```js theme={null} > > ``` > [tab] Other Frameworks > > ```js theme={null} > > ``` API Method: > [tab] React / Next.js > > ```jsx theme={null} > const commentElement = client.getCommentElement(); > commentElement.enableDialogOnTargetElementClick(); > commentElement.disableDialogOnTargetElementClick(); > ``` > [tab] Other Frameworks > > ```jsx theme={null} > const commentElement = Velt.getCommentElement(); > commentElement.enableDialogOnTargetElementClick(); > commentElement.disableDialogOnTargetElementClick(); > ``` #### enablePopoverTriangleComponent Whether the popover triangle appears when Popover Mode is enabled. `Default: true` > [tab] React / Next.js > > ```jsx theme={null} > > ``` > [tab] Other Frameworks > > ```jsx theme={null} > > ``` API Method: > [tab] React / Next.js > > ```jsx theme={null} > const commentElement = client.getCommentElement(); > commentElement.enablePopoverTriangleComponent(); > commentElement.disablePopoverTriangleComponent(); > ``` > [tab] Other Frameworks > > ```jsx theme={null} > const commentElement = Velt.getCommentElement(); > commentElement.enablePopoverTriangleComponent(); > commentElement.disablePopoverTriangleComponent(); > ``` # Comment Bubble #### annotationId * The id of the comment annotation to show the comment bubble on. * The bubble will be rendered only if there is a comment annotation that matches the provided `annotationId` in the current document. > [tab] React / Next.js > > ```jsx theme={null} > > ``` > [tab] Other Frameworks > > ```html theme={null} > > ``` #### targetElementId * The DOM ID of the element where comment bubble is added. * This binds the comment bubble to the element with the provided ID. * The bubble will be rendered only if there is a comment annotation that was added to the element with the provided ID. > [tab] React / Next.js > > ```jsx theme={null} > > ``` > [tab] Other Frameworks > > ```html theme={null} > > ``` #### context * The `context` object to filter which comment annotations to show the comment bubble for. * The bubble will be rendered only if there is a comment annotation that matches the provided `context` in the current document. * Works only with `popover` mode comments. * Perfect for complex tables with filtering and segmentation needs. * Set flexible comment anchoring and filtering logic at the cell level using key-value pairs. * **Supports aggregate views:** Eg: comments added in day view can appear in week/month views automatically. * Context commonly has combined use with [context options](#contextoptions) and the [group matched comments](#groupmatchedcomments) feature. > [tab] React / Next.js > > ```jsx theme={null} > > // Full match > > // Partial match > > ``` > [tab] Other Frameworks > > ```html theme={null} > > > > > > > ``` #### contextOptions * Matching behavior for the context object (default: full match, or set `partialMatch: true` for flexible matching). * **How Partial Match Works:** * A comment will match if ALL provided filter criteria exist in the comment's context * Extra fields in the comment's context don't prevent matching * Missing fields in the comment's context prevent matching * Example: Comment has `{ day: "01", week: "01", month: "jan", product: "cheese", location: "zurich" }` * Filter `{ day: "01", product: "cheese" }` → ✅ matches (both fields exist in comment) * Filter `{ day: "01", category: "dairy" }` → ❌ no match (category doesn't exist in comment) * **Partial Match Examples:** * Comment has `{ day: "01", week: "01", month: "jan", product: "cheese" }` * Filter with `{ day: "01", week: "01", month: "jan", product: "cheese" }` → matches (full) * Filter with `{ week: "01", month: "jan", product: "cheese" }` → matches (partial) * Filter with `{ day: "01", week: "01", month: "jan", product: "cheese", location: "zurich" }` → no match #### groupMatchedComments Whether to group multiple comment annotations in Comment Bubble component when multiple annotations match the provided `context` or `targetElementId`. Default: `false` > [tab] React / Next.js > > **Using Props:** > > ```jsx theme={null} > > ``` > > **Using API:** > > ```jsx theme={null} > const commentElement = client.getCommentElement(); > commentElement.enableGroupMatchedComments(); > commentElement.disableGroupMatchedComments(); > ``` > [tab] Other Frameworks > > **Using Props:** > > ```html theme={null} > > ``` > > **Using API:** > > ```jsx theme={null} > const commentElement = Velt.getCommentElement(); > commentElement.enableGroupMatchedComments(); > commentElement.disableGroupMatchedComments(); > ``` #### commentCountType Whether to show unread or total comment replies count on Comment Bubble Component. Type: [`CommentCountType`](/docs/api-reference/sdk/models/data-models#commentcounttype) * `total`: Shows the total number of replies. (default) * `unread`: Shows the number of unread replies. > [tab] React / Next.js > > ```jsx theme={null} > > ``` > [tab] Other Frameworks > > ```jsx theme={null} > > > ``` #### openDialog Control whether the comment dialog opens when clicking on the comment bubble. When disabled, clicking the bubble will not open the comment dialog. This is useful when you want to handle bubble clicks with custom logic using the [`commentBubbleClicked`](#commentbubbleclicked) event. Default: `true` > [tab] React / Next.js > > ```jsx theme={null} > > ``` > [tab] Other Frameworks > > ```html theme={null} > > ``` #### readOnly The `readOnly` flag prevents users from replying or editing existing comments in the target bubble while still displaying them. This is useful when you want to display comments in a read-only mode where users can view but not modify or respond to comments. Default: `false` > [tab] React / Next.js > > ```jsx theme={null} > > ``` > [tab] Other Frameworks > > ```html theme={null} > > ``` # Video Timeline Comments #### setTotalMediaLength Set the total length of media (in frames or seconds) for the timeline. > [tab] React / Next.js > > **Using Props:** > > ```jsx theme={null} > > ``` > > **Using API Method:** > > ```jsx theme={null} > const commentElement = client.getCommentElement(); > commentElement.setTotalMediaLength(120); > ``` > [tab] Other Frameworks > > **Using Props:** > > ```html theme={null} > > ``` > > **Using API Method:** > > ```jsx theme={null} > const commentElement = Velt.getCommentElement(); > commentElement.setTotalMediaLength(120); > ``` #### offset * Allows comment bubbles to be positioned relative to both parent and child video clips by specifying an offset value. * Default: `0` > [tab] React / Next.js > > ```jsx theme={null} > > ``` > [tab] Other Frameworks > > ```html theme={null} > > ``` # Comment Pin #### enableBubbleOnPin Show a Comment Bubble when user hovers or clicks on the Comment Pin vs showing the Comment Dialog. The comment dialog will open only on clicking the comment bubble. `Default: 'false'` > [tab] React / Next.js with Hooks > > **Using Props:** > > ```jsx theme={null} > > ``` > > **Using API Method:** > > ```jsx theme={null} > const commentElement = useCommentUtils(); > commentElement.enableBubbleOnPin(); > commentElement.disableBubbleOnPin(); > ``` > [tab] React / Next.js > > **Using Props:** > > ```jsx theme={null} > > ``` > > **Using API Method:** > > ```jsx theme={null} > const commentElement = client.getCommentElement(); > commentElement.enableBubbleOnPin(); > commentElement.disableBubbleOnPin(); > ``` > [tab] Other Frameworks > > **Using Props:** > > ```jsx theme={null} > > > ``` > > **Using API Method:** > > ```jsx theme={null} > const commentElement = Velt.getCommentElement(); > commentElement.enableBubbleOnPin(); > commentElement.disableBubbleOnPin(); > ``` #### enableBubbleOnPinHover Show a Comment Bubble when user hovers on the Comment Pin vs clicks on it. `Default: 'true'` > [tab] React / Next.js with Hooks > > **Using Props:** > > ```jsx theme={null} > > ``` > > **Using API Method:** > > ```jsx theme={null} > const commentElement = useCommentUtils(); > > // To enable/disable showing bubble on pin > commentElement.enableBubbleOnPin(); > commentElement.disableBubbleOnPin(); > > // To enable/disable showing bubble on hover > commentElement.enableBubbleOnPinHover(); > commentElement.disableBubbleOnPinHover(); > > ``` > [tab] React / Next.js > > **Using Props:** > > ```jsx theme={null} > > ``` > > **Using API Method:** > > ```jsx theme={null} > const commentElement = client.getCommentElement(); > // To enable/disable showing bubble on pin > commentElement.enableBubbleOnPin(); > commentElement.disableBubbleOnPin(); > > // To enable/disable showing bubble on hover > commentElement.enableBubbleOnPinHover(); > commentElement.disableBubbleOnPinHover(); > ``` > [tab] Other Frameworks > > **Using Props:** > > ```jsx theme={null} > > ``` > > **Using API Method:** > > ```jsx theme={null} > const commentElement = Velt.getCommentElement(); > // To enable/disable showing bubble on pin > commentElement.enableBubbleOnPin(); > commentElement.disableBubbleOnPin(); > > // To enable/disable showing bubble on hover > commentElement.enableBubbleOnPinHover(); > commentElement.disableBubbleOnPinHover(); > > ``` # Legacy Methods #### onCommentAdd > [tab] React / Next.js > > Using Props: > > ```js theme={null} > yourMethod(event)} /> > > const yourMethod = (event) => { > event?.addContext({ customKey: 'customValue' }); > } > ``` > > Using Hooks: > > ```jsx theme={null} > import { useCommentAddHandler } from "@veltdev/react"; > > export default function YourDocument() { > const commentAddEvent = useCommentAddHandler(); > > useEffect(() => { > console.log("commentAddEvent", commentAddEvent); > }, [commentAddEvent]); > > return
; > } > ``` > > Using API: > > ```js theme={null} > const commentElement = client.getCommentElement(); > > commentElement.onCommentAdd().subscribe((event) => { > console.log("commentAddEvent", event); > }); > ``` > [tab] Other Frameworks > > Using Event listener: > > ```js theme={null} > const veltCommentsTag = document.querySelector("velt-comments"); > > veltCommentsTag?.addEventListener("onCommentAdd", (event) => { > console.log("*** onCommentAdd ***"); > console.log(event.detail); > event.detail?.addContext({ customKey: "customValue" }); > }); > ``` > > Using API method: > > ```js theme={null} > const commentElement = Velt.getCommentElement(); > > commentElement.onCommentAdd().subscribe((event) => { > event?.addContext({ customKey: "customValue" }); > }); > ``` **onCommentAdd Event Data Schema** | Field Name | Type | Description | | - | - | - | | addContext | Function | Use this to set custom data on the comment | | annotation | CommentAnnotation | The annotation that is associated with the comment that was updated | | documentId | string | The document ID where the comment was added | | location | Object | The location where the comment was added | | targetAnnotationId | string | The id of the target annotation | #### onCommentUpdate > [tab] React / Next.js > > Using Props: > > ```js theme={null} > yourMethod(event)} />; > > const yourMethod = (event) => { > console.log("commentUpdateEvent", event); > }; > ``` > > Using Hooks: > > ```jsx theme={null} > import { useCommentUpdateHandler } from "@veltdev/react"; > > export default function YourDocument() { > const commentUpdateEvent = useCommentUpdateHandler(); > useEffect(() => { > console.log("commentUpdateEvent", commentUpdateEvent); > }, [commentUpdateEvent]); > > return
; > } > ``` > > Using API: > > ```js theme={null} > const commentElement = client.getCommentElement(); > > commentElement.onCommentUpdate().subscribe((event) => { > console.log("commentUpdateEvent", event); > }); > ``` > [tab] Other Frameworks > > Using Event Listener: > > ```js theme={null} > const veltCommentsTag = document.querySelector('velt-comments'); > > veltCommentsTag?.addEventListener('onCommentUpdate', (event) => { > console.log('**_ onCommentUpdate _**'); > console.log(event.detail); > }); > > ``` > > Using API method: > > ```js theme={null} > const commentElement = Velt.getCommentElement(); > > commentElement.onCommentUpdate().subscribe((event) => { > console.log('commentUpdateEvent', event); > }); > ``` **onCommentUpdate Event Data Schema** | Field Name | Type | Description | | - | - | - | | annotation | CommentAnnotation | The annotation that is associated with the comment that was updated | | type | string | The type of comment that was updated | | targetAnnotationId | string | The ID of the target annotation that contains the comment that was updated | | targetCommentId | number | The ID of the target comment that was updated | | updateContext | Function | Use this to update the custom metadata on the comment annotation. | #### getAllCommentAnnotations * Get all comment annotations for a given document and location. * By default, it will return data for the current `documentId` and `location`. * Params (optional): * `documentId`: string; it will return all comments in the given `documentId`. * `location`: Object; it will return all comments in the given `location`. > [tab] React / Next.js > > **Using Hooks:** > > ```jsx theme={null} > const commentAnnotations = useCommentAnnotations(); > useEffect(() => { > if (commentAnnotations) { > console.log("commentAnnotations", commentAnnotations); > } > }, [commentAnnotations]); > ``` > > **Using API:** > > ```js theme={null} > const commentElement = client.getCommentElement(); > let subscription = commentElement > .getAllCommentAnnotations() > .subscribe((comments) => { > console.log("commentAnnotations", comments); > }); > ``` > > To unsubscribe from the subscription: > > ```jsx theme={null} > subscription?.unsubscribe(); > ``` > [tab] Other Frameworks > > ```js theme={null} > if (Velt) { > const commentElement = Velt.getCommentElement(); > let subscription = commentElement.getAllCommentAnnotations().subscribe((comments) => { > // Do something with comments > }); > } > ``` > > To unsubscribe from the subscription: > > ```jsx theme={null} > subscription?.unsubscribe() > ``` # Notifications Source: https://velt.dev/docs/async-collaboration/comments/notifications There are several options to send notifications to your users. There are three ways to send notifications to your users: > [card] [In-app notifications](#in-app-notifications) > > Add notifications component within your app. > [card] [Email notifications](#email-notifications) > > Send email notifications to your users. > [card] [Webhooks](#webhooks) > > Send notifications to other channels like Slack. Notifications for private comments only go to users who can see the comment, on every channel. [Learn more →](/docs/async-collaboration/notifications/overview#notifications-for-private-comments) ## In-app notifications Add notifications component within your app. Learn more about [In-app notifications](/docs/async-collaboration/notifications/overview). ## Email notifications You can enable email notifications to send out emails whenever you `@mention` a user in the Comments feature or when another user replies to your comment. There are two ways to trigger email notifications: Webhooks and SendGrid. ### Webhooks for non-SendGrid services To learn how to trigger email notifications via Webhooks please refer [here](/docs/webhooks/basic). ### SendGrid Integration To enable Email Notifications, go to the Configurations -> Email Service in the Velt Console, or [click here](https://console.velt.dev/dashboard/config/email). For SendGrid integration, provide the following details: * SendGrid API Key * SendGrid Email Template ID for Comments feature * 'From' Email Address > [!WARNING] > > The 'From' Email Address needs to be whitelisted from your SendGrid account or else it will not work. #### Email Template Data The following fields are sent to Sendgrid: | Field | Type | Description | | - | - | - | | firstComment | [Comment](/docs/api-reference/sdk/models/data-models#comment) | First message in the thread. **Only Contains** `commentId`, `commentText` and `from` properties derived from Comment class. | | latestComment | [Comment](/docs/api-reference/sdk/models/data-models#comment) | Latest message in the thread that prompted the email. **Only Contains** `commentId`, `commentText` and `from` properties derived from Comment class. | | prevComment | [Comment](/docs/api-reference/sdk/models/data-models#comment) | Previous message to the latestMessage. **Only Contains** `commentId`, `commentText` and `from` properties derived from Comment class. | | commentsCount | string | Total number of comments in the comment annotation | | commentsCountMoreThanThree | string | Total number of remaining comments in the comment annotation beyond the three that this payload contains | | fromUser | [User](/docs/api-reference/sdk/models/data-models#user) | Action user's object | | commentAnnotation | [CommentAnnotation](/docs/api-reference/sdk/models/data-models#commentannotation) | The comment annotation object without the `comments` field | | actionType | string | The action that resulted in the notification. You can find the list of action types [here](/docs/webhooks/basic#list-of-action-types) | | documentMetadata | [DocumentMetadata](/docs/api-reference/sdk/models/data-models#documentmetadata) | The document metadata object | These are the older fields that will be deprecated soon. These are already contained in the fields above: | Field | Type | Description | | - | - | - | | message | string | the message of the email | | messageFromName | string | the name of whoever wrote the message that the email is referencing. If name is not found then it will contain the email. | | name | string | the name of the person who performed the action that triggered the email. If name is not found then it will contain the email. Sometimes a notification can be triggered without a message. For those cases, you can use this. | | fromEmail | string | email address of the user who performed the action | | photoUrl | string | avatar URL of user | | pageUrl | string | url of the page the comment is on | | pageTitle | string | title of the web page | | deviceInfo | Object | contains browser, OS and device info | | subject | string | subject of the email | #### Sample Payload sent to SendGrid ```json expandable lines theme={null} { "fromName": "Tony via ", "fromEmail": "noreply@example.com", "replyTo": "tony@example.com", "templateId": "d-60ba77a7a42a4e55803487b40982b499", "toEmail": "jess@example.com", "properties": { "message": "@Jess", "messageFromName": "Tony", "name": "Tony", "fromName": "Tony via ", "fromEmail": "tony@trysnippyly.com", "photoUrl": "PHOTO_URL", "pageUrl": "https://example.com/?scommentId=4Fnt7zTvPv9ggE7OOTVG", "pageTitle": "Example Title", "deviceInfo": {...}, "subject": "added you to a comment on Example Title", "actionType": "newlyAdded", "fromUser": {...}, // User Object "commentAnnotation": {...}, // CommentAnnotation Object "commentsCount": 1, "firstComment": {...}, // Comment Object "prevComment": {...}, // Comment Object "commentsCountMoreThanThree": 0, "latestComment": {...}, // Comment Object "documentMetadata": {...} // DocumentMetadata Object } } ``` #### Download Sample Email Template ![](https://mintcdn.com/velt/kAkMSIYF4ZlrlwLm/images/email-template.png?fit=max\&auto=format\&n=kAkMSIYF4ZlrlwLm\&q=85\&s=caa20104ebe71a81749b642af3ac502e) We have provided this sample HTML email template you can use for your SendGrid email template: [Download Link](https://firebasestorage.googleapis.com/v0/b/snippyly.appspot.com/o/external%2Femail-template.html?alt=media\&token=16a17614-70ca-464c-b6f4-2b2b097b0007) ```html expandable lines theme={null} Email Template
@here testing here functionality
    
``` ## Webhooks Send notifications to other channels like Slack. Learn more about [Webhooks](/docs/webhooks/basic). # Comments Source: https://velt.dev/docs/async-collaboration/comments/overview Your users can add comments in context to ask questions, leave feedback, report bugs etc. We handle all complexity to ensure the comments are robust against content changes. We support many types of comment UX patterns as illustrated below. > [tab] Freestyle > > With `Freestyle` comments, you can pin `Comments` on any elements on the page or draw area comments. > > [Open in larger window](https://demo-examples.vercel.app/async/comments/area-comments?background=000\&theme=dark)     > [View Setup for Freestyle Comments](/docs/async-collaboration/comments/setup/freestyle) > > [https://demo-examples.vercel.app/async/comments/area-comments?background=000\&theme=dark](https://demo-examples.vercel.app/async/comments/area-comments?background=000\&theme=dark) > [tab] Popover > > With `Popover` comments, you can add `Comments` on table cells, like in Google Sheets. > > [Open in larger window](https://demo-examples.vercel.app/async/comments/popover-comments?background=000\&theme=dark)     > [View Setup for Popover Comments](/docs/async-collaboration/comments/setup/popover) > > [https://demo-examples.vercel.app/async/comments/popover-comments?background=000\&theme=dark](https://demo-examples.vercel.app/async/comments/popover-comments?background=000\&theme=dark) > [tab] Stream > > With `Stream` mode, your `Comments` will appear in a column on the right side. > > [Open in larger window](https://demo-examples.vercel.app/async/comments/stream-comments?background=000\&theme=dark)     > [View Setup for Stream Comments](/docs/async-collaboration/comments/setup/stream) > > [https://demo-examples.vercel.app/async/comments/stream-comments?background=000\&theme=dark](https://demo-examples.vercel.app/async/comments/stream-comments?background=000\&theme=dark) > [tab] Text > > With `Text` comments, you can leave `Comments` as text highlights. > > [Open in larger window](https://demo-examples.vercel.app/async/comments/text-comments?background=000\&theme=dark)     > [View Setup for Text Comments](/docs/async-collaboration/comments/setup/text) > > [https://demo-examples.vercel.app/async/comments/text-comments?background=000\&theme=dark](https://demo-examples.vercel.app/async/comments/text-comments?background=000\&theme=dark) > [tab] Tiptap > > Add comments to your Tiptap editor. > > [Open in larger window](https://documentation-app-demo.vercel.app/?focused=true)     > [View Setup for Tiptap Comments](/docs/async-collaboration/comments/setup/tiptap) > > [https://documentation-app-demo.vercel.app/?focused=true](https://documentation-app-demo.vercel.app/?focused=true) > [tab] Inline > > With `Inline` comments, you can add a more traditional style of comments. > > [Open in larger window](https://demo-examples.vercel.app/async/comments/inline-comments?background=000\&theme=dark)     > [View Setup for Inline Comments](/docs/async-collaboration/comments/setup/inline-comments) > > [https://demo-examples.vercel.app/async/comments/inline-comments?background=000\&theme=dark](https://demo-examples.vercel.app/async/comments/inline-comments?background=000\&theme=dark) > [tab] Page > > With `Page` comments, you can leave `Comments` at the page level. > > [Open in larger window](https://demo-examples.vercel.app/async/comments/page-comments?background=000\&theme=dark)     > [View Setup for Page Comments](/docs/async-collaboration/comments/setup/page) > > [https://demo-examples.vercel.app/async/comments/page-comments?background=000\&theme=dark](https://demo-examples.vercel.app/async/comments/page-comments?background=000\&theme=dark) > [tab] Chart > > With `Chart` comments, you can leave `Comments` on popular charting libraries. > > [Open in larger window](https://analytics-chartjs-demo.vercel.app/?focused=true)     > [View Setup for Chart Comments](/docs/async-collaboration/comments/setup/chart-comments-setup/highcharts) > > [https://analytics-chartjs-demo.vercel.app/?focused=true](https://analytics-chartjs-demo.vercel.app/?focused=true) > [tab] Video > > With `Video` comments, you can leave frame by frame `Comments` on videos. > > [Open in larger window](https://demo-examples.vercel.app/async/comments/video-comments?background=000000\&theme=dark)     > [View Setup for Video Comments](/docs/async-collaboration/comments/setup/video-player-setup/video-player-setup) > > [https://demo-examples.vercel.app/async/comments/video-comments?background=000000\&theme=dark](https://demo-examples.vercel.app/async/comments/video-comments?background=000000\&theme=dark) > [tab] Lottie > > With `Lottie` comments, you can leave frame by frame `Comments` on Lottie animations. > > [Open in larger window](https://demo-examples.vercel.app/async/comments/lottie-comments?background=1A1A1A\&theme=dark)     > [View Setup for Lottie Comments](/docs/async-collaboration/comments/setup/lottie-player-setup) > > [https://demo-examples.vercel.app/async/comments/lottie-comments?background=1A1A1A\&theme=dark](https://demo-examples.vercel.app/async/comments/lottie-comments?background=1A1A1A\&theme=dark) There are several customizable components that work as part of the `Comments` feature set. > [tab] Comment Dialog > > ![](https://mintcdn.com/velt/kAkMSIYF4ZlrlwLm/images/customization/velt-comment-dialog-1.png?fit=max\&auto=format\&n=kAkMSIYF4ZlrlwLm\&q=85\&s=317c3dc5977cd95af84575119ffbf3f9) > [tab] Comment Pin > > ![](https://mintcdn.com/velt/kAkMSIYF4ZlrlwLm/images/customization/velt-comment-pin-1.png?fit=max\&auto=format\&n=kAkMSIYF4ZlrlwLm\&q=85\&s=368de01a99459da8605d7acd153480ba) > [tab] Text Comment Tool > > ![](https://mintcdn.com/velt/kAkMSIYF4ZlrlwLm/images/customization/velt-text-comment-1.png?fit=max\&auto=format\&n=kAkMSIYF4ZlrlwLm\&q=85\&s=5bff19c8d18636a33d998a4925322a3f) > [tab] Comment Tool > > ![](https://mintcdn.com/velt/kAkMSIYF4ZlrlwLm/images/customization/velt-comment-tool-1.png?fit=max\&auto=format\&n=kAkMSIYF4ZlrlwLm\&q=85\&s=65ae5eea4040d5ed64947488f24c75c7) # Ace Editor Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/ace ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. * This component is required to render comments in your app. * Set the `text mode` prop to `false` to hide the default text comment tool. > [tab] React / Next.js > > ```js theme={null} > > > > ``` > [tab] Other Frameworks > > ```html theme={null} > > > > ``` #### Step 2: Install the Velt Ace extension ```bash theme={null} npm i @veltdev/ace-velt-comments ``` #### Step 3: Configure the Ace editor with the Velt Comments extension > [tab] React / Next.js > > ```js theme={null} > import { useEffect, useRef, useCallback } from 'react'; > import AceEditor from 'react-ace'; > import 'ace-builds/src-noconflict/mode-markdown'; > import 'ace-builds/src-noconflict/theme-github'; > import { AceVeltComments } from '@veltdev/ace-velt-comments'; > > function AceEditorComponent() { > const editorRef = useRef(null); > const cleanupRef = useRef(null); > > const handleLoad = useCallback((editor) => { > editorRef.current = editor; > // Initialize Velt comments - returns a cleanup function > cleanupRef.current = AceVeltComments(editor); > }, []); > > useEffect(() => { > return () => { > if (cleanupRef.current) { > cleanupRef.current(); > } > }; > }, []); > > return ( > mode="markdown" > theme="github" > name="ace-editor" > defaultValue="Your initial content here" > onLoad={handleLoad} > width="100%" > height="100%" > /> > ); > } > ``` > [tab] Other Frameworks > > ```js theme={null} > import * as ace from 'ace-builds'; > import 'ace-builds/src-noconflict/mode-markdown'; > import 'ace-builds/src-noconflict/theme-github'; > import { AceVeltComments } from '@veltdev/ace-velt-comments'; > > const editor = ace.edit(document.querySelector('#editor')); > editor.setTheme('ace/theme/github'); > editor.session.setMode('ace/mode/markdown'); > editor.setValue('Your initial content here', -1); > > // Initialize Velt comments - returns a cleanup function > const cleanup = AceVeltComments(editor); > > // Call cleanup() when done to remove event listeners > // cleanup(); > ``` #### Step 4: Add a comment button to your Ace editor * Add a button that users can click to add comments after selecting text. > [tab] React / Next.js > > ```js theme={null} > import { addComment } from '@veltdev/ace-velt-comments'; > > // Add this button before in your JSX > > ``` > [tab] Other Frameworks > > ```html theme={null} > > ``` > > ```js theme={null} > import { addComment } from '@veltdev/ace-velt-comments'; > > const addCommentBtn = document.getElementById('add-comment-btn'); > addCommentBtn.addEventListener('mousedown', (e) => e.preventDefault()); > addCommentBtn.addEventListener('click', () => { > addComment({ editor }); > }); > ``` #### Step 5: Call `addComment` to add a comment * Call this method to add a comment to selected text in the Ace editor. You can use this when the user clicks on the comment button or presses a keyboard shortcut. * Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-5). It has the following properties: * `editor`: instance of the Ace Editor. * `editorId`: Id of the Ace editor. Use this if you have multiple Ace editors on the same page in your app. (optional) * `context`: Add any custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional) > [tab] React / Next.js > > ```js theme={null} > import { addComment } from '@veltdev/ace-velt-comments'; > > const addCommentRequest = { > editor: editorRef.current, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > addComment(addCommentRequest); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { addComment } from '@veltdev/ace-velt-comments'; > > const addCommentRequest = { > editor, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > addComment(addCommentRequest); > ``` #### Step 6: Render comments in Ace editor * Get the comment data from Velt SDK and render it in the Ace Editor. * Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-5). It has the following properties: * `editor`: Instance of the Ace Editor. * `editorId`: Id of the Ace editor. Use this if you have multiple Ace editors on the same page in your app. (optional) * `commentAnnotations`: Array of Comment Annotation objects. > [tab] React / Next.js > > ```js theme={null} > import { renderComments } from '@veltdev/ace-velt-comments'; > import { useCommentAnnotations } from '@veltdev/react'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (editorRef.current && annotations?.length) { > const renderCommentsRequest = { > editor: editorRef.current, > editorId: 'EDITOR_ID', > commentAnnotations: annotations, > }; > renderComments(renderCommentsRequest); > } > }, [annotations]); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { renderComments } from '@veltdev/ace-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > if (editor && annotations?.length) { > const renderCommentsRequest = { > editor, > editorId: 'EDITOR_ID', > commentAnnotations: annotations, > }; > renderComments(renderCommentsRequest); > } > }); > ``` #### Step 7: Persist Velt Comment Marks (optional) * By default, Velt comment marks (``) are persisted in the Ace editor by Velt SDK. When the editor loads and the Velt SDK initializes, the marks will be automatically added to the editor. * If you plan to store the contents of the Ace editor on your end with the comment marks already included, you can disable this feature. * Default: `true` ```js theme={null} const cleanup = AceVeltComments(editor, { persistVeltMarks: false, }); ``` #### Step 8: Style the commented text * You can style the commented text by adding CSS for the `velt-comment-text` element. ```css theme={null} velt-comment-text { background-color: rgba(255, 255, 0, 0.3); border-bottom: 2px solid #ffcc00; cursor: pointer; } velt-comment-text:hover { background-color: rgba(255, 255, 0, 0.5); } velt-comment-text.velt-comment-selected { background-color: rgba(255, 255, 0, 0.5); } ``` ## APIs #### [AceVeltComments()](/docs/api-reference/sdk/api/api-methods#aceveltcomments) Initializes the Velt Comments extension for an Ace Editor instance. * Params: `editor: Ace.Editor`, `config?:` [AceVeltCommentsConfig](/docs/api-reference/sdk/models/data-models#aceveltcommentsconfig) * `editorId?: string` - Unique identifier for this editor instance (for multi-editor scenarios) * `persistVeltMarks?: boolean` - Whether to persist Velt marks. Default: `true` * Returns: `() => void` - Cleanup function to remove event listeners > [tab] React / Next.js > > ```tsx theme={null} > import { useRef, useCallback } from 'react'; > import AceEditor from 'react-ace'; > import { AceVeltComments } from '@veltdev/ace-velt-comments'; > > function AceEditorComponent() { > const editorRef = useRef(null); > const cleanupRef = useRef(null); > > const handleLoad = useCallback((editor) => { > editorRef.current = editor; > cleanupRef.current = AceVeltComments(editor, { > editorId: 'my-editor', > persistVeltMarks: true, > }); > }, []); > > return ( > onLoad={handleLoad} > mode="markdown" > theme="github" > name="ace-editor" > /> > ); > } > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import * as ace from 'ace-builds'; > import { AceVeltComments } from '@veltdev/ace-velt-comments'; > > const editor = ace.edit(document.querySelector('#editor')); > > const cleanup = AceVeltComments(editor, { > editorId: 'my-editor', > persistVeltMarks: true, > }); > > // Later, when done: > cleanup(); > ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-5) Creates a comment annotation for the currently selected text in the editor. * Params: * `request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest-5) * `editor: Ace.Editor` * `editorId?: string` * `context?: object` * Returns: `Promise` > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/ace-velt-comments'; > > > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import { addComment } from '@veltdev/ace-velt-comments'; > > addComment({ > editor, > editorId: 'my-editor', > context: { customData: 'value' }, > }); > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-5) Renders and highlights comment annotations in the editor. * Params: * `request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-5) * `editor: Ace.Editor` * `editorId?: string` * `commentAnnotations?:` [CommentAnnotation\[\]](/docs/api-reference/sdk/models/data-models#commentannotation) * Returns: `void` > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { renderComments } from '@veltdev/ace-velt-comments'; > import { useCommentAnnotations } from '@veltdev/react'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (editorRef.current && annotations) { > renderComments({ > editor: editorRef.current, > editorId: 'my-editor', > commentAnnotations: annotations, > }); > } > }, [annotations]); > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import { renderComments } from '@veltdev/ace-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > if (editor && annotations) { > renderComments({ > editor, > editorId: 'my-editor', > commentAnnotations: annotations, > }); > } > }); > ``` # Apryse Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/apryse ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) > [!NOTE] > > The Velt Apryse WebViewer integration is documented for React. This guide covers the React integration only. ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. * This component is required to render comments in your app. * Set the `text mode` prop to `false` to hide the default text comment tool. > [tab] React / Next.js > > ```js theme={null} > > > > ``` #### Step 2: Install the Velt Apryse package ```bash theme={null} npm i @veltdev/apryse-velt-comments ``` `@veltdev/apryse-velt-comments` lists `@pdftron/webviewer` as a **peer dependency** — install it yourself (the package won't bring its own copy, to avoid running two WebViewer runtimes in the same browser): ```bash theme={null} npm i @pdftron/webviewer ``` **Serve Apryse's runtime assets** Apryse's WebViewer isn't just JavaScript — it ships with a **WebAssembly core**, the **Office Editor engine**, and a **UI shell** (HTML/CSS/JS), all under `node_modules/@pdftron/webviewer/public/`. The browser loads these at runtime over **HTTP** from a URL on your site (the `path` option you pass to `WebViewer(...)`), *not* via a JS import. Your bundler won't pick them up on its own, so you need to copy them into your app's static folder so the browser can fetch them. Most teams automate this with a `postinstall` script: ```js theme={null} // scripts/copy-webviewer-assets.mjs import { cpSync, existsSync, mkdirSync, rmSync } from 'node:fs'; import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; const __dirname = dirname(fileURLToPath(import.meta.url)); const root = resolve(__dirname, '..'); const src = resolve(root, 'node_modules/@pdftron/webviewer/public'); const destDir = resolve(root, 'public/lib/webviewer'); if (!existsSync(src)) { console.warn('[copy-webviewer-assets] @pdftron/webviewer not installed yet — skipping.'); process.exit(0); } rmSync(destDir, { recursive: true, force: true }); mkdirSync(destDir, { recursive: true }); for (const folder of ['core', 'ui']) { cpSync(resolve(src, folder), resolve(destDir, folder), { recursive: true }); } ``` Wire it up in `package.json`: ```json theme={null} { "scripts": { "postinstall": "node scripts/copy-webviewer-assets.mjs" } } ``` After install, the assets are at `public/lib/webviewer/core/` (WASM + PDF/Office engines) and `public/lib/webviewer/ui/` (WebViewer UI shell) — which is exactly what the `path: 'lib/webviewer'` option in `WebViewer(...)` (see Step 3) points to. #### Step 3: Create an Apryse WebViewer component with Velt Comments * Attach the extension to the WebViewer instance once it's created. The instance is then the handle that every `addComment` / `renderComments` call uses. * `@pdftron/webviewer` touches the DOM, so import it dynamically (only in the browser) to stay SSR-safe in Next.js, Remix, etc. > [tab] React / Next.js > > ```jsx theme={null} > import { useEffect, useRef, useState } from 'react'; > import { useCommentAnnotations } from '@veltdev/react'; > import { > ApryseVeltComments, > addComment, > renderComments, > } from '@veltdev/apryse-velt-comments'; > > function ApryseEditor() { > const viewerRef = useRef(null); > const instanceRef = useRef(null); > const extensionRef = useRef(null); > const [instance, setInstance] = useState(null); > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (!viewerRef.current || instanceRef.current) return; > let cancelled = false; > > import('@pdftron/webviewer').then(({ default: WebViewer }) => { > if (cancelled) return; > WebViewer( > { > path: 'lib/webviewer', > licenseKey: 'YOUR_APRYSE_LICENSE_KEY', > initialDoc: '/your-document.docx', > initialMode: 'docxEditor', > }, > viewerRef.current, > ).then((webViewerInstance) => { > if (cancelled) return; > instanceRef.current = webViewerInstance; > > // Attach the Velt comments extension to the WebViewer instance. > extensionRef.current = ApryseVeltComments.configure({}).attach( > webViewerInstance, > ); > setInstance(webViewerInstance); > }); > }); > > return () => { > cancelled = true; > extensionRef.current?.detach(); > extensionRef.current = null; > instanceRef.current = null; > setInstance(null); > }; > }, []); > > useEffect(() => { > if (instance && annotations) { > renderComments({ instance, commentAnnotations: annotations }); > } > }, [instance, annotations]); > > return
; > } > ``` #### Step 4: Add a comment button to your WebViewer * Add a button that users can click to add comments after selecting text in the document. * Unlike DOM-based editors, Apryse selections live in the WebViewer's canvas — clicking a button in the host page does **not** clear the selection, so no `onMouseDown` / `preventDefault` dance is needed. Just call `addComment({ instance })`. > [tab] React / Next.js > > ```jsx theme={null} > import { addComment } from '@veltdev/apryse-velt-comments'; > > function AddCommentButton({ instance }) { > const handleAddComment = async () => { > if (!instance) return; > await addComment({ instance }); > }; > > return ; > } > ``` #### Step 5: Call `addComment` to add a comment * Call this method to add a comment to the currently selected text in the WebViewer. You can use this when the user clicks on the comment button or presses a keyboard shortcut. * Params: [`AddCommentArgs`](/docs/api-reference/sdk/models/data-models#addcommentargs). It has the following properties: * `instance`: The Apryse `WebViewerInstance` returned by `WebViewer(...)`. * Returns: [`AddCommentResult`](/docs/api-reference/sdk/models/data-models#addcommentresult) or `null`. Resolves to `null` if no text is selected or the Velt SDK is not yet loaded. On success it returns: * `veltAnnotationId`: The Velt annotation id assigned by the SDK. * `textEditorConfig`: The durable logical anchor stored on the annotation (`{ editorId, text, pageNumber, occurrence }`). > [tab] React / Next.js > > ```js theme={null} > import { addComment } from '@veltdev/apryse-velt-comments'; > > const handleAddComment = async () => { > const result = await addComment({ instance }); > if (!result) { > console.warn('Add comment failed — make sure text is selected.'); > return; > } > console.log('Created annotation:', result.veltAnnotationId); > }; > ``` > [!TIP] > > To scope comments to a specific WebViewer (multi-viewer pages), set the editor id when you attach the extension: `ApryseVeltComments.configure({ editorId: 'EDITOR_ID' }).attach(webViewerInstance)`. `renderComments` will then only paint annotations whose stored `editorId` matches. #### Step 6: Render comments in the WebViewer * Use the `useCommentAnnotations` hook from `@veltdev/react` to get comment data from Velt and render it in the WebViewer. * Params: [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#rendercommentsargs). It has the following properties: * `instance`: The Apryse `WebViewerInstance`. * `commentAnnotations`: Array of Comment Annotation objects from Velt. > [tab] React / Next.js > > ```jsx theme={null} > import { useEffect } from 'react'; > import { renderComments } from '@veltdev/apryse-velt-comments'; > import { useCommentAnnotations } from '@veltdev/react'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (instance && annotations) { > renderComments({ > instance, > commentAnnotations: annotations, > }); > } > }, [instance, annotations]); > ``` > [!TIP] > > The library uses a durable logical anchor (`text` + `occurrence`) per comment — anchors survive document edits, page reflow, and viewer ↔ docxEditor mode switches. Physical positions are re-derived at render time. #### Step 7: Clean up when the component unmounts * `ApryseVeltComments.configure(...).attach(instance)` returns an [`AttachedExtension`](/docs/api-reference/sdk/models/data-models#attachedextension) handle. Call `detach()` from your effect cleanup so every Apryse listener and per-instance cache is released. * If you switch documents inside the same WebViewer (e.g. via `instance.UI.loadDocument(...)`), you do **not** need to detach/re-attach — the extension listens for Apryse's `beforeDocumentLoaded` / `documentLoaded` events and re-syncs the comment highlights automatically. > [tab] React / Next.js > > ```jsx theme={null} > useEffect(() => { > // ...attach as in Step 3... > extensionRef.current = ApryseVeltComments.configure({}).attach(webViewerInstance); > > return () => { > // Removes textSelected / pagesUpdated / documentLoaded / docx-edit > // listeners and clears the per-instance annotation + page-text caches. > extensionRef.current?.detach(); > extensionRef.current = null; > }; > }, []); > ``` #### Step 8: Style the commented text * Comment highlights are rendered as positioned `
` elements inside `` annotation overlays that Apryse manages on each page. * The default styles are set via inline `!important` rules, so to override them target the inner highlight class with a higher-specificity selector or `!important`. ```css theme={null} /* Override the default yellow highlight */ velt-comment-text .velt-apryse-highlight { background-color: rgba(60, 130, 246, 0.30) !important; border-bottom: 2px solid rgba(60, 130, 246, 0.95) !important; } /* Hover state — apply to the host element */ velt-comment-text:hover .velt-apryse-highlight { background-color: rgba(60, 130, 246, 0.50) !important; } ``` > [!NOTE] > > `` lives inside the `` shadow root, so global CSS automatically reaches it (the browser applies host-page styles into open shadow roots for unknown custom elements). ## APIs #### [ApryseVeltComments.configure()](/docs/api-reference/sdk/api/api-methods#apryseveltcomments-configure) Creates the Velt Comments extension for the Apryse WebViewer. It exposes a `configure(...).attach(instance)` pattern — each `.attach()` returns a handle whose `.detach()` undoes everything for that instance. * Params: `config?:` [ApryseVeltCommentsConfig](/docs/api-reference/sdk/models/data-models#apryseveltcommentsconfig) * `editorId?: string` - Unique identifier for this WebViewer instance (for multi-viewer scenarios). Default: `'apryse'`. * Returns: `ApryseVeltComments` (call `.attach(instance)` to wire it to a WebViewer, which returns an [`AttachedExtension`](/docs/api-reference/sdk/models/data-models#attachedextension)) > [tab] React / Next.js > > ```tsx theme={null} > import { ApryseVeltComments } from '@veltdev/apryse-velt-comments'; > > const extension = ApryseVeltComments.configure({ > editorId: 'my-editor', > }).attach(webViewerInstance); > > // later, on unmount: > extension.detach(); > ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-7) Creates a comment annotation for the currently selected text in the WebViewer. * Params: * `request:` [AddCommentArgs](/docs/api-reference/sdk/models/data-models#addcommentargs) * `instance: WebViewerInstance` * Returns: `Promise<`[AddCommentResult](/docs/api-reference/sdk/models/data-models#addcommentresult)` | null>` > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/apryse-velt-comments'; > > > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-7) Renders and highlights comment annotations in the WebViewer. * Params: * `request:` [RenderCommentsArgs](/docs/api-reference/sdk/models/data-models#rendercommentsargs) * `instance: WebViewerInstance` * `commentAnnotations:` [CommentAnnotation\[\]](/docs/api-reference/sdk/models/data-models#commentannotation) * Returns: `void` > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { renderComments } from '@veltdev/apryse-velt-comments'; > import { useCommentAnnotations } from '@veltdev/react'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (instance && annotations) { > renderComments({ > instance, > commentAnnotations: annotations, > }); > } > }, [instance, annotations]); > ``` # Comments Source: https://velt.dev/docs/async-collaboration/comments/setup/canvas Add comments to an HTML Canvas. > [tab] React / Next.js > > ## 1. Import the VeltCommentPin component and the useCommentAnnotations() hook. > > Import the `VeltCommentPin` component and the `useCommentAnnotations()` hook. > > ```jsx theme={null} > import { VeltCommentPin, useCommentAnnotations } from '@veltdev/react'; > ``` > > ## 2. Add custom metadata when comment is added > > Use the `onCommentAdd` method to add custom metadata to a comment when a new comment is being added. > > This metadata can be used later to set the position of the Comment Pin. > You need to set the mandatory `commentType: 'manual'` property to the metadata object. > > ```jsx theme={null} > yourMethod(event)} /> > > const yourMethod = (event) => { > event?.addContext({ customKey: 'customValue', commentType: 'manual' }); > } > > ``` > > ## 3. Retrieve all Comment Annotations > > Retrieve all `Comment Annotations` using the `useCommentAnnotations()` hook. > > To learn more about the `useCommentAnnotations()` hook, [read here](/docs/api-reference/sdk/api/react-hooks#usegetcommentannotations). > > ```jsx theme={null} > let commentAnnotations = useCommentAnnotations() > ``` > > ## 4. Render the Velt Comment Pin component and set the position > > Add the `Velt Comment Pin` component and pass in the `Comment Annotation Id`. > Now retrieve the `context` to retrieve the custom metadata you set earlier and use it to set the position of the `Comment Pin`. > > ```jsx theme={null} > > let commentAnnotations = useCommentAnnotations() > > return ( >
> { > commentAnnotations.map((commentAnnotation) => { > return ( >
position: 'absolute', > left: commentAnnotation.context.position.x + dragPosition.x, > top: commentAnnotation.context.position.y + dragPosition.y, > transform: 'translate(0%, -100%)' > }}> > >
> ) > }) > } >
> ) > ``` > [tab] Other Frameworks > > ## 1. Add custom metadata when comment is added > > Use the `onCommentAdd` method to add custom metadata to a comment when a new comment is being added. > > This metadata can be used later to set the position of the Comment Pin. > You need to set the mandatory `commentType: 'manual'` property to the metadata object. > > ```js theme={null} > const veltCommentsTag = document.querySelector('velt-comments'); > > veltCommentsTag?.addEventListener('onCommentAdd', (event) => { > console.log('*** onCommentAdd ***'); > console.log(event.detail); > event.detail?.addContext({ customKey: 'customValue', commentType: 'manual'}); > }); > > ``` > > ## 2. Retrieve all Comment Annotations > > Retrieve all existing `Comment Annotations` using the `getAllCommentAnnotations()` method. > > To learn more about the `getAllCommentAnnotations` method, [read here](/docs/async-collaboration/comments/customize-behavior#getcommentannotations). > > ```js theme={null} > const commentElement = Velt.getCommentElement(); > let subscription = commentElement.getAllCommentAnnotations().subscribe((commentAnnotations) => { > // console.log(commentAnnotations); > }); > ``` > > To unsubscribe from the subscription: > > ```jsx theme={null} > subscription?.unsubscribe() > ``` > > ## 3. Render the Velt Comment Pin component and set the position > > Add the `Velt Comment Pin` component and pass in the `Comment Annotation Id`. > Now retrieve the `context` to retrieve the custom metadata you set earlier and use it to set the position of the `Comment Pin`. > > ```js theme={null} > const commentElement = Velt.getCommentElement(); > > let subscription = commentElement.getAllCommentAnnotations().subscribe((commentAnnotations) => { > renderCommentAnnotations(commentAnnotations); > }); > > const commentsContainer = document.getElementById('comments-container'); > > function renderCommentAnnotations(commentAnnotations) { > commentAnnotations.forEach((commentAnnotation) => { > if (!document.getElementById(`comment-pin-container-${commentAnnotation.annotationId}`)) { > // Add Comment Pin if it doesn't exist > const { x, y } = commentAnnotation.context.position; > var commentPinContainer = document.createElement('div'); > commentPinContainer.className = 'comment-pin-container'; > commentPinContainer.id = `comment-pin-container-${commentAnnotation.annotationId}`; > commentPinContainer.style.left = x + 'px'; > commentPinContainer.style.top = y + 'px'; > commentPinContainer.innerHTML = ``; > commentsContainer?.appendChild(commentPinContainer); > } > }); > } > > > ``` ```jsx React / Next.js theme={null} import { VeltCommentPin, useCommentAnnotations } from '@veltdev/react'; export default function YourDocument() { const yourMethod = (event) => { event?.addContext({ customKey: 'customValue', commentType: 'manual' }); } let commentAnnotations = useCommentAnnotations() return ( yourMethod(event)} />
{ commentAnnotations.map((commentAnnotation) => { return (
) }) }
) } ``` ```html HTML theme={null} ``` # Overview Source: https://velt.dev/docs/async-collaboration/comments/setup/canvas-comments/overview Within any charts library you have the option to manually set the position of a Comment Annotation using the `Comment Pin` component. ## How to Use Use `Comment Pin` in combination with the following: 1. `onCommentAdd`: Add custom metadata when adding a comment. This metadata can be used later to set the position of the Comment Pin. [Learn more](/docs/async-collaboration/comments/customize-behavior#event-subscription) 2. `getAllCommentAnnotations`: Get all Comment Annotations with the custom metadata you set using above. Render the Comment Pin component and use the custom metadata to set its position yourself. Note for react developers hooks are also available. [Learn more](/docs/async-collaboration/comments/customize-behavior#getcommentannotations) # ChartJS Comments Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/chart-comments-setup/chartjs ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/velt-chartjs-barchart.gif?s=06110c61913bae362b8942fd9d92eac9) > [tab] React / Next.js > > ## 1. Import Components from Chart.js > > ```jsx theme={null} > import { Chart as ChartJS, BarElement } from 'chart.js'; > import { Bar } from 'react-chartjs-2' > ``` > > ## 2. Import Comments Components and Hooks from Velt > > * Add `VeltComments` to the root of your app. This component is required to render comments in your app. > * Add the `VeltCommentTool` component wherever you want to show the comment tool button. Clicking on it initiates comment mode & changes your mouse cursor to a comment pin. > > ![](https://mintcdn.com/velt/2O8vk8YlVD4Kq-ni/images/comment-tool.png?fit=max\&auto=format\&n=2O8vk8YlVD4Kq-ni\&q=85\&s=f6542acc54050b4b607812391c0b97ad) > > ```jsx theme={null} > import { useCommentModeState, VeltCommentPin, VeltCommentTool, VeltComments } from '@veltdev/react'; > ``` > > ## 3. Create a ref for the ChartJS component > > * Create a `ref` and pass it into the `ref` property of the `ChartJS` component. > > ```jsx theme={null} > const chartRef = useRef(null); > > > ``` > > ## 4. Add a container div for the ChartJS component > > 1. Apply `position: relative` style to the div. This ensures accurate positioning of Velt Comment Pins. > > 2. Set `data-velt-manual-comment-container` to `true`. This: > > * informs Velt which div to use for positioning > > * disables Velt's automatic comment positioning system within this div, allowing for manual positioning of comment pins > > 3. Give a unique ID to the chart to scope comments to the specific chart, isolating them from other charts. > > ```jsx theme={null} > const chartId = 'dataAnalyticsChart'; // Unique ID for the chart > ``` > > ```jsx theme={null} > return ( >
onClick={handleChartClick} > data-velt-manual-comment-container="true"> > > >
> ); > ``` > > ## 5. Add a Comment when the user clicks on the chart > > 1. Handle chart click to find nearest data point and add a comment. *(Check `handleChartClick() method` on the right)* > > 2. Create `context` object which contains the information about the series, x-axis value, y-axis value, chartId and anything else that's relevant. This will be used when rendering the comment pin. *(Check `handleChartClick() method` on the right)* > > 3. Add comment with the `context` data. *(Check `addManualComment() method` on the right)* > > * Only add a comment if the Velt `commentModeState` is true and the Velt `client` is available. > > ## 6. Render the Velt Comment Pins and set its position > > 1. Get all comment annotations. > 2. Loop through it and render the comment pin. > 3. Use the `context` data in `CommentAnnotation`, to set the position of the comment pin. *(Check `showCommentPin() method` on the right)* > > ```jsx theme={null} > const commentAnnotations = useCommentAnnotations(); // Get Velt comment annotations > const [chartCommentAnnotations, setChartCommentAnnotations] = React.useState([]); // Store annotations for this chart > > useEffect(() => { > // Filter and store comments for the current chart, using unique chart ID > const chartCommentAnnotations = commentAnnotations?.filter((comment) => comment.context?.chartId === chartId); > setChartCommentAnnotations(chartCommentAnnotations as any || []); > }, [commentAnnotations]); > > return ( > ... {/* Rest of the container code. */} > > {/* Loop through comment annotations and render the comment pin. */} > {chartCommentAnnotations.map((comment, index) => showCommentPin(comment))} > > ... {/* Rest of the container code. */} > ); > ``` > [tab] HTML (coming soon) > > Coming Soon ```js React / Next.js theme={null} import React, { useEffect, useRef, useMemo } from 'react'; import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, BarElement, Title, Tooltip, Legend, Filler,} from 'chart.js'; import { Bar } from 'react-chartjs-2'; import { useVeltClient, useCommentAnnotations, useCommentModeState, VeltCommentPin } from '@veltdev/react'; // Register the necessary Chart.js components ChartJS.register(CategoryScale, LinearScale, PointElement, BarElement, Title, Tooltip, Legend, Filler); // Define the data for the chart const scores = [6, 5, 5, 5, 3, 4, 6, 4, 5]; const labels = [100, 200, 300, 400, 500, 600, 700]; // Set the options for the chart const options: any = { // your chart options }; const BarChart = () => { const chartId = 'dataAnalyticsChart'; // Unique ID for the chart const chartRef = useRef(null); // Reference to the chart instance const { client } = useVeltClient(); // Get Velt client const commentModeState = useCommentModeState(); // Get Velt comment mode state const commentAnnotations = useCommentAnnotations(); // Get Velt comment annotations const [chartCommentAnnotations, setChartCommentAnnotations] = React.useState([]); // State for chart comments // Update chart comments when annotations change useEffect(() => { // Filter comments for the current chart, using unique chart ID const chartCommentAnnotations = commentAnnotations?.filter((comment) => comment.context?.chartId === chartId); setChartCommentAnnotations(chartCommentAnnotations as any || []); }, [commentAnnotations]); // Handle chart clicks to find nearest data point and add a comment const handleChartClick = (event: any) => { const chart: any = chartRef.current; if (chart) { // Get the nearest element to the click event const elements = chart.getElementsAtEventForMode(event.nativeEvent, 'nearest', { intersect: true }, false); if (elements.length > 0) { const element = elements[0]; const datasetIndex = element.datasetIndex; const index = element.index; const dataset = chart.data.datasets[datasetIndex]; const xValue = chart.data.labels[index]; const yValue = dataset.data[index]; const context = { seriesId: dataset.label, xValue, yValue, chartId }; addManualComment(context); // Add a comment at the nearest data point with the context data } } }; // Add a manual comment to the chart const addManualComment = (context: any) => { try { if (client && commentModeState) { const commentElement = client.getCommentElement(); commentElement.addManualComment({ context }); // Add a Velt comment } } catch (error) { console.error('Error adding manual comment', error); } }; // Find the exact point on the chart to place a comment pin const findPoint = (seriesId: any, xValue: any, yValue: any) => { const chart: any = chartRef.current; if (chart) { const dataset = chart.data.datasets.find((dataset: any) => dataset.label === seriesId); const index = chart.data.labels.indexOf(xValue); if (dataset && index !== -1) { const yValueInDataset = dataset.data[index]; if (yValueInDataset === yValue) { return { x: chart.scales.x.getPixelForValue(index), y: chart.scales.y.getPixelForValue(yValue) }; // Set the x, y position for the comment pin } } } return null; }; // Show the comment pin on the chart at the specified point const showCommentPin = (commentAnnotation: any) => { const context = commentAnnotation.context || {}; const point = findPoint(context.seriesId, context.xValue, context.yValue); if (point) { const { x, y } = point; return (
{/* Velt comment pin component */}
); } return null; }; // Memoize the chart data const data = useMemo(() => { return { datasets: [ { label: 'Mis datos', tension: 0.3, data: scores, borderColor: 'rgb(75, 192, 192)', backgroundColor: 'rgba(75, 192, 192, 0.3)', }, ], labels, }; }, []); return (
Bar Chart With Comments
{/* Keep the parent div as relative, as comment pin will be placed with absolute position */} {/* Set "data-velt-manual-comment-container" to true, so that comment pin will know which div to consider while positioning */}
{/* Render the Bar chart */} {chartCommentAnnotations.map((comment, index) => showCommentPin(comment))} {/* Show all comment pins */}
); }; export default BarChart; ``` # Custom Charts Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/chart-comments-setup/custom-charts ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/velt-chartjs-barchart.gif?s=06110c61913bae362b8942fd9d92eac9) > [!NOTE] > > Here we have used ChartJS as an example library, you can follow the approach for any other charting library > [tab] React / Next.js > > ## 1. Import Components from your Charts Library > > ```jsx theme={null} > import { Chart as ChartJS, BarElement } from 'chart.js'; > import { Bar } from 'react-chartjs-2' > ``` > > ## 2. Import Comments Components and Hooks from Velt > > * Add `VeltComments` to the root of your app. This component is required to render comments in your app. > * Add the `VeltCommentTool` component wherever you want to show the comment tool button. Clicking on it initiates comment mode & changes your mouse cursor to a comment pin. > > ![](https://mintcdn.com/velt/2O8vk8YlVD4Kq-ni/images/comment-tool.png?fit=max\&auto=format\&n=2O8vk8YlVD4Kq-ni\&q=85\&s=f6542acc54050b4b607812391c0b97ad) > > ```jsx theme={null} > import { useCommentModeState, VeltCommentPin, VeltCommentTool, VeltComments } from '@veltdev/react'; > ``` > > ## 3. Create a ref for the Chart component > > * Create a `ref` and pass it into the `ref` property of the `ChartJS` component. > > ```jsx theme={null} > const chartRef = useRef(null); > > > ``` > > ## 4. Add a container div for the Chart component > > 1. Apply `position: relative` style to the div. This ensures accurate positioning of Velt Comment Pins. > > 2. Set `data-velt-manual-comment-container` to `true`. This: > > * informs Velt which div to use for positioning > > * disables Velt's automatic comment positioning system within this div, allowing for manual positioning of comment pins > > 3. Give a unique ID to the chart to scope comments to the specific chart, isolating them from other charts. > > ```jsx theme={null} > const chartId = 'dataAnalyticsChart'; // Unique ID for the chart > ``` > > ```jsx theme={null} > return ( >
onClick={handleChartClick} > data-velt-manual-comment-container="true"> > > >
> ); > ``` > > ## 5. Add a Comment when the user clicks on the chart > > 1. Handle chart click to find nearest data point and add a comment. *(Check `handleChartClick() method` on the right)* > > 2. Create `context` object which contains the information about the series, x-axis value, y-axis value, chartId and anything else that's relevant. This will be used when rendering the comment pin. *(Check `handleChartClick() method` on the right)* > > 3. Add comment with the `context` data. *(Check `addManualComment() method` on the right)* > > * Only add a comment if the Velt `commentModeState` is true and the Velt `client` is available. > > ## 6. Render the Velt Comment Pins and set its position > > 1. Get all comment annotations. > 2. Loop through it and render the comment pin. > 3. Use the `context` data in `CommentAnnotation`, to set the position of the comment pin. *(Check `showCommentPin() method` on the right)* > > ```jsx theme={null} > const commentAnnotations = useCommentAnnotations(); // Get Velt comment annotations > const [chartCommentAnnotations, setChartCommentAnnotations] = React.useState([]); // Store annotations for this chart > > useEffect(() => { > // Filter and store comments for the current chart, using unique chart ID > const chartCommentAnnotations = commentAnnotations?.filter((comment) => comment.context?.chartId === chartId); > setChartCommentAnnotations(chartCommentAnnotations as any || []); > }, [commentAnnotations]); > > return ( > ... {/* Rest of the container code. */} > > {/* Loop through comment annotations and render the comment pin. */} > {chartCommentAnnotations.map((comment, index) => showCommentPin(comment))} > > ... {/* Rest of the container code. */} > ); > ``` > [tab] HTML (coming soon) > > Coming Soon ```js React / Next.js theme={null} import React, { useEffect, useRef, useMemo } from 'react'; import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, BarElement, Title, Tooltip, Legend, Filler,} from 'chart.js'; import { Bar } from 'react-chartjs-2'; import { useVeltClient, useCommentAnnotations, useCommentModeState, VeltCommentPin } from '@veltdev/react'; // Register the necessary Chart.js components ChartJS.register(CategoryScale, LinearScale, PointElement, BarElement, Title, Tooltip, Legend, Filler); // Define the data for the chart const scores = [6, 5, 5, 5, 3, 4, 6, 4, 5]; const labels = [100, 200, 300, 400, 500, 600, 700]; // Set the options for the chart const options: any = { // your chart options }; const BarChart = () => { const chartId = 'dataAnalyticsChart'; // Unique ID for the chart const chartRef = useRef(null); // Reference to the chart instance const { client } = useVeltClient(); // Get Velt client const commentModeState = useCommentModeState(); // Get Velt comment mode state const commentAnnotations = useCommentAnnotations(); // Get Velt comment annotations const [chartCommentAnnotations, setChartCommentAnnotations] = React.useState([]); // State for chart comments // Update chart comments when annotations change useEffect(() => { // Filter comments for the current chart, using unique chart ID const chartCommentAnnotations = commentAnnotations?.filter((comment) => comment.context?.chartId === chartId); setChartCommentAnnotations(chartCommentAnnotations as any || []); }, [commentAnnotations]); // Handle chart clicks to find nearest data point and add a comment const handleChartClick = (event: any) => { const chart: any = chartRef.current; if (chart) { // Get the nearest element to the click event const elements = chart.getElementsAtEventForMode(event.nativeEvent, 'nearest', { intersect: true }, false); if (elements.length > 0) { const element = elements[0]; const datasetIndex = element.datasetIndex; const index = element.index; const dataset = chart.data.datasets[datasetIndex]; const xValue = chart.data.labels[index]; const yValue = dataset.data[index]; const context = { seriesId: dataset.label, xValue, yValue, chartId }; addManualComment(context); // Add a comment at the nearest data point with the context data } } }; // Add a manual comment to the chart const addManualComment = (context: any) => { try { if (client && commentModeState) { const commentElement = client.getCommentElement(); commentElement.addManualComment({ context }); // Add a Velt comment } } catch (error) { console.error('Error adding manual comment', error); } }; // Find the exact point on the chart to place a comment pin const findPoint = (seriesId: any, xValue: any, yValue: any) => { const chart: any = chartRef.current; if (chart) { const dataset = chart.data.datasets.find((dataset: any) => dataset.label === seriesId); const index = chart.data.labels.indexOf(xValue); if (dataset && index !== -1) { const yValueInDataset = dataset.data[index]; if (yValueInDataset === yValue) { return { x: chart.scales.x.getPixelForValue(index), y: chart.scales.y.getPixelForValue(yValue) }; // Set the x, y position for the comment pin } } } return null; }; // Show the comment pin on the chart at the specified point const showCommentPin = (commentAnnotation: any) => { const context = commentAnnotation.context || {}; const point = findPoint(context.seriesId, context.xValue, context.yValue); if (point) { const { x, y } = point; return (
{/* Velt comment pin component */}
); } return null; }; // Memoize the chart data const data = useMemo(() => { return { datasets: [ { label: 'Mis datos', tension: 0.3, data: scores, borderColor: 'rgb(75, 192, 192)', backgroundColor: 'rgba(75, 192, 192, 0.3)', }, ], labels, }; }, []); return (
Bar Chart With Comments
{/* Keep the parent div as relative, as comment pin will be placed with absolute position */} {/* Set "data-velt-manual-comment-container" to true, so that comment pin will know which div to consider while positioning */}
{/* Render the Bar chart */} {chartCommentAnnotations.map((comment, index) => showCommentPin(comment))} {/* Show all comment pins */}
); }; export default BarChart; ``` # Highcharts Comments Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/chart-comments-setup/highcharts ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Charts-Comments.gif?s=fd119fbdf4018e3fd93fe06a4fb88f67) > [tab] React / Next.js > > ## 1. Import components from Highcharts > > ```jsx theme={null} > import Highcharts from 'highcharts'; > import HighchartsReact from 'highcharts-react-official'; > ``` > > ## 2. Import Comment components from Velt > > * Add `VeltComments` once to the root of your app. This component is required to render comments in your app. > > ```jsx theme={null} > import { VeltHighChartComments, VeltComments } from '@veltdev/react'; > ``` > > ## 3. Create a ref for the HighchartsReact component > > * Create a `ref` and pass it into the `ref` property of the `HighchartsReact` component. > * This ref object will be used by Velt to get the Chart data and add comment pin to it. > > ```jsx theme={null} > const chartComponentRef = useRef(null); > > highcharts={Highcharts} > options={options} > ref={chartComponentRef} > /> > ``` > > ## 4. Add a container div for the HighchartsReact component > > * Give it a `position: relative` style. This will help position the Velt Comment Pins accurately. > > ```jsx theme={null} >
> highcharts={Highcharts} > options={options} > ref={chartComponentRef} > /> >
> ``` > > ## 5. Add VeltHighChartComments component in the same container > > * Conditionally render `VeltHighChartsComments` in the same container div as the `HighchartsReact` component. > * Set a unique `id` in the VeltHighChartsComments component to scope comments to the specific chart, isolating them from other charts. > * Pass the `chartComputedData` prop with the `ref` you created earlier. > > ```jsx theme={null} >
> highcharts={Highcharts} > options={options} > ref={chartComponentRef} > /> > { > chartComponentRef.current && > } >
> ``` > > ## 6. (Optional) Customize the Chart Metadata displayed in the Comment Dialog > > * Pass an array to the `dialogMetadataTemplate` prop in the VeltHighChartsComments component. > * This array determines the chart metadata displayed in the comment dialog, representing the data point (e.g., x-axis and y-axis values) on which the comment was added. > * Customize the order of the keys or remove unnecessary keys to control how the metadata is presented in the comment dialog. > > `Default: ['groupId', 'label', 'value']` > > For example: > > ```jsx theme={null} > id="HighChartsLineChartExample" > chartComputedData={chartComputedData} > dialogMetadataTemplate={['label', 'value', 'groupId']} /> > ``` > [tab] HTML (coming soon) > > Coming Soon ```js React / Next.js theme={null} import React, { useEffect, useRef, useState } from 'react'; import { VeltHighChartComments } from '@veltdev/react'; import Highcharts from 'highcharts'; import HighchartsReact from 'highcharts-react-official'; function HighChartsLineChartExample() { const [data, setData] = useState(CHART_DATA); const chartComponentRef = useRef(null); const options = { // your chart options }; return (
{ chartComponentRef.current && }
); } ``` # NivoCharts Comments Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/chart-comments-setup/nivo-charts ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Charts-Comments.gif?s=fd119fbdf4018e3fd93fe06a4fb88f67) > [tab] React / Next.js > > ## 1. Import components from Nivo Charts > > ```jsx theme={null} > import { ResponsiveLine } from '@nivo/line'; > ``` > > ## 2. Import VeltNivoChartComments component from Velt > > * Add `VeltComments` once to the root of your app. This component is required to render comments in your app. > > ```jsx theme={null} > import { VeltNivoChartComments, VeltComments } from '@veltdev/react'; > ``` > > ## 3. Add a container div for the Nivo Chart component > > * Add a `nivo-chart-container` class to it. This will help us position the Velt Comment Pins accurately. > > ```jsx theme={null} >
> data={data} > layers={[ > 'grid', 'markers', 'axes', 'areas', 'crosshair', > 'lines', 'slices', 'legends', 'points', > ]} > /> >
> ``` > > ## 4. Add VeltNivoChartComments to the Nivo Chart component > > * Add a custom function as a layer inside your Nivo Chart component and return `VeltNivoChartComments` component. > * Set a unique `id` in the VeltNivoChartComments component to scope comments to the specific chart, isolating them from other charts. > * Pass the `chartComputedData` props to it. > > ```jsx theme={null} > data={data} > layers={[ > 'grid', 'markers', 'axes', 'areas', 'crosshair', > 'lines', 'slices', 'legends', 'points', > // Add this function with VeltNivoChartComments > // component to allow Velt comments inside the Chart > (chartComputedData) => { > return ( > > ) > } > ]} > /> > ``` > > ## 5. (Optional) Customize the Chart Metadata displayed in the Comment Dialog > > * Pass an array to the `dialogMetadataTemplate` prop in the VeltHighChartsComments component. > * This array determines the chart metadata displayed in the comment dialog, representing the data point (e.g., x-axis and y-axis values) on which the comment was added. > * Customize the order of the keys or remove unnecessary keys to control how the metadata is presented in the comment dialog. > > `Default: ['groupId', 'label', 'value']` > > For example: > > ```jsx theme={null} > id="NivoLineChartExample" > chartComputedData={chartComputedData} > dialogMetadataTemplate={['label', 'value', 'groupId']} /> > ``` > [tab] HTML (coming soon) > > Coming Soon ```js React / Next.js theme={null} import { ResponsiveLine } from '@nivo/line'; import { VeltNivoChartComments } from '@veltdev/react'; import { useState } from 'react' function YourComponent() { const [data, setData] = useState(CHART_DATA); return ( // add nivo-chart-container class to the parent element of your NivoChart
{ return ( ) } ]} />
) } ``` # CKEditor Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/ckeditor Add Velt comments to a CKEditor 5 editor with the Velt CKEditor comments plugin. ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. * This component is required to render comments in your app. * Set the `text mode` prop to `false` to hide the default text comment tool. * CKEditor selections are handled by `@veltdev/ckeditor-velt-comments`. * Authenticate the user with `authProvider` and set the Velt document before users add comments. * Add `VeltCommentsSidebar` if you want a Google Docs-style comment sidebar. > [tab] React / Next.js > > ```tsx theme={null} > import { VeltComments, VeltCommentsSidebar, VeltProvider, useSetDocument } from '@veltdev/react'; > > const user = { > userId: 'user-1', > organizationId: 'org-1', > name: 'User One', > email: 'user@example.com', > }; > > function VeltSetup() { > useSetDocument('document-id', { documentName: 'Document name' }); > return null; > } > > function App() { > return ( > > > > > {/* Your app content */} > > ); > } > ``` #### Step 2: Install the Velt CKEditor extension ```bash theme={null} npm i @veltdev/ckeditor-velt-comments @ckeditor/ckeditor5-react ckeditor5 ``` `ckeditor5` is a peer dependency of the Velt CKEditor package and must be provided by your app. Import the CKEditor CSS once in your app so the editor and the Velt overlay render correctly. > [tab] React / Next.js > > ```tsx theme={null} > import 'ckeditor5/ckeditor5.css'; > ``` #### Step 3: Configure the CKEditor editor with the Velt Comments plugin Add `VeltCommentsPlugin` to the CKEditor `plugins` list and configure it with `veltComments`. Capture the editor instance from `onReady`, then render Velt comment annotations into that instance with `renderComments`. > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect, useState } from 'react'; > import { CKEditor } from '@ckeditor/ckeditor5-react'; > import { > ClassicEditor, > Essentials, > Paragraph, > Heading, > Bold, > Italic, > Link, > List, > BlockQuote, > type Editor, > } from 'ckeditor5'; > import { useCommentAnnotations } from '@veltdev/react'; > import { > VeltCommentsPlugin, > renderComments, > } from '@veltdev/ckeditor-velt-comments'; > import 'ckeditor5/ckeditor5.css'; > > const EDITOR_ID = 'my-editor'; > > function CKEditorWithComments() { > const [editor, setEditor] = useState(null); > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (!editor) return; > > renderComments({ > editor, > editorId: EDITOR_ID, > commentAnnotations: annotations ?? [], > }); > }, [editor, annotations]); > > return ( > editor={ClassicEditor} > config={{ > licenseKey: 'GPL', > plugins: [ > Essentials, > Paragraph, > Heading, > Bold, > Italic, > Link, > List, > BlockQuote, > VeltCommentsPlugin, > ], > toolbar: [ > 'undo', > 'redo', > '|', > 'heading', > '|', > 'bold', > 'italic', > 'link', > '|', > 'bulletedList', > 'numberedList', > '|', > 'blockQuote', > ], > initialData: '

Select text, then add a comment.

', > veltComments: { editorId: EDITOR_ID }, > }} > onReady={(nextEditor) => setEditor(nextEditor)} > onAfterDestroy={() => setEditor(null)} > /> > ); > } > ``` #### Step 4: Add a comment button to your CKEditor editor Add a button that users can click to add comments after selecting text in the CKEditor editor. **Important:** Use `onMouseDown` with `preventDefault()` so the browser does not move focus away from the editor before `addComment` reads the current selection. Keep the actual `addComment` call in `onClick`. > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/ckeditor-velt-comments'; > > const handleAddComment = () => { > if (!editor) return; > > void addComment({ > editor, > editorId: EDITOR_ID, > }); > }; > > > ``` #### Step 5: Call `addComment` to add a comment * Call this method to add a comment to selected text in the CKEditor editor. * Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#ckeditor-addcommentrequest). It has the following properties: * `editor`: CKEditor 5 `Editor` instance from `onReady`. * `editorId`: Id of the editor. Use this if you have multiple CKEditor editors on the same page. (optional) * `context`: [`CommentAnnotationContext`](/docs/api-reference/sdk/models/data-models#ckeditor-commentannotationcontext) for custom metadata to attach to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional) * Returns: `Promise`. > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/ckeditor-velt-comments'; > > const addCommentRequest = { > editor, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > void addComment(addCommentRequest); > ``` The library automatically writes `context.textEditorConfig` with the selected text, its occurrence index in the document, and the editor ID when one is provided. #### Step 6: Render comments in CKEditor editor * Get the comment data from Velt SDK and render it in the CKEditor editor. * Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#ckeditor-rendercommentsrequest). It has the following properties: * `editor`: CKEditor 5 `Editor` instance. * `editorId`: Id of the editor. Use this if you have multiple CKEditor editors on the same page. (optional) * `commentAnnotations`: Array of [`CommentAnnotation`](/docs/api-reference/sdk/models/data-models#commentannotation) objects. * Returns: `void`. > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { useCommentAnnotations } from '@veltdev/react'; > import { renderComments } from '@veltdev/ckeditor-velt-comments'; > > const commentAnnotations = useCommentAnnotations(); > > useEffect(() => { > if (!editor) return; > > renderComments({ > editor, > editorId: 'EDITOR_ID', > commentAnnotations: commentAnnotations ?? [], > }); > }, [editor, commentAnnotations]); > ``` #### Step 7: Re-apply highlights after reloading content Comment highlights are view-only overlay elements positioned over the commented text. They are not stored in the CKEditor document, so your saved HTML, schema, and undo history stay clean. Highlight positions are tracked with CKEditor model ranges and re-positioned as the document changes. Call `renderComments` whenever the editor is recreated or its content is replaced. The `useEffect` in Step 6 handles this automatically when the `editor` instance or the annotation list changes. #### Step 8: Style the commented text * Comment highlights are rendered as `velt-comment-text` overlay markers. * You can override the marker styles in your app CSS. ```css theme={null} velt-comment-text { background-color: rgba(255, 212, 0, 0.4); border-bottom: 2px solid #ffd400; cursor: pointer; } velt-comment-text:hover, velt-comment-text[comment-selected="true"], velt-comment-text.velt-comment-selected { background-color: rgba(255, 212, 0, 0.7); } ``` ## Complete Example [https://sample-apps-ckeditor-comments-demo.vercel.app/](https://sample-apps-ckeditor-comments-demo.vercel.app/) ## APIs #### [VeltCommentsPlugin](/docs/api-reference/sdk/api/api-methods#ckeditor-veltcommentsplugin) The CKEditor 5 plugin that powers Velt comments. Add it to the `` component's `config.plugins` list and configure it with `config.veltComments`. * Config: [`VeltCommentsPluginConfig`](/docs/api-reference/sdk/models/data-models#ckeditor-veltcommentspluginconfig) * Returns: CKEditor plugin class > [tab] React / Next.js > > ```tsx theme={null} > import { VeltCommentsPlugin } from '@veltdev/ckeditor-velt-comments'; > > editor={ClassicEditor} > config={{ > plugins: [Essentials, Paragraph, VeltCommentsPlugin], > veltComments: { editorId: 'my-editor' }, > }} > /> > ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#ckeditor-addcomment) Creates a comment annotation for the currently selected text in CKEditor. * Signature: `async (request:` [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#ckeditor-addcommentrequest)`) => Promise` * Params: `request:` [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#ckeditor-addcommentrequest) * Returns: `Promise` > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/ckeditor-velt-comments'; > > void addComment({ > editor, > editorId: 'my-editor', > }); > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#ckeditor-rendercomments) Resolves and highlights Velt comment annotations in CKEditor. * Signature: `(request:` [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#ckeditor-rendercommentsrequest)`) => void` * Params: `request:` [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#ckeditor-rendercommentsrequest) * Returns: `void` > [tab] React / Next.js > > ```tsx theme={null} > import { renderComments } from '@veltdev/ckeditor-velt-comments'; > > renderComments({ > editor, > editorId: 'my-editor', > commentAnnotations: annotations ?? [], > }); > ``` # CodeMirror Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/codemirror ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. * This component is required to render comments in your app. * Set the `text mode` prop to `false` to hide the default text comment tool. > [tab] React / Next.js > > ```js theme={null} > > > > ``` > [tab] Other Frameworks > > ```html theme={null} > > > > ``` #### Step 2: Install the Velt CodeMirror extension ```bash theme={null} npm i @veltdev/codemirror-velt-comments ``` #### Step 3: Configure the CodeMirror editor with the Velt Comments extension > [tab] React / Next.js > > ```js theme={null} > import { EditorView, basicSetup } from 'codemirror'; > import { CodemirrorVeltComments } from '@veltdev/codemirror-velt-comments'; > > const view = new EditorView({ > doc: 'Your initial content here', > extensions: [ > basicSetup, > CodemirrorVeltComments(), > // ... other extensions > ], > parent: editorRef.current, > }); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { EditorView, basicSetup } from 'codemirror'; > import { CodemirrorVeltComments } from '@veltdev/codemirror-velt-comments'; > > const editorView = new EditorView({ > doc: 'Your initial content here', > extensions: [ > basicSetup, > CodemirrorVeltComments(), > // ... other extensions > ], > parent: document.querySelector('#editor'), > }); > ``` #### Step 4: Add a comment button to your CodeMirror editor Add a button that users can click to add comments after selecting text. **Important:** When clicking a button, the browser moves focus to the button which clears the editor selection. You need to save the selection on `mousedown` (before focus changes) and restore it before adding the comment. > [tab] React / Next.js > > ```js theme={null} > import { useRef, useState, useEffect } from 'react'; > import { EditorView, basicSetup } from 'codemirror'; > import { CodemirrorVeltComments, addComment } from '@veltdev/codemirror-velt-comments'; > > function CodeMirrorEditor() { > const editorRef = useRef(null); > const [editorView, setEditorView] = useState(null); > const savedSelectionRef = useRef(null); > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (!editorRef.current) return; > > const view = new EditorView({ > doc: 'Your initial content here', > extensions: [ > basicSetup, > CodemirrorVeltComments(), > ], > parent: editorRef.current, > }); > > setEditorView(view); > return () => view.destroy(); > }, []); > > const saveSelection = () => { > if (editorView) { > const { from, to } = editorView.state.selection.main; > if (from !== to) { > savedSelectionRef.current = { from, to }; > } > } > }; > > const handleAddComment = () => { > if (editorView) { > if (savedSelectionRef.current) { > const { from, to } = savedSelectionRef.current; > if (from !== to) { > editorView.dispatch({ > selection: { anchor: from, head: to } > }); > } > } > addComment({ editor: editorView }); > savedSelectionRef.current = null; > } > }; > > return ( >
> >
>
> ); > } > ``` > [tab] Other Frameworks > > ```html theme={null} > > >
> ``` > > ```js theme={null} > import { EditorView, basicSetup } from 'codemirror'; > import { CodemirrorVeltComments, addComment } from '@veltdev/codemirror-velt-comments'; > > const editorView = new EditorView({ > doc: 'Your initial content here', > extensions: [ > basicSetup, > CodemirrorVeltComments(), > ], > parent: document.querySelector('#editor'), > }); > > let savedSelection = null; > > const saveSelection = () => { > if (editorView) { > const { from, to } = editorView.state.selection.main; > if (from !== to) { > savedSelection = { from, to }; > } > } > }; > > const addCommentToEditor = () => { > if (editorView) { > if (savedSelection && savedSelection.from !== savedSelection.to) { > editorView.dispatch({ > selection: { anchor: savedSelection.from, head: savedSelection.to } > }); > } > addComment({ editor: editorView }); > savedSelection = null; > } > }; > > const addCommentBtn = document.getElementById('add-comment-btn'); > addCommentBtn.addEventListener('mousedown', (e) => { > e.preventDefault(); > saveSelection(); > }); > addCommentBtn.addEventListener('click', addCommentToEditor); > ``` #### Step 5: Call `addComment` to add a comment * Call this method to add a comment to selected text in the CodeMirror editor. You can use this when the user clicks on the comment button or presses a keyboard shortcut. * Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-4). It has the following properties: * `editor`: instance of the CodeMirror EditorView. * `editorId`: Id of the CodeMirror editor. Use this if you have multiple CodeMirror editors on the same page in your app. (optional) * `context`: Add any custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional) > [tab] React / Next.js > > ```js theme={null} > import { addComment } from '@veltdev/codemirror-velt-comments'; > > const addCommentRequest = { > editor: editorView, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > addComment(addCommentRequest); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { addComment } from '@veltdev/codemirror-velt-comments'; > > const addCommentRequest = { > editor: editorView, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > addComment(addCommentRequest); > ``` #### Step 6: Render comments in CodeMirror editor * Get the comment data from Velt SDK and render it in the CodeMirror editor. * Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-4). It has the following properties: * `editor`: Instance of the CodeMirror EditorView. * `editorId`: Id of the CodeMirror editor. Use this if you have multiple CodeMirror editors on the same page in your app. (optional) * `commentAnnotations`: Array of Comment Annotation objects. > [tab] React / Next.js > > ```js theme={null} > import { renderComments } from '@veltdev/codemirror-velt-comments'; > import { useCommentAnnotations } from '@veltdev/react'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (editorView && annotations?.length) { > const renderCommentsRequest = { > editor: editorView, > editorId: 'EDITOR_ID', > commentAnnotations: annotations, > }; > renderComments(renderCommentsRequest); > } > }, [editorView, annotations]); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { renderComments } from '@veltdev/codemirror-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > if (editorView && annotations?.length) { > const renderCommentsRequest = { > editor: editorView, > editorId: 'EDITOR_ID', > commentAnnotations: annotations, > }; > renderComments(renderCommentsRequest); > } > }); > ``` #### Step 7: Persist Velt Comment Marks (optional) * By default, Velt comment marks (``) are persisted in the CodeMirror editor by Velt SDK. When the editor loads and the Velt SDK initializes, the marks will be automatically added to the editor. * If you plan to store the contents of the CodeMirror editor on your end with the comment marks already included, you can disable this feature. * Default: `true` ```js theme={null} const editorView = new EditorView({ extensions: [ CodemirrorVeltComments({ persistVeltMarks: false, }), // ... other extensions ], parent: editorRef.current, }); ``` #### Step 8: Style the commented text * You can style the commented text by adding CSS for the `velt-comment-text` element. ```css theme={null} velt-comment-text { background-color: rgba(255, 255, 0, 0.3); border-bottom: 2px solid #ffcc00; cursor: pointer; } velt-comment-text:hover { background-color: rgba(255, 255, 0, 0.5); } velt-comment-text.velt-comment-selected { background-color: rgba(255, 255, 0, 0.5); } ``` ## APIs #### [CodemirrorVeltComments()](/docs/api-reference/sdk/api/api-methods#codemirrorveltcomments) Creates the Velt Comments extension for CodeMirror. * Params: `config?:` [CodemirrorVeltCommentsConfig](/docs/api-reference/sdk/models/data-models#codemirrorveltcommentsconfig) * `editorId?: string` - Unique identifier for this editor instance (for multi-editor scenarios) * `persistVeltMarks?: boolean` - Whether to persist Velt marks. Default: `true` * Returns: CodeMirror `Extension` > [tab] React / Next.js > > ```tsx theme={null} > import { EditorView } from 'codemirror'; > import { CodemirrorVeltComments } from '@veltdev/codemirror-velt-comments'; > > const view = new EditorView({ > extensions: [ > CodemirrorVeltComments({ > editorId: 'my-editor', > persistVeltMarks: true, > }), > ], > parent: editorRef.current, > }); > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import { EditorView } from 'codemirror'; > import { CodemirrorVeltComments } from '@veltdev/codemirror-velt-comments'; > > const editorView = new EditorView({ > extensions: [ > CodemirrorVeltComments({ > editorId: 'my-editor', > persistVeltMarks: true, > }), > ], > parent: document.body, > }); > ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-4) Creates a comment annotation for the currently selected text in the editor. * Params: * `request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest-4) * `editor: EditorView` * `editorId?: string` * `context?: object` * Returns: `Promise` > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/codemirror-velt-comments'; > > > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import { addComment } from '@veltdev/codemirror-velt-comments'; > > addComment({ > editor: editorView, > editorId: 'my-editor', > context: { customData: 'value' }, > }); > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-4) Renders and highlights comment annotations in the editor. * Params: * `request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-4) * `editor: EditorView` * `editorId?: string` * `commentAnnotations?:` [CommentAnnotation\[\]](/docs/api-reference/sdk/models/data-models#commentannotation) * Returns: `void` > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { renderComments } from '@veltdev/codemirror-velt-comments'; > import { useCommentAnnotations } from '@veltdev/react'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (editorView && annotations) { > renderComments({ > editor: editorView, > editorId: 'my-editor', > commentAnnotations: annotations, > }); > } > }, [editorView, annotations]); > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import { renderComments } from '@veltdev/codemirror-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > if (editorView && annotations) { > renderComments({ > editor: editorView, > editorId: 'my-editor', > commentAnnotations: annotations, > }); > } > }); > ``` # DraftJS Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/draftjs ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. * This component is required to render comments in your app. * Set the `text mode` prop to `false` to hide the default text comment tool. > [tab] React / Next.js > > ```js theme={null} > > > > ``` #### Step 2: Install the Velt DraftJS extension ```bash theme={null} npm i @veltdev/draftjs-velt-comments draft-js ``` #### Step 3: Configure the DraftJS editor with the Velt Comments extension Use `DraftJSVeltEditor` instead of the standard DraftJS `Editor`. This wrapper component handles the DraftJS decorator setup, content change detection, and annotation tracking. > [tab] React / Next.js > > ```js theme={null} > import { useState } from 'react'; > import { EditorState } from 'draft-js'; > import { DraftJSVeltEditor } from '@veltdev/draftjs-velt-comments'; > > function DraftJSEditor() { > const [editorState, setEditorState] = useState(() => > EditorState.createEmpty() > ); > > return ( > editorState={editorState} > onChange={setEditorState} > placeholder="Start typing..." > /> > ); > } > ``` #### Step 4: Add a comment button to your DraftJS editor * Add a button that users can click after selecting text in the DraftJS editor. * Use `onMouseDown` with `preventDefault()` so the browser does not move focus away from the editor and clear the current text selection. > [tab] React / Next.js > > ```js theme={null} > import { useCallback, useEffect, useRef, useState } from 'react'; > import { EditorState } from 'draft-js'; > import { > DraftJSVeltEditor, > addComment, > } from '@veltdev/draftjs-velt-comments'; > > function DraftJSEditor() { > const [editorState, setEditorState] = useState(() => > EditorState.createEmpty() > ); > > const editorRef = useRef({ editorState, setEditorState }); > > useEffect(() => { > editorRef.current = { editorState, setEditorState }; > }, [editorState]); > > const handleAddComment = useCallback(() => { > addComment({ editor: editorRef.current }); > }, []); > > return ( >
> > > editorState={editorState} > onChange={setEditorState} > placeholder="Start typing..." > /> >
> ); > } > ``` #### Step 5: Call `addComment` to add a comment * Call this method to add a comment to selected text in the DraftJS editor. * Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-7) * `editor`: DraftJS editor wrapper object with `{ editorState, setEditorState }`. * `editorId`: Id of the editor. Use this if you have multiple DraftJS editors on the same page. (optional) * `context`: Add custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional) > [tab] React / Next.js > > ```js theme={null} > import { addComment } from '@veltdev/draftjs-velt-comments'; > > const addCommentRequest = { > editor, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > addComment(addCommentRequest); > ``` #### Step 6: Render comments in DraftJS editor * Get comment data from Velt SDK and render it in the DraftJS editor. * Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-7) * `editor`: DraftJS editor wrapper object with `{ editorState, setEditorState }`. * `editorId`: Id of the editor. Use this if you have multiple DraftJS editors on the same page. (optional) * `commentAnnotations`: Array of Comment Annotation objects. > [tab] React / Next.js > > ```js theme={null} > import { useEffect, useRef, useState } from 'react'; > import { EditorState } from 'draft-js'; > import { useCommentAnnotations } from '@veltdev/react'; > import { > DraftJSVeltEditor, > renderComments, > } from '@veltdev/draftjs-velt-comments'; > > function DraftJSEditor() { > const annotations = useCommentAnnotations(); > const [editorState, setEditorState] = useState(() => > EditorState.createEmpty() > ); > > const editorRef = useRef({ editorState, setEditorState }); > > useEffect(() => { > editorRef.current = { editorState, setEditorState }; > }, [editorState]); > > useEffect(() => { > renderComments({ > editor: editorRef.current, > editorId: 'EDITOR_ID', > commentAnnotations: annotations ?? [], > }); > }, [annotations]); > > return ( > editorState={editorState} > onChange={setEditorState} > /> > ); > } > ``` #### Step 7: Persist DraftJS content without Velt comment entities (optional) * When saving editor content to your backend, remove Velt comment entities to keep your stored content clean. * Use `exportContentStateWithoutComments` before converting DraftJS content to raw JSON. ```js theme={null} import { convertToRaw } from 'draft-js'; import { exportContentStateWithoutComments } from '@veltdev/draftjs-velt-comments'; const cleanContent = exportContentStateWithoutComments( editorState.getCurrentContent() ); const rawContent = convertToRaw(cleanContent); ``` #### Step 8: Style the commented text * Style the commented text by adding CSS for the `velt-comment-text` element. ```css theme={null} velt-comment-text { background-color: rgba(255, 255, 0, 0.3); border-bottom: 2px solid #ffcc00; cursor: pointer; } velt-comment-text:hover { background-color: rgba(255, 255, 0, 0.5); } velt-comment-text.velt-comment-selected { background-color: rgba(255, 255, 0, 0.5); } ``` ## Complete Example [https://sample-apps-draftjs-comments-demo.vercel.app/](https://sample-apps-draftjs-comments-demo.vercel.app/) ## APIs #### [DraftJSVeltEditor](/docs/api-reference/sdk/api/api-methods#draftjsvelteditor) A wrapper around the DraftJS `Editor` component that automatically handles decorator setup, content change detection, and Velt annotation context updates. * Props: [`DraftJSVeltEditorProps`](/docs/api-reference/sdk/models/data-models#draftjsvelteditorprops) * `editorState`: Current DraftJS editor state. * `onChange`: Callback when the editor state changes. * `editorId`: Optional editor ID for multi-editor scenarios. * All other standard DraftJS `Editor` props are forwarded. > [tab] React / Next.js > > ```jsx theme={null} > import { DraftJSVeltEditor } from '@veltdev/draftjs-velt-comments'; > > editorState={editorState} > onChange={setEditorState} > editorId="my-editor" > placeholder="Start typing..." > /> > ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-8) Creates a comment annotation for the currently selected text in the editor. * Signature: `async (request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest-7)`) => Promise` * Params: `request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest-7) * Returns: `Promise` > [tab] React / Next.js > > ```jsx theme={null} > import { addComment } from '@veltdev/draftjs-velt-comments'; > > const handleAddComment = () => { > addComment({ editor, editorId: 'my-editor' }); > }; > > > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-8) Renders and highlights comment annotations in the DraftJS editor. * Signature: `(request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-7)`) => void` * Params: `request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-7) * Returns: `void` > [tab] React / Next.js > > ```jsx theme={null} > import { renderComments } from '@veltdev/draftjs-velt-comments'; > > useEffect(() => { > renderComments({ > editor: editorRef.current, > editorId: 'my-editor', > commentAnnotations, > }); > }, [commentAnnotations]); > ``` #### [exportContentStateWithoutComments()](/docs/api-reference/sdk/api/api-methods#exportcontentstatewithoutcomments) Returns a DraftJS `ContentState` without Velt comment entities. Use it before saving content outside Velt. > [tab] React / Next.js > > ```jsx theme={null} > import { convertToRaw } from 'draft-js'; > import { exportContentStateWithoutComments } from '@veltdev/draftjs-velt-comments'; > > const cleanContent = exportContentStateWithoutComments( > editorState.getCurrentContent() > ); > const rawContent = convertToRaw(cleanContent); > ``` # Freestyle Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/freestyle ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Freestyle-Comment.gif?s=ff59589d7645c5e1a251a482964fc129) > [tab] React / Next.js > > ## 1. Import Comment components > > Import the `VeltComments` component and the `VeltCommentTool` component. > > ```js theme={null} > import { > VeltProvider, > VeltComments, > VeltCommentTool > } from '@veltdev/react'; > ``` > > ## 2. Add Comments component > > Add the `VeltComments` component to the root of your app. > > This component is required to render comments in your app. > > ```js theme={null} > > > > ``` > > ## 3. Add Comment Tool component > > Add the `VeltCommentTool` component wherever you want to show the comment tool button. > > ![](https://mintcdn.com/velt/2O8vk8YlVD4Kq-ni/images/comment-tool.png?fit=max\&auto=format\&n=2O8vk8YlVD4Kq-ni\&q=85\&s=f6542acc54050b4b607812391c0b97ad) > > Clicking on it initiates comment mode & changes your mouse cursor to a comment pin. Now you can click anywhere on the document to attach comments to any elements. > > ```js theme={null} >
> >
> ``` > > ## 4. Test Integration > > Test it out by opening the page with Velt components in your browser. > > Click on the `Comment Tool` and click anywhere on the page to add a comment. > > ![](https://mintcdn.com/velt/gY7ilEx2g4g3-HVe/images/standard-comment.png?fit=max\&auto=format\&n=gY7ilEx2g4g3-HVe\&q=85\&s=6f894dc613dc924c3fa070780a479496) > [tab] Other Frameworks > > ## 1. Add Comment component > > Add the comment component to your template. Try to put it as close to the root level of your ``. > > This component is required to render comments in your app. > > ```html theme={null} > > > > ``` > > ## 2. Add Comment Tool component > > Add the `` component wherever you want to show the comment tool button. > > ![](https://mintcdn.com/velt/2O8vk8YlVD4Kq-ni/images/comment-tool.png?fit=max\&auto=format\&n=2O8vk8YlVD4Kq-ni\&q=85\&s=f6542acc54050b4b607812391c0b97ad) > > Clicking on it initiates comment mode & changes your mouse cursor to a comment pin. Now you can click anywhere on the document to attach comments to any elements. > > ```js theme={null} >
> >
> ``` > > ## 3. Test Integration > > Test it out by adding a comment. > > You should be able to leave comments using the `Comment Tool`. > > ![](https://mintcdn.com/velt/gY7ilEx2g4g3-HVe/images/standard-comment.png?fit=max\&auto=format\&n=gY7ilEx2g4g3-HVe\&q=85\&s=6f894dc613dc924c3fa070780a479496) ```jsx React / Next.js theme={null} import { VeltProvider, VeltComments, VeltCommentTool } from '@veltdev/react'; export default function App() { return (
); } ``` ```html HTML theme={null} Comment documentation
``` # Inline Comments Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/inline-comments ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/inline-comment.gif?s=2dec4833ca1e492d6e8945db7ca527db) > [tab] React / Next.js > > ## 1. Import Comment components > > Import the `VeltProvider`, `VeltComments`, and `VeltInlineCommentsSection` component. > > ```js theme={null} > import { VeltProvider, VeltComments, VeltInlineCommentsSection } from '@veltdev/react'; > ``` > > ## 2. Add VeltComments component > > * Add the `VeltComments` component to the root of your app where your `VeltProvider` is. > * This component is required to render comments in your app. > > ```js theme={null} > > > > ``` > > ## 3. Add container to hold Inline Comments component > > * Create an element to hold your Inline Comments component, such as a `div` or `section`. > * Add a unique element `id` to it. > > ```jsx theme={null} >
>
Your Article
>
> ``` > > ## 4. Add VeltInlineCommentsSection component > > * Add `VeltInlineCommentsSection` component inside your container. > * Add `targetElementId` property to the Velt Inline Comments component. This needs to match the id you set to the container. This binds the Inline Comments component with the desired container. > > ```jsx theme={null} > targetElementId="container-id" > /> > ``` > > ## 5. (Optional) Make it single threaded or multithreaded > > * Default: `true` > * By default inline comment section is multithreaded. > * You can make it single threaded by setting `multiThread` attribute to `false`. > > ```jsx theme={null} > > ``` > > ## 6. (Optional) Customize placeholder text > > Customize the placeholder text for comment, reply, and composer input fields. > > ```jsx theme={null} > commentPlaceholder="Add a comment..." > replyPlaceholder="Write a reply..." > composerPlaceholder="Start typing..." > /> > ``` > > To customize placeholder text shown when **editing** an existing comment or reply, use `editPlaceholder`, `editCommentPlaceholder`, and `editReplyPlaceholder`. See [`VeltInlineCommentsSectionProps`](/docs/api-reference/sdk/models/data-models#veltinlinecommentssectionprops) for details. > > ## 7. (Optional) Enable message truncation > > * Default: `false` > * Truncate long messages in the list, showing a **Show more** toggle after the specified number of lines. > * Use `messageTruncationLines` to control the cutoff (default: `4`). > > ```jsx theme={null} > targetElementId="article0" > messageTruncation={true} > messageTruncationLines={3} > /> > ``` > [tab] Other Frameworks > > ## 1. Add velt-comments component > > * Add the Velt Comments component to the root of your app. > * This component is required to render comments in your app. > > ```html theme={null} > > > > ``` > > ## 2. Add container to hold Inline Comments component > > * Create an element to hold your Inline Comments component, such as a `div` or `section`. > * Add a unique element `id` to it. > > ```html theme={null} >
>
Your Article
>
> ``` > > ## 3. Add velt-inline-comments-section component > > * Add `velt-inline-comments-section` component inside your container. > * Add `target-element-id` property to the Velt Inline Comments component. This needs to match the id you set to the container. This binds the Inline Comments component with the desired container. > > ```jsx theme={null} > target-element-id="container-id" > shadow-dom="false" > dialog-variant="dialog-variant" > variant="inline-section-variant" > dark-mode="true" > > > > ``` > > ## 4. (Optional) Make it single threaded or multithreaded > > * Default: `true` > * By default inline comments are multithreaded. > * You can make it single threaded by setting `multi-thread` attribute to `false`. > > ```html theme={null} > > > ``` > > ## 5. (Optional) Customize placeholder text > > Customize the placeholder text for comment, reply, and composer input fields. > > ```html theme={null} > comment-placeholder="Add a comment..." > reply-placeholder="Write a reply..." > composer-placeholder="Start typing..." > > > > ``` > > To customize placeholder text shown when **editing** an existing comment or reply, use `edit-placeholder`, `edit-comment-placeholder`, and `edit-reply-placeholder`. See [`VeltInlineCommentsSectionProps`](/docs/api-reference/sdk/models/data-models#veltinlinecommentssectionprops) for details. > > ## 6. (Optional) Enable message truncation > > * Default: `false` > * Truncate long messages in the list, showing a **Show more** toggle after the specified number of lines. > * Use `message-truncation-lines` to control the cutoff (default: `4`). > > ```html theme={null} > target-element-id="article0" > message-truncation="true" > message-truncation-lines="3"> > > ``` ```jsx React / Next.js theme={null} import { VeltProvider, VeltComments } from '@veltdev/react'; export default function App() { return (
Your Article
); } ``` ```html HTML theme={null} Comment documentation
Your Article
``` # Lexical Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/lexical ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. * This component is required to render comments in your app. * Set the `text mode` prop to `false` to hide the default text comment tool. > [tab] React / Next.js > > ```js theme={null} > > > > ``` > [tab] Other Frameworks > > ```html theme={null} > > > > ``` #### Step 2: Install the Velt Lexical extension ```bash theme={null} npm install @veltdev/lexical-velt-comments @veltdev/client lexical ``` #### Step 3: Configure the Lexical editor with the Velt Comments extension * Register the `CommentNode` and configure your Lexical editor. > [tab] React / Next.js > > ```js theme={null} > import { LexicalComposer } from '@lexical/react/LexicalComposer'; > import { CommentNode } from '@veltdev/lexical-velt-comments'; > > const initialConfig = { > namespace: 'MyEditor', > nodes: [CommentNode], > onError: (error) => console.error(error), > }; > > function App() { > return ( > > {/* Editor plugins */} > > ); > } > ``` > [tab] Other Frameworks > > ```js theme={null} > import { createEditor } from 'lexical'; > import { registerRichText } from '@lexical/rich-text'; > import { CommentNode, addComment, renderComments } from '@veltdev/lexical-velt-comments'; > > const editor = createEditor({ > namespace: 'MyEditor', > nodes: [CommentNode], > onError: (error) => { > throw error; > }, > }); > > // Set the root element > editor.setRootElement(document.querySelector('#editor')); > > // Register rich text support > registerRichText(editor); > ``` #### Step 4: Add a comment button * Add a button that users can click to add comments after selecting text. > [tab] React / Next.js > > ```js theme={null} > import { useCallback } from 'react'; > import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'; > import { addComment } from '@veltdev/lexical-velt-comments'; > > function AddCommentPlugin() { > const [editor] = useLexicalComposerContext(); > > const handleAddComment = useCallback(() => { > addComment({ editor }); > }, [editor]); > > return ( > > ); > } > ``` > [tab] Other Frameworks > > ```html theme={null} > >
> ``` > > ```js theme={null} > import { addComment } from '@veltdev/lexical-velt-comments'; > > const addCommentBtn = document.getElementById('add-comment-btn'); > addCommentBtn.addEventListener('click', () => { > addComment({ editor }); > }); > ``` #### Step 5: Call `addComment` to add a comment * Call this method to add a comment to selected text in the Lexical editor. You can use this when the user clicks on a comment button or presses a keyboard shortcut. * Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-3). It has the following properties: * `editor`: Instance of the Lexical Editor. * `editorId`: Id of the editor. Use this if you have multiple Lexical editors on the same page. (optional) * `context`: Add any custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional) > [tab] React / Next.js > > ```js theme={null} > import { addComment } from '@veltdev/lexical-velt-comments'; > > const addCommentRequest = { > editor, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > addComment(addCommentRequest); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { addComment } from '@veltdev/lexical-velt-comments'; > > const addCommentRequest = { > editor, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > addComment(addCommentRequest); > ``` #### Step 6: Render comments in Lexical editor * Get the comment data from Velt SDK and render it in the Lexical Editor. * Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-3). It has the following properties: * `editor`: Instance of the Lexical Editor. * `editorId`: Id of the editor. Use this if you have multiple Lexical editors on the same page. (optional) * `commentAnnotations`: Array of Comment Annotation objects. > [tab] React / Next.js > > ```js theme={null} > import { renderComments } from '@veltdev/lexical-velt-comments'; > import { useCommentAnnotations } from '@veltdev/react'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (editor && annotations) { > renderComments({ > editor, > editorId: 'EDITOR_ID', > commentAnnotations: annotations, > }); > } > }, [editor, annotations]); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { renderComments } from '@veltdev/lexical-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > if (editor && annotations?.length) { > const renderCommentsRequest = { > editor, > editorId: 'EDITOR_ID', > commentAnnotations: annotations, > }; > renderComments(renderCommentsRequest); > } > }); > ``` #### Step 7: Persist editor content without Velt marks (optional) * When saving editor content to your backend, you may want to exclude Velt comment marks to keep the content clean. * Use `exportJSONWithoutComments` to export the editor state as JSON without Velt comment nodes. ```js theme={null} import { exportJSONWithoutComments } from '@veltdev/lexical-velt-comments'; // Get clean editor state JSON without Velt comment marks const cleanState = exportJSONWithoutComments(editor); // Save to your backend localStorage.setItem('editor-content', JSON.stringify(cleanState)); ``` #### Step 8: Style the commented text * Style the commented text by adding CSS for the `velt-comment-text` element. ```css theme={null} velt-comment-text { background-color: rgba(255, 255, 0, 0.3); border-bottom: 2px solid #ffcc00; cursor: pointer; } velt-comment-text:hover { background-color: rgba(255, 255, 0, 0.5); } velt-comment-text.velt-comment-selected { background-color: rgba(255, 255, 0, 0.5); } ``` ## Complete Example [https://sample-apps-lexical-comments-demo.vercel.app/](https://sample-apps-lexical-comments-demo.vercel.app/) ## APIs #### [CommentNode](/docs/api-reference/sdk/models/data-models#commentnode) A custom Lexical node used to wrap commented text with comment annotation metadata. * Usage: Register the node with your Lexical editor so comment elements render correctly. > [tab] React / Next.js > > ```tsx theme={null} > import { LexicalComposer } from '@lexical/react/LexicalComposer'; > import { CommentNode } from '@veltdev/lexical-velt-comments'; > > const initialConfig = { > namespace: 'MyEditor', > nodes: [CommentNode], > onError: console.error, > }; > > export default function Editor() { > return {/* plugins */}; > } > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import { createEditor } from 'lexical'; > import { CommentNode } from '@veltdev/lexical-velt-comments'; > > const editor = createEditor({ > namespace: 'MyEditor', > nodes: [CommentNode], > onError: (error) => { > throw error; > }, > }); > ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment) Creates a comment annotation for the currently selected text in the editor. * Params: * `request:` [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-3) * `editor: LexicalEditor` * `editorId?: string` * `context?: object` * Returns: `Promise` > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/lexical-velt-comments'; > > > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import { addComment } from '@veltdev/lexical-velt-comments'; > > addComment({ > editor, > editorId: 'my-editor', > context: { customData: 'value' }, > }); > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments) Renders and highlights comment annotations in the editor. * Params: * `request:` [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-3) * `editor: LexicalEditor` * `editorId?: string` * `commentAnnotations?:` [`CommentAnnotation[]`](/docs/api-reference/sdk/models/data-models#commentannotation) * Returns: `void` > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { renderComments } from '@veltdev/lexical-velt-comments'; > import { useCommentAnnotations } from '@veltdev/react'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (editor && annotations) { > renderComments({ > editor, > editorId: 'my-editor', > commentAnnotations: annotations, > }); > } > }, [editor, annotations]); > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import { renderComments } from '@veltdev/lexical-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > if (editor && annotations) { > renderComments({ > editor, > editorId: 'my-editor', > commentAnnotations: annotations, > }); > } > }); > ``` #### [exportJSONWithoutComments()](/docs/api-reference/sdk/api/api-methods#exportjsonwithoutcomments) Exports the editor state as serialized JSON while stripping out all comment nodes and normalizing adjacent text nodes. * Params: `editor:` `LexicalEditor` * Returns: `SerializedEditorState` ```tsx theme={null} import { exportJSONWithoutComments } from '@veltdev/lexical-velt-comments'; const cleanState = exportJSONWithoutComments(editor); ``` # Lottie Player Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/lottie-player-setup ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Lottie-Comment.gif?s=a476a0d427c271ab7318d390d5f18d67) > [tab] React / Next.js > > > [!WARNING] > > > > Make sure you turn React strict mode off. > > **1. Add Velt Components in your app** > > ### a. Add the `VeltComments` component in the root of your app > > Add the `VeltComments` component to enable the Comment feature in your app. > > Enable the follow attributes to be `true`: > > * `priority`: allows user to P0, P1, or P2 as priority. You can customize this list. > * `autoCategorize`: allows AI to categorize comment as Question, Feedback, Bug, Other. You can customize this list. > * `commentIndex`: shows a small icon showing index of the comment in order of creation. > > ```jsx theme={null} > > ``` > > ### b. Add the `VeltCommentTool` component wherever you want your render the comment tool. > > Note you can also provide your own button to this component. > > ```jsx theme={null} > > > > ``` > > ### c. Place the `VeltCommentPlayerTimeline` component as a sibling to your video player. > > To show comment bubbles on your player seek bar, add the `` component as a sibling to your video player component. > > It will auto adjust to the same width as your video player. > > ```jsx theme={null} >
> > >
> ``` > > > [!NOTE] > > > > Right now we assume you have a maximum of one `` component and one sibling video player component per `documentID` > > > [!WARNING] > > > > Ensure that the parent container of `` doesn't have CSS position value as 'static'. > > ### d. Add the `` component. > > (Optional) To embed the sidebar in your existing component, set `embedMode` prop as `true`. > > ```jsx theme={null} > > ``` > > ### e. Add the `` component. > > This will open or close the Comment Sidebar. > Note you can also provide your own button to this component. > > ```jsx theme={null} > >
> {/* your custom button (optional) */} >
>
> ``` > > **2. Set the `totalMediaLength` on the `VeltCommentPlayerTimeline`** > > You can pass an integer to `totalMediaLength` using props to represent the total number of frames or seconds in the video: > > ```jsx theme={null} > > ``` > > Alternatively, you can set this using API method call. This is useful if you first need to grab the total frames from another method before setting it. > > ```jsx theme={null} > const commentElement = client.getCommentElement(); > commentElement.setTotalMediaLength(120); > ``` > > **3. Subscribe to when the Comment Tool is activated by the User.** > > Add an event handler on where you originally placed `` to handle `onCommentModeChange` events. > > Use this whenever the user clicks on the comment tool, to pause your player and set a new `Location` in the Velt SDK. > > Setting a `Location` in the Velt SDK ensures that the comments are tied to that particular media frame or timestamp. > > ```jsx theme={null} > > onCommentModeChange(mode)} /> > > const onCommentModeChange = (mode) => { > // mode will be `true` if the user has activated the comment tool > // If the comment tool is active, pause the player and set the "location". > if (mode) { > // pause player > // See step 8 below for details > setLocation() > } > }); > > ``` > > **4. Set Velt Location** > > You can pass in a key value pair object that represents the current state of your player. If you are using the `VeltCommentPlayerTimeline` component, ensure to set the current rounded frame or second in the special key `currentMediaPosition`. > > > [!NOTE] > > > > `currentMediaPosition` is a protected keyword that is used to arrange the comment bubbles on top of the video player timeline in the correct spot > > ```jsx theme={null} > const setLocation = (client) => { > > // set currentMediaPosition property on a Location object to represent the current frame > let location = { > currentMediaPosition : 120 > } > //set the Location using the client > client.setLocation(location) > > } > ``` > > **5. When the player is played, remove Velt `Location` to remove comments from the media.** > > Call `removeLocation()` when your player starts playing: > > ```jsx theme={null} > const removeLocation = () => { > //remove the location, so the video player can play without comments appearing in frames > client.removeLocation() > } > ``` > > **6. Set your player's state when the user clicks on the comment.** > > Add the `onCommentClick` event handler on the `VeltCommentsSidebar` & `VeltCommentPlayerTimeline` components you added earlier. > The event will give you back the `location` object that you had set earlier. > > You can use this object to update your player state and also update the SDK's `location` so that we can start rendering the comments associated with that `location`. > > ### a. Handle it on the `VeltCommentsSidebar`: > > ```jsx theme={null} > onCommentClick(event)} /> > > const onCommentClick = (event) => { > if (event) { > // Get the location object from the event. > const { location } = event; > if (location) { > // Get the media position where the comment was added. > const { currentMediaPosition } = location; > if (currentMediaPosition) { > // Pause the player. > > // Seek to the given comment media position. > > // Set the Velt Location to the clicked comment location. > client.setLocation(location); > } > } > } > } > ``` > > ### b. Handle it on the `VeltCommentPlayerTimeline`: > > ```jsx theme={null} > onTimelineCommentClick(event)} /> > > const onTimelineCommentClick = (event) => { > if (event) { > // Get the location object from the event. > const { location } = event; > if (location) { > // Get the media position where the comment was added. > const { currentMediaPosition } = location; > if (currentMediaPosition) { > // Pause the player. > > // Seek to the given comment media position. > > // Set the Velt Location to the clicked comment location. > client.setLocation(location); > } > } > } > } > ``` > > The clicked Comment data will be in the following format: > > | property | type | description | > | - | - | - | > | `documentId` | string | The document ID where the comment was added | > | `location` | object | The location where the comment was added | > | `targetElementId` | string | The DOM ID of the target element on which the comment was added | > | `context` | Object | Any context data passed when the comment was added | > > # Additional Configurations > > ## Allow comments only on certain elements > > Provide a list of element DOM IDs where commenting should be allowed. > Comments will be disabled for all other elements. > > ```jsx theme={null} > const commentElement = client.getCommentElement(); > commentElement.allowedElementIds(['lottiePlayerContainer']); > ``` > [tab] Other Frameworks > > **1. Add Velt Components in your app** > > ### a. Add the `VeltComments` component in the root of your app > > Add the `VeltComments` component to enable the Comment feature in your app. > > Enable the follow attributes to be `true`: > > * `priority`: allows user to P0, P1, or P2 as priority. You can customize this list. > * `auto-categorize`: allows AI to categorize comment as Question, Feedback, Bug, Other. You can customize this list. > * `comment-index`: shows a small icon showing index of the comment in order of creation. > > ```jsx theme={null} > > ``` > > ### b. Add the `velt-comment-tool` component wherever you want your render the comment tool. > > Note you can also provide your own button to this component. > > ```jsx theme={null} > > > > ``` > > ### c. Place the `velt-commen-player-timeline` component as a sibling to your video player. > > To show comment bubbles on your player seek bar, add the `` component as a sibling to your video player component. > > It will auto adjust to the same width as your video player. > > ```jsx theme={null} >
> > >
> ``` > > > [!NOTE] > > > > Right now we assume you have a maximum of one `` component and one sibling video player component per `documentID` > > > [!WARNING] > > > > Ensure that the parent container of `` doesn't have CSS position value as 'static'. > > ### d. Add the `` component. > > (Optional) To embed the sidebar in your existing component, set `embed-mode` prop as `true`. > > ```jsx theme={null} > > ``` > > ### e. Add the `` component. > > This will open or close the Comment Sidebar. > Note you can also provide your own button to this component. > > ```jsx theme={null} > > > > ``` > > **2. Set the `total-media-length` on the `velt-comment-player-timeline`** > > You can pass an integer to `total-media-length` using props to represent the total number of frames or seconds in the video: > > ```jsx theme={null} > > ``` > > Alternatively, you can set this using API method call. This is useful if you first need to grab the total frames from another method before setting it. > > ```jsx theme={null} > const commentElement = Velt.getCommentElement(); > commentElement.setTotalMediaLength(120); > ``` > > **3. Subscribe to when the Comment Tool is activated by the User.** > > Add an event handler to handle `onCommentModeChange` events. > > Use this whenever the user clicks on the comment tool, to pause your player and set a new `Location` in the Velt SDK. > > Setting a `Location` in the Velt SDK ensures that the comments are tied to that particular media frame or timestamp. > > ```jsx theme={null} > const commentElement = Velt.getCommentElement(); > let subscription = commentElement.onCommentModeChange().subscribe((mode) => { > // mode will be `true` if the user has activated the comment tool > // If the comment tool is active, pause the player and set the "location". > if (mode) { > // pause player > // See step 8 below for details > setLocation() > } > }); > ``` > > To unsubscribe from the subscription: > > ```jsx theme={null} > subscription?.unsubscribe() > ``` > > **4. Set Velt Location** > > You can pass in a key value pair object that represents the current state of your player. If you are using the `velt-comment-player-timeline` component, ensure to set the current rounded frame or second in the special key `current-media-position`. > > > [!NOTE] > > > > `current-media-position` is a protected keyword that is used to arrange the comment bubbles on top of the video player timeline in the correct spot > > ```jsx theme={null} > const setLocation = (client) => { > > // set currentMediaPosition property on a Location object to represent the current frame > let location = { > currentMediaPosition : 120 > } > //set the Location using the client > Velt.setLocation(location) > > } > ``` > > **5. When the player is played, remove Velt `Location` to remove comments from the media.** > > Call `removeLocation()` when your player starts playing: > > ```jsx theme={null} > const removeLocation = () => { > //remove the location, so the video player can play without comments appearing in frames > Velt.removeLocation() > } > ``` > > **6. Set your player's state when the user clicks on the comment.** > > Add the `onCommentClick` event handler on the `VeltCommentsSidebar` & `VeltCommentPlayerTimeline` components you added earlier. > The event will give you back the `location` object that you had set earlier. > You can use this object to update your player state and also update the SDK's `location` so that we can start rendering the comments associated with that `location`. > > ### a. Handle it on the `velt-comments-sidebar`: > > ```jsx theme={null} > > > const onCommentClick = (event) => { > if (event) { > // Get the location object from the event. > const { location } = event; > if (location) { > // Get the media position where the comment was added. > const { currentMediaPosition } = location; > if (currentMediaPosition) { > // Pause the player. > > // Seek to the given comment media position. > > // Set the Velt Location to the clicked comment location. > client.setLocation(location); > } > } > } > } > > const commentElement = Velt.getCommentElement(); > let subscription = commentElement.onSidebarButtonOnCommentDialogClick().subscribe((event) => onCommentClick(event)); > ``` > > To unsubscribe from the subscription: > > ```jsx theme={null} > subscription?.unsubscribe() > ``` > > ### b. Handle it on the ``: > > ```html theme={null} > > > ``` > > The clicked Comment data will be in the following format: > > | property | type | description | > | - | - | - | > | `documentId` | string | The document ID where the comment was added | > | `location` | object | The location where the comment was added | > | `targetElementId` | string | The DOM ID of the target element on which the comment was added | > | `context` | Object | Any context data passed when the comment was added | > > # Additional Configurations > > ## Allow comments only on certain elements > > Provide a list of element DOM IDs where commenting should be allowed. > Comments will be disabled for all other elements. > > ```jsx theme={null} > const commentElement = Velt.getCommentElement(); > commentElement.allowedElementIds(['lottiePlayerContainer']); > ``` # Monaco Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/monaco Add Velt text comments to a Monaco editor with the Velt Monaco comments package. ![Add text comments in an editor](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) The Monaco integration renders comment highlights as view-only overlay elements positioned over the commented text. It does not modify your Monaco model, undo history, or saved source code. ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. This component is required to create and render comments in your app. * Authenticate the user with `authProvider` and set the Velt document before users add comments. * Set the `textMode` prop to `false` to hide the default Velt text comment tool. Monaco selections are handled by `@veltdev/monaco-velt-comments`. * Add `VeltCommentsSidebar` if you want a Google Docs-style comment sidebar. > [tab] React / Next.js > > ```tsx theme={null} > import { VeltComments, VeltCommentsSidebar, VeltProvider, useSetDocument } from '@veltdev/react'; > > const user = { > userId: 'user-1', > organizationId: 'org-1', > name: 'User One', > email: 'user@example.com', > }; > > function VeltSetup() { > useSetDocument('document-id', { documentName: 'Document name' }); > return null; > } > > function App() { > return ( > > > > > {/* Your app content */} > > ); > } > ``` > [tab] Other Frameworks > > ```html theme={null} > > > > ``` #### Step 2: Install the Velt Monaco extension > [tab] React / Next.js > > ```bash theme={null} > npm i @veltdev/monaco-velt-comments monaco-editor @monaco-editor/react > ``` > [tab] Other Frameworks > > ```bash theme={null} > npm i @veltdev/monaco-velt-comments monaco-editor @veltdev/client > ``` `monaco-editor` is a peer dependency and must be provided by your Monaco app. The package uses the Monaco editor instance your app creates and does not bundle Monaco at runtime. #### Step 3: Register the Monaco editor with Velt Comments Register the integration on the Monaco editor instance returned by `monaco.editor.create` or by `@monaco-editor/react`'s `onMount`. Keep the returned handle so you can dispose it on teardown. > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect, useRef, useState } from 'react'; > import { Editor as MonacoReact, loader } from '@monaco-editor/react'; > import { useCommentAnnotations } from '@veltdev/react'; > import * as monaco from 'monaco-editor'; > import { > registerVeltComments, > renderComments, > type MonacoEditor, > type VeltCommentsHandle, > } from '@veltdev/monaco-velt-comments'; > > loader.config({ monaco }); > > const EDITOR_ID = 'my-editor'; > > function MonacoTextEditor() { > const [editor, setEditor] = useState(null); > const handleRef = useRef(null); > const commentAnnotations = useCommentAnnotations(); > > useEffect(() => { > if (!editor) return; > > renderComments({ > editor, > editorId: EDITOR_ID, > commentAnnotations: commentAnnotations ?? [], > }); > }, [editor, commentAnnotations]); > > useEffect(() => { > return () => handleRef.current?.dispose(); > }, []); > > return ( > height="480px" > defaultLanguage="typescript" > defaultValue={'const greeting = "hello world";\n'} > options={{ automaticLayout: true, wordWrap: 'on' }} > onMount={(mountedEditor) => { > setEditor(mountedEditor); > handleRef.current = registerVeltComments(mountedEditor, { > editorId: EDITOR_ID, > }); > }} > /> > ); > } > ``` > [tab] Other Frameworks > > ```ts theme={null} > import * as monaco from 'monaco-editor'; > import { registerVeltComments } from '@veltdev/monaco-velt-comments'; > > const editor = monaco.editor.create(document.querySelector('#editor'), { > value: 'const greeting = "hello world";\n', > language: 'typescript', > automaticLayout: true, > wordWrap: 'on', > }); > > const handle = registerVeltComments(editor, { > editorId: 'my-editor', > }); > > // Later, for example during teardown: > handle.dispose(); > ``` #### Step 4: Add a comment button to your Monaco editor Add a button that users can click to add comments after selecting text in the Monaco editor. **Important:** Use `onMouseDown` with `preventDefault()` so the browser does not move focus away from Monaco before `addComment` reads the current selection. Keep the actual `addComment` call in `onClick`. > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/monaco-velt-comments'; > > const handleAddComment = () => { > if (!editor) return; > > void addComment({ > editor, > editorId: EDITOR_ID, > }); > }; > > > ``` > [tab] Other Frameworks > > ```html theme={null} > >
> ``` > > ```ts theme={null} > import { addComment } from '@veltdev/monaco-velt-comments'; > > const addCommentButton = document.querySelector('#add-comment'); > > addCommentButton.addEventListener('mousedown', (event) => { > event.preventDefault(); > }); > > addCommentButton.addEventListener('click', () => { > void addComment({ editor, editorId: 'my-editor' }); > }); > ``` Registering the integration also adds an **Add Comment** Monaco editor action in the command palette and right-click menu. The action is enabled only when there is a non-empty editor selection. #### Step 5: Call `addComment` to add a comment * Call this method to add a comment to selected text in the Monaco editor. * Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-10). It has the following properties: * `editor`: Monaco `IStandaloneCodeEditor` instance. * `editorId`: Id of the editor. Use this if you have multiple Monaco editors on the same page. (optional) * `context`: Add custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional) > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/monaco-velt-comments'; > > const addCommentRequest = { > editor, > editorId: 'EDITOR_ID', > context: { > fileId: 'file-123', > language: 'typescript', > }, > }; > > void addComment(addCommentRequest); > ``` > [tab] Other Frameworks > > ```ts theme={null} > import { addComment } from '@veltdev/monaco-velt-comments'; > > const addCommentRequest = { > editor, > editorId: 'EDITOR_ID', > context: { > fileId: 'file-123', > language: 'typescript', > }, > }; > > void addComment(addCommentRequest); > ``` The library automatically writes `context.textEditorConfig` with the selected text, its 1-based occurrence index in the document, and the editor ID when one is provided. #### Step 6: Render comments in Monaco editor * Get the comment data from Velt SDK and render it in the Monaco editor. * Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-10). It has the following properties: * `editor`: Monaco `IStandaloneCodeEditor` instance. * `editorId`: Id of the editor. Use this if you have multiple Monaco editors on the same page. (optional) * `commentAnnotations`: Array of Comment Annotation objects. > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { useCommentAnnotations } from '@veltdev/react'; > import { renderComments } from '@veltdev/monaco-velt-comments'; > > const commentAnnotations = useCommentAnnotations(); > > useEffect(() => { > if (!editor) return; > > renderComments({ > editor, > editorId: 'EDITOR_ID', > commentAnnotations: commentAnnotations ?? [], > }); > }, [editor, commentAnnotations]); > ``` > [tab] Other Frameworks > > ```ts theme={null} > import { renderComments } from '@veltdev/monaco-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > renderComments({ > editor, > editorId: 'EDITOR_ID', > commentAnnotations: annotations, > }); > }); > ``` #### Step 7: Re-apply Monaco comment highlights (optional) * Monaco renders comment highlights as view-only overlay elements. * The integration does not write Velt comment marks into your Monaco model or saved source code. * Save your Monaco model value normally. After you call `model.setValue(...)`, `editor.setModel(...)`, or load saved content, call `renderComments` again. ```ts theme={null} const value = editor.getValue(); // Save value to your backend. renderComments({ editor, editorId: 'EDITOR_ID', commentAnnotations, }); ``` #### Step 8: Style the commented text * You can style the commented text by adding CSS for the `velt-comment-text` element. * Monaco highlights are rendered as overlay elements in the outer document, so broad `velt-comment-text` styles are appropriate for this integration. ```css theme={null} velt-comment-text { background-color: rgba(255, 212, 0, 0.4); border-bottom: 2px solid #ffd400; cursor: pointer; } velt-comment-text:hover, velt-comment-text[comment-selected="true"], velt-comment-text.velt-comment-selected { background-color: rgba(255, 212, 0, 0.7); } ``` ### Multiple Monaco editors When using multiple Monaco editors on the same page, provide unique `editorId` values. The library stores `editorId` in `context.textEditorConfig.editorId` and filters annotations by that value when rendering. ```tsx theme={null} const editor1Handle = registerVeltComments(editor1, { editorId: 'editor-1' }); const editor2Handle = registerVeltComments(editor2, { editorId: 'editor-2' }); await addComment({ editor: editor1, editorId: 'editor-1', }); renderComments({ editor: editor2, editorId: 'editor-2', commentAnnotations, }); editor1Handle.dispose(); editor2Handle.dispose(); ``` ### TypeScript support The package includes full TypeScript definitions. ```ts theme={null} import type { AddCommentRequest, AnchorEntry, CommentAnnotation, CommentAnnotationContext, MonacoEditor, MonacoVeltCommentsConfig, RenderCommentsRequest, SelectionContext, SyncAnchor, VeltCommentsHandle, } from '@veltdev/monaco-velt-comments'; ``` ## Complete Example > [tab] React / Next.js > > ```tsx theme={null} > import { useCallback, useEffect, useRef, useState } from 'react'; > import { Editor as MonacoReact, loader } from '@monaco-editor/react'; > import { > VeltComments, > VeltCommentsSidebar, > VeltCommentsSidebarButton, > VeltPresence, > VeltProvider, > useCommentAnnotations, > useSetDocument, > } from '@veltdev/react'; > import * as monaco from 'monaco-editor'; > import { > addComment, > registerVeltComments, > renderComments, > type MonacoEditor, > type VeltCommentsHandle, > } from '@veltdev/monaco-velt-comments'; > > loader.config({ monaco }); > > const EDITOR_ID = 'main-editor'; > > function InitializeDocument() { > useSetDocument('monaco-comments-doc', { > documentName: 'Monaco Comments Document', > }); > > return null; > } > > function MyEditor() { > const [editor, setEditor] = useState(null); > const handleRef = useRef(null); > const commentAnnotations = useCommentAnnotations(); > > useEffect(() => { > if (!editor) return; > > renderComments({ > editor, > editorId: EDITOR_ID, > commentAnnotations: commentAnnotations ?? [], > }); > }, [editor, commentAnnotations]); > > useEffect(() => { > return () => handleRef.current?.dispose(); > }, []); > > const handleAddComment = useCallback(() => { > if (!editor) return; > > void addComment({ > editor, > editorId: EDITOR_ID, > context: { source: 'monaco-editor' }, > }); > }, [editor]); > > return ( >
>
> > > >
> > height="480px" > defaultLanguage="typescript" > defaultValue={'const greeting = "hello world";\n'} > options={{ > automaticLayout: true, > wordWrap: 'on', > scrollBeyondLastLine: false, > }} > onMount={(mountedEditor) => { > setEditor(mountedEditor); > handleRef.current = registerVeltComments(mountedEditor, { > editorId: EDITOR_ID, > }); > }} > /> >
> ); > } > > const user = { > userId: 'user-1', > organizationId: 'org-1', > name: 'User One', > email: 'user@example.com', > }; > > export default function App() { > return ( > > > > > > > ); > } > ``` > [tab] Other Frameworks > > ```ts theme={null} > import { initVelt } from '@veltdev/client'; > import * as monaco from 'monaco-editor'; > import { > addComment, > registerVeltComments, > renderComments, > } from '@veltdev/monaco-velt-comments'; > > const client = await initVelt('API_KEY'); > await client.identify({ > userId: 'user-1', > organizationId: 'org-1', > name: 'User One', > email: 'user@example.com', > }); > > client.setDocument('monaco-comments-doc', { > documentName: 'Monaco Comments Document', > }); > > const editor = monaco.editor.create(document.querySelector('#editor'), { > value: 'const greeting = "hello world";\n', > language: 'typescript', > automaticLayout: true, > wordWrap: 'on', > }); > > const editorId = 'main-editor'; > const handle = registerVeltComments(editor, { editorId }); > const commentElement = Velt.getCommentElement(); > > commentElement.getAllCommentAnnotations().subscribe((commentAnnotations) => { > renderComments({ > editor, > editorId, > commentAnnotations, > }); > }); > > const addCommentButton = document.querySelector('#add-comment'); > addCommentButton.addEventListener('mousedown', (event) => { > event.preventDefault(); > }); > addCommentButton.addEventListener('click', () => { > void addComment({ editor, editorId }); > }); > > window.addEventListener('beforeunload', () => { > handle.dispose(); > editor.dispose(); > }); > ``` ## APIs #### [registerVeltComments()](/docs/api-reference/sdk/api/api-methods#registerveltcomments) Registers the Velt comments integration on a Monaco editor instance. The call is idempotent per editor and returns a handle that tears down editor listeners, tracking decorations, overlay elements, renderer state, and local selected-comment subscriber cleanup. * Params: * `editor`: Monaco `IStandaloneCodeEditor` instance. * `config`: [`MonacoVeltCommentsConfig`](/docs/api-reference/sdk/models/data-models#monacoveltcommentsconfig). (optional) * Returns: [`VeltCommentsHandle`](/docs/api-reference/sdk/models/data-models#veltcommentshandle) > [tab] React / Next.js > > ```tsx theme={null} > import { registerVeltComments } from '@veltdev/monaco-velt-comments'; > > const handle = registerVeltComments(editor, { > editorId: 'my-editor', > }); > > handle.dispose(); > ``` > [tab] Other Frameworks > > ```ts theme={null} > import { registerVeltComments } from '@veltdev/monaco-velt-comments'; > > const handle = registerVeltComments(editor, { > editorId: 'my-editor', > }); > > handle.dispose(); > ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-11) Creates a Velt comment annotation for the currently selected Monaco text. The selected text and its occurrence index are stored in `annotation.context.textEditorConfig`; the document content is not modified. * Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-10) * Returns: `Promise` > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/monaco-velt-comments'; > > await addComment({ > editor, > editorId: 'my-editor', > context: { > fileId: 'file-123', > language: 'typescript', > }, > }); > ``` > [tab] Other Frameworks > > ```ts theme={null} > import { addComment } from '@veltdev/monaco-velt-comments'; > > await addComment({ > editor, > editorId: 'my-editor', > context: { > fileId: 'file-123', > language: 'typescript', > }, > }); > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-11) Resolves Velt comment annotations to Monaco ranges and renders them as stable `` overlay elements positioned over the commented text. * Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-10) * Returns: `void` > [tab] React / Next.js > > ```tsx theme={null} > import { renderComments } from '@veltdev/monaco-velt-comments'; > > renderComments({ > editor, > editorId: 'my-editor', > commentAnnotations: commentAnnotations ?? [], > }); > ``` > [tab] Other Frameworks > > ```ts theme={null} > import { renderComments } from '@veltdev/monaco-velt-comments'; > > renderComments({ > editor, > editorId: 'my-editor', > commentAnnotations, > }); > ``` #### [isVeltAvailable()](/docs/api-reference/sdk/api/api-methods#isveltavailable) Checks whether the Velt SDK is loaded on `window.Velt`. * Params: none * Returns: `boolean` > [tab] React / Next.js > > ```tsx theme={null} > import { isVeltAvailable, renderComments } from '@veltdev/monaco-velt-comments'; > > if (isVeltAvailable()) { > renderComments({ editor, editorId: 'my-editor', commentAnnotations }); > } > ``` > [tab] Other Frameworks > > ```ts theme={null} > import { isVeltAvailable, renderComments } from '@veltdev/monaco-velt-comments'; > > if (isVeltAvailable()) { > renderComments({ editor, editorId: 'my-editor', commentAnnotations }); > } > ``` # Nutrient Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/nutrient Add Velt text comments to a Nutrient Web SDK PDF viewer with the Velt Nutrient comments extension. ![Add text comments in an editor](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) The Nutrient integration renders each Velt comment as a view-only overlay positioned over the commented PDF text with Nutrient `CustomOverlayItem`s. It does not modify your PDF. Comment anchors are stored as a durable `{ text, pageNumber, occurrence }` object and re-resolved against the page text whenever comments render. ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. This component is required to create and render comments in your app. * Authenticate the user with `authProvider` and set the Velt document before users add comments. * Set the `textMode` prop to `false` to hide the default Velt text comment tool. Nutrient selections are handled by `@veltdev/nutrient-velt-comments`. * Add `VeltCommentsSidebar` if you want a Google Docs-style comment sidebar. > [tab] React / Next.js > > ```tsx theme={null} > import { VeltComments, VeltCommentsSidebar, VeltProvider, useSetDocument } from '@veltdev/react'; > > const user = { > userId: 'user-1', > organizationId: 'org-1', > name: 'User One', > email: 'user@example.com', > }; > > function VeltSetup() { > useSetDocument('document-id', { documentName: 'Document name' }); > return null; > } > > function App() { > return ( > > > > > {/* Your app content */} > > ); > } > ``` #### Step 2: Install the Velt Nutrient extension ```bash theme={null} npm i @veltdev/nutrient-velt-comments @nutrient-sdk/viewer@1.15.1 ``` `@nutrient-sdk/viewer` is a peer dependency used for types. Use the same Nutrient version that you load from the CDN script. Load the Nutrient Web SDK at runtime so your app does not bundle the browser-only PDF viewer and WebAssembly assets. > [tab] React / Next.js > > ```tsx theme={null} > import Script from 'next/script'; > > const NUTRIENT_CDN_SCRIPT = > 'https://cdn.cloud.nutrient.io/pspdfkit-web@1.15.1/nutrient-viewer.js'; > > export default function RootLayout({ children }: { children: React.ReactNode }) { > return ( > > >
``` # Plate Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/plate ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) > [!NOTE] > > Plate.js is a React-only framework. This guide covers the React integration only. ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. * This component is required to render comments in your app. * Set the `text mode` prop to `false` to hide the default text comment tool. > [tab] React / Next.js > > ```js theme={null} > > > > ``` #### Step 2: Install the Velt Plate extension ```bash theme={null} npm i @veltdev/plate-comments-react ``` #### Step 3: Configure the Plate editor with the Velt Comments extension * Import `VeltCommentsPlugin` and add it to your Plate editor's plugins array. > [tab] React / Next.js > > ```js theme={null} > import { Plate, PlateContent, usePlateEditor } from '@platejs/core/react'; > import { VeltCommentsPlugin } from '@veltdev/plate-comments-react'; > > function PlateEditor() { > const editor = usePlateEditor({ > plugins: [VeltCommentsPlugin], > value: initialValue, // Your initial editor content > }); > > return ( > > > > ); > } > ``` #### Step 4: Add a comment button to your Plate editor * Add a button that users can click to add comments after selecting text. * Use `onMouseDown` with `preventDefault` to preserve the editor selection when clicking the button. > [tab] React / Next.js > > ```js theme={null} > import { Plate, PlateContent, usePlateEditor } from '@platejs/core/react'; > import { VeltCommentsPlugin, addComment } from '@veltdev/plate-comments-react'; > > function PlateEditor() { > const editor = usePlateEditor({ > plugins: [VeltCommentsPlugin], > value: initialValue, > }); > > const handleAddComment = () => { > if (editor) { > addComment({ editor }); > } > }; > > return ( >
> > > > >
> ); > } > ``` #### Step 5: Call `addComment` to add a comment * Call this method to add a comment to selected text in the Plate editor. You can use this when the user clicks on the comment button or presses a keyboard shortcut. * Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-4). It has the following properties: * `editor`: Instance of the Plate editor. * `editorId`: Id of the Plate editor. Use this if you have multiple Plate editors on the same page in your app. (optional) * `context`: Add any custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional) > [tab] React / Next.js > > ```js theme={null} > import { addComment } from '@veltdev/plate-comments-react'; > > const addCommentRequest = { > editor, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > addComment(addCommentRequest); > ``` #### Step 6: Render comments in Plate editor * Get the comment data from Velt SDK using the `useCommentAnnotations` hook and render it in the Plate editor. * Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-4). It has the following properties: * `editor`: Instance of the Plate editor. * `editorId`: Id of the Plate editor. Use this if you have multiple Plate editors on the same page in your app. (optional) * `commentAnnotations`: Array of Comment Annotation objects. > [tab] React / Next.js > > ```js theme={null} > import { useEffect } from 'react'; > import { renderComments } from '@veltdev/plate-comments-react'; > import { useCommentAnnotations } from '@veltdev/react'; > > function PlateEditor() { > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (editor && annotations) { > renderComments({ > editor, > editorId: 'EDITOR_ID', > commentAnnotations: annotations, > }); > } > }, [editor, annotations]); > > // ... rest of component > } > ``` #### Step 7: Persist Velt Comment Marks (optional) * By default, Velt comment marks are persisted by the Velt SDK. When the editor loads and the Velt SDK initializes, the marks will be automatically added to the editor. * If you plan to store the contents of the Plate editor on your end with the comment marks already included, you can disable this feature. * Default: `true` ```js theme={null} const editor = usePlateEditor({ plugins: [ VeltCommentsPlugin.configure({ options: { persistVeltMarks: false, }, }), ], }); ``` #### Step 8: Style the commented text * You can style the commented text by adding CSS for the `velt-comment-text` element. ```css theme={null} velt-comment-text { background-color: rgba(255, 255, 0, 0.3); border-bottom: 2px solid #ffcc00; cursor: pointer; } velt-comment-text:hover { background-color: rgba(255, 255, 0, 0.5); } velt-comment-text.velt-comment-selected { background-color: rgba(255, 255, 0, 0.5); } ``` ## APIs #### [VeltCommentsPlugin.configure()](/docs/api-reference/sdk/api/api-methods#veltcommentsplugin-configure) A Plate.js plugin for Velt Comments integration. * Params: `options?:` [VeltCommentsPluginConfig](/docs/api-reference/sdk/models/data-models#veltcommentspluginconfig) * `editorId?: string` - Unique identifier for this editor instance (for multi-editor scenarios). * `persistVeltMarks?: boolean` - Whether to persist Velt marks. Default: `true`. * Returns: Plate Plugin > [tab] React / Next.js > > ```tsx theme={null} > import { usePlateEditor } from '@platejs/core/react'; > import { VeltCommentsPlugin } from '@veltdev/plate-comments-react'; > > // Basic usage > const editor = usePlateEditor({ > plugins: [VeltCommentsPlugin], > }); > > // With configuration > const editor = usePlateEditor({ > plugins: [ > VeltCommentsPlugin.configure({ > options: { > editorId: 'my-editor', > persistVeltMarks: true, > }, > }), > ], > }); > ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-4) Creates a comment annotation for the currently selected text in the editor. * Params: * `request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest-4) * `editor: PlateEditor` * `editorId?: string` * `context?: object` * Returns: `Promise` > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/plate-comments-react'; > > > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-4) Renders and highlights comment annotations in the editor. * Params: * `request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-4) * `editor: PlateEditor` * `editorId?: string` * `commentAnnotations?:` [CommentAnnotation\[\]](/docs/api-reference/sdk/models/data-models#commentannotation) * Returns: `void` > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { renderComments } from '@veltdev/plate-comments-react'; > import { useCommentAnnotations } from '@veltdev/react'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (editor && annotations) { > renderComments({ > editor, > editorId: 'my-editor', > commentAnnotations: annotations, > }); > } > }, [editor, annotations]); > ``` #### [exportJSONWithoutComments()](/docs/api-reference/sdk/api/api-methods#exportjsonwithoutcomments-2) Exports the editor content as JSON with Velt comment elements removed. Useful when saving content to your backend without comment markup. * Params: `content: Descendant[]` - The editor content (Slate nodes). * Returns: `Descendant[]` - Content with comment elements removed. > [tab] React / Next.js > > ```tsx theme={null} > import { exportJSONWithoutComments } from '@veltdev/plate-comments-react'; > > const saveContent = () => { > const cleanContent = exportJSONWithoutComments(editor.children); > // Save cleanContent to your backend > }; > ``` #### PlateVeltComment React component for rendering Velt comment elements in the editor. This is automatically used by the plugin, but can be referenced for custom render element implementations. > [tab] React / Next.js > > ```tsx theme={null} > import { PlateVeltComment, VeltCommentsElement } from '@veltdev/plate-comments-react'; > > const renderElement = (props) => { > if (props.element.type === 'veltComment') { > return ; > } > // ... other elements > }; > ``` # Popover Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/popover ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Cell-Comment.gif?s=df0ac829cfa2bf8c2a47cce2d565fc37) ## Step 1: Import Comment components > [tab] React / Next.js > > Import the `VeltComments`, `VeltCommentTool`, and `VeltCommentBubble` components. > > ```js theme={null} > import { > VeltProvider, > VeltComments, > VeltCommentTool, > VeltCommentBubble > } from '@veltdev/react'; > ``` > [tab] HTML > > No imports needed. The Velt SDK is loaded via script tag. ## Step 2: Add Comments component with Popover mode Add the Comments component to the root of your app and enable Popover mode. This component is required to render comments in your app. Popover mode means comments can be attached to specific target elements (similar to Google Sheets). > [tab] React / Next.js > > ```js theme={null} > > > > ``` > [tab] Other Frameworks > > Add the comment component to your template close to the root level of your ``. > > ```html theme={null} > > > > ``` ## Step 3: Add the Comment Tool component There are two patterns for adding the Comment Tool: * Add a Comment Tool next to each element you want to comment on * Have a single Comment Tool and use it to pin comments on elements ### a. Comment Tool next to each element Add a Comment Tool near each cell or element you want to comment on. For example, in a table you could add this tool to each cell and show it on hover or right click context menu. * Add unique DOM ID to each element * Set the `targetElementId` to match the element's ID * When users click on the Comment Tool, it attaches a Comment to that element * If your app is more complex and cannot have unique IDs for each element (e.g., table cell), you could also use `context` to bind the element and comment with custom metadata, which can then be used to filter, group, and render comments that match specific criteria. [Learn more](/docs/async-collaboration/comments/customize-behavior#aggregation) ![](https://mintcdn.com/velt/2O8vk8YlVD4Kq-ni/images/comment-tool.png?fit=max\&auto=format\&n=2O8vk8YlVD4Kq-ni\&q=85\&s=f6542acc54050b4b607812391c0b97ad) Once the Comment is added, you'll see a triangle on the top right corner of the element. ![](https://mintcdn.com/velt/vGgIoGfoceFP8dEI/images/popover-comment-show.png?fit=max\&auto=format\&n=vGgIoGfoceFP8dEI\&q=85\&s=fb9f1f0e706b14296b86d255dfcb7284) > [tab] React / Next.js > > ```jsx theme={null} >
>
> >
>
> >
>
> ``` > [tab] HTML > > ```html theme={null} >
>
> >
>
> >
>
> ``` ### b. Single Comment Tool ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/freestyle-popover.gif?s=ed078b4a7a751aee1e0f2aab6361b4c2) Add a Comment Tool in a single location such as the navigation bar. * Add unique DOM ID and `data-velt-target-comment-element-id` attribute to each element (both with the same value) * When users click on the Comment Tool and then click on the target element, it attaches a Comment to it * You can only add one Comment Annotation (thread) per element with this approach * If your app is more complex and cannot have unique IDs for each element (e.g., table cell), you could also use `context` to bind the element and comment with custom metadata, which can then be used to filter, group, and render comments that match specific criteria. [Learn more](/docs/async-collaboration/comments/customize-behavior#aggregation) > [!WARNING] > > If you don't add the `data-velt-target-comment-element-id` attribute, you will be adding multiple Comment Annotations on the same element. > [tab] React / Next.js > > ```jsx theme={null} >
> >
>
>
>
>
>
>
> ``` > [tab] HTML > > ```html theme={null} >
> >
>
>
>
>
>
>
> ``` ## Step 4: Add Metadata to the Comment * Render additional data on comments UI * Create custom UI components * Enable comment filtering on custom data * Use the metadata later when processing notifications ### a. Using Comment Tool > [tab] React / Next.js > > ```jsx theme={null} > > ``` > [tab] HTML > > ```html theme={null} > > ``` ### b. Using Comment Add Event Callback Learn more about it [here](/docs/async-collaboration/comments/customize-behavior#addcontext). ## Step 5: Add the Comment Bubble component (optional) ![](https://mintcdn.com/velt/vGgIoGfoceFP8dEI/images/popover-bubble.png?fit=max\&auto=format\&n=vGgIoGfoceFP8dEI\&q=85\&s=877e3867de36da7674269cf22f068a7b) > [!WARNING] > > Either use this or the default triangle component. Using both could cause visual UX issues. Turn off the triangle by setting `popoverTriangleComponent` to `false` in the Velt Comments component. The Comment Bubble component: * Displays a count of replies for a comment thread * Must have the same `targetElementId` or `context` as its associated element and comment tool * Can show either total replies or only unread replies * Can be placed anywhere in your UI **Props:** * `commentCountType`: Which count to display * `total`: Total number of replies (default) * `unread`: Number of unread replies > [tab] React / Next.js > > ```js theme={null} >
>
> > commentCountType="unread" > targetElementId="cell-id-1" > /> >
>
> > commentCountType="unread" > targetElementId="cell-id-2" > /> >
>
> ``` > [tab] HTML > > ```html theme={null} >
>
> > comment-count-type="unread" > target-element-id="cell-id-1" > > >
>
> > comment-count-type="unread" > target-element-id="cell-id-2" > > >
>
> ``` ### Remove Popover Mode Triangle (optional) ![](https://mintcdn.com/velt/vGgIoGfoceFP8dEI/images/popover-comment-pin.png?fit=max\&auto=format\&n=vGgIoGfoceFP8dEI\&q=85\&s=1143f721774cb8eed6085c9a0d43079a) You can remove the triangle that appears in Popover mode. By default, the triangle is enabled. > [tab] React / Next.js > > ```jsx theme={null} > > ``` > > API Method: > > ```jsx theme={null} > const commentElement = client.getCommentElement(); > commentElement.enablePopoverTriangleComponent(); > commentElement.disablePopoverTriangleComponent(); > ``` > [tab] HTML > > ```html theme={null} > > ``` > > API Method: > > ```jsx theme={null} > const commentElement = client.getCommentElement(); > commentElement.enablePopoverTriangleComponent(); > commentElement.disablePopoverTriangleComponent(); > ``` ## Step 6: Test Integration Test it out by opening the page with Velt components in your browser. Click on the Comment Tool and leave a comment on the target element. ![](https://mintcdn.com/velt/vGgIoGfoceFP8dEI/images/popover-comment-pin.png?fit=max\&auto=format\&n=vGgIoGfoceFP8dEI\&q=85\&s=1143f721774cb8eed6085c9a0d43079a) ## Complete Example > [tab] React / Next.js > > ```jsx theme={null} > import { > VeltProvider, > VeltComments, > VeltCommentTool, > VeltCommentBubble > } from '@veltdev/react'; > > export default function App() { > return ( > > > > {/* Pattern a: Comment Tool next to each element */} >
>
> > >
>
> >
>
> > {/* Pattern b: Single Comment Tool */} >
> >
>
> Content >
>
> Content >
>
>
>
> ); > } > ``` > [tab] HTML > > ```html theme={null} > > > > >
>
> > >
>
> >
>
> > >
> >
>
> Content >
>
> Content >
>
>
> > ``` # ProseMirror Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/prosemirror ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. * This component is required to render comments in your app. * Set the `text mode` prop to `false` to hide the default text comment tool. > [tab] React / Next.js > > ```js theme={null} > > > > ``` > [tab] Other Frameworks > > ```html theme={null} > > > > ``` #### Step 2: Install the Velt ProseMirror extension ```bash theme={null} npm i @veltdev/prosemirror-velt-comments prosemirror-model prosemirror-state prosemirror-view ``` For the examples below, also install the standard ProseMirror example packages: ```bash theme={null} npm i prosemirror-schema-basic prosemirror-example-setup ``` #### Step 3: Configure the ProseMirror editor with the Velt Comments plugin Add `VeltCommentsPlugin` to the `plugins` array when creating your `EditorState`. > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect, useRef } from 'react'; > import { schema } from 'prosemirror-schema-basic'; > import { exampleSetup } from 'prosemirror-example-setup'; > import { EditorState } from 'prosemirror-state'; > import { EditorView } from 'prosemirror-view'; > import { VeltCommentsPlugin } from '@veltdev/prosemirror-velt-comments'; > > const EDITOR_ID = 'my-editor'; > > function ProseMirrorEditor() { > const containerRef = useRef(null); > const viewRef = useRef(null); > > useEffect(() => { > if (!containerRef.current) return; > > const state = EditorState.create({ > schema, > plugins: [ > ...exampleSetup({ schema }), > VeltCommentsPlugin({ editorId: EDITOR_ID }), > ], > }); > > const view = new EditorView(containerRef.current, { state }); > viewRef.current = view; > > return () => { > view.destroy(); > viewRef.current = null; > }; > }, []); > > return
; > } > ``` > [tab] Other Frameworks > > ```js theme={null} > import { schema } from 'prosemirror-schema-basic'; > import { exampleSetup } from 'prosemirror-example-setup'; > import { EditorState } from 'prosemirror-state'; > import { EditorView } from 'prosemirror-view'; > import { VeltCommentsPlugin } from '@veltdev/prosemirror-velt-comments'; > > const state = EditorState.create({ > schema, > plugins: [ > ...exampleSetup({ schema }), > VeltCommentsPlugin({ editorId: 'my-editor' }), > ], > }); > > const view = new EditorView(document.querySelector('#editor'), { state }); > ``` #### Step 4: Add a comment button to your ProseMirror editor Add a button that users can click to add comments after selecting text in the ProseMirror editor. **Important:** Use `onMouseDown` with `preventDefault()` so the browser does not move focus away from the editor before `addComment` reads the current selection. > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/prosemirror-velt-comments'; > > const handleAddComment = () => { > if (!viewRef.current) return; > > addComment({ > editor: viewRef.current, > editorId: EDITOR_ID, > }); > }; > > > ``` > [tab] Other Frameworks > > ```js theme={null} > import { addComment } from '@veltdev/prosemirror-velt-comments'; > > const addCommentButton = document.querySelector('#add-comment'); > > addCommentButton.addEventListener('mousedown', (event) => { > event.preventDefault(); > }); > > addCommentButton.addEventListener('click', () => { > addComment({ editor: view, editorId: 'my-editor' }); > }); > ``` #### Step 5: Call `addComment` to add a comment * Call this method to add a comment to selected text in the ProseMirror editor. * Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-8). It has the following properties: * `editor`: ProseMirror `EditorView`. * `editorId`: Id of the editor. Use this if you have multiple ProseMirror editors on the same page. (optional) * `context`: Add custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional) > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/prosemirror-velt-comments'; > > const addCommentRequest = { > editor: viewRef.current, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > addComment(addCommentRequest); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { addComment } from '@veltdev/prosemirror-velt-comments'; > > const addCommentRequest = { > editor: view, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > addComment(addCommentRequest); > ``` #### Step 6: Render comments in ProseMirror editor * Get the comment data from Velt SDK and render it in the ProseMirror editor. * Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-8). It has the following properties: * `editor`: ProseMirror `EditorView`. * `editorId`: Id of the editor. Use this if you have multiple ProseMirror editors on the same page. (optional) * `commentAnnotations`: Array of Comment Annotation objects. > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { useCommentAnnotations } from '@veltdev/react'; > import { renderComments } from '@veltdev/prosemirror-velt-comments'; > > const commentAnnotations = useCommentAnnotations(); > > useEffect(() => { > if (!viewRef.current) return; > > renderComments({ > editor: viewRef.current, > editorId: 'EDITOR_ID', > commentAnnotations: commentAnnotations ?? [], > }); > }, [commentAnnotations]); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { renderComments } from '@veltdev/prosemirror-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > renderComments({ > editor: view, > editorId: 'EDITOR_ID', > commentAnnotations: annotations, > }); > }); > ``` #### Step 7: Re-apply ProseMirror comment highlights (optional) * ProseMirror renders comment highlights as view-only overlay elements. * The integration does not write Velt comment marks into your ProseMirror schema or saved document. * Save your ProseMirror document normally. After you recreate the `EditorView` or replace document content, call `renderComments` again. ```ts theme={null} const json = view.state.doc.toJSON(); // Save json to your backend. renderComments({ editor: view, editorId: 'EDITOR_ID', commentAnnotations, }); ``` #### Step 8: Style the commented text * You can style the commented text by adding CSS for the `velt-comment-text` element. * Use the `comment-available` attribute to apply styles only after comment data has loaded. ```css theme={null} velt-comment-text[comment-available="true"] { background-color: rgba(255, 255, 0, 0.3); border-bottom: 2px solid #ffcc00; cursor: pointer; } velt-comment-text[comment-available="true"]:hover { background-color: rgba(255, 255, 0, 0.5); } velt-comment-text.velt-comment-selected { background-color: rgba(255, 255, 0, 0.5); } ``` ## Complete Example [https://sample-apps-prosemirror-comments-demo.vercel.app/](https://sample-apps-prosemirror-comments-demo.vercel.app/) ## APIs #### [VeltCommentsPlugin()](/docs/api-reference/sdk/api/api-methods#veltcommentsplugin) Creates the ProseMirror plugin that powers Velt comments. Add it to your editor state's `plugins` array. * Params: `config?:` [`VeltCommentsPluginConfig`](/docs/api-reference/sdk/models/data-models#veltcommentspluginconfig-1) * Returns: ProseMirror `Plugin` > [tab] React / Next.js > > ```tsx theme={null} > import { schema } from 'prosemirror-schema-basic'; > import { exampleSetup } from 'prosemirror-example-setup'; > import { EditorState } from 'prosemirror-state'; > import { VeltCommentsPlugin } from '@veltdev/prosemirror-velt-comments'; > > const state = EditorState.create({ > schema, > plugins: [ > ...exampleSetup({ schema }), > VeltCommentsPlugin({ editorId: 'my-editor' }), > ], > }); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { VeltCommentsPlugin } from '@veltdev/prosemirror-velt-comments'; > > VeltCommentsPlugin({ editorId: 'my-editor' }); > ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-9) Creates a comment annotation for the currently selected text in the editor. * Signature: `async (request:` [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-8)`) => Promise` * Params: `request:` [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-8) * Returns: `Promise` > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/prosemirror-velt-comments'; > > const handleAddComment = () => { > if (!viewRef.current) return; > addComment({ editor: viewRef.current, editorId: 'my-editor' }); > }; > > > ``` > [tab] Other Frameworks > > ```js theme={null} > import { addComment } from '@veltdev/prosemirror-velt-comments'; > > addComment({ > editor: view, > editorId: 'my-editor', > context: { customData: 'value' }, > }); > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-9) Renders and highlights comment annotations in the ProseMirror editor. * Signature: `(request:` [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-8)`) => void` * Params: `request:` [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-8) * Returns: `void` > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { useCommentAnnotations } from '@veltdev/react'; > import { renderComments } from '@veltdev/prosemirror-velt-comments'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (!viewRef.current) return; > > renderComments({ > editor: viewRef.current, > editorId: 'my-editor', > commentAnnotations: annotations ?? [], > }); > }, [annotations]); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { renderComments } from '@veltdev/prosemirror-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > renderComments({ > editor: view, > editorId: 'my-editor', > commentAnnotations: annotations, > }); > }); > ``` #### [veltCommentsPluginKey](/docs/api-reference/sdk/api/api-methods#veltcommentspluginkey) The ProseMirror `PluginKey` used by the package. Use it only for advanced inspection of plugin state. * Params: none * Returns: `PluginKey` ```ts theme={null} import { veltCommentsPluginKey } from '@veltdev/prosemirror-velt-comments'; const state = veltCommentsPluginKey.getState(view.state); const anchors = state?.anchors; ``` # Quill Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/quill ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. * This component is required to render comments in your app. * Set the `text mode` prop to `false` to hide the default text comment tool. > [tab] React / Next.js > > ```js theme={null} > > > > ``` > [tab] Other Frameworks > > ```html theme={null} > > > > ``` #### Step 2: Install the Velt Quill extension ```bash theme={null} npm i @veltdev/quill-velt-comments ``` #### Step 3: Configure the Quill editor with the Velt Comments module > [tab] React / Next.js > > ```js theme={null} > import { useEffect, useRef, useState } from 'react'; > import Quill from 'quill'; > import { QuillVeltComments } from '@veltdev/quill-velt-comments'; > > // Register the module with Quill (once, outside component) > Quill.register('modules/veltComments', QuillVeltComments); > > function QuillEditor() { > const editorRef = useRef(null); > const [quill, setQuill] = useState(null); > > useEffect(() => { > if (!editorRef.current) return; > > const quillInstance = new Quill(editorRef.current, { > theme: 'snow', > modules: { > veltComments: { > persistVeltMarks: true, > }, > }, > }); > > setQuill(quillInstance); > }, []); > > return
; > } > ``` > [tab] Other Frameworks > > ```js theme={null} > import Quill from 'quill'; > import { QuillVeltComments } from '@veltdev/quill-velt-comments'; > > // Register the module with Quill > Quill.register('modules/veltComments', QuillVeltComments); > > // Create editor with the module enabled > const quill = new Quill('#editor', { > theme: 'snow', > modules: { > veltComments: { > persistVeltMarks: true, > }, > }, > }); > ``` #### Step 4: Add a comment button to your Quill editor Add a button that users can click to add comments after selecting text. > [!WARNING] > > When clicking a button, the browser moves focus to the button which clears the editor selection. You must save the selection on `mousedown` (before focus changes) and restore it before adding the comment. > [tab] React / Next.js > > ```js theme={null} > import { useCallback, useRef } from 'react'; > import { addComment } from '@veltdev/quill-velt-comments'; > > // Inside your QuillEditor component from Step 3: > const savedSelectionRef = useRef(null); > > const handleAddComment = useCallback(() => { > if (quill) { > if (savedSelectionRef.current) { > quill.setSelection(savedSelectionRef.current.index, savedSelectionRef.current.length); > } > addComment({ editor: quill }); > savedSelectionRef.current = null; > } > }, [quill]); > > // In your JSX: > > ``` > [tab] Other Frameworks > > ```html theme={null} > >
> ``` > > ```js theme={null} > import { addComment } from '@veltdev/quill-velt-comments'; > > let savedSelection = null; > const btn = document.getElementById('add-comment-btn'); > > btn.addEventListener('mousedown', () => { > const sel = quill.getSelection(); > if (sel && sel.length > 0) savedSelection = sel; > }); > > btn.addEventListener('click', () => { > if (savedSelection) quill.setSelection(savedSelection.index, savedSelection.length); > addComment({ editor: quill }); > savedSelection = null; > }); > ``` > [!TIP] > > Unlike Tiptap, Quill does not have a built-in bubble menu. You will need to create your own comment button or toolbar item. #### Step 5: Call `addComment` to add a comment * Call this method to add a comment to selected text in the Quill editor. You can use this when the user clicks on the comment button or presses a keyboard shortcut. * Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-6). It has the following properties: * `editor`: Instance of the Quill editor. * `editorId`: Id of the Quill editor. Use this if you have multiple Quill editors on the same page. (optional) * `context`: Add any custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional) > [tab] React / Next.js > > ```js theme={null} > import { addComment } from '@veltdev/quill-velt-comments'; > > const addCommentRequest = { > editor: quill, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > addComment(addCommentRequest); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { addComment } from '@veltdev/quill-velt-comments'; > > const addCommentRequest = { > editor: quill, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > addComment(addCommentRequest); > ``` #### Step 6: Render comments in Quill editor * Get the comment data from Velt SDK and render it in the Quill editor. * Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-6). It has the following properties: * `editor`: Instance of the Quill editor. * `editorId`: Id of the Quill editor. Use this if you have multiple Quill editors on the same page. (optional) * `commentAnnotations`: Array of Comment Annotation objects. > [tab] React / Next.js > > ```js theme={null} > import { renderComments } from '@veltdev/quill-velt-comments'; > import { useCommentAnnotations } from '@veltdev/react'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (quill && annotations?.length) { > const renderCommentsRequest = { > editor: quill, > editorId: 'EDITOR_ID', > commentAnnotations: annotations, > }; > renderComments(renderCommentsRequest); > } > }, [quill, annotations]); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { renderComments } from '@veltdev/quill-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > if (quill && annotations?.length) { > const renderCommentsRequest = { > editor: quill, > editorId: 'EDITOR_ID', > commentAnnotations: annotations, > }; > renderComments(renderCommentsRequest); > } > }); > ``` #### Step 7: Persist Velt Comment Marks (optional) * By default, Velt comment marks (``) are persisted by the Velt SDK. When the editor loads and the Velt SDK initializes, the marks will be automatically added to the editor. * If you plan to store the contents of the Quill editor on your end with the comment marks already included, you can disable this feature. * Default: `true` ```js theme={null} const quill = new Quill(editorRef.current, { theme: 'snow', modules: { veltComments: { persistVeltMarks: false, }, }, }); ``` #### Step 8: Style the commented text * You can style the commented text by adding CSS for the `velt-comment-text` element. ```css theme={null} velt-comment-text { background-color: rgba(255, 255, 0, 0.3); border-bottom: 2px solid #ffcc00; cursor: pointer; } velt-comment-text:hover { background-color: rgba(255, 255, 0, 0.5); } velt-comment-text.velt-comment-selected { background-color: rgba(255, 255, 0, 0.5); } ``` ## APIs #### [QuillVeltComments](/docs/api-reference/sdk/api/api-methods#quillveltcomments) The Velt Comments module for Quill. Register it with Quill before creating the editor. * Params: `options?:` [QuillVeltCommentsConfig](/docs/api-reference/sdk/models/data-models#quillveltcommentsconfig) * `editorId?: string` - Unique identifier for this editor instance (for multi-editor scenarios) * `persistVeltMarks?: boolean` - Whether to persist Velt marks. Default: `true` * Returns: `Quill Module` > [tab] React / Next.js > > ```tsx theme={null} > import Quill from 'quill'; > import { QuillVeltComments } from '@veltdev/quill-velt-comments'; > > Quill.register('modules/veltComments', QuillVeltComments); > > const quillInstance = new Quill(editorRef.current, { > theme: 'snow', > modules: { > veltComments: { > editorId: 'my-editor', > persistVeltMarks: true, > }, > }, > }); > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import Quill from 'quill'; > import { QuillVeltComments } from '@veltdev/quill-velt-comments'; > > Quill.register('modules/veltComments', QuillVeltComments); > > const quill = new Quill('#editor', { > theme: 'snow', > modules: { > veltComments: { > editorId: 'my-editor', > persistVeltMarks: true, > }, > }, > }); > ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-6) Creates a comment annotation for the currently selected text in the editor. * Params: * `request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest-6) * `editor: Quill` * `editorId?: string` * `context?: object` * Returns: `Promise` > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/quill-velt-comments'; > > > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import { addComment } from '@veltdev/quill-velt-comments'; > > addComment({ > editor: quill, > editorId: 'my-editor', > context: { customData: 'value' }, > }); > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-6) Renders and highlights comment annotations in the editor. * Params: * `request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-6) * `editor: Quill` * `editorId?: string` * `commentAnnotations?:` [CommentAnnotation\[\]](/docs/api-reference/sdk/models/data-models#commentannotation) * Returns: `void` > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { renderComments } from '@veltdev/quill-velt-comments'; > import { useCommentAnnotations } from '@veltdev/react'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (quill && annotations) { > renderComments({ > editor: quill, > editorId: 'my-editor', > commentAnnotations: annotations, > }); > } > }, [quill, annotations]); > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import { renderComments } from '@veltdev/quill-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > if (quill && annotations) { > renderComments({ > editor: quill, > editorId: 'my-editor', > commentAnnotations: annotations, > }); > } > }); > ``` # SlateJS Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/slatejs ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. * This component is required to render comments in your app. * Set the `text mode` prop to `false` to hide the default text comment tool. > [tab] React / Next.js > > ```js theme={null} > > > > ``` #### Step 2: Install the Velt SlateJS extension ```bash theme={null} npm i @veltdev/slate-velt-comments ``` #### Step 3: Configure the SlateJS editor with the Velt Comments extension > [tab] React / Next.js > > ```js theme={null} > import { withVeltComments } from '@veltdev/slate-velt-comments'; > import { withReact, withHistory } from 'slate-react'; > > const editor = withVeltComments( > withReact(withHistory(createEditor())), > { HistoryEditor: SlateHistoryEditor } > ); > ``` #### Step 4: Register Velt component type in SlateJS * Register the Velt Comments Element type with your SlateJS editor's custom types. * This ensures proper type checking for the comments functionality. > [tab] React / Next.js > > ```ts theme={null} > import type { VeltCommentsElement } from '@veltdev/slate-velt-comments'; > > type CustomElement = VeltCommentsElement; > > declare module 'slate' { > interface CustomTypes { > Element: CustomElement; > } > } > ``` #### Step 5: Add a comment button to your SlateJS editor * Add a button that appears in the context menu of your SlateJS editor when the user selects text. * This button will be used to add a comment to the selected text. > [tab] React / Next.js > > ```js theme={null} > import { addComment } from '@veltdev/slate-velt-comments'; > import { useSlate } from 'slate-react'; > > const CommentButton = (props) => { > const editor = useSlate(); > > return ( > > ); > }; > ``` #### Step 6: Call `addComment` to add a comment * Call this method to add a comment to selected text in the SlateJS editor. You can use this when the user clicks on the comment button in context menu or presses a keyboard shortcut. * Params: `AddCommentRequest` * `editorId`: string, the id of the editor. Use this if you have multiple editors in your app. * `editor`: instance of the SlateJS editor. * `context`: optional object to set the Comment Annotation's [custom metadata](/docs/async-collaboration/comments/customize-behavior#metadata). > [tab] React / Next.js > > ```js theme={null} > import { addComment } from '@veltdev/slate-velt-comments'; > import { useSlate } from 'slate-react'; > > const CommentButton = (props) => { > const editor = useSlate(); > > return ( > > ); > }; > ``` #### Step 7: Render comments in SlateJS editor * Get the comment data. * Render the comments in the SlateJS editor. * Params: `RenderCommentsRequest` * `editorId`: string, the id of the editor. Use this if you have multiple editors in your app. * `editor`: instance of the SlateJS editor. * `commentAnnotations`: CommentAnnotation\[] > [tab] React / Next.js > > ```js theme={null} > import { renderComments } from '@veltdev/slate-velt-comments'; > > const commentAnnotations = useCommentAnnotations(); > > useEffect(() => { > if (editor && commentAnnotations) { > renderComments({ editor, commentAnnotations }); > } > }, [commentAnnotations, editor]); > ``` #### Step 8: Style the commented text * You can style the commented text by adding a CSS class to the `velt-comment-text` element. * By using the `comment-available` attribute, you can apply styles only when the comment data has loaded. ```css theme={null} velt-comment-text[comment-available="true"] { background-color: #ffff00; } ``` ## Complete Example [https://slatejs-app-demo.vercel.app/](https://slatejs-app-demo.vercel.app/) ## APIs #### [withVeltComments()](/docs/api-reference/sdk/api/api-methods#withveltcomments) Augment a Slate editor with Velt Comments support (adds schema/commands/normalizers). * Params: * `editor: Editor` * `options?: VeltCommentsEditorOptions` * Returns: `VeltCommentsEditor` > [tab] React / Next.js > > ```jsx theme={null} > import { withVeltComments } from '@veltdev/slate-velt-comments'; > import { withReact, withHistory } from 'slate-react'; > > const editor = withVeltComments( > withReact(withHistory(createEditor())), > { HistoryEditor: SlateHistoryEditor } > ); > ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment) Creates a comment annotation for the currently selected text in the editor. * Signature: `async (request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest)`) => Promise` * Params: `request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest) * Returns: `Promise` > [tab] React / Next.js > > ```jsx theme={null} > import { addComment } from '@veltdev/slate-velt-comments'; > > > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments) Renders and highlights comment annotations in the editor. * Signature: `(request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest)`) => void` * Params: `request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest) * Returns: `void` > [tab] React / Next.js > > ```jsx theme={null} > import { renderComments } from '@veltdev/slate-velt-comments'; > import type { CommentAnnotation } from '@veltdev/types'; > > useEffect(() => { > if (editor && commentAnnotations) { > renderComments({ editor, commentAnnotations }); > } > }, [editor, commentAnnotations]); > ``` #### [SlateVeltComment](/docs/api-reference/sdk/api/api-methods#slateveltcomment) React component that renders a Velt comment text element with annotation ID. * Params: * `props: RenderElementProps` * `element:` [VeltCommentsElement](/docs/api-reference/sdk/models/data-models#veltcommentselement) * Returns: `N/A` ```tsx theme={null} import { SlateVeltComment } from '@veltdev/slate-velt-comments'; import type { RenderElementProps } from 'slate-react'; import type { VeltCommentsElement } from '@veltdev/slate-velt-comments'; const RenderElement = (props: RenderElementProps) => { if (props.element.type === 'veltComment') { return ; } return

{props.children}

; }; ``` # SpreadJS Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/spreadjs Add Velt comments to a SpreadJS workbook with the Velt SpreadJS comments extension. ![Add text comments in a spreadsheet](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) The SpreadJS integration renders each Velt comment as a view-only overlay positioned over the commented cell or range. It does not modify your workbook. Comment anchors are stored as durable `{ sheetName, row, col, rowCount, colCount }` data and re-resolved to pixels with SpreadJS cell geometry whenever comments render. ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. This component is required to create and render comments in your app. * Authenticate the user with `authProvider` and set the Velt document before users add comments. * Set the `textMode` prop to `false` to hide the default Velt text comment tool. SpreadJS selections are handled by `@veltdev/spreadjs-velt-comments`. * Add `VeltCommentsSidebar` if you want a Google Docs-style comment sidebar. > [tab] React / Next.js > > ```tsx theme={null} > import { VeltComments, VeltCommentsSidebar, VeltProvider, useSetDocument } from '@veltdev/react'; > > const user = { > userId: 'user-1', > organizationId: 'org-1', > name: 'User One', > email: 'user@example.com', > }; > > function VeltSetup() { > useSetDocument('spreadsheet-id', { documentName: 'Spreadsheet name' }); > return null; > } > > function App() { > return ( > > > > > {/* Your app content */} > > ); > } > ``` #### Step 2: Install the Velt SpreadJS extension ```bash theme={null} npm i @veltdev/spreadjs-velt-comments @mescius/spread-sheets @mescius/spread-sheets-io ``` `@mescius/spread-sheets` is a peer dependency of the Velt SpreadJS package. `@mescius/spread-sheets-io` is required when you import XLSX files into a workbook. > [tab] React / Next.js > > ```tsx theme={null} > import '@mescius/spread-sheets/styles/gc.spread.sheets.excel2013white.css'; > ``` #### Step 3: Configure the SpreadJS workbook with the Velt Comments extension Create the workbook, import your spreadsheet, then attach `SpreadJSVeltComments` after the import completes. The same workbook instance is used by `addComment` and `renderComments`. > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect, useRef, useState } from 'react'; > import { useCommentAnnotations } from '@veltdev/react'; > import { > SpreadJSVeltComments, > renderComments, > type AttachedExtension, > type SpreadInstance, > } from '@veltdev/spreadjs-velt-comments'; > > const EDITOR_ID = 'my-workbook'; > > function SpreadsheetEditor() { > const hostRef = useRef(null); > const workbookRef = useRef(null); > const extensionRef = useRef(null); > const [instance, setInstance] = useState(null); > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (!hostRef.current || workbookRef.current) return; > > let cancelled = false; > const host = hostRef.current; > > import('@mescius/spread-sheets').then(async (spreadModule) => { > const GC = 'default' in spreadModule ? spreadModule.default : spreadModule; > await import('@mescius/spread-sheets-io'); > if (cancelled || workbookRef.current) return; > > const workbook = new GC.Spread.Sheets.Workbook(host); > workbookRef.current = workbook; > > const response = await fetch('/your-workbook.xlsx'); > const file = new File([await response.blob()], 'your-workbook.xlsx'); > > workbook.import( > file, > () => { > if (cancelled) return; > > extensionRef.current = SpreadJSVeltComments > .configure({ editorId: EDITOR_ID }) > .attach(workbook); > setInstance(workbook); > }, > (error: unknown) => console.error('XLSX import failed', error), > { fileType: GC.Spread.Sheets.FileType.excel }, > ); > }); > > return () => { > cancelled = true; > extensionRef.current?.detach(); > workbookRef.current?.destroy(); > workbookRef.current = null; > setInstance(null); > }; > }, []); > > useEffect(() => { > if (!instance) return; > > renderComments({ > instance, > commentAnnotations: annotations ?? [], > }); > }, [instance, annotations]); > > return
; > } > ``` #### Step 4: Add a comment button to your SpreadJS workbook SpreadJS renders the grid to a canvas, so there is no DOM text selection for a default text bubble menu. Add a toolbar button or contextual selection bubble that uses the workbook's selected cell/range state, then call `addComment({ instance })`. > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/spreadjs-velt-comments'; > > const handleAddComment = async () => { > if (!instance) return; > > const result = await addComment({ instance }); > if (!result) { > console.warn('Select a cell or range before adding a comment.'); > } > }; > > > ``` #### Step 5: Call `addComment` to add a comment * Call this method to add a comment to the currently selected cell or range. * Params: [`AddCommentArgs`](/docs/api-reference/sdk/models/data-models#spreadjs-addcommentargs). It has the following properties: * `instance`: SpreadJS workbook instance created with `new GC.Spread.Sheets.Workbook(host)`. * Returns: [`Promise`](/docs/api-reference/sdk/models/data-models#spreadjs-addcommentresult). It returns `null` if no cell/range is selected or Velt is not loaded. > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/spreadjs-velt-comments'; > > const result = await addComment({ instance }); > ``` To scope comments to a specific workbook on pages with multiple SpreadJS instances, pass an editor id when attaching the extension: ```tsx theme={null} SpreadJSVeltComments.configure({ editorId: 'EDITOR_ID' }).attach(workbook); ``` #### Step 6: Render comments in SpreadJS workbook * Get comment data from the Velt SDK and render it in the SpreadJS workbook. * Params: [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#spreadjs-rendercommentsargs). It has the following properties: * `instance`: SpreadJS workbook instance. * `commentAnnotations`: Array of Comment Annotation objects. > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { useCommentAnnotations } from '@veltdev/react'; > import { renderComments } from '@veltdev/spreadjs-velt-comments'; > > const commentAnnotations = useCommentAnnotations(); > > useEffect(() => { > if (!instance) return; > > renderComments({ > instance, > commentAnnotations: commentAnnotations ?? [], > }); > }, [instance, commentAnnotations]); > ``` Highlights are view-only. The library re-derives each highlight from its [`TextEditorConfig`](/docs/api-reference/sdk/models/data-models#spreadjs-texteditorconfig) anchor and SpreadJS repositions the overlays across scroll, zoom, row/column resize, and sheet changes. Re-run `renderComments` when Velt's annotation list changes or when you import a new workbook. #### Step 7: Clean up the Velt SpreadJS extension `SpreadJSVeltComments.configure(...).attach(instance)` returns an [`AttachedExtension`](/docs/api-reference/sdk/models/data-models#spreadjs-attachedextension). Call `detach()` in your effect cleanup to remove listeners, clear per-instance state, and remove overlay elements before destroying the workbook. ```tsx theme={null} return () => { extensionRef.current?.detach(); extensionRef.current = null; workbookRef.current?.destroy(); }; ``` #### Step 8: Style the commented text * Each comment is rendered through a `.velt-spreadjs-overlay` layer with a `.velt-spreadjs-highlight` range fill and a `velt-comment-text` marker. * Override the default inline highlight styles with `!important`. ```css theme={null} .velt-spreadjs-highlight { background-color: rgba(255, 212, 0, 0.36) !important; border: 1.5px solid rgba(255, 170, 0, 0.95) !important; } velt-comment-text:hover .velt-spreadjs-highlight, velt-comment-text[comment-selected="true"] .velt-spreadjs-highlight, velt-comment-text.velt-comment-selected .velt-spreadjs-highlight { background-color: rgba(255, 212, 0, 0.62) !important; } ``` ## Complete Example [https://sample-apps-spreadjs-comments-demo.vercel.app/](https://sample-apps-spreadjs-comments-demo.vercel.app/) ## APIs #### [SpreadJSVeltComments](/docs/api-reference/sdk/api/api-methods#spreadjs-spreadjsveltcomments) Creates the Velt Comments extension for a SpreadJS workbook. Use `SpreadJSVeltComments.configure(...).attach(instance)` to attach it to a workbook instance. * Config: [`SpreadJSVeltCommentsConfig`](/docs/api-reference/sdk/models/data-models#spreadjs-spreadjsveltcommentsconfig) * Returns: `SpreadJSVeltComments` > [tab] React / Next.js > > ```tsx theme={null} > import { SpreadJSVeltComments } from '@veltdev/spreadjs-velt-comments'; > > const attached = SpreadJSVeltComments > .configure({ editorId: 'my-workbook' }) > .attach(instance); > > attached.detach(); > ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#spreadjs-addcomment) Creates a comment annotation for the currently selected SpreadJS cell or range. * Signature: `async (args: AddCommentArgs) => Promise` * Params: `args:` [`AddCommentArgs`](/docs/api-reference/sdk/models/data-models#spreadjs-addcommentargs) * Returns: `Promise`; see [`AddCommentResult`](/docs/api-reference/sdk/models/data-models#spreadjs-addcommentresult). > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/spreadjs-velt-comments'; > > const result = await addComment({ instance }); > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#spreadjs-rendercomments) Renders and updates Velt comment highlights in the SpreadJS workbook. * Signature: `(args:` [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#spreadjs-rendercommentsargs)`) => void` * Params: `args:` [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#spreadjs-rendercommentsargs) * Returns: `void` > [tab] React / Next.js > > ```tsx theme={null} > import { renderComments } from '@veltdev/spreadjs-velt-comments'; > > renderComments({ > instance, > commentAnnotations: annotations ?? [], > }); > ``` # Stream Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/stream ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/View-Stream-Comments.gif?s=bb2b9f6334216c89547474edcaf72d93) > [tab] React / Next.js > > ## 1. Import Comment components > > Import the `VeltComments` component. > > ```js theme={null} > import { > VeltProvider, > VeltComments, > } from '@veltdev/react'; > ``` > > ## 2. Add `VeltComments` component with Stream mode > > Add the `VeltComments` component inside a scrolling container. Make it a sibling to the element that contains the content you want to be commented. > > In the `VeltComments` component, mark the `streamMode` attribute as `true`. > > Also set the `streamViewContainerId` attribute to the id of the scrolling container. > > Stream mode renders all comment dialog boxes in a column on the right side similar to Google Docs. It works well with Text mode, which is enabled by default. > > Setting a reference to the container ID helps us position & scroll the comment stream as the user scrolls more robustly. > > ```js theme={null} > >
> //This element is scrollable >
> //This element contains the content that you want to be commented. >
> streamMode={true} > streamViewContainerId="scrolling-container-id" > /> >
>
> > ``` > > ## 3. Test Integration > > Test it out by adding a comment. > > Select any text, a `Comment Tool` button will appear near the highlighted text. > > Click on it to add a comment and see the comment appear in the comment stream. > [tab] Other Frameworks > > ## 1. Add the velt-comments component with Stream mode > > Add the `` component inside a scrolling container. Make it a sibling to the element that contains the content you want to be commented. > > In the `` component, mark the `stream-mode` attribute as `true`. > > Also set the `stream-view-container-id` attribute to the id of the scrolling container. > > Stream mode renders all comment dialog boxes in a column on the right side similar to Google Docs. It works well with Text mode, which is enabled by default. > > Setting a reference to the container ID helps us position & scroll the comment stream as the user scrolls more robustly. > > ```html theme={null} > >
> //This element is scrollable >
> //This element contains the content that you want to be commented. >
> stream-mode="true" > stream-view-container-id="scrolling-comment-stream" > > >
> > ``` > > ## 2. Test Integration > > Test it out by adding a comment. > > Select any text, a `Comment Tool` button will appear near the highlighted text. > > Click on it to add a comment and see the comment appear in the comment stream. ```jsx React / Next.js theme={null} import { VeltProvider, VeltComments, VeltCommentTool } from '@veltdev/react'; export default function App() { return (
//This element is scrollable
//This element contains the content that you want to be commented.
); } ``` ```html HTML theme={null} Comment documentation
//This element is scrollable
//This element contains the content that you want to be commented.
``` # SuperDoc Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/superdoc ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) The SuperDoc integration renders Velt comment highlights as view-only overlay elements positioned over the commented text. It does not write Velt comment marks into your DOCX content. Comment anchors are stored as a durable text and occurrence pair, then resolved against the live SuperDoc document whenever comments render. ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. * This component is required to render comments in your app. * Set the `textMode` prop to `false` to hide the default text comment tool. > [tab] React / Next.js > > ```tsx theme={null} > import { VeltComments, VeltProvider } from '@veltdev/react'; > > > > > ``` #### Step 2: Install the Velt SuperDoc extension ```bash theme={null} npm i @veltdev/superdoc-velt-comments @harbour-enterprises/superdoc ``` SuperDoc is browser-only because it touches `window` and the DOM. Import its stylesheet globally, then dynamically import the SuperDoc SDK and Velt extension inside a client-side effect. ```tsx theme={null} import '@harbour-enterprises/superdoc/style.css'; ``` #### Step 3: Configure the SuperDoc editor with the Velt Comments extension Create the SuperDoc editor, disable SuperDoc's built-in comments, then attach `SuperDocVeltComments` from the editor's `onReady` callback. > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect, useRef, useState } from 'react'; > import { useCommentAnnotations } from '@veltdev/react'; > import type { > AttachedExtension, > SuperDocInstance, > } from '@veltdev/superdoc-velt-comments'; > > const EDITOR_ID = 'my-doc'; > > function SuperDocEditor() { > const hostRef = useRef(null); > const superdocRef = useRef(null); > const extensionRef = useRef(null); > const [instance, setInstance] = useState(null); > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (!hostRef.current || superdocRef.current) return; > > let cancelled = false; > const host = hostRef.current; > > Promise.all([ > import('@harbour-enterprises/superdoc'), > import('@veltdev/superdoc-velt-comments'), > ]).then(([{ SuperDoc }, wrapper]) => { > if (cancelled) return; > > superdocRef.current = new SuperDoc({ > selector: host, > toolbar: '#superdoc-toolbar', > document: '/sample.docx', > documentMode: 'editing', > modules: { comments: false }, > onReady: () => { > if (cancelled || !superdocRef.current) return; > > extensionRef.current = wrapper.SuperDocVeltComments > .configure({ editorId: EDITOR_ID }) > .attach(superdocRef.current); > setInstance(superdocRef.current); > }, > }); > }); > > return () => { > cancelled = true; > extensionRef.current?.detach(); > extensionRef.current = null; > superdocRef.current?.destroy(); > superdocRef.current = null; > setInstance(null); > }; > }, []); > > useEffect(() => { > if (!instance) return; > > import('@veltdev/superdoc-velt-comments').then(({ renderComments }) => { > renderComments({ > instance, > commentAnnotations: annotations ?? [], > }); > }); > }, [instance, annotations]); > > return ( > <> >
>
> > ); > } > ``` #### Step 4: Add a comment button to your SuperDoc editor Add a button users can click after selecting text in the SuperDoc editor. Use `onMouseDown` with `preventDefault()` so clicking the button does not clear the current editor selection before `addComment` reads it. Keep the actual `addComment` call in `onClick`. > [tab] React / Next.js > > ```tsx theme={null} > const handleAddComment = async () => { > if (!instance) return; > > const { addComment } = await import('@veltdev/superdoc-velt-comments'); > const result = await addComment({ instance }); > > if (!result) { > console.warn('Select text in the document before adding a comment.'); > } > }; > > > ``` #### Step 5: Call `addComment` to add a comment * Call this method to add a comment to selected text in the SuperDoc editor. * Params: [`AddCommentArgs`](/docs/api-reference/sdk/models/data-models#addcommentargs-1). It has the following properties: * `instance`: SuperDoc editor instance returned by `new SuperDoc(...)`. * Returns: [`Promise`](/docs/api-reference/sdk/models/data-models#addcommentresult-1). It returns `null` if no text is selected or Velt is not loaded. > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/superdoc-velt-comments'; > > const result = await addComment({ instance }); > ``` To scope comments to a specific editor on pages with multiple SuperDoc instances, pass an editor id when attaching the extension: ```tsx theme={null} SuperDocVeltComments.configure({ editorId: 'EDITOR_ID' }).attach(superdoc); ``` #### Step 6: Render comments in the SuperDoc editor * Get the comment data from Velt SDK and render it in the SuperDoc editor. * Params: [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#rendercommentsargs-1). It has the following properties: * `instance`: SuperDoc editor instance. * `commentAnnotations`: Array of Comment Annotation objects. > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { useCommentAnnotations } from '@veltdev/react'; > import { renderComments } from '@veltdev/superdoc-velt-comments'; > > const commentAnnotations = useCommentAnnotations(); > > useEffect(() => { > if (!instance) return; > > renderComments({ > instance, > commentAnnotations: commentAnnotations ?? [], > }); > }, [instance, commentAnnotations]); > ``` Highlights are view-only. The library re-derives each highlight from its [`TextEditorConfig`](/docs/api-reference/sdk/models/data-models#texteditorconfig-5) anchor and remaps live ranges as the document changes. You do not need to call `renderComments` on every edit, scroll, zoom, or resize. Re-run it when Velt's annotation list changes. #### Step 7: Clean up the SuperDoc extension `SuperDocVeltComments.configure(...).attach(instance)` returns an [`AttachedExtension`](/docs/api-reference/sdk/models/data-models#attachedextension-1). Call `detach()` in your effect cleanup to remove listeners, clear per-instance state, and remove overlay elements before destroying the editor. ```tsx theme={null} return () => { extensionRef.current?.detach(); extensionRef.current = null; superdocRef.current?.destroy(); }; ``` #### Step 8: Style the commented text * You can style commented text by adding CSS for the `velt-comment-text` element. * SuperDoc highlights are light-DOM overlay elements inside `div.velt-superdoc-overlay-root`, so a global stylesheet can reach them. * The default highlight rules use inline `!important` styles, so overrides should use `!important`. ```css theme={null} velt-comment-text { background-color: rgba(255, 212, 0, 0.4) !important; border-bottom: 2px solid #ffd400 !important; cursor: pointer; } velt-comment-text:hover { background-color: rgba(255, 212, 0, 0.6) !important; } velt-comment-text[comment-selected="true"], velt-comment-text.velt-comment-selected { background-color: rgba(255, 212, 0, 0.7) !important; } ``` ## Complete Example [https://sample-apps-superdoc-comments-demo.vercel.app/](https://sample-apps-superdoc-comments-demo.vercel.app/) ## APIs #### [SuperDocVeltComments](/docs/api-reference/sdk/api/api-methods#superdocveltcomments) Creates the Velt Comments extension for a SuperDoc editor. Use `SuperDocVeltComments.configure(...).attach(instance)` to attach it to an editor instance. * Config: [`SuperDocVeltCommentsConfig`](/docs/api-reference/sdk/models/data-models#superdocveltcommentsconfig) * Returns: `SuperDocVeltComments` > [tab] React / Next.js > > ```tsx theme={null} > import { SuperDocVeltComments } from '@veltdev/superdoc-velt-comments'; > > const attached = SuperDocVeltComments > .configure({ editorId: 'my-doc' }) > .attach(superdoc); > > attached.detach(); > ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-12) Creates a comment annotation for the currently selected text in the SuperDoc editor. * Signature: `async (args: AddCommentArgs) => Promise` * Params: `args:` [`AddCommentArgs`](/docs/api-reference/sdk/models/data-models#addcommentargs-1) * Returns: `Promise`; see [`AddCommentResult`](/docs/api-reference/sdk/models/data-models#addcommentresult-1). > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/superdoc-velt-comments'; > > const result = await addComment({ instance }); > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-12) Renders and updates Velt comment highlights in the SuperDoc editor. * Signature: `(args:` [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#rendercommentsargs-1)`) => void` * Params: `args:` [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#rendercommentsargs-1) * Returns: `void` > [tab] React / Next.js > > ```tsx theme={null} > import { renderComments } from '@veltdev/superdoc-velt-comments'; > > renderComments({ > instance, > commentAnnotations: annotations ?? [], > }); > ``` # Text Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/text ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) > [tab] React / Next.js > > ## 1. Import Comment components > > Import the `VeltComments` component. > > ```js theme={null} > import { VeltProvider, VeltComments } from '@veltdev/react'; > ``` > > ## 2. Add Comment component with Text mode > > Add the `VeltComments` component to the root of your app. > > This component is required to render comments in your app. > > Text mode is enabled by default. To disable it, set the `textMode` attribute to `false`. > > Text mode allows users to select any text and attach comments to it similar to Google Docs. > > ```js theme={null} > > > > ``` > > ## 3. Test Integration > > Test it out by opening the page with Velt components in your browser. > > Select any text, a `Comment Tool` button will appear near the highlighted text. Click on it to add a comment. > > ![](https://mintcdn.com/velt/gY7ilEx2g4g3-HVe/images/text-comment.png?fit=max\&auto=format\&n=gY7ilEx2g4g3-HVe\&q=85\&s=e2938519d890a5c020d1da5407c4557c) > [tab] Other Frameworks > > ## 1. Add Comment component with Text mode > > Add the comment component to your template. Try to put it as close to the root level of your ``. > > This component is required to render comments in your app. Text mode allows users to attach comments to highlighted text. > > ```html theme={null} > > > > ``` > > ## 2. Test Integration > > Test it out by opening the page with Velt components in your browser. > > Select any text, a `Comment Tool` button will appear near the highlighted text. Click on it to add a comment. > > ![](https://mintcdn.com/velt/gY7ilEx2g4g3-HVe/images/text-comment.png?fit=max\&auto=format\&n=gY7ilEx2g4g3-HVe\&q=85\&s=e2938519d890a5c020d1da5407c4557c) ```jsx React / Next.js theme={null} import { VeltProvider, VeltComments } from '@veltdev/react'; export default function App() { return ( ); } ``` ```html HTML theme={null} Comment documentation ``` # TinyMCE Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/tinymce Add Velt text comments to a TinyMCE editor with the Velt TinyMCE comments plugin. ![Add text comments in an editor](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) The TinyMCE integration renders comment highlights as view-only overlay elements positioned over the commented text. It does not modify your TinyMCE content, schema, undo history, or saved HTML. ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. This component is required to create and render comments in your app. * Authenticate the user with `authProvider` and set the Velt document before users add comments. * Set the `textMode` prop to `false` to hide the default Velt text comment tool. TinyMCE selections are handled by `@veltdev/tinymce-velt-comments`. * Add `VeltCommentsSidebar` if you want a Google Docs-style comment sidebar. > [tab] React / Next.js > > ```tsx theme={null} > import { VeltComments, VeltCommentsSidebar, VeltProvider, useSetDocument } from '@veltdev/react'; > > const user = { > userId: 'user-1', > organizationId: 'org-1', > name: 'User One', > email: 'user@example.com', > }; > > function VeltSetup() { > useSetDocument('document-id', { documentName: 'Document name' }); > return null; > } > > function App() { > return ( > > > > > {/* Your app content */} > > ); > } > ``` > [tab] Other Frameworks > > ```html theme={null} > > > > ``` #### Step 2: Install the Velt TinyMCE extension > [tab] React / Next.js > > ```bash theme={null} > npm i @veltdev/tinymce-velt-comments @tinymce/tinymce-react tinymce > ``` > [tab] Other Frameworks > > ```bash theme={null} > npm i @veltdev/tinymce-velt-comments @veltdev/client tinymce > ``` `tinymce` is a peer dependency and must be provided by your TinyMCE app. Import the self-hosted TinyMCE assets used by your editor so `@tinymce/tinymce-react` and the Velt plugin use the same TinyMCE instance. #### Step 3: Configure the TinyMCE editor with the Velt Comments plugin Add `VeltCommentsPlugin` to the TinyMCE `plugins` list and set `velt_comments_editor_id` in the editor init options. Capture the TinyMCE editor instance from `onInit` or the `init` event, then render Velt comment annotations into the editor with `renderComments`. > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect, useState } from 'react'; > import { Editor as TinyMCEReact } from '@tinymce/tinymce-react'; > import { useCommentAnnotations } from '@veltdev/react'; > import type { Editor as TinyMCEEditor } from 'tinymce'; > import { VeltCommentsPlugin, renderComments } from '@veltdev/tinymce-velt-comments'; > > import 'tinymce'; > import 'tinymce/icons/default'; > import 'tinymce/themes/silver'; > import 'tinymce/models/dom'; > import 'tinymce/plugins/lists'; > import 'tinymce/plugins/link'; > import 'tinymce/skins/ui/oxide/skin.min.css'; > import contentUiCss from 'tinymce/skins/ui/oxide/content.min.css?raw'; > import contentCss from 'tinymce/skins/content/default/content.min.css?raw'; > > const EDITOR_ID = 'my-editor'; > > function TinyMCEEditor() { > const [editor, setEditor] = useState(null); > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (!editor) return; > > renderComments({ > editor, > editorId: EDITOR_ID, > commentAnnotations: annotations ?? [], > }); > }, [editor, annotations]); > > return ( > licenseKey="gpl" > initialValue="

Select text, then add a comment.

" > init={{ > license_key: 'gpl', > skin: false, > content_css: false, > content_style: `${contentUiCss}\n${contentCss}`, > plugins: ['lists', 'link', VeltCommentsPlugin], > toolbar: 'undo redo | bold italic | bullist numlist | link | addveltcomment', > velt_comments_editor_id: EDITOR_ID, > }} > onInit={(_event, nextEditor) => setEditor(nextEditor)} > /> > ); > } > ``` > [tab] Other Frameworks > > ```js theme={null} > import tinymce from 'tinymce'; > import { VeltCommentsPlugin } from '@veltdev/tinymce-velt-comments'; > > let editor; > > tinymce.init({ > selector: '#editor', > license_key: 'gpl', > plugins: [VeltCommentsPlugin], > toolbar: 'undo redo | bold italic | addveltcomment', > velt_comments_editor_id: 'my-editor', > setup: (nextEditor) => { > nextEditor.on('init', () => { > editor = nextEditor; > }); > }, > }); > ``` > [!TIP] > > The package registers a TinyMCE plugin named `veltcomments`. You can pass the exported `VeltCommentsPlugin` constant in `plugins`, or use the string `'veltcomments'` after the package has been imported. It also registers a TinyMCE toolbar button named `addveltcomment`. #### Step 4: Add a comment button to your TinyMCE editor Add a button that users can click to add comments after selecting text in the TinyMCE editor. **Important:** Use `onMouseDown` with `preventDefault()` so the browser does not move focus away from the editor before `addComment` reads the current selection. Keep the actual `addComment` call in `onClick`. > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/tinymce-velt-comments'; > > const handleAddComment = () => { > if (!editor) return; > > void addComment({ > editor, > editorId: EDITOR_ID, > }); > }; > > > ``` > [tab] Other Frameworks > > ```html theme={null} > >
> ``` > > ```js theme={null} > import { addComment } from '@veltdev/tinymce-velt-comments'; > > const addCommentButton = document.querySelector('#add-comment'); > > addCommentButton.addEventListener('mousedown', (event) => { > event.preventDefault(); > }); > > addCommentButton.addEventListener('click', () => { > void addComment({ editor, editorId: 'my-editor' }); > }); > ``` #### Step 5: Call `addComment` to add a comment * Call this method to add a comment to selected text in the TinyMCE editor. * Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-9). It has the following properties: * `editor`: TinyMCE `Editor` instance. * `editorId`: Id of the editor. Use this if you have multiple TinyMCE editors on the same page. (optional) * `context`: Add custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional) > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/tinymce-velt-comments'; > > const addCommentRequest = { > editor, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > void addComment(addCommentRequest); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { addComment } from '@veltdev/tinymce-velt-comments'; > > const addCommentRequest = { > editor, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > void addComment(addCommentRequest); > ``` The library automatically writes `context.textEditorConfig` with the selected text, its 1-based occurrence index in the document, and the editor ID when one is provided. If the editor is inside an element with `data-velt-location-id`, that value is sent to Velt as the annotation location. #### Step 6: Render comments in TinyMCE editor * Get the comment data from Velt SDK and render it in the TinyMCE editor. * Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-9). It has the following properties: * `editor`: TinyMCE `Editor` instance. * `editorId`: Id of the editor. Use this if you have multiple TinyMCE editors on the same page. (optional) * `commentAnnotations`: Array of Comment Annotation objects. > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { useCommentAnnotations } from '@veltdev/react'; > import { renderComments } from '@veltdev/tinymce-velt-comments'; > > const commentAnnotations = useCommentAnnotations(); > > useEffect(() => { > if (!editor) return; > > renderComments({ > editor, > editorId: 'EDITOR_ID', > commentAnnotations: commentAnnotations ?? [], > }); > }, [editor, commentAnnotations]); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { renderComments } from '@veltdev/tinymce-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > renderComments({ > editor, > editorId: 'EDITOR_ID', > commentAnnotations: annotations, > }); > }); > ``` `renderComments` filters annotations by `context.textEditorConfig.editorId`. Resolved comments with `status.type === 'terminal'` are hidden unless they are currently selected in Velt. #### Step 7: Re-apply TinyMCE comment highlights (optional) * TinyMCE renders comment highlights as view-only overlay elements in the outer document. * The integration does not write Velt comment marks into your TinyMCE content or undo history. * Save your TinyMCE content normally. After you recreate the editor or replace content with `editor.setContent(...)`, call `renderComments` again. ```ts theme={null} const html = editor.getContent(); // Save html to your backend. renderComments({ editor, editorId: 'EDITOR_ID', commentAnnotations, }); ``` #### Step 8: Style the commented text * You can style the commented text by adding CSS for the `velt-comment-text` element. * TinyMCE highlights are overlay elements in the outer document, not inside the editor iframe, so add this CSS to your page stylesheet instead of `content_style`. ```css theme={null} velt-comment-text { background-color: rgba(255, 212, 0, 0.4); border-bottom: 2px solid #ffd400; cursor: pointer; } velt-comment-text:hover { background-color: rgba(255, 212, 0, 0.6); } velt-comment-text[comment-selected="true"], velt-comment-text.velt-comment-selected { background-color: rgba(255, 212, 0, 0.7); } ``` #### Using TinyMCE without React For a vanilla TinyMCE app, initialize Velt with `@veltdev/client`, add the Velt comments web component to the page, and subscribe to annotations through the Velt comment element. ```bash theme={null} npm install @veltdev/client ``` ```html theme={null}
``` ```ts theme={null} import { initVelt } from '@veltdev/client'; import tinymce from 'tinymce'; import { VeltCommentsPlugin, addComment, renderComments, } from '@veltdev/tinymce-velt-comments'; const EDITOR_ID = 'my-editor'; const velt = await initVelt('YOUR_API_KEY'); await velt.identify({ userId: 'user-1', organizationId: 'org-1', name: 'User One', email: 'user@example.com', }); velt.setDocument('document-id', { documentName: 'Document name' }); const [editor] = await tinymce.init({ selector: '#editor', license_key: 'gpl', plugins: [VeltCommentsPlugin], toolbar: 'bold italic | addveltcomment', velt_comments_editor_id: EDITOR_ID, }); document.getElementById('add-comment-btn')?.addEventListener('mousedown', (event) => { event.preventDefault(); }); document.getElementById('add-comment-btn')?.addEventListener('click', () => { void addComment({ editor, editorId: EDITOR_ID }); }); velt.getCommentElement()?.getAllCommentAnnotations().subscribe((annotations) => { renderComments({ editor, editorId: EDITOR_ID, commentAnnotations: annotations }); }); ``` #### Multiple TinyMCE editors When using multiple editors on the same page, provide a unique `editorId` to TinyMCE's `velt_comments_editor_id` init option, `addComment`, and `renderComments`. ```ts theme={null} const [editor1] = await tinymce.init({ target: document.querySelector('#editor-1') as HTMLElement, license_key: 'gpl', plugins: [VeltCommentsPlugin], toolbar: 'addveltcomment', velt_comments_editor_id: 'editor-1', }); const [editor2] = await tinymce.init({ target: document.querySelector('#editor-2') as HTMLElement, license_key: 'gpl', plugins: [VeltCommentsPlugin], toolbar: 'addveltcomment', velt_comments_editor_id: 'editor-2', }); await addComment({ editor: editor1, editorId: 'editor-1' }); await addComment({ editor: editor2, editorId: 'editor-2' }); renderComments({ editor: editor1, editorId: 'editor-1', commentAnnotations, }); renderComments({ editor: editor2, editorId: 'editor-2', commentAnnotations, }); ``` #### TypeScript support The package includes TypeScript definitions. Key type exports: ```ts theme={null} import type { AddCommentRequest, RenderCommentsRequest, TinymceVeltCommentsConfig, CommentAnnotationContext, } from '@veltdev/tinymce-velt-comments'; import type { CommentAnnotation } from '@veltdev/types'; ``` Runtime exports: ```ts theme={null} import { VeltCommentsPlugin, registerVeltCommentsPlugin, addComment, renderComments, } from '@veltdev/tinymce-velt-comments'; ``` ## Complete Example [https://sample-apps-tinymce-comments-demo.vercel.app/](https://sample-apps-tinymce-comments-demo.vercel.app/) ## APIs #### [VeltCommentsPlugin](/docs/api-reference/sdk/api/api-methods#veltcommentsplugin-1) The registered TinyMCE plugin name (`'veltcomments'`) that powers Velt comments. Importing the library registers it; add it to the TinyMCE editor's `plugins` list. **Init options:** * `velt_comments_editor_id?: string` - Unique identifier for this editor instance. * `velt_comments_persist_marks?: boolean` - Reserved for API parity; highlights are always rendered as view-only overlays. > [tab] React / Next.js > > ```tsx theme={null} > import { VeltCommentsPlugin } from '@veltdev/tinymce-velt-comments'; > > licenseKey="gpl" > init={{ > license_key: 'gpl', > plugins: ['lists', 'link', VeltCommentsPlugin], > toolbar: 'bold italic | addveltcomment', > velt_comments_editor_id: 'my-editor', > }} > /> > ``` > [tab] Other Frameworks > > ```js theme={null} > import { VeltCommentsPlugin } from '@veltdev/tinymce-velt-comments'; > > tinymce.init({ > selector: '#editor', > license_key: 'gpl', > plugins: [VeltCommentsPlugin], > toolbar: 'bold italic | addveltcomment', > velt_comments_editor_id: 'my-editor', > }); > ``` #### [registerVeltCommentsPlugin()](/docs/api-reference/sdk/api/api-methods#registerveltcommentsplugin) Explicitly registers the `veltcomments` plugin with a TinyMCE instance. Importing the package auto-registers the plugin when a TinyMCE instance is available; use this method when TinyMCE is loaded or provided later. **Parameters:** * `instance?: TinyMCE` - TinyMCE instance to register against. **Returns:** `void` ```ts theme={null} import tinymce from 'tinymce'; import { registerVeltCommentsPlugin } from '@veltdev/tinymce-velt-comments'; registerVeltCommentsPlugin(tinymce); ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-10) Creates a Velt comment annotation for the currently selected TinyMCE text. * Signature: `async (request:` [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-9)`) => Promise` * Params: `request:` [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-9) * Returns: `Promise` > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/tinymce-velt-comments'; > > const handleAddComment = () => { > if (!editor) return; > void addComment({ editor, editorId: 'my-editor' }); > }; > > > ``` > [tab] Other Frameworks > > ```js theme={null} > import { addComment } from '@veltdev/tinymce-velt-comments'; > > void addComment({ > editor, > editorId: 'my-editor', > context: { customData: 'value' }, > }); > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-10) Resolves Velt comment annotations back to TinyMCE DOM ranges and renders stable `` overlay elements for the visible comments. * Signature: `(request:` [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-9)`) => void` * Params: `request:` [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-9) * Returns: `void` > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { useCommentAnnotations } from '@veltdev/react'; > import { renderComments } from '@veltdev/tinymce-velt-comments'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (!editor) return; > > renderComments({ > editor, > editorId: 'my-editor', > commentAnnotations: annotations ?? [], > }); > }, [editor, annotations]); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { renderComments } from '@veltdev/tinymce-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > renderComments({ > editor, > editorId: 'my-editor', > commentAnnotations: annotations, > }); > }); > ``` # Tiptap Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/tiptap ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/Add-Text-Comments.gif?s=1da499b73486c2acd4667b517baab389) ## Setup #### Step 1: Add Comment components * Add the `Velt Comments` component to the root of your app. * This component is required to render comments in your app. * Set the `text mode` prop to `false` to hide the default text comment tool. > [tab] React / Next.js > > ```js theme={null} > > > > ``` > [tab] Other Frameworks > > ```html theme={null} > > > > ``` #### Step 2: Install the Velt Tiptap extension ```bash theme={null} npm i @veltdev/tiptap-velt-comments ``` #### Step 3: Configure the Tiptap editor with the Velt Comments extension > [tab] React / Next.js > > ```js theme={null} > import { TiptapVeltComments } from '@veltdev/tiptap-velt-comments'; > > const editor = new Editor({ > extensions: [ > TiptapVeltComments, > // ... other extensions > ], > }); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { TiptapVeltComments } from '@veltdev/tiptap-velt-comments'; > > const editor = new Editor({ > extensions: [ > TiptapVeltComments, > // ... other extensions > ], > }); > ``` #### Step 4: Add a comment button to your Tiptap editor Add a button in your existing bubble menu or create a new bubble menu that appears when users select text in the editor. > [tab] React / Next.js > > ```js theme={null} > import { BubbleMenu, EditorContent, useEditor } from '@tiptap/react'; > import { addComment } from '@veltdev/tiptap-velt-comments'; > > export default function TipTapComponent() { > const editor = useEditor({ > // ... your editor configuration > }); > > const addTiptapVeltComment = () => { > if (editor) { > addComment({ editor }); > } > }; > > return ( >
> > > {/* Bubble Menu for Comments */} > {editor && ( > >
> >
>
> )} >
> ); > } > ``` > [tab] Other Frameworks > > ```html theme={null} > >
>
> >
> ``` > > ```js theme={null} > import { BubbleMenu, Editor } from '@tiptap/core'; > import { addComment } from '@veltdev/tiptap-velt-comments'; > > const editor = new Editor({ > element: document.querySelector('#editor'), > // ... your editor configuration > }); > > const addTiptapVeltComment = () => { > if (editor) { > addComment({ editor }); > } > }; > > // Create bubble menu > const bubbleMenu = new BubbleMenu({ > editor, > element: document.querySelector('.bubble-menu'), > tippyOptions: { duration: 100 }, > }); > > // Add click handler to comment button > document.querySelector('.comment-button').addEventListener('click', (e) => { > e.preventDefault(); > e.stopPropagation(); > addTiptapVeltComment(); > }); > ``` > [!TIP] > > Refer to the [Tiptap BubbleMenu documentation](https://tiptap.dev/docs/editor/extensions/functionality/bubble-menu) to learn more about customizing the bubble menu behavior. #### Step 5: Call `addComment` to add a comment * Call this method to add a comment to selected text in the Tiptap editor. You can use this when the user clicks on the comment button in context menu or presses a keyboard shortcut. * Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-1). It has the following properties: * `editor`: instance of the Tiptap editor. * `editorId`: Id of the tiptap editor. Use this if you have multiple tiptap editors on the same page in your app. (optional) * `context`: Add any custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional) > [tab] React / Next.js > > ```js theme={null} > import { addComment } from '@veltdev/tiptap-velt-comments'; > > const addCommentRequest = { > editor, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > addComment(addCommentRequest); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { addComment } from '@veltdev/tiptap-velt-comments'; > > const addCommentRequest = { > editor, > editorId: 'EDITOR_ID', > context: { > storyId: 'story-id', > storyName: 'story-name', > }, > }; > > addComment(addCommentRequest); > ``` #### Step 6: Render comments in Tiptap editor * Get the comment data from Velt SDK and render it in the Tiptap Editor. * Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-1). It has the following properties: * `editor`: Instance of the Tiptap editor. * `editorId`: Id of the tiptap editor. Use this if you have multiple tiptap editors on the same page in your app. (optional) * `commentAnnotations`: Array of Comment Annotation objects. > [tab] React / Next.js > > ```js theme={null} > import { renderComments } from '@veltdev/tiptap-velt-comments'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (editor && annotations?.length) { > const renderCommentsRequest = { > editor, > editorId: 'EDITOR_ID', > annotations, > }; > renderComments(renderCommentsRequest); > } > }, [editor, annotations]); > ``` > [tab] Other Frameworks > > ```js theme={null} > import { renderComments } from '@veltdev/tiptap-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > if (editor && annotations?.length) { > const renderCommentsRequest = { > editor, > editorId: 'EDITOR_ID', > commentAnnotations: annotations, > }; > renderComments(renderCommentsRequest); > } > }); > ``` #### Step 7: Persist Velt Comment Marks (optional) * By default, Velt comment marks (``) are persisted in the Tiptap editor by Velt SDK. When the editor loads and the velt sdk initializes, the marks will be automatically added to the editor by us. * If you plan to store the contents of the tiptap editor as raw html on your end then you should turn off this feature since you will already be storing the Velt comment marks. * Default: `true` ```js theme={null} const editor = new Editor({ extensions: [ TiptapVeltComments.configure({ persistVeltMarks: false }), // ... other extensions ], }); ``` #### Step 8: Style the commented text * You can style the commented text by adding a CSS class to the `velt-comment-text` element. * By using the `comment-available` attribute, you can apply styles only when the comment data has loaded. ```css theme={null} velt-comment-text[comment-available="true"] { background-color: #ffff00; } ``` ## Complete Example [https://documentation-app-demo.vercel.app/](https://documentation-app-demo.vercel.app/) ## APIs #### [TiptapVeltComments.configure()](/docs/api-reference/sdk/api/api-methods#tiptapveltcomments-configure) A custom Tiptap extension for Velt comments. * Params: `options?:` [TiptapVeltCommentsOptions](/docs/api-reference/sdk/models/data-models#tiptapveltcommentsoptions) * Returns: `TiptapVeltComments` > [tab] React / Next.js > > ```tsx theme={null} > import { useEditor } from '@tiptap/react'; > import StarterKit from '@tiptap/starter-kit'; > import { TiptapVeltComments } from '@veltdev/tiptap-velt-comments'; > > const editor = useEditor({ > extensions: [ > StarterKit, > TiptapVeltComments.configure({ > editorId: 'my-editor', > persistVeltMarks: true, > }), > ], > content: '

Your content

', > }); > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import { Editor } from '@tiptap/core'; > import StarterKit from '@tiptap/starter-kit'; > import { TiptapVeltComments } from '@veltdev/tiptap-velt-comments'; > > const editor = new Editor({ > element: document.querySelector('#editor'), > extensions: [ > StarterKit, > TiptapVeltComments.configure({ > editorId: 'my-editor', > persistVeltMarks: true, > }), > ], > content: '

Your content

', > }); > ``` #### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-2) Creates a comment annotation for the currently selected text in the editor. * Params: * `request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest) * `editor: Editor` * `editorId?: string` * `context?: object` * Returns: `Promise` > [tab] React / Next.js > > ```tsx theme={null} > import { addComment } from '@veltdev/tiptap-velt-comments'; > > > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import { addComment } from '@veltdev/tiptap-velt-comments'; > > addComment({ > editor, > editorId: 'my-editor', > context: { customData: 'value' }, > }); > ``` #### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-2) Renders and highlights comment annotations in the editor. * Params: * `request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest) * `editor: Editor` * `editorId?: string` * `commentAnnotations?:` [CommentAnnotation\[\]](/docs/api-reference/sdk/models/data-models#commentannotation) * Returns: `void` > [tab] React / Next.js > > ```tsx theme={null} > import { useEffect } from 'react'; > import { renderComments } from '@veltdev/tiptap-velt-comments'; > import { useCommentAnnotations } from '@veltdev/react'; > > const annotations = useCommentAnnotations(); > > useEffect(() => { > if (editor && annotations) { > renderComments({ > editor, > editorId: 'my-editor', > commentAnnotations: annotations, > }); > } > }, [editor, annotations]); > ``` > [tab] Other Frameworks > > ```tsx theme={null} > import { renderComments } from '@veltdev/tiptap-velt-comments'; > > const commentElement = Velt.getCommentElement(); > commentElement.getAllCommentAnnotations().subscribe((annotations) => { > if (editor && annotations) { > renderComments({ > editor, > editorId: 'my-editor', > commentAnnotations: annotations, > }); > } > }); > ``` # Custom Video Player Setup Source: https://velt.dev/docs/async-collaboration/comments/setup/video-player-setup/custom-video-player-setup Use this guide to add collaboration into your own custom video player. ![](https://mintcdn.com/velt/gAz_vLsG-ukKamYM/gifs/custom-video-player.gif?s=969c638e66ef591467cb2203924c7b9e) ## Setup ### Step 1: Set up Velt Components in your app You will be using the following components: * `Velt Comments`: Renders comments on the DOM. * `Velt Comment Tool`: Enables or disables adding comments. * `Velt Reaction Tool`: Enables or disables adding reactions. * `Velt Comment Player Timeline`: Adds comments bubble over your player seek bar. * `Velt Comments Sidebar`: Adds a sidebar that shows all comments. Users can also search, filter & navigate to the comments from here. * `Velt Sidebar Button`: Toggles the sidebar on/off. #### A) Add the `Velt Comments` component in the root of your app Add the `Velt Comments` component to the root of your app. > [tab] React / Next.js > > ```jsx theme={null} > > ``` > [tab] Other Frameworks > > ```html theme={null} > > ``` #### B) Add the `Velt Comment Tool` component wherever you want your render the comment tool. Note you can also provide your own button to this component. > [tab] React / Next.js > > ```jsx theme={null} > > > > ``` > [tab] Other Frameworks > > ```jsx theme={null} > > > > ``` > [!NOTE] > > **Disable Comment Tool** > You can disable the comment tool to temporarily or conditionally restrict comment creation while still allowing users to view existing comments. > > > [accordion] See Example > > > > > [tab] React / Next.js > > > > > > ```jsx theme={null} > > > > > > > > > > > > ``` > > > > > [tab] Other Frameworks > > > > > > ```html theme={null} > > > > > > > > > > > > ``` #### C) Add the `Velt Reaction Tool` component wherever you want your render the reaction tool. * Provide the video player ID on which you want the reactions to be added. * Add an event handler to handle `onReactionToolClick` events. > [tab] React / Next.js > > ```jsx theme={null} > onReactionToolClick={() => onReactionToolClick()}> > > ``` > [tab] Other Frameworks > > ```html theme={null} >
> >
> ``` > > ```js theme={null} > const reactionToolTag = document.querySelector('velt-reaction-tool'); > reactionToolTag.addEventListener('onReactionToolClick', (event) => { > console.log('reaction tool clicked', event.detail); > }); > ``` #### D) Place the `Velt Comment Player Timeline` component as a sibling to your video player. * To show comment bubbles on your player seek bar, add the `Velt Comment Player Timeline` component as a sibling to your video player component. * It will auto adjust to the same width as your video player. > [!NOTE] > > Right now we assume you have a maximum of one `velt comment player timeline` component and one sibling video player component per `documentID` > [!WARNING] > > Ensure that the parent container of `velt comment player timeline` doesn't have CSS position value as 'static'. > [!NOTE] > > `videoPlayerId` is optional and helps support multiple players/timelines on the same page. > > * If omitted, the timeline shows all comments for the current document (for the active version). > * If provided, the timeline shows only comments whose `location.videoPlayerId` matches the given `videoPlayerId`. > > Tip: Use the same id on your player element and when setting `location.videoPlayerId` so the timeline can correctly associate comments with the player. > [tab] React / Next.js > > ```jsx theme={null} >
> > >
> ``` > [tab] Other Frameworks > > ```jsx theme={null} >
> > >
> ``` #### E) Add `id` to the video player or its parent element. * If you don't have access to the raw `