Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(agent): slash command typeahead in the agent composer (#5882)

Eric Hayes4e1d9dc9ecd6
diff --git a/apps/web/src/features/block-agent/component/AgentComposer.tsx b/apps/web/src/features/block-agent/component/AgentComposer.tsx
index 5947322143..3a7ebc1230 100644
--- a/apps/web/src/features/block-agent/component/AgentComposer.tsx
+++ b/apps/web/src/features/block-agent/component/AgentComposer.tsx
@@ -40,6 +40,7 @@ export function AgentComposer() {
autofocus={autofocus}
busy={composer.busy()}
disabled={loadFailed()}
+ commands={() => metadata()?.availableCommands ?? []}
onSend={composer.send}
onStop={composer.stop}
modelControl={
diff --git a/apps/web/src/features/block-agent/ui/AgentInput.tsx b/apps/web/src/features/block-agent/ui/AgentInput.tsx
index 3660c1175f..956be4186c 100644
--- a/apps/web/src/features/block-agent/ui/AgentInput.tsx
+++ b/apps/web/src/features/block-agent/ui/AgentInput.tsx
@@ -8,6 +8,7 @@
import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';
import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';
+import type { AgentCommandItem } from '@core/component/LexicalMarkdown/plugins';
import { Button, SendButton, Surface } from '@ui';
import { createSignal, type JSX, Show } from 'solid-js';
@@ -17,6 +18,11 @@ export interface AgentInputProps {
busy?: boolean;
disabled?: boolean;
autofocus?: boolean;
+ /**
+ * Slash commands the harness advertises (ACP `available_commands_update`);
+ * typing `/` opens a typeahead over them. `/` stays plain text while empty.
+ */
+ commands?: () => AgentCommandItem[];
/** Receives the composed markdown. */
onSend: (markdown: string) => void;
onStop?: () => void;
@@ -57,6 +63,7 @@ export function AgentInput(props: AgentInputProps) {
.withHistory({ timeGap: 400 })
.withCode()
.withRestoreFocus()
+ .withAgentCommands({ commands: () => props.commands?.() ?? [] })
.onEnter(() => {
send();
return true;
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.ts b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.ts
index 602425d0f8..d519d8d92b 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.ts
@@ -6,6 +6,7 @@ import type { Action } from '../plugins/actions/types';
import { buildHandleFromConfig } from './buildHandleFromConfig';
import type {
ActionsOptions,
+ AgentCommandsOptions,
EditorBuilder,
EditorCallbacks,
EditorConfig,
@@ -180,6 +181,18 @@ export class EditorConfigBuilder implements EditorBuilder {
return this;
}
+ /**
+ * Enable the agent commands (`/`) typeahead menu — for agent composers.
+ * Lists the slash commands a connected coding agent advertises over ACP;
+ * selecting one inserts `/name` as plain text, which is sent to the agent
+ * as ordinary prompt text. Shares the `/` trigger with the actions and
+ * skills menus, so it only takes effect when both are disabled.
+ */
+ withAgentCommands(config: AgentCommandsOptions): this {
+ this.state.agentCommands = config;
+ return this;
+ }
+
singleLine(): this {
this.state.singleLine = true;
return this;
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx
index 22978b9c2a..960b37cc7e 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx
@@ -21,6 +21,7 @@ import {
import { DecoratorRenderer } from '../component/core/DecoratorRenderer';
import { NodeAccessoryRenderer } from '../component/core/NodeAccessoryRenderer';
import { ActionMenu } from '../component/menu/ActionsMenu';
+import { AgentCommandsMenu } from '../component/menu/AgentCommandsMenu';
import { EmojiMenu } from '../component/menu/EmojiMenu';
import { FloatingFormatMenu } from '../component/menu/FloatingFormatMenu';
import { FloatingLinkMenu } from '../component/menu/FloatingLinkMenu';
@@ -347,6 +348,19 @@ export const MarkdownShell: Component<
)}
</Show>
+ {/* Agent Commands Menu */}
+ <Show when={state.agentCommandsMenuOps}>
+ {(menu) => (
+ <AgentCommandsMenu
+ editor={editor}
+ menu={menu()}
+ commands={builderConfig.agentCommands?.commands ?? (() => [])}
+ useBlockBoundary={false}
+ portalScope={props.portalScope}
+ />
+ )}
+ </Show>
+
{/* Floating Link & Selection Format Menus */}
<Show
when={
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts b/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts
index 9e437a1681..ac27769744 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts
@@ -5,6 +5,7 @@ import { createSignal } from 'solid-js';
import { createLexicalWrapper } from '../context/LexicalWrapperContext';
import {
actionsPlugin,
+ agentCommandsPlugin,
awaitPlugin,
codePlugin,
createAccessoryStore,
@@ -97,6 +98,16 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {
config.type !== 'plain-text'
? createMenuOperations()
: undefined;
+ // Agent commands (`/` menu) list the slash commands a connected coding
+ // agent advertises over ACP. They share the `/` trigger with the actions
+ // and skills menus, so they only activate when neither owns it.
+ const agentCommandsMenuOps =
+ config.agentCommands &&
+ !actionsMenuOps &&
+ !skillsMenuOps &&
+ config.type !== 'plain-text'
+ ? createMenuOperations()
+ : undefined;
const accessoryStoreResult = config.code ? createAccessoryStore() : undefined;
const accessoryStore = accessoryStoreResult?.[0];
@@ -208,6 +219,15 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {
if (skillsMenuOps) {
plugins.use(skillsPlugin({ menu: skillsMenuOps }));
}
+
+ if (agentCommandsMenuOps && config.agentCommands) {
+ plugins.use(
+ agentCommandsPlugin({
+ menu: agentCommandsMenuOps,
+ commands: config.agentCommands.commands,
+ })
+ );
+ }
}
// Media (images, videos)
@@ -306,7 +326,8 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {
(tagsMenuOps?.isOpen() ?? false) ||
(emojisMenuOps?.isOpen() ?? false) ||
(snippetsMenuOps?.isOpen() ?? false) ||
- (skillsMenuOps?.isOpen() ?? false),
+ (skillsMenuOps?.isOpen() ?? false) ||
+ (agentCommandsMenuOps?.isOpen() ?? false),
})
);
}
@@ -332,7 +353,16 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {
const actions = actionsMenuOps?.isOpen() ?? false;
const snippets = snippetsMenuOps?.isOpen() ?? false;
const skills = skillsMenuOps?.isOpen() ?? false;
- return mentions || tags || emojis || actions || snippets || skills;
+ const agentCommands = agentCommandsMenuOps?.isOpen() ?? false;
+ return (
+ mentions ||
+ tags ||
+ emojis ||
+ actions ||
+ snippets ||
+ skills ||
+ agentCommands
+ );
},
};
@@ -355,6 +385,7 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {
emojisMenuOps,
snippetsMenuOps,
skillsMenuOps,
+ agentCommandsMenuOps,
accessoryStore,
dragInsertStore,
draggableBlockStore,
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.ts b/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.ts
index c2d8b04487..d61b49f5f9 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.ts
@@ -8,6 +8,7 @@ import type { Store } from 'solid-js/store';
import type { MentionBucketId } from '../component/menu/MentionsMenu/MentionsMenuController';
import type { createLexicalWrapper } from '../context/LexicalWrapperContext';
import type {
+ AgentCommandItem,
AutoLinkMatchMode,
createAccessoryStore,
createDraggableBlockStore,
@@ -58,6 +59,11 @@ export interface TagsOptions {
setTags?: (tags: ReadonlySet<TagMentionLifecycle>) => void;
}
+export interface AgentCommandsOptions {
+ /** Reactive source of the slash commands the connected agent advertises. */
+ commands: () => AgentCommandItem[];
+}
+
/** Intentional extension point — no options yet. */
export type EmojisOptions = Record<string, never>;
@@ -149,6 +155,13 @@ export interface EditorConfig {
* actions are disabled.
*/
skills?: boolean;
+ /**
+ * Agent commands (`/` menu) list the slash commands a connected coding
+ * agent advertises over ACP — for agent composers. Shares the `/` trigger
+ * with the actions and skills menus, so this only takes effect when both
+ * are disabled.
+ */
+ agentCommands?: AgentCommandsOptions;
emojis?: EmojisOptions;
links?: LinksOptions;
history?: HistoryOptions;
@@ -186,6 +199,7 @@ export interface EditorInternals {
emojisMenuOps: ReturnType<typeof createMenuOperations> | undefined;
snippetsMenuOps: ReturnType<typeof createMenuOperations> | undefined;
skillsMenuOps: ReturnType<typeof createMenuOperations> | undefined;
+ agentCommandsMenuOps: ReturnType<typeof createMenuOperations> | undefined;
accessoryStore: ReturnType<typeof createAccessoryStore>[0] | undefined;
dragInsertStore: ReturnType<typeof createDragInsertStore>[0] | undefined;
draggableBlockStore:
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/AgentCommandsMenu/AgentCommandsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/AgentCommandsMenu/AgentCommandsMenu.tsx
new file mode 100644
index 0000000000..ebb015a588
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/AgentCommandsMenu/AgentCommandsMenu.tsx
@@ -0,0 +1,281 @@
+import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';
+import clickOutside from '@core/directive/clickOutside';
+import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
+import { cn, Surface } from '@ui';
+import type { LexicalEditor } from 'lexical';
+import {
+ createEffect,
+ createSignal,
+ For,
+ onCleanup,
+ onMount,
+ Show,
+ untrack,
+} from 'solid-js';
+import { floatWithSelection } from '../../../directive/floatWithSelection';
+import {
+ type AgentCommandItem,
+ CLOSE_AGENT_COMMAND_SEARCH_COMMAND,
+ INSERT_AGENT_COMMAND_COMMAND,
+} from '../../../plugins/agent-commands';
+import type { MenuOperations } from '../../../shared/inlineMenu';
+import { useMenuKeyboardNavigation } from '../useMenuKeyboardNavigation';
+
+false && clickOutside;
+false && floatWithSelection;
+
+// Height consumed by Surface's border + vertical padding
+const PANEL_DECORATION_HEIGHT = 18;
+
+type AgentCommandsMenuProps = {
+ editor: LexicalEditor;
+ menu: MenuOperations;
+ /** Slash commands advertised by the connected agent. */
+ commands: () => AgentCommandItem[];
+ /** whether the menu checks against block boundary in floating middleware. uses floating-ui default if false. */
+ useBlockBoundary?: boolean;
+ portalScope?: PortalScope;
+};
+
+/**
+ * Typeahead menu opened by typing `/` in an agent composer. Lists the slash
+ * commands the connected coding agent advertised over ACP; selecting one
+ * inserts `/name` as plain text at the cursor — commands travel to the agent
+ * as ordinary prompt text.
+ */
+export function AgentCommandsMenu(props: AgentCommandsMenuProps) {
+ const searchTerm = props.menu.searchTerm;
+ const activeSearchTerm = () => (props.menu.isOpen() ? searchTerm() : '');
+
+ // Name-prefix matches first, then substring matches on name or description.
+ const filteredCommands = () => {
+ const term = activeSearchTerm().trim().toLowerCase();
+ const all = props.commands();
+ if (!term) return all;
+ const prefix: AgentCommandItem[] = [];
+ const contains: AgentCommandItem[] = [];
+ for (const command of all) {
+ const name = command.name.toLowerCase();
+ if (name.startsWith(term)) {
+ prefix.push(command);
+ } else if (
+ name.includes(term) ||
+ command.description.toLowerCase().includes(term)
+ ) {
+ contains.push(command);
+ }
+ }
+ return [...prefix, ...contains];
+ };
+
+ const [selectedIndex, setSelectedIndex] = createSignal(0);
+ const [mountSelection, setMountSelection] = createSignal<Selection | null>();
+ const [escapeSpaceState, setEscapeSpaceState] = createSignal<
+ 'start' | 'single' | null
+ >('start');
+
+ const { isKeypressActive } = useIsKeyPressActive();
+ const setSelectedIndexFromMouse = (index: number) => {
+ if (isKeypressActive()) return;
+ setSelectedIndex(index);
+ };
+
+ const [menuOpen, setMenuOpen] = [props.menu.isOpen, props.menu.setIsOpen];
+
+ createEffect(() => {
+ if (menuOpen()) {
+ setMountSelection(document.getSelection());
+ setSelectedIndex(0);
+ setEscapeSpaceState('start');
+ } else {
+ setMountSelection(null);
+ }
+ });
+
+ createEffect(() => {
+ searchTerm();
+ setSelectedIndex(0);
+ });
+
+ createEffect(() => {
+ const count = filteredCommands().length;
+ if (count > 0 && selectedIndex() >= count) {
+ setSelectedIndex(count - 1);
+ }
+ });
+
+ const closeMenu = () => {
+ props.editor.dispatchCommand(CLOSE_AGENT_COMMAND_SEARCH_COMMAND, undefined);
+ setMenuOpen(false);
+ };
+
+ const insertCommand = (command: AgentCommandItem) => {
+ props.editor.dispatchCommand(INSERT_AGENT_COMMAND_COMMAND, command);
+ };
+
+ useMenuKeyboardNavigation({
+ isActive: menuOpen,
+ onUp: () => {
+ const items = filteredCommands();
+ if (items.length === 0) return;
+ setSelectedIndex((selectedIndex() - 1 + items.length) % items.length);
+ },
+ onDown: () => {
+ const items = filteredCommands();
+ if (items.length === 0) return;
+ setSelectedIndex((selectedIndex() + 1) % items.length);
+ },
+ onLeft: () => {
+ // block horizontal arrows
+ },
+ onRight: () => {
+ // block horizontal arrows
+ },
+ onSelect: () => {
+ const selectedItem = filteredCommands()[selectedIndex()];
+ if (selectedItem) {
+ insertCommand(selectedItem);
+ } else {
+ closeMenu();
+ }
+ },
+ onClose: closeMenu,
+ onSpace: () => {
+ switch (escapeSpaceState()) {
+ case 'single':
+ case 'start':
+ closeMenu();
+ return true;
+ case null:
+ setEscapeSpaceState('single');
+ return false;
+ }
+ return false;
+ },
+ onOtherKey: () => {
+ setEscapeSpaceState(null);
+ },
+ });
+
+ const focusOut = () => {
+ closeMenu();
+ };
+ onMount(() => {
+ document.addEventListener('focusout', focusOut);
+ onCleanup(() => {
+ document.removeEventListener('focusout', focusOut);
+ });
+ });
+
+ const [menuAvailableHeight, setMenuAvailableHeight] = createSignal<
+ number | undefined
+ >(undefined);
+
+ const contentMaxHeight = () => {
+ const h = menuAvailableHeight();
+ if (h === undefined) return 256;
+ return Math.min(256, Math.max(0, h - PANEL_DECORATION_HEIGHT));
+ };
+
+ return (
+ <Show when={menuOpen()}>
+ <ScopedPortal scope={props.portalScope}>
+ <div
+ class="w-96 max-w-[calc(100cqw-1rem-2px)] cursor-default select-none z-modal-content menu-open-animation"
+ use:floatWithSelection={{
+ selection: untrack(mountSelection),
+ reactiveOnContainer: props.editor.getRootElement(),
+ useBlockBoundary: props.useBlockBoundary,
+ onAvailableHeight: setMenuAvailableHeight,
+ }}
+ use:clickOutside={() => {
+ closeMenu();
+ }}
+ on:touchstart={(e) => e.stopPropagation()}
+ >
+ <Surface
+ depth={2}
+ class="pt-2 pb-1.5 shadow-lg shadow-drop-shadow rounded-xl"
+ >
+ <div class="px-3.5 pb-1 text-xs font-medium text-ink-muted">
+ Commands
+ </div>
+ <Show
+ when={filteredCommands().length > 0}
+ fallback={
+ <div class="px-3.5 pb-1 text-ink-extra-muted">No results</div>
+ }
+ >
+ <div
+ class="overflow-y-auto scrollbar-hidden"
+ style={{ 'max-height': `${contentMaxHeight()}px` }}
+ >
+ <For each={filteredCommands()}>
+ {(command, index) => (
+ <AgentCommandRow
+ command={command}
+ index={index()}
+ selected={index() === selectedIndex()}
+ itemAction={() => insertCommand(command)}
+ setIndex={setSelectedIndexFromMouse}
+ />
+ )}
+ </For>
+ </div>
+ </Show>
+ </Surface>
+ </div>
+ </ScopedPortal>
+ </Show>
+ );
+}
+
+function AgentCommandRow(props: {
+ command: AgentCommandItem;
+ index: number;
+ selected: boolean;
+ itemAction: () => void;
+ setIndex: (index: number) => void;
+}) {
+ let itemRef: HTMLDivElement | undefined;
+
+ createEffect(() => {
+ if (props.selected && itemRef) {
+ itemRef.scrollIntoView({ block: 'nearest' });
+ }
+ });
+
+ return (
+ <div
+ ref={itemRef}
+ on:mouseup={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ on:mousedown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ on:click={(e) => {
+ props.itemAction();
+ e.stopPropagation();
+ }}
+ on:mousemove={() => props.setIndex(props.index)}
+ class={cn('group flex items-baseline gap-2 p-1.5 mx-1.5 rounded-md', {
+ 'bg-ink/5': props.selected,
+ })}
+ >
+ <span class="shrink-0 text-ink text-xs sm:text-sm font-medium">
+ /{props.command.name}
+ </span>
+ <Show when={props.command.inputHint}>
+ <span class="shrink-0 text-xs text-ink-extra-muted">
+ {props.command.inputHint}
+ </span>
+ </Show>
+ <span class="min-w-0 truncate text-xs text-ink-muted">
+ {props.command.description}
+ </span>
+ </div>
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/AgentCommandsMenu/index.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/AgentCommandsMenu/index.ts
new file mode 100644
index 0000000000..955e0f81d5
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/AgentCommandsMenu/index.ts
@@ -0,0 +1 @@
+export * from './AgentCommandsMenu';
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/agent-commands/agentCommandsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/agent-commands/agentCommandsPlugin.ts
new file mode 100644
index 0000000000..5343097a45
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/agent-commands/agentCommandsPlugin.ts
@@ -0,0 +1,223 @@
+import { $dfsIterator, mergeRegister } from '@lexical/utils';
+import type { PeerIdValidator } from '@macro-inc/lexical-core';
+import {
+ $collapseInlineSearch,
+ $createInlineSearchNode,
+ $handleInlineSearchNodeMutation,
+ $handleInlineSearchNodeTransform,
+ $isInlineSearchNode,
+ $removeInlineSearch,
+ InlineSearchNode,
+ InlineSearchNodesType,
+ validTriggerPosition,
+} from '@macro-inc/lexical-core';
+import {
+ $createTextNode,
+ $insertNodes,
+ COMMAND_PRIORITY_CRITICAL,
+ COMMAND_PRIORITY_HIGH,
+ COMMAND_PRIORITY_LOW,
+ createCommand,
+ KEY_ENTER_COMMAND,
+ KEY_ESCAPE_COMMAND,
+ type LexicalCommand,
+ type LexicalEditor,
+ type LexicalNode,
+} from 'lexical';
+import type { MenuOperations } from '../../shared/inlineMenu';
+
+/**
+ * A slash command advertised by a connected coding agent (ACP
+ * `available_commands_update`). Structurally matches the folded session
+ * metadata's `AvailableCommand` without coupling the editor to that
+ * service-client type.
+ */
+export type AgentCommandItem = {
+ /** Bare command name without the leading slash, e.g. `qc` or `compact`. */
+ name: string;
+ description: string;
+ /** Hint for the command's free-form argument text, if it accepts any. */
+ inputHint: string | null;
+};
+
+const TYPE_AGENT_COMMAND_SYMBOL_COMMAND: LexicalCommand<void> = createCommand(
+ 'AGENT_COMMAND_SYMBOL_COMMAND'
+);
+
+export const CLOSE_AGENT_COMMAND_SEARCH_COMMAND: LexicalCommand<void> =
+ createCommand('CLOSE_AGENT_COMMAND_SEARCH_COMMAND');
+
+export const REMOVE_AGENT_COMMAND_SEARCH_COMMAND: LexicalCommand<void> =
+ createCommand('REMOVE_AGENT_COMMAND_SEARCH_COMMAND');
+
+/**
+ * Replaces the active `/` search with the chosen command as plain text.
+ * Slash commands travel to the agent as ordinary prompt text (`/name args`),
+ * so unlike skills there is no node to insert — just the literal `/name`.
+ */
+export const INSERT_AGENT_COMMAND_COMMAND: LexicalCommand<AgentCommandItem> =
+ createCommand('INSERT_AGENT_COMMAND_COMMAND');
+
+type AgentCommandsPluginProps = {
+ menu: MenuOperations;
+ /** Reactive source of the commands the connected agent advertises. */
+ commands: () => AgentCommandItem[];
+ peerIdValidator?: PeerIdValidator;
+};
+
+// Validators for the position of the / trigger: start of line or after
+// whitespace, matching the skills and actions menu triggers.
+const beforeRegex = /\s$/;
+const afterRegex = /^\s/;
+
+function $isCommandSearchNode(
+ node: LexicalNode | null | undefined
+): node is InlineSearchNode {
+ return (
+ $isInlineSearchNode(node) &&
+ node.getTextContent().trim().charAt(0) === InlineSearchNodesType.Actions
+ );
+}
+
+function $getActiveCommandSearchNode(): InlineSearchNode | null {
+ for (const { node } of $dfsIterator()) {
+ if ($isCommandSearchNode(node)) {
+ return node;
+ }
+ }
+
+ return null;
+}
+
+/**
+ * Registers the `/` trigger for the agent commands menu. Typing `/` at a
+ * valid trigger position (start of line or after whitespace) opens a
+ * typeahead listing the slash commands the connected agent advertised over
+ * ACP; selecting one inserts `/name` as plain text at the cursor (see
+ * AgentCommandsMenu). The `/` falls through as regular text while the agent
+ * has not advertised any commands.
+ *
+ * Shares the `/` symbol with the actions and skills menus, so this plugin
+ * must only be enabled in editors where both of those are disabled — the
+ * agent block's composer.
+ */
+function registerAgentCommandsPlugin(
+ editor: LexicalEditor,
+ props: AgentCommandsPluginProps
+) {
+ function registerSymbolListener() {
+ const listener = (e: KeyboardEvent) => {
+ if (e.key === '/') {
+ editor.dispatchCommand(TYPE_AGENT_COMMAND_SYMBOL_COMMAND, undefined);
+ }
+ };
+
+ return editor.registerRootListener((root, prev) => {
+ if (root) {
+ root.addEventListener('keydown', listener);
+ }
+ if (prev) {
+ prev.removeEventListener('keydown', listener);
+ }
+ });
+ }
+
+ const { menu } = props;
+
+ function typeSymbolCommand() {
+ if (props.commands().length === 0) return false;
+ const shouldTrigger = validTriggerPosition(editor, beforeRegex, afterRegex);
+ if (shouldTrigger) {
+ editor.update(() => {
+ $insertNodes([$createInlineSearchNode('/')]);
+ });
+ return true;
+ }
+ return false;
+ }
+
+ function insertCommand(command: AgentCommandItem) {
+ menu.setSearchTerm('');
+ menu.setIsOpen(false);
+
+ editor.update(() => {
+ const searchNode = $getActiveCommandSearchNode();
+ if (!searchNode) {
+ return;
+ }
+
+ searchNode.selectEnd();
+ searchNode.remove();
+ // Trailing space only when the command takes arguments; a bare command
+ // is ready to send with Enter as-is.
+ const text = command.inputHint ? `/${command.name} ` : `/${command.name}`;
+ const textNode = $createTextNode(text);
+ $insertNodes([textNode]);
+ textNode.selectEnd();
+ });
+ }
+
+ return mergeRegister(
+ registerSymbolListener(),
+ // When you type /
+ editor.registerCommand(
+ TYPE_AGENT_COMMAND_SYMBOL_COMMAND,
+ typeSymbolCommand,
+ COMMAND_PRIORITY_LOW
+ ),
+ editor.registerCommand(
+ CLOSE_AGENT_COMMAND_SEARCH_COMMAND,
+ () => $collapseInlineSearch(props.peerIdValidator),
+ COMMAND_PRIORITY_LOW
+ ),
+ editor.registerCommand(
+ KEY_ESCAPE_COMMAND,
+ () => $collapseInlineSearch(props.peerIdValidator),
+ COMMAND_PRIORITY_HIGH
+ ),
+ editor.registerCommand(
+ REMOVE_AGENT_COMMAND_SEARCH_COMMAND,
+ () => $removeInlineSearch(props.peerIdValidator),
+ COMMAND_PRIORITY_HIGH
+ ),
+ editor.registerCommand(
+ INSERT_AGENT_COMMAND_COMMAND,
+ (payload) => {
+ insertCommand(payload);
+ return true;
+ },
+ COMMAND_PRIORITY_HIGH
+ ),
+ // Menu ENTERS should not propagate to the editor.
+ editor.registerCommand(
+ KEY_ENTER_COMMAND,
+ () => menu.isOpen(),
+ COMMAND_PRIORITY_CRITICAL
+ ),
+ editor.registerNodeTransform(InlineSearchNode, (node: InlineSearchNode) =>
+ $handleInlineSearchNodeTransform(node, InlineSearchNodesType.Actions)
+ ),
+ editor.registerMutationListener(
+ InlineSearchNode,
+ (mutatedNodes, { prevEditorState }) =>
+ $handleInlineSearchNodeMutation(
+ editor,
+ prevEditorState,
+ mutatedNodes,
+ InlineSearchNodesType.Actions,
+ {
+ onDestroy: () => menu.closeMenu(),
+ onCreate: () => menu.openMenu(),
+ onUpdate: (search) => {
+ menu.setSearchTerm(search);
+ },
+ },
+ props.peerIdValidator
+ )
+ )
+ );
+}
+
+export function agentCommandsPlugin(props: AgentCommandsPluginProps) {
+ return (editor: LexicalEditor) => registerAgentCommandsPlugin(editor, props);
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/agent-commands/index.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/agent-commands/index.ts
new file mode 100644
index 0000000000..93154abff0
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/agent-commands/index.ts
@@ -0,0 +1 @@
+export * from './agentCommandsPlugin';
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/index.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/index.ts
index 23b022b09a..dbe53e501c 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/index.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/index.ts
@@ -1,4 +1,5 @@
export * from './actions';
+export * from './agent-commands';
export * from './await';
export * from './blame-tooltip';
export * from './checklist';