Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Run skills named anywhere in a message, several at once (#4319)

Aditya Umalebd5b2b214f04
diff --git a/server/host/skills-library.ts b/server/host/skills-library.ts
index ed6f06ac32..ef305056ff 100644
--- a/server/host/skills-library.ts
+++ b/server/host/skills-library.ts
@@ -1,13 +1,14 @@
import { randomUUID } from "node:crypto";
import { join } from "node:path";
+import { skillCommandTurnText, skillMentions } from "../../shared/skill-command.ts";
import type { SkillRequestCardData, SkillShareRecord } from "../../shared/skill-request.ts";
import { narrowestAudience, intersectAudience } from "../bot-visibility.ts";
import { DATA_DIR, type AppConfig } from "../config.ts";
import { appendDecision } from "../decision-log.ts";
import { UNDO_STALE, type DirectApply } from "../direct-apply.ts";
import {
- expandImportedSkillCommand, importedSkillListings, importedSkillsFor, importedSkillsPrompt, nativeSkillFolders, readImportedSkillFile, readImportedSkills,
+ importedSkillListings, importedSkillsFor, importedSkillsPrompt, nativeSkillFolders, readImportedSkillFile, readImportedSkills,
type ImportedSkillView, type SkillTurnEngine,
} from "../imported-skills.ts";
import { nativeSkillListing, nativeSkills, readNativeSkillFile } from "../native-skills.ts";
@@ -24,7 +25,7 @@ import {
updateSharedLearnedSkill,
type ShareBot,
} from "../skill-share.ts";
-import { expandSkillCommandTurnText, listSkills, readSkillFile, resolveBotSkills, skillsSystemPrompt, type SkillListing } from "../skills.ts";
+import { enabledSkillFiles, listSkills, readSkillFile, resolveBotSkills, skillsSystemPrompt, type SkillListing } from "../skills.ts";
import type { BotRecord, Message, Store } from "../store.ts";
import { claudeUserSkillsEnabled } from "../turn-settings.ts";
import { TASK_WORKSPACES_DIR } from "../workspace.ts";
@@ -253,17 +254,23 @@ export function createSkillsLibraryHost(deps: SkillsLibraryHostDeps) {
return importsFor(bot, conversationSkills(bot, threadId), instance);
},
- /** `/name` for one of the bot's own, library or imported skills, or one its engine loads by itself. */
+ /** Each `/name` in the message for one of the bot's own, library or imported skills, or one its engine loads by itself. */
expandSkillCommand(bot: BotRecord, threadId: string, text: string, instance?: TurnInstance): string {
+ const mentioned = skillMentions(text);
+ if (!mentioned.length) return text;
const assigned = skillsLibraryEnabled(cfg) ? liveAssigned(bot) : undefined;
- const own = expandSkillCommandTurnText(bot.id, text, assigned);
- if (own !== text || !text.trimStart().startsWith("/")) return own;
- const imported = expandImportedSkillCommand(text, importsFor(bot, assigned, instance));
- if (imported !== text) return imported;
- // A skill switched off on the Skills page stays off, even when the engine holds one of the same name.
- const switched = new Set([...resolveBotSkills(bot.id, assigned), ...importedSkillListings(bot.id, new Set())]
- .filter((skill) => !skill.enabled).map((skill) => skill.name));
- return expandImportedSkillCommand(text, nativesFor(bot, threadId, instance).filter((skill) => !switched.has(skill.name)));
+ const files = enabledSkillFiles(bot.id, mentioned, assigned);
+ const add = (skills: readonly ImportedSkillView[]) => {
+ for (const skill of skills) if (mentioned.includes(skill.name) && !files.has(skill.name)) files.set(skill.name, skill.file);
+ };
+ if (files.size < mentioned.length) add(importsFor(bot, assigned, instance));
+ if (files.size < mentioned.length) {
+ // A skill switched off on the Skills page stays off, even when the engine holds one of the same name.
+ const switched = new Set([...resolveBotSkills(bot.id, assigned), ...importedSkillListings(bot.id, new Set())]
+ .filter((skill) => !skill.enabled).map((skill) => skill.name));
+ add(nativesFor(bot, threadId, instance).filter((skill) => !switched.has(skill.name)));
+ }
+ return skillCommandTurnText(text, files);
},
shareNote(bot: BotRecord, threadId: string, enabled: boolean): TurnShareNote {
diff --git a/server/imported-skills.ts b/server/imported-skills.ts
index 0c3a04dca4..bc7c16230a 100644
--- a/server/imported-skills.ts
+++ b/server/imported-skills.ts
@@ -14,7 +14,7 @@ import { homedir } from "node:os";
import { dirname, isAbsolute, join, resolve } from "node:path";
import { z } from "zod";
-import { parseSkillCommand } from "../shared/skill-command.ts";
+import { skillCommandTurnText } from "../shared/skill-command.ts";
import { isSkillName } from "../shared/skill-md.ts";
import { writeFileAtomic } from "./atomic.ts";
import { DATA_DIR } from "./config.ts";
@@ -410,14 +410,7 @@ export function importedSkillsPrompt(skills: readonly ImportedSkillView[]): stri
/** `/name` for an imported skill, the way a bot's own skill command reads. */
export function expandImportedSkillCommand(text: string, skills: readonly ImportedSkillView[]): string {
- if (!text.trimStart().startsWith("/")) return text;
- const command = parseSkillCommand(text, skills.map((skill) => skill.name));
- const skill = command && skills.find((candidate) => candidate.name === command.name);
- if (!command || !skill) return text;
- const lead = `The user ran your ${command.name} skill with /${command.name}. Read ${JSON.stringify(skill.file)} with your file tools and follow it for this turn.`;
- return command.request
- ? `${lead} Where the skill says {input}, use the request.\n\nRequest: ${command.request}`
- : `${lead} There is no further request, so run it as the skill describes.`;
+ return skillCommandTurnText(text, new Map(skills.map((skill) => [skill.name, skill.file])));
}
const NATIVE_SKILL_DIRS = [".claude/skills", ".agents/skills", ".grok/skills"];
diff --git a/server/native-skills.test.ts b/server/native-skills.test.ts
index eb0b23ccf4..03a2d4eabc 100644
--- a/server/native-skills.test.ts
+++ b/server/native-skills.test.ts
@@ -67,6 +67,10 @@ describe("skills the engine loads by itself", () => {
expect(host.expandSkillCommand(bot, "main", "/growth-data-expert find churn")).toContain(`Read ${JSON.stringify(shared)}`);
expect(host.expandSkillCommand(bot, "main", "/bot-notes")).toContain(`Read ${JSON.stringify(own)}`);
expect(host.expandSkillCommand(bot, "main", "/mine go")).toContain(JSON.stringify(join("workspaces", bot.id, "skills", "mine")).slice(1, -1));
+ const both = host.expandSkillCommand(bot, "main", "find churn with /growth-data-expert, then /mine");
+ expect(both).toContain(`${JSON.stringify(shared)} for /growth-data-expert`);
+ expect(both).toMatch(new RegExp(`workspaces.${bot.id}.skills.mine.SKILL\\.md" for /mine`));
+ expect(both).toContain("Request: find churn with /growth-data-expert, then /mine");
});
it("stay out of a bot or team package, which carries only the bot's own, library and imported skills", () => {
diff --git a/server/skill-command.test.ts b/server/skill-command.test.ts
index 4150070621..ca16c17b13 100644
--- a/server/skill-command.test.ts
+++ b/server/skill-command.test.ts
@@ -3,13 +3,12 @@ import { join } from "node:path";
import { enabledSkillFile, expandSkillCommandTurnText, installSkill, setSkillEnabled } from "./skills.ts";
import { workspaceDir } from "./workspace.ts";
-import { BUILT_IN_SLASH_COMMANDS, offersSkillCommand, parseSkillCommand } from "../shared/skill-command.ts";
+import { BUILT_IN_SLASH_COMMANDS, offersSkillCommand, parseSkillCommand, skillMentions } from "../shared/skill-command.ts";
const SKILL = (name: string) =>
`---\nname: ${name}\ndescription: Writes the weekly standup note.\n---\n\n# Standup\n\nSummarize {input} as three bullets.\n`;
-function botWith(name: string, enabled = true): string {
- const bot = `slash-bot-${Math.random().toString(36).slice(2, 10)}`;
+function botWith(name: string, enabled = true, bot = `slash-bot-${Math.random().toString(36).slice(2, 10)}`): string {
const installed = installSkill(bot, "local:test", [{ path: "SKILL.md", content: SKILL(name) }]);
expect("error" in installed).toBe(false);
if (enabled) expect("error" in setSkillEnabled(bot, name, true)).toBe(false);
@@ -20,6 +19,8 @@ describe("parseSkillCommand", () => {
it("reads a leading /name and the request after it", () => {
expect(parseSkillCommand("/standup", ["standup"])).toEqual({ name: "standup", request: "" });
expect(parseSkillCommand("/standup the billing work\nand more", ["standup"])).toEqual({ name: "standup", request: "the billing work\nand more" });
+ expect(parseSkillCommand("/standup.", ["standup"])).toEqual({ name: "standup", request: "" });
+ expect(parseSkillCommand("/standup: the billing work", ["standup"])).toEqual({ name: "standup", request: "the billing work" });
expect(parseSkillCommand(" /weekly-2 go", ["weekly-2"])).toEqual({ name: "weekly-2", request: "go" });
});
@@ -49,6 +50,37 @@ describe("expandSkillCommandTurnText", () => {
expect(text).toContain("Request: the billing work");
expect(text).toContain("{input}");
expect(expandSkillCommandTurnText(bot, "/standup")).toContain("There is no further request");
+ expect(expandSkillCommandTurnText(bot, "/standup.")).toContain("There is no further request");
+ });
+
+ it("runs a skill named later in the message with the whole message as the request", () => {
+ const bot = botWith("standup");
+ const file = join(workspaceDir(bot), "skills", "standup", "SKILL.md");
+ const text = expandSkillCommandTurnText(bot, "write up the billing work with /standup please");
+ expect(text).toContain(`Read ${JSON.stringify(file)}`);
+ expect(text).toContain("Request: write up the billing work with /standup please");
+ expect(expandSkillCommandTurnText(bot, "first line\n/standup.")).toContain(`Read ${JSON.stringify(file)}`);
+ });
+
+ it("runs every skill named in one message", () => {
+ const bot = botWith("review", true, botWith("standup"));
+ const standup = join(workspaceDir(bot), "skills", "standup", "SKILL.md");
+ const review = join(workspaceDir(bot), "skills", "review", "SKILL.md");
+ const text = expandSkillCommandTurnText(bot, "/review the diff, then /standup it and /review again");
+ expect(text).toContain("ran 2 of your skills with /review, /standup");
+ expect(text).toContain(`${JSON.stringify(review)} for /review`);
+ expect(text).toContain(`${JSON.stringify(standup)} for /standup`);
+ expect(text).toContain("Request: /review the diff, then /standup it and /review again");
+ });
+
+ it("leaves paths, links and built-in commands alone", () => {
+ const bot = botWith("standup");
+ expect(expandSkillCommandTurnText(bot, "open notes/standup now")).toBe("open notes/standup now");
+ expect(expandSkillCommandTurnText(bot, "see https://x.test/standup")).toBe("see https://x.test/standup");
+ expect(expandSkillCommandTurnText(bot, "the /standups folder")).toBe("the /standups folder");
+ expect(skillMentions("run /learn then /goal and /standup")).toEqual(["standup"]);
+ expect(skillMentions("open /standup.txt or /standup,now")).toEqual([]);
+ expect(expandSkillCommandTurnText(bot, "open /standup.txt")).toBe("open /standup.txt");
});
it("passes a disabled skill, an unknown name and plain text through", () => {
diff --git a/server/skills.ts b/server/skills.ts
index b2a016e6bb..0136ae265d 100644
--- a/server/skills.ts
+++ b/server/skills.ts
@@ -33,7 +33,7 @@ import {
} from "./skill-storage.ts";
import { workspaceDir } from "./workspace.ts";
import { isSkillName, parseSkillMd, scanSkillText, SKILL_FILE_MAX_BYTES, type ParsedSkill } from "../shared/skill-md.ts";
-import { parseSkillCommand } from "../shared/skill-command.ts";
+import { skillCommandTurnText, skillMentions } from "../shared/skill-command.ts";
export {
DESCRIPTION_MAX,
@@ -1299,23 +1299,18 @@ export function skillsSystemPrompt(botId: string, assignedLibrary?: readonly str
}
export function enabledSkillFile(botId: string, name: string, assignedLibrary?: readonly string[]): string | null {
- const skill = resolveBotSkills(botId, assignedLibrary).find((entry) => entry.name === name && entry.enabled);
- if (!skill) return null;
- const entry = readManifest(botId)[name];
- return entry ? join(skillTarget(workspaceDir(botId), name, entry), "SKILL.md") : librarySkillFilePath(name);
+ return enabledSkillFiles(botId, [name], assignedLibrary).get(name) ?? null;
+}
+
+/** SKILL.md of each named skill that is on for the bot. */
+export function enabledSkillFiles(botId: string, names: readonly string[], assignedLibrary?: readonly string[]): Map<string, string> {
+ if (!names.length) return new Map();
+ const on = new Set(resolveBotSkills(botId, assignedLibrary).filter((skill) => skill.enabled).map((skill) => skill.name)), manifest = readManifest(botId);
+ return new Map(names.filter((name) => on.has(name)).map((name) => [name, manifest[name] ? join(skillTarget(workspaceDir(botId), name, manifest[name]), "SKILL.md") : librarySkillFilePath(name)] as const));
}
export function expandSkillCommandTurnText(botId: string, text: string, assignedLibrary?: readonly string[]): string {
- if (!text.trimStart().startsWith("/")) return text;
- const names = resolveBotSkills(botId, assignedLibrary).filter((skill) => skill.enabled).map((skill) => skill.name);
- const command = parseSkillCommand(text, names);
- if (!command) return text;
- const file = enabledSkillFile(botId, command.name, assignedLibrary);
- if (!file) return text;
- const lead = `The user ran your ${command.name} skill with /${command.name}. Read ${JSON.stringify(file)} with your file tools and follow it for this turn.`;
- return command.request
- ? `${lead} Where the skill says {input}, use the request.\n\nRequest: ${command.request}`
- : `${lead} There is no further request, so run it as the skill describes.`;
+ return skillCommandTurnText(text, enabledSkillFiles(botId, skillMentions(text), assignedLibrary));
}
export function resolveBotSkills(botId: string, assignedLibrary: readonly string[] | undefined): SkillListing[] {
diff --git a/shared/skill-command.ts b/shared/skill-command.ts
index c4cfea6580..7233dd2f62 100644
--- a/shared/skill-command.ts
+++ b/shared/skill-command.ts
@@ -1,8 +1,9 @@
-// `/<skill-name>` at the start of a message runs one of the bot's enabled
-// skills for that turn. Like /learn and /setup it is a turn-text rewrite on
-// the server: the transcript keeps the person's raw "/name …" message, and
-// only the text the engine reads names the skill and its SKILL.md. Shared so
-// the composer menu and the server agree on which names are commands.
+// `/<skill-name>` at the start of a message, or after a space anywhere in it,
+// runs one of the bot's enabled skills for that turn, and one message can run
+// several. Like /learn and /setup it is a turn-text rewrite on the server: the
+// transcript keeps the person's raw message, and only the text the engine reads
+// names each skill and its SKILL.md. Shared so the composer menu and the server
+// agree on which names are commands.
import { isSkillName } from "./skill-md.ts";
/** Commands the app already owns. A skill with one of these names keeps
@@ -15,10 +16,10 @@ export interface SkillCommand {
request: string;
}
-/** `/name` or `/name request` where name is one of `skills`. Anything else,
+/** `/name` or `/name request` where name is one of `skills`; punctuation right after the name (`/name.`) ends it. Anything else,
* including an engine's own slash command, is ordinary text. */
export function parseSkillCommand(text: string, skills: Iterable<string>): SkillCommand | null {
- const match = /^\/([a-z0-9-]+)(?:\s+|$)([\s\S]*)$/.exec(text.trimStart());
+ const match = /^\/([a-z0-9-]+)(?:[.,;:!?)]+(?=\s|$))?(?:\s+|$)([\s\S]*)$/.exec(text.trimStart());
if (!match) return null;
const name = match[1]!;
if (!isSkillName(name) || BUILT_IN_SLASH_COMMANDS.includes(name)) return null;
@@ -30,3 +31,30 @@ export function parseSkillCommand(text: string, skills: Iterable<string>): Skill
export function offersSkillCommand(name: string): boolean {
return isSkillName(name) && !BUILT_IN_SLASH_COMMANDS.includes(name);
}
+
+/** Each `/name` that starts the message or follows a space, in order and once each, never a built-in. A path or link
+ * such as "a/b" or "https://x/y" names nothing. */
+export function skillMentions(text: string): string[] {
+ const found = new Set<string>();
+ for (const match of text.matchAll(/(?:^|\s)\/([a-z0-9-]+)(?=$|\s|[.,;:!?)]+(?:$|\s))/g)) {
+ if (offersSkillCommand(match[1]!)) found.add(match[1]!);
+ }
+ return [...found];
+}
+
+/** What the engine reads for a message that ran skills with `/name`: which SKILL.md to read and follow, then the
+ * request. `files` maps each skill the bot has to its SKILL.md; any other `/word` stays plain text. */
+export function skillCommandTurnText(text: string, files: ReadonlyMap<string, string>): string {
+ const names = skillMentions(text).filter((name) => files.has(name));
+ if (!names.length) return text;
+ const read = (name: string) => JSON.stringify(files.get(name));
+ const lead = names.length === 1
+ ? `The user ran your ${names[0]} skill with /${names[0]}. Read ${read(names[0]!)} with your file tools and follow it for this turn.`
+ : `The user ran ${names.length} of your skills with ${names.map((name) => `/${name}`).join(", ")}. Read ` +
+ `${names.map((name) => `${read(name)} for /${name}`).join(", ")} with your file tools and follow each for this turn.`;
+ const leading = names.length === 1 ? parseSkillCommand(text, names) : null;
+ const request = leading ? leading.request : text.trim();
+ return request
+ ? `${lead} Where ${names.length === 1 ? "the" : "a"} skill says {input}, use the request.\n\nRequest: ${request}`
+ : `${lead} There is no further request, so run it as the skill describes.`;
+}
diff --git a/src/components/Composer.slash.test.ts b/src/components/Composer.slash.test.ts
new file mode 100644
index 0000000000..86d7fd69e0
--- /dev/null
+++ b/src/components/Composer.slash.test.ts
@@ -0,0 +1,93 @@
+// @vitest-environment happy-dom
+// The / menu in the real composer: skills can be picked anywhere in a message, built-in commands only at its start.
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Bot } from "@/state/store";
+import { restoreComposerDraft } from "@/lib/drafts";
+
+const ENGINE = "claude-3f0c2b1e-9d1a-4c55-8a51-0a3a6f1e2b7c";
+vi.mock("@/state/store", async (importOriginal) => {
+ const original = await importOriginal<typeof import("@/state/store")>();
+ return { ...original, useStore: () => ({
+ state: { ...original.initialState, bots: [bot], instances: [{
+ instanceId: ENGINE, driverKind: "claudeAgent", displayName: "Claude", capabilities: { agentsMcp: true },
+ }] },
+ dispatch: vi.fn(),
+ }) };
+});
+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));
+vi.mock("@/lib/use-slash-skills", () => ({
+ useSlashSkills: (_botId: string | undefined, _threadId: string, active: boolean) =>
+ active ? [{ name: "standup", description: "Writes the weekly standup note." }] : [],
+}));
+vi.mock("./CallView", () => ({ CallButton: () => null }));
+
+import { Composer } from "./Composer";
+
+const bot: Bot = {
+ id: "slash-bot", threadId: "slash-thread", name: "Atlas", title: "", description: "",
+ color: "blue", notifications: false, unread: false, busy: false, messages: [],
+ modelSelection: { instanceId: ENGINE, model: "fake" },
+};
+const draftId = `bot:${bot.id}:${bot.threadId}`;
+
+describe("the / menu in the composer", () => {
+ let root: Root;
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} });
+ vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
+ restoreComposerDraft(draftId, { text: "", attachments: [] });
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ flushSync(() => root.render(createElement(Composer, { bot })));
+ });
+
+ afterEach(() => {
+ flushSync(() => root.unmount());
+ container.remove();
+ restoreComposerDraft(draftId, { text: "", attachments: [] });
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ function fill(text: string, caret = text.length) {
+ flushSync(() => restoreComposerDraft(draftId, { text, attachments: [] }));
+ const input = container.querySelector("textarea")!;
+ input.setSelectionRange(caret, caret);
+ flushSync(() => input.dispatchEvent(new KeyboardEvent("keyup", { key: "/", bubbles: true })));
+ return input;
+ }
+ const options = () => [...document.body.querySelectorAll<HTMLElement>('[role="option"]')];
+ const labels = () => options().map((option) => option.querySelector(".truncate")?.textContent);
+
+ it("offers the built-in commands and skills at the start of a message", () => {
+ fill("/");
+ expect(labels()).toEqual(["/goal", "/learn", "/setup", "/standup"]);
+ });
+
+ it("offers only skills after a space later in the message, and puts the pick in place", () => {
+ const input = fill("write it up with /");
+ expect(labels()).toEqual(["/standup"]);
+ flushSync(() => options()[0]!.click());
+ expect(input.value).toBe("write it up with /standup ");
+ });
+
+ it("adds no second space when text already follows the pick", () => {
+ const input = fill("use /st later", "use /st".length);
+ flushSync(() => options()[0]!.click());
+ expect(input.value).toBe("use /standup later");
+ });
+
+ it("opens nothing inside a path or link", () => {
+ fill("open notes/st");
+ expect(options()).toEqual([]);
+ fill("see https://x.test/");
+ expect(options()).toEqual([]);
+ });
+});
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
index 713b0c72e6..1ed94e14ec 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -304,13 +304,14 @@ export function Composer({
const commandCandidates = useMemo(() => {
if (!slash || slash.start === dismissedSlashAt) return [];
const available: ComposerSlashCommand[] = [];
- if (!group?.dm) available.push({
+ const builtIns = slash.start === 0; // Built-in commands only work at the start of a message; skills can be named anywhere.
+ if (builtIns && !group?.dm) available.push({
kind: "command",
id: "goal",
label: "/goal",
description: t(group ? "composer.command.goalDesc" : "composer.command.goalBotDesc"),
});
- if (canLearn) {
+ if (builtIns && canLearn) {
available.push({
kind: "command",
id: "learn",
@@ -318,7 +319,7 @@ export function Composer({
description: t("composer.command.learnDesc"),
});
}
- if (!group && supportsAgents(state.instances, bot)) available.push({
+ if (builtIns && !group && supportsAgents(state.instances, bot)) available.push({
kind: "command",
id: "setup",
label: "/setup",
@@ -387,7 +388,8 @@ export function Composer({
const pickCommand = (command: ComposerSlashCommand | undefined) => {
if (!slash || !command) return;
- const replacement = command.kind === "skill" ? `${command.label} `
+ const spaceAfter = /^\s/.test(text.slice(slash.end)) ? "" : " ";
+ const replacement = command.kind === "skill" ? `${command.label}${spaceAfter}`
: command.id === "learn" ? "/learn " : command.id === "setup" ? "/setup " : "";
const next = replaceComposerSlashTrigger(text, slash, replacement);
editText(next.text);
diff --git a/src/lib/composer-commands.test.ts b/src/lib/composer-commands.test.ts
index 18f89686f1..eb11265751 100644
--- a/src/lib/composer-commands.test.ts
+++ b/src/lib/composer-commands.test.ts
@@ -10,13 +10,23 @@ import {
import { enabledSlashSkills } from "./use-slash-skills";
describe("composer slash commands", () => {
- it("opens command search only for the first unfinished token", () => {
+ it("opens command search for the unfinished slash token at the caret", () => {
expect(composerSlashTrigger("/", 1)).toEqual({ query: "", start: 0, end: 1 });
expect(composerSlashTrigger("/go", 3)).toEqual({ query: "go", start: 0, end: 3 });
- expect(composerSlashTrigger("hello /go", 9)).toBeNull();
expect(composerSlashTrigger("/goal write", 11)).toBeNull();
});
+ it("opens command search for a slash token later in the message", () => {
+ expect(composerSlashTrigger("hello /go", 9)).toEqual({ query: "go", start: 6, end: 9 });
+ expect(composerSlashTrigger("first line\n/", 12)).toEqual({ query: "", start: 11, end: 12 });
+ expect(composerSlashTrigger("use /stand later", 10)).toEqual({ query: "stand", start: 4, end: 10 });
+ expect(composerSlashTrigger("a/b", 3)).toBeNull();
+ expect(composerSlashTrigger("see http://x/", 13)).toBeNull();
+ expect(
+ replaceComposerSlashTrigger("use /stand later", { query: "stand", start: 4, end: 10 }, "/standup "),
+ ).toEqual({ text: "use /standup later", caret: 13 });
+ });
+
it("replaces the active token without losing text after the caret", () => {
expect(
replaceComposerSlashTrigger("/go later", { query: "go", start: 0, end: 3 }, ""),
diff --git a/src/lib/composer-commands.ts b/src/lib/composer-commands.ts
index 33b8b14f81..cac267b67f 100644
--- a/src/lib/composer-commands.ts
+++ b/src/lib/composer-commands.ts
@@ -32,9 +32,10 @@ export interface ComposerSlashTrigger {
export function composerSlashTrigger(text: string, caretInput: number): ComposerSlashTrigger | null {
const caret = Math.max(0, Math.min(text.length, Math.floor(caretInput)));
const prefix = text.slice(0, caret);
- const match = /^\/([a-z0-9-]*)$/i.exec(prefix);
+ const match = /(?:^|\s)\/([a-z0-9-]*)$/i.exec(prefix);
if (!match) return null;
- return { query: match[1] ?? "", start: 0, end: caret };
+ const query = match[1] ?? "";
+ return { query, start: caret - query.length - 1, end: caret };
}
export function goalTextFromComposer(text: string): string | null {