Add context mentions: @-mention menu (chip + inline modes) and slash commands#360
Add context mentions: @-mention menu (chip + inline modes) and slash commands#360becomevocal wants to merge 31 commits into
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
| getInlineMessageFields?: () => { | ||
| content: string; | ||
| contextMentions: AgentWidgetContextMentionRef[]; | ||
| contentSegments: AgentWidgetContentSegment[]; |
There was a problem hiding this comment.
Async
doSubmit lacks a concurrent-call guard
doSubmit is now an async function and handleSubmit fires it with void doSubmit(). Between when doSubmit yields at await mentionOrchestrator?.takeInlineCommand(value) and when session.sendMessage() eventually calls setStreaming(true), session.isStreaming() still returns false. A second form submission (e.g. double-click, rapid Enter) that arrives in that window will pass the isStreaming() guard in handleSubmit, enter a second concurrent doSubmit(), read the same textarea.value, and call session.sendMessage() twice — sending an identical message.
The old synchronous handleSubmit was immune because setStreaming(true) was called before control ever returned to the event loop. The async path has a real gap for slash commands on first use (chunk load + "prompt" resolve) and a microtask gap for every other path. Adding a let submitting = false flip-flop around doSubmit closes it.
This commit introduces a new context mentions feature that allows users to pull external context into a single turn by typing `@` or clicking a context button. The feature includes a searchable menu for selecting context items, which are then attached as removable chips in the message composer. The implementation includes a demo page, updates to the README, and necessary configurations in the build process. Additionally, the context mentions are designed to be lazy-loaded, ensuring no bundle cost for unused installs. This enhancement improves the user experience by providing a more interactive and context-aware messaging interface.
This commit introduces several enhancements to the context mentions feature, including: - A new `contextMentions.renderMentionItem` hook for custom row rendering while maintaining built-in menu functionality. - The `renderMentionChip` now receives the resolved payload for select-resolved sources, allowing for content previews on hover. - The `createSmartDomMentionSource` function now includes a `mapItem` option to reshape surfaced items without needing a complete source rewrite. - Updates to the context mentions demo page to showcase various rendering variants and their configurations. These changes improve customization and user interaction within the context mentions feature, enhancing the overall user experience.
This commit introduces several improvements to the ghost button styles used for the context mentions feature. Key changes include: - Updated the `ghost` variant in the theme configuration to include a `hoverBackground` property. - Refactored the appearance of the `.persona-attachment-button` and `.persona-mention-button` to utilize CSS variables for consistent theming. - Removed inline styles for button appearance, relying on the new CSS rules for hover effects and background colors. - Added tests to ensure the correct mapping of ghost button tokens to CSS variables. These updates enhance the visual consistency and interactivity of the context mentions buttons, improving the overall user experience.
This commit introduces a new context mention picker that replaces the previous behavior of inserting a trigger character (`@`) into the composer. Key changes include: - The "add context" button now opens a picker with a focused search field, allowing users to filter and select mentions without leaving stray characters in the input. - A new `searchPlaceholder` option has been added to customize the search field's placeholder text. - CSS updates provide new hooks for styling the picker and its components. - Tests have been added to ensure the functionality of the new picker behavior and its integration with the context mention controller. These enhancements improve the user experience by providing a cleaner and more intuitive way to insert context mentions.
This commit introduces a new slash commands feature that allows users to execute commands by typing `/` in the composer. Key changes include: - Support for multiple trigger channels alongside `@` context mentions, enabling a unified command menu. - New command types: `prompt`, `action`, and `server`, each with distinct behaviors and configurations. - A demo page showcasing various command flavors and their functionalities. - Updates to the context mentions engine to accommodate slash commands, including new types and capabilities for command handling. These enhancements improve the user experience by providing a more interactive and versatile messaging interface, allowing for seamless command execution within the chat environment.
This commit introduces several enhancements to the context mentions feature, focusing on performance and user experience. Key changes include: - The context mention menu and chip runtime are now lazy-loaded for both ESM/CJS consumers, reducing bundle size for unused installs. - Improved correctness by ensuring that structured `context.mentions` does not re-attach older mentions to subsequent messages. - Accessibility improvements, including better ARIA attributes and touch target sizes. - Updates to the demo pages to reflect the new functionality and customization options.
…handling This commit introduces several key enhancements to the context mentions feature, focusing on user experience and functionality. Notable changes include: - Implementation of inline completion for slash commands, allowing users to type arguments directly in the composer after selecting a command. - Introduction of `argsPlaceholder` for commands, providing visual hints in the mention menu to guide users on expected input. - Updates to the context mention engine to support new command types and behaviors, including improved handling of server commands and action commands. - Enhancements to the demo pages to showcase the new inline completion feature and its usage.
This commit introduces several improvements to the context mentions feature, focusing on accessibility and user experience. Key changes include: - The affordance button now defaults to a "+" icon, recognized as the "add context" signifier, instead of the "@" glyph, which is more suited for power users. - Updated demo documentation to clarify when to show or hide the affordance button based on user context. - CSS adjustments to ensure proper spacing and responsiveness of the notes section in the demo. - Added tests to verify the new default icon behavior and customization options for power-user surfaces.
This commit enhances the CSS for demo components by: - Adding `flex-wrap` to the toolbar variants to prevent overflow at medium widths, ensuring a more responsive design. - Adjusting row gaps for better spacing in the variant group. - Removing `z-index` from the launcher scene mount to prevent stacking context issues on mobile, allowing the widget to open fullscreen correctly.
This commit introduces a new inline context mentions feature, allowing users to insert mentions as atomic tokens within the text composer. Key changes include: - Implementation of `contextMentions.display: "inline"` to replace the default chip row with a contenteditable surface. - The inline tokens maintain their position in the sentence, enhancing readability and user experience. - A demo page has been added to showcase the inline functionality, including token styling options and interaction behaviors. - Lazy loading of the contenteditable engine ensures minimal impact on performance for users not utilizing this feature.
This commit introduces improvements to the inline context mentions feature, focusing on menu positioning and user experience. Key changes include: - Implementation of horizontal anchoring for the mention menu, allowing it to align with the `@` trigger glyph in a Slack-style manner. - Addition of a `horizontalOffset` option to control the menu's left positioning based on the trigger's location, ensuring it remains within the composer bounds. - New utility function `getLogicalRangeRect` to measure the bounding rect of the logical range, enhancing the accuracy of menu placement. - Comprehensive tests added to verify the new positioning behavior and ensure consistent functionality across different scenarios.
This commit improves the context mention feature by implementing a ResizeObserver to track the composer’s auto-growing behavior. Key changes include: - The mention menu now repositions dynamically as the composer resizes, ensuring it remains anchored to the `@` trigger glyph. - Added methods to observe and disconnect the ResizeObserver, preventing memory leaks and ensuring proper cleanup. - Comprehensive tests have been added to verify the new resizing behavior and ensure consistent functionality across various scenarios.
…lity This commit refactors the context mention loaders to improve code maintainability and performance. Key changes include: - Introduction of a `createChunkLoader` utility to handle memoization, rejection-retry semantics, and dynamic imports for context mentions and markdown parsers. - Simplification of the context mention loaders by replacing redundant code with the new utility, enhancing readability and reducing potential errors. - Addition of comprehensive tests for the `createChunkLoader` functionality to ensure reliability and correctness across various scenarios. - Removal of outdated loader implementations, streamlining the codebase and improving overall efficiency.
…egions This commit improves the context mentions feature by enhancing accessibility and user feedback. Key changes include: - Implementation of assertive live regions for announcing resolve failures, ensuring screen readers convey errors effectively. - Updates to the context mention controller to reflect the open state of the picker on the affordance button, improving user interaction. - Introduction of aria attributes for better semantic structure in the mention menu, including proper roles for options and groups. - Comprehensive tests added to verify the new accessibility features and ensure consistent functionality across various scenarios.
…eduplication This commit improves the inline context mentions feature by allowing the same item to be mentioned multiple times within a message, similar to behaviors seen in Slack and other platforms. Key changes include: - Updates to the mention rejection logic to permit duplicate inline mentions while ensuring that the resolved payload is deduplicated at submission. - Adjustments to the `admit` method to reflect the new inline behavior, allowing duplicates without triggering rejection. - Comprehensive tests added to verify the new functionality and ensure that the LLM receives the context only once while rendering all tokens in the message bubble.
This commit introduces significant improvements to the context mentions feature by allowing each resolved mention's body to be wrapped in a configurable block format. Key changes include: - Implementation of `contextMentions.llmFormat`, enabling options for fenced code blocks, Anthropic's document shape, or custom formatting functions. - Updates to the inline demo and context mention manager to reflect the new block formatting, ensuring consistent behavior across different mention types. - Comprehensive tests added to verify the new formatting options and ensure that the LLM receives the correctly formatted context. - Adjustments to the session handling to accommodate the new block structure, enhancing the overall user experience and message clarity.
…pport This commit improves the inline context mentions feature by introducing vertical anchoring for the mention menu. Key changes include: - The mention menu now anchors vertically to the trigger line when the `@` glyph is below line 1, ensuring better alignment and visibility. - A new `verticalOffset` option has been added to the `PopoverOptions`, allowing for customizable vertical positioning based on the trigger's location. - Updates to the context mention controller to handle the new vertical anchoring logic, improving the overall user experience. - Comprehensive tests have been added to verify the new vertical positioning behavior and ensure consistent functionality across various scenarios.
This commit introduces comprehensive documentation for the context mentions feature, detailing its functionality and configuration. Key changes include: - Creation of a new `CONTEXT-MENTIONS.md` file that outlines how users can pull external context into messages using `@` mentions. - Updates to existing documentation to reference the new context mentions guide and its configuration options, including `contextMentions` settings for enabling the feature, display modes, and source management. - Enhancements to the `CONFIGURATION-REFERENCE.md` to include a dedicated section for context mentions, detailing available options and their descriptions. - Improved user guidance with links to live demos showcasing both chip and inline modes for context mentions. - Overall, these changes aim to enhance user understanding and implementation of the context mentions feature within the widget.
…utation to track mentions correctly. Add test to ensure the context row displays on the first mention. Remove unused app ID field from RuntypeClientInitResponse.
…lity computation to track mentions correctly, ensuring the first chip appears as expected. Modify `createMentionChip` to return a getter for the live element, preventing issues with detached nodes. Add a test to verify that custom-rendered chips can be removed after their DOM nodes are swapped.
…dling. This update ensures that pressing stop during a pending mention resolve aborts the turn without dispatching, and that the inline composer's placeholder updates do not overwrite an explicit host-provided aria-label. Comprehensive tests have been added to verify these behaviors.
This commit introduces several improvements to the context mentions feature, including: - Updates to the mention structure to embed full reference objects instead of individual fields, enhancing data integrity. - Removal of unused composer document APIs to streamline the codebase. - Enhancements to the mention menu rendering, allowing for proper grouping and header overrides for ungrouped items. - Comprehensive tests added to ensure the new mention structure and menu behavior function as expected.
This commit introduces performance enhancements to the context mention feature by implementing key optimizations: - Reuse of option rows in the mention menu across renders, reducing rendering churn and improving efficiency. - Caching of the smart-DOM mention source's page snapshot with a short TTL, minimizing main-thread stalls during empty queries on content-heavy pages. - Comprehensive tests added to validate the new rendering behavior and caching logic, ensuring consistent performance improvements.
This commit introduces a new rendering method for user messages that processes segmented prose through the same transform pipeline as other message types. Key changes include: - Mention slots are treated as placeholders during transformation and are replaced with atomic tokens in the output. - A fallback mechanism ensures that if a transform drops a mention slot, the original segment is rendered verbatim, preserving the mention. - Comprehensive tests have been added to validate the new rendering behavior, ensuring that mentions are correctly processed and displayed.
This commit updates the inline mention feature to automatically insert a separating space after a mention token, aligning behavior with popular messaging platforms like Slack and Notion. Key changes include: - The insertion of a space after a mention unless the next character is already whitespace, allowing for seamless typing and chaining of mentions. - Adjustments to tests to verify the new behavior, ensuring that caret positioning and text output reflect the updated functionality. - Documentation added to clarify the new behavior and its impact on user experience.
This commit enhances the context mentions demo by introducing a new display control for switching between chip and inline token rendering. Key changes include: - Updated the demo description to clarify the functionality of both display modes. - Added detailed sections for display options, chip rendering variants, and token styling controls. - Removed the inline context mentions demo file and its associated script, consolidating functionality into the main context mentions demo. - Adjusted the Vite configuration to reflect the removal of the inline demo. - Updated navigation links and descriptions to ensure clarity and consistency across the documentation.
…ry copy-button styles, ensuring the stylesheet remains under the 15 kB gzip budget. Additionally, add base styles for the code-copy wrapper and related elements in home.css to enhance code block functionality.
This commit modifies the intro card component to render with a transparent background and no box shadow, aligning with common practices in chat UIs. The previous elevated card appearance can still be achieved through theme tokens. Additionally, tests and theme configurations have been updated to reflect this change, ensuring the intro card defaults to a flat design when no specific tokens are set.
|
Too many files changed for review. ( Bypass the limit by tagging |
What does this PR do?
Adds a context mentions system to the composer, letting users pull host-provided context into a turn by typing
@(or clicking an "add context" button) and picking from a searchable, grouped menu. Disabled by default and fully lazy-loaded, so initial bundle size is not affected.contextMentionsconfig (sources,trigger,maxMentions,llmFormat, render overrides, and more), exported source helpers (createStaticMentionSource,defaultMentionFilter, a Smart DOM Reader source), resolve-on-select with caching/abort, per-mention delimited LLM blocks (auto-escalating fenced default, Anthropic<document>shape, or custom), and full listbox accessibility (keyboard nav,aria-activedescendant, live regions, ≥44px targets). The menu/chip runtime lives in a separate lazycontext-mentions.jschunk.display: "inline"). Slack/Linear/Cursor-style atomic@tokensthat stay in the sentence, backed by a contenteditable composer shipped as its own ~3 kB lazy chunk. Trigger-anchored menu positioning, duplicate tokens with payload dedup at submit, orderedcontentSegmentsso sent bubbles re-render tokens in place, andrenderMentionTokenfor custom token rendering. Default stays"chip"./-command menu runs alongside@mentions on the shared lazy runtime. Commands are verbs (prompt/action/server) with args,‹hint›placeholders, and Slack-style inline completion;createSlashCommandsSource()builds a command source.components.button.ghost.*tokens (new--persona-button-ghost-*variables, newhoverBackgroundtoken), replacing the attachment button's hardcoded inline styles. Both sit in the composer's left action cluster.Also includes three new showcase demos (
context-mentions,context-mentions-inline,slash-commands), a full feature doc (packages/widget/docs/CONTEXT-MENTIONS.md), and updates to the configuration reference, theme config, and plugins docs.Type of change
Checklist
pnpm lintpassespnpm typecheckpassespnpm --filter @runtypelabs/persona test:run) and I added tests for new behaviorpackages/widgetorpackages/proxy(pnpm changeset). Not required for changes only underexamples/,docs/, CI, or toolingGreptile Summary
This PR introduces a comprehensive context-mentions system to the widget composer —
@-chip mentions, inline@-token mode (Slack/Linear style), and slash commands — all lazy-loaded from a separate chunk so sites that don't enable the feature pay zero additional bundle cost. The PR also adds ghost-button theming and replaces ad-hoc inline attachment-button styles with CSS token variables.@or click, and inline mode additionally swaps the<textarea>for a contenteditable surface via a second lazy chunk.performSubmit(async) replaces the old synchronoushandleSubmit, gated by asubmitInFlightflip-flop to prevent double-dispatch; chip mentions resolve before API dispatch with deep-merged context maps; slash commands dispatch as action/prompt/server variants.@tokens(inline mode) via a placeholder-nonce pipeline that survives the full markdown/postprocess/sanitize transform.Confidence Score: 5/5
Safe to merge. The core submit path, mention finalization, and abort/re-entrancy guards are all correctly implemented; the two observations are limited to silent degradation in an uncommon server-command error path and unlinked abort signals that are a resource-hygiene concern rather than incorrect behavior.
The orchestrator → controller → manager layering is well-designed, the
submitInFlightguard and deepmergeMentionContextboth address previously flagged races, and the lazy-chunk retry/fallback paths degrade gracefully. The two remaining observations affect edge cases only and do not corrupt state or expose user data.packages/widget/src/utils/context-mention-controller.ts — the
dispatchInlineCommandserver finalize andresolveContextsignal handling.Important Files Changed
submitInFlightguard and mention orchestrator integration;mergeMentionContext/mergeFinalizedMentionshelpers added for deep context merging. The orchestrator setup, listener registry, and inline-swap wiring are well-structured.applyMentionBundlefor post-echo, pre-dispatch mention finalization; abort-guard correctly checks bothcontroller.signal.abortedandthis.abortController !== controller. Image-only fallback text now correctly excludes mention-only messages.finalizelacks error handling parity with chip/inline mentions;resolveContextcreates unlinked abort signals.onMentionResolveError, and drop only the failing item at finalize time.onComposerSwapreplay are all handled correctly.renderSegmentsWithTransformfor inline-mode bubbles. The PUA-nonce placeholder pipeline with a survived-check fallback is well-guarded against transform edge cases.execCommand-with-fallback for paste (previously flagged); token deletion, caret mapping, and IME guarding are comprehensive. Lives in the separate inline lazy chunk.buildContextAggregate(shared between agent and flow payload builders) that merges context-provider results with the latest turn'smentionContextunder the"mentions"key. Previously flagged: the"mentions"key is effectively reserved and undocumented.providefor eager builds. Clean and well-tested.Sequence Diagram
%%{init: {'theme': 'neutral'}}%% sequenceDiagram participant User participant UI as ui.ts (handleSubmit) participant Orch as ContextMentionOrchestrator participant Engine as ContextMentionEngine (lazy) participant Manager as ContextMentionManager participant Session as AgentWidgetSession participant Client as AgentWidgetClient User->>UI: "types @query / presses Enter" UI->>Orch: handleInput(inputType) Orch->>Engine: ensureEngine() [lazy load chunk] Engine->>Manager: menu open → user selects item Manager->>Manager: add() → startPending() → resolvePending() Note over Manager: chip rendered, resolve in-flight User->>UI: presses Enter (submit) UI->>UI: submitInFlight guard UI->>Orch: takeInlineCommand(value) [await] Orch-->>UI: null (no inline command) UI->>Orch: collectForSubmit() Orch->>Manager: collectForSubmit() → detaches chips, returns refs + finalize UI->>Session: sendMessage(text, mentions, contentParts, contentSegments) Session->>Session: appendMessage(userMessage) + setStreaming(true) Session->>Session: applyMentionBundle() [await finalize()] Manager->>Manager: finalize() → awaits in-flight resolves, builds bundle Session->>Session: merge blocks/contentParts/context into stored message Session->>Client: dispatch(snapshot) Client->>Client: buildContextAggregate() → merges contextProviders + mentionContext Client-->>Session: SSE stream Session-->>UI: onMessagesChanged → re-render bubbles%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%% sequenceDiagram participant User participant UI as ui.ts (handleSubmit) participant Orch as ContextMentionOrchestrator participant Engine as ContextMentionEngine (lazy) participant Manager as ContextMentionManager participant Session as AgentWidgetSession participant Client as AgentWidgetClient User->>UI: "types @query / presses Enter" UI->>Orch: handleInput(inputType) Orch->>Engine: ensureEngine() [lazy load chunk] Engine->>Manager: menu open → user selects item Manager->>Manager: add() → startPending() → resolvePending() Note over Manager: chip rendered, resolve in-flight User->>UI: presses Enter (submit) UI->>UI: submitInFlight guard UI->>Orch: takeInlineCommand(value) [await] Orch-->>UI: null (no inline command) UI->>Orch: collectForSubmit() Orch->>Manager: collectForSubmit() → detaches chips, returns refs + finalize UI->>Session: sendMessage(text, mentions, contentParts, contentSegments) Session->>Session: appendMessage(userMessage) + setStreaming(true) Session->>Session: applyMentionBundle() [await finalize()] Manager->>Manager: finalize() → awaits in-flight resolves, builds bundle Session->>Session: merge blocks/contentParts/context into stored message Session->>Client: dispatch(snapshot) Client->>Client: buildContextAggregate() → merges contextProviders + mentionContext Client-->>Session: SSE stream Session-->>UI: onMessagesChanged → re-render bubblesReviews (3): Last reviewed commit: "Refactor context mentions demo and remov..." | Re-trigger Greptile