Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(editor): add / slash-command palette for invoking agent skills (#3159)
Qi Yijiazhen91c1e5141198
diff --git a/packages/ui/markdown/Markdown.tsx b/packages/ui/markdown/Markdown.tsxindex a561c57994..323e424cf9 100644--- a/packages/ui/markdown/Markdown.tsx+++ b/packages/ui/markdown/Markdown.tsx@@ -78,12 +78,12 @@ export interface MarkdownProps {}// Sanitization schema — extends GitHub defaults to allow code highlighting classes-// and the mention:// protocol used for @mentions.+// and Multica's internal mention/slash protocols.const sanitizeSchema = {...defaultSchema,protocols: {...defaultSchema.protocols,- href: [...(defaultSchema.protocols?.href ?? []), 'mention'],+ href: [...(defaultSchema.protocols?.href ?? []), 'mention', 'slash'],},attributes: {...defaultSchema.attributes,@@ -107,11 +107,12 @@ const sanitizeSchema = {}/**- * Custom URL transform that allows mention:// protocol (used for @mentions)- * while keeping the default security for all other URLs.+ * Custom URL transform that allows Multica internal protocols while keeping+ * the default security for all other URLs.*/function urlTransform(url: string): string {if (url.startsWith('mention://')) return url+ if (url.startsWith('slash://skill/')) return urlreturn defaultUrlTransform(url)}@@ -207,6 +208,14 @@ function createComponents()}+ if (href?.startsWith('slash://skill/')) {+ return (+ <span className="slash-command text-primary font-semibold mx-0.5">+ {children}+ </span>+ )+ }+const handleClick = (e: React.MouseEvent): void => {e.preventDefault()if (href) {diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsxindex 5810933ad6..ab3299cb16 100644--- a/packages/views/chat/components/chat-input.tsx+++ b/packages/views/chat/components/chat-input.tsx@@ -230,11 +230,13 @@ export function ChatInput({onSubmit={handleSend}onUploadFile={uploadEnabled ? handleUpload : undefined}debounceMs={100}+ enableSlashCommands// Chat is short-form — the floating formatting toolbar is// more distraction than feature here.showBubbleMenu={false}- // Mod+Enter submits. Bare Enter falls through to Tiptap's- // default, which continues lists/quotes and breaks paragraphs.+ // Chat intentionally leaves submitOnEnter at its default false:+ // Mod+Enter submits, while bare Enter falls through to Tiptap's+ // default behavior for lists, quotes, and paragraph breaks.// Without this, Enter-as-send would steal the only key that// continues a bullet list, leaving users stuck after one item./>diff --git a/packages/views/common/markdown.test.tsx b/packages/views/common/markdown.test.tsxindex c807e82445..f2736b99e4 100644--- a/packages/views/common/markdown.test.tsx+++ b/packages/views/common/markdown.test.tsx@@ -36,4 +36,14 @@ describe("Markdown", () => {expect(screen.getByText("uv run --extra dev pytest -q")).toHaveClass(...ligatureClasses);});++ it("renders slash skill links as slash command pills", () => {+ const { container } = render(+ <Markdown>[/deploy](slash://skill/abc-123)</Markdown>,+ );++ const pill = container.querySelector(".slash-command");+ expect(pill).not.toBeNull();+ expect(pill?.textContent).toBe("/deploy");+ });});diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsxindex 8c9016b4f7..cc3a1abf2d 100644--- a/packages/views/editor/content-editor.tsx+++ b/packages/views/editor/content-editor.tsx@@ -96,6 +96,8 @@ interface ContentEditorProps {* prompts) but *preserving* an existing one still matters.*/disableMentions?: boolean;+ /** Enable the chat-only `/` skill picker. Defaults false. */+ enableSlashCommands?: boolean;/*** Attachments referenced by this content. The download buttons on file* cards and images inside the editor look up an attachment by `url` and@@ -139,6 +141,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(submitOnEnter = false,currentIssueId,disableMentions = false,+ enableSlashCommands = false,attachments,},ref,@@ -182,6 +185,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(onUploadFileRef,submitOnEnter,disableMentions,+ enableSlashCommands,}),onUpdate: ({ editor: ed }) => {if (!onUpdateRef.current) return;diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.tsindex 557978141c..456f3395b3 100644--- a/packages/views/editor/extensions/index.ts+++ b/packages/views/editor/extensions/index.ts@@ -38,6 +38,8 @@ import type { UploadResult } from "@multica/core/hooks/use-file-upload";import { escapeMarkdownLabel } from "../utils/escape-markdown-label";import { BaseMentionExtension } from "./mention-extension";import { createMentionSuggestion } from "./mention-suggestion";+import { SlashCommandExtension } from "./slash-command-extension";+import { createSlashCommandSuggestion } from "./slash-command-suggestion";import { CodeBlockView } from "./code-block-view";import { PatchedListItem } from "./list-item";import { createMarkdownPasteExtension } from "./markdown-paste";@@ -105,6 +107,8 @@ export interface EditorExtensionsOptions {* system prompts) but *preserving* an existing one still matters.*/disableMentions?: boolean;+ /** When true, attach the `/` skill picker. Default false. */+ enableSlashCommands?: boolean;}export function createEditorExtensions(@@ -154,6 +158,13 @@ export function createEditorExtensions(? { suggestion: createMentionSuggestion(options.queryClient) }: {}),}),+ SlashCommandExtension.configure({+ HTMLAttributes: { class: "slash-command" },+ suggestion:+ options.enableSlashCommands && options.queryClient+ ? createSlashCommandSuggestion(options.queryClient)+ : { char: "/", allow: () => false },+ }),Typography,Placeholder.configure({ placeholder: placeholderText }),createMarkdownPasteExtension(),diff --git a/packages/views/editor/extensions/slash-command-extension.test.ts b/packages/views/editor/extensions/slash-command-extension.test.tsnew file mode 100644index 0000000000..e54660ada5--- /dev/null+++ b/packages/views/editor/extensions/slash-command-extension.test.ts@@ -0,0 +1,89 @@+import { describe, expect, it } from "vitest";+import { SlashCommandExtension } from "./slash-command-extension";++const tokenizer = SlashCommandExtension.config.markdownTokenizer!;++const startFn = tokenizer.start as (src: string) => number;+const tokenizeFn = tokenizer.tokenize as (+ src: string,+) => { type: string; raw: string; attributes: Record<string, string> } | undefined;+const renderMarkdown = SlashCommandExtension.config.renderMarkdown as (+ node: { attrs: Record<string, string> },+) => string;+const renderHTML = SlashCommandExtension.config.renderHTML as (+ this: { options: { HTMLAttributes: Record<string, string> } },+ props: {+ node: { attrs: Record<string, string | undefined> };+ HTMLAttributes: Record<string, string>;+ },+) => [string, Record<string, string>, string];++function tokenize(src: string) {+ const start = startFn(src);+ if (start === -1) return undefined;+ return tokenizeFn(src.slice(start));+}++describe("slash command tokenizer", () => {+ it("parses a slash skill link", () => {+ const token = tokenize("[/git-commit](slash://skill/aaa-bbb)");++ expect(token).toBeDefined();+ expect(token!.attributes.label).toBe("git-commit");+ expect(token!.attributes.id).toBe("aaa-bbb");+ });++ it("round-trips through renderMarkdown", () => {+ const md = renderMarkdown({+ attrs: { id: "skill-1", label: "deploy" },+ });++ expect(md).toBe("[/deploy](slash://skill/skill-1)");+ expect(tokenize(md)?.attributes).toEqual({+ id: "skill-1",+ label: "deploy",+ });+ });++ it("uses a generic fallback when rendering markdown without a label", () => {+ const md = renderMarkdown({+ attrs: { id: "skill-1" },+ });++ expect(md).toBe("[/?](slash://skill/skill-1)");+ });++ it("does not write an unused slash-specific id attribute", () => {+ const [, attrs, text] = renderHTML.call(+ { options: { HTMLAttributes: { class: "slash-command" } } },+ {+ node: { attrs: { id: "skill-1", label: "deploy" } },+ HTMLAttributes: {},+ },+ );++ expect(attrs).toMatchObject({+ "data-type": "slash-command",+ class: "slash-command",+ });+ expect(attrs).not.toHaveProperty("data-slash-id");+ expect(text).toBe("/deploy");+ });++ it("handles labels with escaped brackets", () => {+ const md = renderMarkdown({+ attrs: { id: "skill-1", label: "deploy[prod]" },+ });++ expect(md).toBe("[/deploy\\[prod\\]](slash://skill/skill-1)");+ expect(tokenize(md)?.attributes.label).toBe("deploy[prod]");+ });++ it("does not match ordinary markdown links", () => {+ expect(tokenize("[docs](https://example.com)")).toBeUndefined();+ });++ it("does not match slash action links", () => {+ expect(tokenize("[/deploy](slash://action/deploy)")).toBeUndefined();+ });+});diff --git a/packages/views/editor/extensions/slash-command-extension.ts b/packages/views/editor/extensions/slash-command-extension.tsnew file mode 100644index 0000000000..eb6147a6ec--- /dev/null+++ b/packages/views/editor/extensions/slash-command-extension.ts@@ -0,0 +1,65 @@+import Mention from "@tiptap/extension-mention";+import { mergeAttributes } from "@tiptap/core";+import { ReactNodeViewRenderer } from "@tiptap/react";+import { SlashCommandView } from "./slash-command-view";+import { formatSlashCommandLabel } from "./slash-command-utils";++export const SlashCommandExtension = Mention.extend({+ name: "slashCommand",++ addNodeView() {+ return ReactNodeViewRenderer(SlashCommandView);+ },++ renderHTML({ node, HTMLAttributes }) {+ return [+ "span",+ mergeAttributes(+ { "data-type": "slash-command" },+ this.options.HTMLAttributes,+ HTMLAttributes,+ ),+ `/${formatSlashCommandLabel(node.attrs.label)}`,+ ];+ },++ addAttributes() {+ return { ...this.parent?.() };+ },++ parseHTML() {+ return [{ tag: 'span[data-type="slash-command"]' }];+ },++ markdownTokenizer: {+ name: "slashCommand",+ level: "inline" as const,+ start(src: string) {+ return src.search(/\[\/(?:\\.|[^\]])+\]\(slash:\/\/skill\//);+ },+ tokenize(src: string) {+ const match = src.match(+ /^\[\/((?:\\.|[^\]])+)\]\(slash:\/\/skill\/([^)]+)\)/,+ );+ if (!match) return undefined;+ const rawLabel = match[1]?.replace(/\\\[/g, "[").replace(/\\\]/g, "]");+ return {+ type: "slashCommand",+ raw: match[0],+ attributes: { label: rawLabel, id: match[2] },+ };+ },+ },++ parseMarkdown: (token: any, helpers: any) => {+ return helpers.createNode("slashCommand", token.attributes);+ },++ renderMarkdown: (node: any) => {+ const { id, label } = node.attrs || {};+ const safeLabel = formatSlashCommandLabel(label)+ .replace(/\[/g, "\\[")+ .replace(/\]/g, "\\]");+ return `[/${safeLabel}](slash://skill/${id})`;+ },+});diff --git a/packages/views/editor/extensions/slash-command-suggestion.test.tsx b/packages/views/editor/extensions/slash-command-suggestion.test.tsxnew file mode 100644index 0000000000..bb66b2aa09--- /dev/null+++ b/packages/views/editor/extensions/slash-command-suggestion.test.tsx@@ -0,0 +1,329 @@+import { render } from "@testing-library/react";+import { createRef, type ReactNode } from "react";+import { beforeAll, describe, expect, it, vi } from "vitest";+import { I18nProvider } from "@multica/core/i18n/react";+import { workspaceKeys } from "@multica/core/workspace/queries";+import type { Agent, MemberWithUser } from "@multica/core/types";+import type { QueryClient } from "@tanstack/react-query";+import enEditor from "../../locales/en/editor.json";++const TEST_RESOURCES = {+ en: { editor: enEditor },+};++function I18nWrapper({ children }: { children: ReactNode }) {+ return (+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ {children}+ </I18nProvider>+ );+}++beforeAll(() => {+ Element.prototype.scrollIntoView = vi.fn();+});++vi.mock("@multica/core/platform", () => ({+ getCurrentWsId: () => "ws-1",+}));++const authState = { user: { id: "u1" } as { id: string } | null };+vi.mock("@multica/core/auth", () => ({+ useAuthStore: { getState: () => authState },+}));++const chatState = { selectedAgentId: "agent-1" as string | null };+vi.mock("@multica/core/chat", () => ({+ useChatStore: { getState: () => chatState },+}));++import {+ SlashCommandList,+ type SlashCommandListRef,+ createSlashCommandSuggestion,+ type SlashCommandItem,+} from "./slash-command-suggestion";++function agent(overrides: Partial<Agent>): Agent {+ return {+ id: "agent-1",+ workspace_id: "ws-1",+ runtime_id: "runtime-1",+ name: "Agent",+ description: "",+ instructions: "",+ avatar_url: null,+ runtime_mode: "local",+ runtime_config: {},+ custom_args: [],+ visibility: "workspace",+ status: "idle",+ max_concurrent_tasks: 1,+ model: "",+ owner_id: null,+ skills: [],+ created_at: "",+ updated_at: "",+ archived_at: null,+ archived_by: null,+ ...overrides,+ };+}++function fakeQc(data: {+ members?: Array<Pick<MemberWithUser, "user_id" | "name" | "role">>;+ agents?: Agent[];+}): QueryClient {+ const map = new Map<string, unknown>();+ map.set(JSON.stringify(workspaceKeys.members("ws-1")), data.members ?? []);+ map.set(JSON.stringify(workspaceKeys.agents("ws-1")), data.agents ?? []);+ return {+ getQueryData: (key: readonly unknown[]) => map.get(JSON.stringify(key)),+ } as unknown as QueryClient;+}++function items(qc: QueryClient, query = ""): SlashCommandItem[] {+ const config = createSlashCommandSuggestion(qc);+ return config.items!({ query, editor: {} as never }) as SlashCommandItem[];+}++describe("slash command suggestion items", () => {+ it("returns all active agent skills when query is empty", () => {+ chatState.selectedAgentId = "agent-1";+ const qc = fakeQc({+ members: [{ user_id: "u1", name: "Alice", role: "member" }],+ agents: [+ agent({+ id: "agent-1",+ skills: [+ { id: "s1", name: "deploy", description: "Ship changes" },+ { id: "s2", name: "review", description: "Review code" },+ ],+ }),+ ],+ });++ expect(items(qc).map((i) => i.label)).toEqual(["deploy", "review"]);+ });++ it("filters skills by name case-insensitively", () => {+ chatState.selectedAgentId = "agent-1";+ const qc = fakeQc({+ members: [{ user_id: "u1", name: "Alice", role: "member" }],+ agents: [+ agent({+ id: "agent-1",+ skills: [+ { id: "s1", name: "Deploy", description: "" },+ { id: "s2", name: "Review", description: "" },+ ],+ }),+ ],+ });++ expect(items(qc, "dep").map((i) => i.id)).toEqual(["s1"]);+ });++ it("filters skills by description", () => {+ chatState.selectedAgentId = "agent-1";+ const qc = fakeQc({+ members: [{ user_id: "u1", name: "Alice", role: "member" }],+ agents: [+ agent({+ id: "agent-1",+ skills: [+ { id: "s1", name: "deploy", description: "Ship changes" },+ { id: "s2", name: "review", description: "Read a pull request" },+ ],+ }),+ ],+ });++ expect(items(qc, "pull").map((i) => i.id)).toEqual(["s2"]);+ });++ it("tolerates skills with missing descriptions from cached API data", () => {+ chatState.selectedAgentId = "agent-1";+ const qc = fakeQc({+ members: [{ user_id: "u1", name: "Alice", role: "member" }],+ agents: [+ agent({+ id: "agent-1",+ skills: [+ { id: "s1", name: "deploy" } as Agent["skills"][number],+ ],+ }),+ ],+ });++ expect(() => items(qc, "dep")).not.toThrow();+ expect(items(qc, "dep")).toEqual([+ { id: "s1", label: "deploy", description: "" },+ ]);+ });++ it("returns empty when the active agent has no skills", () => {+ chatState.selectedAgentId = "agent-1";+ const qc = fakeQc({+ members: [{ user_id: "u1", name: "Alice", role: "member" }],+ agents: [agent({ id: "agent-1", skills: [] })],+ });++ expect(items(qc)).toEqual([]);+ });++ it("caps results at 20", () => {+ chatState.selectedAgentId = "agent-1";+ const qc = fakeQc({+ members: [{ user_id: "u1", name: "Alice", role: "member" }],+ agents: [+ agent({+ id: "agent-1",+ skills: Array.from({ length: 25 }, (_, i) => ({+ id: `s${i}`,+ name: `skill-${i}`,+ description: "",+ })),+ }),+ ],+ });++ expect(items(qc)).toHaveLength(20);+ });++ it("falls back to the first available agent when selectedAgentId is stale", () => {+ chatState.selectedAgentId = "missing";+ const qc = fakeQc({+ members: [{ user_id: "u1", name: "Alice", role: "member" }],+ agents: [+ agent({+ id: "agent-1",+ skills: [{ id: "s1", name: "deploy", description: "" }],+ }),+ ],+ });++ expect(items(qc).map((i) => i.id)).toEqual(["s1"]);+ });++ it("returns empty when no agents exist", () => {+ const qc = fakeQc({+ members: [{ user_id: "u1", name: "Alice", role: "member" }],+ agents: [],+ });++ expect(items(qc)).toEqual([]);+ });++ it("excludes skills from private agents the user cannot access", () => {+ chatState.selectedAgentId = "private-agent";+ const qc = fakeQc({+ members: [+ { user_id: "u1", name: "Alice", role: "member" },+ { user_id: "u2", name: "Bob", role: "member" },+ ],+ agents: [+ agent({+ id: "private-agent",+ visibility: "private",+ owner_id: "u2",+ skills: [{ id: "private-skill", name: "secret", description: "" }],+ }),+ ],+ });++ expect(items(qc)).toEqual([]);+ });+});++describe("SlashCommandList keyboard handling", () => {+ it("lets Enter and arrow keys fall through when there are no selectable items", () => {+ const ref = createRef<SlashCommandListRef>();++ render(+ <I18nWrapper>+ <SlashCommandList ref={ref} items={[]} query="" command={vi.fn()} />+ </I18nWrapper>,+ );++ expect(+ ref.current?.onKeyDown({+ event: new KeyboardEvent("keydown", { key: "Enter" }),+ }),+ ).toBe(false);+ expect(+ ref.current?.onKeyDown({+ event: new KeyboardEvent("keydown", { key: "Enter", metaKey: true }),+ }),+ ).toBe(false);+ expect(+ ref.current?.onKeyDown({+ event: new KeyboardEvent("keydown", { key: "ArrowUp" }),+ }),+ ).toBe(false);+ expect(+ ref.current?.onKeyDown({+ event: new KeyboardEvent("keydown", { key: "ArrowDown" }),+ }),+ ).toBe(false);+ });++ it("handles Enter and arrow keys when selectable items exist", () => {+ const ref = createRef<SlashCommandListRef>();+ const command = vi.fn();+ const selectableItems: SlashCommandItem[] = [+ { id: "s1", label: "deploy", description: "Ship changes" },+ { id: "s2", label: "review", description: "Review code" },+ ];++ render(+ <I18nWrapper>+ <SlashCommandList+ ref={ref}+ items={selectableItems}+ query=""+ command={command}+ />+ </I18nWrapper>,+ );++ expect(+ ref.current?.onKeyDown({+ event: new KeyboardEvent("keydown", { key: "ArrowUp" }),+ }),+ ).toBe(true);+ expect(+ ref.current?.onKeyDown({+ event: new KeyboardEvent("keydown", { key: "ArrowDown" }),+ }),+ ).toBe(true);+ expect(+ ref.current?.onKeyDown({+ event: new KeyboardEvent("keydown", { key: "Enter" }),+ }),+ ).toBe(true);+ expect(command).toHaveBeenCalledWith(selectableItems[0]);+ });+});++describe("SlashCommandList empty states", () => {+ it("shows a configured-skills empty state before search text is entered", () => {+ const { getByText } = render(+ <I18nWrapper>+ <SlashCommandList items={[]} query="" command={vi.fn()} />+ </I18nWrapper>,+ );++ expect(getByText("No skills configured")).toBeInTheDocument();+ });++ it("shows a no-results empty state when search text has no matches", () => {+ const { getByText } = render(+ <I18nWrapper>+ <SlashCommandList items={[]} query="deploy" command={vi.fn()} />+ </I18nWrapper>,+ );++ expect(getByText("No matching skills")).toBeInTheDocument();+ });+});diff --git a/packages/views/editor/extensions/slash-command-suggestion.tsx b/packages/views/editor/extensions/slash-command-suggestion.tsxnew file mode 100644index 0000000000..a716e6d8d5--- /dev/null+++ b/packages/views/editor/extensions/slash-command-suggestion.tsx@@ -0,0 +1,262 @@+"use client";++import {+ forwardRef,+ useCallback,+ useEffect,+ useImperativeHandle,+ useRef,+ useState,+} from "react";+import { computePosition, flip, offset, shift } from "@floating-ui/dom";+import { ReactRenderer } from "@tiptap/react";+import type { QueryClient } from "@tanstack/react-query";+import type { SuggestionOptions, SuggestionProps } from "@tiptap/suggestion";+import { useAuthStore } from "@multica/core/auth";+import { useChatStore } from "@multica/core/chat";+import { getCurrentWsId } from "@multica/core/platform";+import { canAssignAgentToIssue } from "@multica/core/permissions";+import { isImeComposing } from "@multica/core/utils";+import { workspaceKeys } from "@multica/core/workspace/queries";+import type { Agent, MemberWithUser } from "@multica/core/types";+import { useT } from "../../i18n";++const MAX_ITEMS = 20;++export interface SlashCommandItem {+ id: string;+ label: string;+ description: string;+}++interface SlashCommandListProps {+ items: SlashCommandItem[];+ query: string;+ command: (item: SlashCommandItem) => void;+}++export interface SlashCommandListRef {+ onKeyDown: (props: { event: KeyboardEvent }) => boolean;+}++export const SlashCommandList = forwardRef<+ SlashCommandListRef,+ SlashCommandListProps+>(function SlashCommandList({ items, query, command }, ref) {+ const { t } = useT("editor");+ const [selectedIndex, setSelectedIndex] = useState(0);+ const itemRefs = useRef<(HTMLButtonElement | null)[]>([]);++ useEffect(() => {+ setSelectedIndex(0);+ }, [items]);++ useEffect(() => {+ itemRefs.current[selectedIndex]?.scrollIntoView({ block: "nearest" });+ }, [selectedIndex]);++ const selectItem = useCallback(+ (index: number) => {+ const item = items[index];+ if (!item) return;+ command(item);+ },+ [items, command],+ );++ useImperativeHandle(ref, () => ({+ onKeyDown: ({ event }) => {+ if (isImeComposing(event)) return false;+ if (event.key === "ArrowUp") {+ if (items.length === 0) return false;+ setSelectedIndex((i) => (i + items.length - 1) % items.length);+ return true;+ }+ if (event.key === "ArrowDown") {+ if (items.length === 0) return false;+ setSelectedIndex((i) => (i + 1) % items.length);+ return true;+ }+ if (event.key === "Enter") {+ if (items.length === 0) return false;+ selectItem(selectedIndex);+ return true;+ }+ return false;+ },+ }));++ if (items.length === 0) {+ return (+ <div className="rounded-md border bg-popover p-2 text-xs text-muted-foreground shadow-md">+ {t(($) =>+ query.trim()+ ? $.slash_command.no_results+ : $.slash_command.no_skills_configured,+ )}+ </div>+ );+ }++ return (+ <div className="rounded-md border bg-popover py-1 shadow-md w-72 max-h-[300px] overflow-y-auto">+ {items.map((item, index) => (+ <button+ key={item.id}+ ref={(el) => {+ itemRefs.current[index] = el;+ }}+ className={`flex w-full flex-col gap-0.5 px-3 py-1.5 text-left text-xs transition-colors ${+ selectedIndex === index ? "bg-accent" : "hover:bg-accent/50"+ }`}+ onClick={() => selectItem(index)}+ >+ <span className="font-medium">/{item.label}</span>+ {item.description && (+ <span className="truncate text-muted-foreground">+ {item.description}+ </span>+ )}+ </button>+ ))}+ </div>+ );+});++function buildItems(qc: QueryClient, query: string): SlashCommandItem[] {+ const wsId = getCurrentWsId();+ if (!wsId) return [];++ const agents: Agent[] = qc.getQueryData(workspaceKeys.agents(wsId)) ?? [];+ const members: MemberWithUser[] =+ qc.getQueryData(workspaceKeys.members(wsId)) ?? [];+ // Tiptap calls suggestion items outside React render, so direct store reads+ // are intentional here.+ const { selectedAgentId } = useChatStore.getState();+ const userId = useAuthStore.getState().user?.id ?? null;+ const memberRole = members.find((m) => m.user_id === userId)?.role ?? null;++ const availableAgents = agents.filter(+ (a) =>+ !a.archived_at &&+ canAssignAgentToIssue(a, { userId, role: memberRole }).allowed,+ );+ const activeAgent =+ availableAgents.find((a) => a.id === selectedAgentId) ??+ availableAgents[0] ??+ null;++ const q = query.toLowerCase();+ return (activeAgent?.skills ?? [])+ .filter(+ (s) =>+ !q ||+ s.name.toLowerCase().includes(q) ||+ (s.description ?? "").toLowerCase().includes(q),+ )+ .slice(0, MAX_ITEMS)+ .map((s) => ({ id: s.id, label: s.name, description: s.description ?? "" }));+}++export function createSlashCommandSuggestion(qc: QueryClient): Omit<+ SuggestionOptions<SlashCommandItem>,+ "editor"+> {+ let renderer: ReactRenderer<SlashCommandListRef> | null = null;+ let popup: HTMLDivElement | null = null;++ return {+ char: "/",+ items: ({ query }) => buildItems(qc, query),+ command: ({ editor, range, props }) => {+ const nodeAfter = editor.view.state.selection.$to.nodeAfter;+ const overrideSpace = nodeAfter?.text?.startsWith(" ");+ if (overrideSpace) {+ range.to += 1;+ }++ editor+ .chain()+ .focus()+ .insertContentAt(range, [+ {+ type: "slashCommand",+ attrs: {+ id: props.id,+ label: props.label,+ mentionSuggestionChar: "/",+ },+ },+ { type: "text", text: " " },+ ])+ .run();++ window.getSelection()?.collapseToEnd();+ },+ render: () => {+ return {+ onStart: (props: SuggestionProps<SlashCommandItem>) => {+ renderer = new ReactRenderer(SlashCommandList, {+ props: {+ items: props.items,+ query: props.query,+ command: props.command,+ },+ editor: props.editor,+ });++ popup = document.createElement("div");+ popup.style.position = "fixed";+ popup.style.zIndex = "50";+ popup.appendChild(renderer.element);+ document.body.appendChild(popup);++ updatePosition(popup, props.clientRect);+ },+ onUpdate: (props: SuggestionProps<SlashCommandItem>) => {+ renderer?.updateProps({+ items: props.items,+ query: props.query,+ command: props.command,+ });+ if (popup) updatePosition(popup, props.clientRect);+ },+ onKeyDown: (props: { event: KeyboardEvent }) => {+ if (props.event.key === "Escape") {+ cleanup();+ return true;+ }+ return renderer?.ref?.onKeyDown(props) ?? false;+ },+ onExit: () => {+ cleanup();+ },+ };+ },+ };++ function updatePosition(+ el: HTMLDivElement,+ clientRect: (() => DOMRect | null) | null | undefined,+ ) {+ if (!clientRect) return;+ const virtualEl = {+ getBoundingClientRect: () => clientRect() ?? new DOMRect(),+ };+ computePosition(virtualEl, el, {+ placement: "bottom-start",+ strategy: "fixed",+ middleware: [offset(4), flip(), shift({ padding: 8 })],+ }).then(({ x, y }) => {+ el.style.left = `${x}px`;+ el.style.top = `${y}px`;+ });+ }++ function cleanup() {+ renderer?.destroy();+ renderer = null;+ popup?.remove();+ popup = null;+ }+}diff --git a/packages/views/editor/extensions/slash-command-utils.ts b/packages/views/editor/extensions/slash-command-utils.tsnew file mode 100644index 0000000000..a1a4f93a2d--- /dev/null+++ b/packages/views/editor/extensions/slash-command-utils.ts@@ -0,0 +1,3 @@+export function formatSlashCommandLabel(label: unknown): string {+ return typeof label === "string" && label.trim().length > 0 ? label : "?";+}diff --git a/packages/views/editor/extensions/slash-command-view.tsx b/packages/views/editor/extensions/slash-command-view.tsxnew file mode 100644index 0000000000..eca9ab31ec--- /dev/null+++ b/packages/views/editor/extensions/slash-command-view.tsx@@ -0,0 +1,14 @@+"use client";++import { NodeViewWrapper } from "@tiptap/react";+import type { NodeViewProps } from "@tiptap/react";+import { formatSlashCommandLabel } from "./slash-command-utils";++export function SlashCommandView({ node }: NodeViewProps) {+ const { label } = node.attrs;+ return (+ <NodeViewWrapper as="span" className="inline">+ <span className="slash-command">/{formatSlashCommandLabel(label)}</span>+ </NodeViewWrapper>+ );+}diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsxindex 79f32de6ae..591bb642b9 100644--- a/packages/views/editor/readonly-content.test.tsx+++ b/packages/views/editor/readonly-content.test.tsx@@ -386,3 +386,24 @@ describe("ReadonlyContent file-card → AttachmentBlock HTML routing", () => {expect(queryByText("report.html")).toBeNull();});});++describe("ReadonlyContent slash command rendering", () => {+ it("renders slash skill links as slash command pills", () => {+ const { container } = render(+ <ReadonlyContent content="[/deploy](slash://skill/abc-123)" />,+ );++ const pill = container.querySelector(".slash-command");+ expect(pill).not.toBeNull();+ expect(pill?.textContent).toBe("/deploy");+ });++ it("does not affect regular links", () => {+ const { container } = render(+ <ReadonlyContent content="[docs](https://example.com)" />,+ );++ expect(container.querySelector(".slash-command")).toBeNull();+ expect(container.querySelector("a")).not.toBeNull();+ });+});diff --git a/packages/views/editor/readonly-content.tsx b/packages/views/editor/readonly-content.tsxindex 602071eb01..4f1ac9c9ae 100644--- a/packages/views/editor/readonly-content.tsx+++ b/packages/views/editor/readonly-content.tsx@@ -66,7 +66,7 @@ const sanitizeSchema = {...defaultSchema,protocols: {...defaultSchema.protocols,- href: [...(defaultSchema.protocols?.href ?? []), "mention"],+ href: [...(defaultSchema.protocols?.href ?? []), "mention", "slash"],},attributes: {...defaultSchema.attributes,@@ -95,6 +95,7 @@ const sanitizeSchema = {function urlTransform(url: string): string {if (url.startsWith("mention://")) return url;+ if (url.startsWith("slash://skill/")) return url;return defaultUrlTransform(url);}@@ -138,6 +139,10 @@ function ReadonlyLink({}) {const slug = useWorkspaceSlug();+ if (href?.startsWith("slash://skill/")) {+ return <span className="slash-command">{children}</span>;+ }+if (isMentionHref(href)) {const match = href.match(/^mention:\/\/(member|agent|issue|all)\/(.+)$/);if (match?.[1] === "issue" && match[2]) {diff --git a/packages/views/editor/styles/prose.css b/packages/views/editor/styles/prose.cssindex 33a41b0ed8..548a33dcaf 100644--- a/packages/views/editor/styles/prose.css+++ b/packages/views/editor/styles/prose.css@@ -262,6 +262,14 @@margin: 0 0.125rem;}+/* Slash command pills */+.rich-text-editor .slash-command {+ color: var(--primary);+ font-weight: 600;+ text-decoration: none;+ margin: 0 0.125rem;+}+/* Strong / emphasis */.rich-text-editor strong {font-weight: 600;diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.jsonindex 4a140c2204..3b73ec9c2b 100644--- a/packages/views/locales/en/editor.json+++ b/packages/views/locales/en/editor.json@@ -57,6 +57,10 @@"searching": "Searching...","no_results": "No results"},+ "slash_command": {+ "no_skills_configured": "No skills configured",+ "no_results": "No matching skills"+ },"code_block": {"copy_code": "Copy code","show_preview": "Show preview",diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.jsonindex 75dbb130ea..504ff7631c 100644--- a/packages/views/locales/ja/editor.json+++ b/packages/views/locales/ja/editor.json@@ -72,5 +72,9 @@"mermaid": {"render_error": "Mermaid ダイアグラムを描画できません。","rendering": "ダイアグラムを描画中…"+ },+ "slash_command": {+ "no_skills_configured": "設定済みスキルなし",+ "no_results": "一致するスキルなし"}}diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.jsonindex 0a4292b272..51d93c1d59 100644--- a/packages/views/locales/ko/editor.json+++ b/packages/views/locales/ko/editor.json@@ -72,5 +72,9 @@"mermaid": {"render_error": "Mermaid 다이어그램을 렌더링할 수 없습니다.","rendering": "다이어그램 렌더링 중..."+ },+ "slash_command": {+ "no_skills_configured": "구성된 스킬 없음",+ "no_results": "일치하는 스킬 없음"}}diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.jsonindex c9db7364d3..ec715e6c65 100644--- a/packages/views/locales/zh-Hans/editor.json+++ b/packages/views/locales/zh-Hans/editor.json@@ -57,6 +57,10 @@"searching": "搜索中...","no_results": "无结果"},+ "slash_command": {+ "no_skills_configured": "暂无配置的技能",+ "no_results": "没有匹配的技能"+ },"code_block": {"copy_code": "复制代码","show_preview": "显示预览",diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex d235875316..d1c954ff2e 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -183,6 +183,37 @@ func buildChatPrompt(task Task) string {var b strings.Builderb.WriteString("You are running as a chat assistant for a Multica workspace.\n")b.WriteString("A user is chatting with you directly. Respond to their message.\n\n")+ if task.Agent != nil && len(task.Agent.Skills) > 0 {+ refs := ExtractSlashSkills(task.ChatMessage)+ if len(refs) > 0 {+ agentSkills := make(map[string]string, len(task.Agent.Skills))+ for _, s := range task.Agent.Skills {+ agentSkills[s.ID] = s.Name+ }++ selected := make([]string, 0, len(refs))+ seen := make(map[string]struct{}, len(refs))+ for _, ref := range refs {+ name, ok := agentSkills[ref.ID]+ if !ok {+ continue+ }+ if _, ok := seen[ref.ID]; ok {+ continue+ }+ seen[ref.ID] = struct{}{}+ selected = append(selected, name)+ }++ if len(selected) > 0 {+ b.WriteString("Explicitly selected skills:\n")+ for _, name := range selected {+ fmt.Fprintf(&b, "- %s\n", name)+ }+ b.WriteString("\n")+ }+ }+ }fmt.Fprintf(&b, "User message:\n%s\n", task.ChatMessage)// List attachments by id + filename so the agent can fetch them via// the CLI. We deliberately do NOT inline the URL: chat attachmentsdiff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.goindex 825c0ab5e7..a000daba35 100644--- a/server/internal/daemon/prompt_test.go+++ b/server/internal/daemon/prompt_test.go@@ -249,6 +249,111 @@ func TestBuildPromptSquadLeaderNoActionForAgentTrigger(t *testing.T) {}}+func TestBuildChatPromptSlashSkills(t *testing.T) {+ t.Run("injects selected skills block", func(t *testing.T) {+ task := Task{+ ChatSessionID: "sess-1",+ ChatMessage: "please [/deploy](slash://skill/abc-123) this",+ Agent: &AgentData{+ Skills: []SkillData{{ID: "abc-123", Name: "deploy"}},+ },+ }+ out := buildChatPrompt(task)+ if !strings.Contains(out, "Explicitly selected skills:\n- deploy\n") {+ t.Fatalf("expected selected skills block, got:\n%s", out)+ }+ if !strings.Contains(out, "User message:\nplease [/deploy](slash://skill/abc-123) this") {+ t.Fatalf("expected raw user message preserved, got:\n%s", out)+ }+ })++ t.Run("ignores skills not belonging to agent", func(t *testing.T) {+ task := Task{+ ChatSessionID: "sess-1",+ ChatMessage: "[/hacker-skill](slash://skill/evil-id)",+ Agent: &AgentData{+ Skills: []SkillData{{ID: "good-id", Name: "deploy"}},+ },+ }+ out := buildChatPrompt(task)+ if strings.Contains(out, "Explicitly selected skills") {+ t.Fatalf("should not inject block for unknown skill ID, got:\n%s", out)+ }+ })++ t.Run("validates by ID not label", func(t *testing.T) {+ task := Task{+ ChatSessionID: "sess-1",+ ChatMessage: "[/deploy](slash://skill/wrong-id)",+ Agent: &AgentData{+ Skills: []SkillData{{ID: "real-id", Name: "deploy"}},+ },+ }+ out := buildChatPrompt(task)+ if strings.Contains(out, "Explicitly selected skills") {+ t.Fatalf("matching label with wrong ID must not pass, got:\n%s", out)+ }+ })++ t.Run("uses canonical name not label", func(t *testing.T) {+ task := Task{+ ChatSessionID: "sess-1",+ ChatMessage: "[/spoofed-name](slash://skill/real-id)",+ Agent: &AgentData{+ Skills: []SkillData{{ID: "real-id", Name: "deploy"}},+ },+ }+ out := buildChatPrompt(task)+ if !strings.Contains(out, "- deploy\n") {+ t.Fatalf("expected canonical name 'deploy', got:\n%s", out)+ }+ if strings.Contains(out, "- spoofed-name\n") {+ t.Fatalf("selected skills block must not use spoofed label, got:\n%s", out)+ }+ if !strings.Contains(out, "User message:\n[/spoofed-name](slash://skill/real-id)") {+ t.Fatalf("expected raw user message with spoofed label preserved, got:\n%s", out)+ }+ })++ t.Run("deduplicates skills", func(t *testing.T) {+ task := Task{+ ChatSessionID: "sess-1",+ ChatMessage: "[/deploy](slash://skill/a) and [/deploy](slash://skill/a) again",+ Agent: &AgentData{+ Skills: []SkillData{{ID: "a", Name: "deploy"}},+ },+ }+ out := buildChatPrompt(task)+ if strings.Count(out, "- deploy") != 1 {+ t.Fatalf("expected exactly 1 '- deploy', got:\n%s", out)+ }+ })++ t.Run("omits block when no valid skills", func(t *testing.T) {+ task := Task{+ ChatSessionID: "sess-1",+ ChatMessage: "just a normal message",+ Agent: &AgentData{Skills: []SkillData{{ID: "a", Name: "deploy"}}},+ }+ out := buildChatPrompt(task)+ if strings.Contains(out, "Explicitly selected skills") {+ t.Fatalf("should not inject block when no slash links, got:\n%s", out)+ }+ })++ t.Run("omits block when agent has no skills", func(t *testing.T) {+ task := Task{+ ChatSessionID: "sess-1",+ ChatMessage: "[/deploy](slash://skill/abc-123)",+ Agent: &AgentData{},+ }+ out := buildChatPrompt(task)+ if strings.Contains(out, "Explicitly selected skills") {+ t.Fatalf("should not inject block for agent with no skills, got:\n%s", out)+ }+ })+}+// TestBuildPromptDefaultMentionsRecent pins that the catch-all fallback// prompt (no trigger comment, no chat, no autopilot, no quick-create) also// teaches the agent about --recent as the long-issue-friendly alternativediff --git a/server/internal/daemon/slash_skill.go b/server/internal/daemon/slash_skill.gonew file mode 100644index 0000000000..42033939d8--- /dev/null+++ b/server/internal/daemon/slash_skill.go@@ -0,0 +1,35 @@+package daemon++import (+ "regexp"+ "strings"+)++var slashSkillRe = regexp.MustCompile(+ `\[/((?:[^\]\\]|\\.)+)\]\(slash://skill/([^)]+)\)`,+)++type SlashSkillRef struct {+ Label string+ ID string+}++func ExtractSlashSkills(md string) []SlashSkillRef {+ matches := slashSkillRe.FindAllStringSubmatch(md, -1)+ seen := make(map[string]struct{}, len(matches))+ refs := make([]SlashSkillRef, 0, len(matches))++ for _, m := range matches {+ id := m[2]+ if _, ok := seen[id]; ok {+ continue+ }+ seen[id] = struct{}{}++ label := strings.ReplaceAll(m[1], `\[`, "[")+ label = strings.ReplaceAll(label, `\]`, "]")+ refs = append(refs, SlashSkillRef{Label: label, ID: id})+ }++ return refs+}diff --git a/server/internal/daemon/slash_skill_test.go b/server/internal/daemon/slash_skill_test.gonew file mode 100644index 0000000000..0d4cfa829d--- /dev/null+++ b/server/internal/daemon/slash_skill_test.go@@ -0,0 +1,69 @@+package daemon++import "testing"++func TestExtractSlashSkills(t *testing.T) {+ t.Run("parses basic link", func(t *testing.T) {+ refs := ExtractSlashSkills("please [/deploy](slash://skill/abc-123) this")+ if len(refs) != 1 {+ t.Fatalf("expected 1 ref, got %d", len(refs))+ }+ if refs[0].Label != "deploy" || refs[0].ID != "abc-123" {+ t.Fatalf("unexpected ref: %+v", refs[0])+ }+ })++ t.Run("parses escaped brackets", func(t *testing.T) {+ refs := ExtractSlashSkills(`[/deploy\[prod\]](slash://skill/x)`)+ if len(refs) != 1 || refs[0].Label != "deploy[prod]" {+ t.Fatalf("unexpected refs: %+v", refs)+ }+ })++ t.Run("deduplicates by ID", func(t *testing.T) {+ refs := ExtractSlashSkills("[/a](slash://skill/same) and [/b](slash://skill/same)")+ if len(refs) != 1 {+ t.Fatalf("expected 1 ref after dedupe, got %d", len(refs))+ }+ })++ t.Run("ignores slash action links", func(t *testing.T) {+ refs := ExtractSlashSkills("[/x](slash://action/y)")+ if len(refs) != 0 {+ t.Fatalf("expected 0 refs for action link, got %d", len(refs))+ }+ })++ t.Run("ignores normal markdown links", func(t *testing.T) {+ refs := ExtractSlashSkills("[docs](https://example.com)")+ if len(refs) != 0 {+ t.Fatalf("expected 0 refs for normal link, got %d", len(refs))+ }+ })++ t.Run("ignores mention links", func(t *testing.T) {+ refs := ExtractSlashSkills("[@user](mention://member/id)")+ if len(refs) != 0 {+ t.Fatalf("expected 0 refs for mention link, got %d", len(refs))+ }+ })++ t.Run("extracts multiple distinct skills", func(t *testing.T) {+ refs := ExtractSlashSkills("[/a](slash://skill/id-1) and [/b](slash://skill/id-2)")+ if len(refs) != 2 {+ t.Fatalf("expected 2 refs, got %d", len(refs))+ }+ })+}++func TestExtractSlashSkillsDoesNotMatchPartialProtocol(t *testing.T) {+ for _, md := range []string{+ "[/x](slash://y)",+ "[/x](slash://skills/y)",+ "[/x](slash://skill-extra/y)",+ } {+ if refs := ExtractSlashSkills(md); len(refs) != 0 {+ t.Errorf("expected 0 refs for %q, got %d", md, len(refs))+ }+ }+}diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex fb9ed8ece2..2496ca1d18 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -113,6 +113,7 @@ type AgentData struct {// SkillData represents a structured skill for task execution.type SkillData struct {+ ID string `json:"id"`Name string `json:"name"`Description string `json:"description,omitempty"`Content string `json:"content"`diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 6ccfa4c5e2..700ec6f874 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -1690,7 +1690,12 @@ func (s *TaskService) LoadAgentSkills(ctx context.Context, agentID pgtype.UUID)result := make([]AgentSkillData, 0, len(skills))for _, sk := range skills {- data := AgentSkillData{Name: sk.Name, Description: sk.Description, Content: sk.Content}+ data := AgentSkillData{+ ID: util.UUIDToString(sk.ID),+ Name: sk.Name,+ Description: sk.Description,+ Content: sk.Content,+ }files, _ := s.Queries.ListSkillFiles(ctx, sk.ID)for _, f := range files {data.Files = append(data.Files, AgentSkillFileData{Path: f.Path, Content: f.Content})@@ -1702,6 +1707,7 @@ func (s *TaskService) LoadAgentSkills(ctx context.Context, agentID pgtype.UUID)// AgentSkillData represents a skill for task execution responses.type AgentSkillData struct {+ ID string `json:"id"`Name string `json:"name"`Description string `json:"description,omitempty"`Content string `json:"content"`