Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(composer): refuse a slash submission when the command source fails (#795)

vastsa16d114b6bd51
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
index 777c0a686..ab33c78a4 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
@@ -14,6 +14,10 @@ import { api } from "../../../../lib/api";
import { draftKeyForSession } from "../../../../lib/composer-draft-cache";
import { runExtensionCommand, runPaletteCommand } from "../../../../lib/commands";
import { resolveComposerCommand } from "../../../../hooks/use-composer-autocomplete";
+import {
+ parseSlashSubmission,
+ resolveSlashDispatch,
+} from "../slash-dispatch";
import { readEditorValue, setEditorCaret, type ComposerFileReference } from "../editor";
import type { ComposerDraftController } from "./useComposerDraft";
@@ -204,17 +208,25 @@ export function useComposerSubmit({
invalidatePromptEnhancement();
const submittedDraftKey = draftKey;
// Slash dispatch stays local for builtin and extension commands, while
- // templates, skills, and unknown aliases continue as normal prompt text.
- if (!steering && serializedContent.startsWith("/")) {
- const commandEnd = serializedContent.search(/\s/);
- const name = serializedContent.slice(
- 1,
- commandEnd === -1 ? undefined : commandEnd,
- );
- const command = name ? await resolveComposerCommand(name) : null;
- if (command && command.kind !== "template" && command.id) {
- const commandBody =
- commandEnd === -1 ? "" : serializedContent.slice(commandEnd).trim();
+ // templates, skills, and unknown aliases continue as normal prompt text. A
+ // command source that cannot be read is a third case: the composer cannot
+ // prove `/compact` is not a builtin, so it refuses the submission and keeps
+ // the text out of the model's input (issue #795).
+ if (!steering) {
+ const slashSubmission = parseSlashSubmission(serializedContent);
+ const resolution = slashSubmission
+ ? await resolveComposerCommand(slashSubmission.name)
+ : null;
+ const dispatch = resolveSlashDispatch(slashSubmission, resolution);
+ if (dispatch.action === "blocked") {
+ showToast(t("chat.slashCommandSourceUnavailable"), {
+ variant: "error",
+ });
+ return;
+ }
+ if (dispatch.action === "dispatch") {
+ const command = dispatch.command;
+ const commandBody = dispatch.body;
const isModeCommand =
command.id === "builtin.mode.agent" ||
command.id === "builtin.mode.plan" ||
diff --git a/apps/desktop/src/features/chat/composer/slash-dispatch.ts b/apps/desktop/src/features/chat/composer/slash-dispatch.ts
new file mode 100644
index 000000000..264a0d2b1
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/slash-dispatch.ts
@@ -0,0 +1,64 @@
+import type { ComposerCommand } from "@pi-desktop/shared";
+
+import type { ComposerCommandResolution } from "../../../hooks/use-composer-autocomplete";
+
+/**
+ * Slash submission dispatch for the composer (issue #795).
+ *
+ * Kept free of React and of the store so the decision can be tested on its own:
+ * the only input is the typed text plus the command resolution the autocomplete
+ * hook produced for it.
+ */
+
+/** A submission that starts with `/name`, split into its name and body. */
+export type SlashSubmission = {
+ name: string;
+ body: string;
+};
+
+/**
+ * Split a composer submission into a slash name and body, or `null` when the
+ * text is not a slash submission at all — it does not start with `/`, or holds
+ * nothing after the slash.
+ */
+export function parseSlashSubmission(content: string): SlashSubmission | null {
+ if (!content.startsWith("/")) return null;
+ const end = content.search(/\s/);
+ const name = content.slice(1, end === -1 ? undefined : end);
+ if (!name) return null;
+ return { name, body: end === -1 ? "" : content.slice(end).trim() };
+}
+
+/**
+ * What the composer does with one submission.
+ *
+ * `blocked` is the fail-closed branch: the command source could not be read, so
+ * the composer cannot prove `/compact` is not a builtin and shows an error
+ * instead of handing the text to the model.
+ */
+export type SlashDispatch =
+ | { action: "dispatch"; command: ComposerCommand & { id: string }; body: string }
+ | { action: "prompt" }
+ | { action: "blocked"; error: Error };
+
+/**
+ * Decide the fate of one submission. Templates, unknown aliases, and
+ * command entries without a dispatchable id keep the prompt path — that is
+ * older behavior than the source-failure branch — while an unreadable source
+ * blocks the submission so a control command is never degraded into prompt
+ * text.
+ */
+export function resolveSlashDispatch(
+ submission: SlashSubmission | null,
+ resolution: ComposerCommandResolution | null,
+): SlashDispatch {
+ if (!submission || !resolution) return { action: "prompt" };
+ if (resolution.status === "unavailable") {
+ return { action: "blocked", error: resolution.error };
+ }
+ if (resolution.status === "unknown") return { action: "prompt" };
+ const { command } = resolution;
+ const { id } = command;
+ if (command.kind === "template" || !id) return { action: "prompt" };
+ return { action: "dispatch", command: { ...command, id }, body: submission.body };
+}
diff --git a/apps/desktop/src/hooks/use-composer-autocomplete.ts b/apps/desktop/src/hooks/use-composer-autocomplete.ts
index 0e790ff5e..8e7cb4132 100644
--- a/apps/desktop/src/hooks/use-composer-autocomplete.ts
+++ b/apps/desktop/src/hooks/use-composer-autocomplete.ts
@@ -104,15 +104,28 @@ function filterFiles(entries: FsIndexEntry[], query: string): AutocompleteItem[]
})).map(({ entry, match }) => ({ kind: "path", entry, match }));
}
+/**
+ * Result of resolving one typed "/name" at send time.
+ *
+ * `unavailable` is the branch that keeps a failed source read from looking like
+ * "no such command": the composer can only guess whether `/compact` is a
+ * builtin it must not send to the model, so it refuses the submission instead
+ * of degrading a control command into prompt text (issue #795).
+ */
+export type ComposerCommandResolution =
+ | { status: "resolved"; command: ComposerCommand }
+ | { status: "unknown" }
+ | { status: "unavailable"; error: Error };
+
/**
* Resolve a typed "/name" against the merged command and skill list at send
- * time (builtin/plugin dispatch and skill validation); templates and unknown
- * names return as-is/null and stay on the prompt path. Reuses the menu's TTL
- * cache when warm.
+ * time (builtin/plugin dispatch and skill validation); templates, non-command
+ * names, and unknown names stay on the prompt path. Reuses the menu's TTL cache
+ * when warm, so a warm cache keeps resolving through a source blip.
*/
export async function resolveComposerCommand(
name: string,
-): Promise<ComposerCommand | null> {
+): Promise<ComposerCommandResolution> {
const key = useAppStore.getState().workspace?.path ?? "";
if (
!commandsCache ||
@@ -122,11 +135,17 @@ export async function resolveComposerCommand(
try {
const res = await api.composerCommands();
commandsCache = { key, at: Date.now(), commands: res.commands };
- } catch {
- return null;
+ } catch (error) {
+ // Deliberately leaves the cache cold: the next attempt re-reads the
+ // source, which is what makes the refusal retriable.
+ return {
+ status: "unavailable",
+ error: error instanceof Error ? error : new Error(String(error)),
+ };
}
}
- return commandsCache.commands.find((c) => c.name === name) ?? null;
+ const command = commandsCache.commands.find((c) => c.name === name);
+ return command ? { status: "resolved", command } : { status: "unknown" };
}
export function useComposerAutocomplete({
diff --git a/apps/desktop/test/slash-command-source.test.mjs b/apps/desktop/test/slash-command-source.test.mjs
new file mode 100644
index 000000000..26ca2ce6c
--- /dev/null
+++ b/apps/desktop/test/slash-command-source.test.mjs
@@ -0,0 +1,200 @@
+/**
+ * Issue #795 ①: a slash command must never be degraded into prompt text.
+ *
+ * The composer resolves a typed `/name` against the merged command source
+ * (builtin + plugin + extension + skill + template) at send time. When that IPC
+ * read fails the old code returned `null`, which the submit path read as "not a
+ * command" — so `/compact` was sent to the model as ordinary text and the model
+ * acted on it as an instruction. These tests lock the three outcomes apart.
+ */
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+import { readFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));
+
+const load = (relative) =>
+ import(pathToFileURL(join(here, relative)).href);
+
+const { resolveComposerCommand } = await load("../src/hooks/use-composer-autocomplete.ts");
+const { parseSlashSubmission, resolveSlashDispatch } = await load(
+ "../src/features/chat/composer/slash-dispatch.ts",
+);
+const { api } = await load("../src/lib/api.ts");
+const { useAppStore } = await load("../src/stores/app-store.ts");
+
+const read = (path) => readFile(new URL(path, import.meta.url), "utf8");
+
+/** Run `body` with `api.composerCommands` replaced, restoring it afterwards. */
+async function withCommandSource(replacement, body) {
+ const original = api.composerCommands;
+ api.composerCommands = replacement;
+ try {
+ return await body();
+ } finally {
+ api.composerCommands = original;
+ }
+}
+
+/** Point the store at a fresh workspace so the module-level TTL cache misses. */
+function useWorkspace(path) {
+ useAppStore.setState({ workspace: { path } });
+}
+
+test("an unreadable command source refuses the submission instead of sending it", async () => {
+ useWorkspace("/pi-795-source-unavailable");
+ await withCommandSource(
+ async () => {
+ throw new Error("composer/commands unavailable");
+ },
+ async () => {
+ const resolution = await resolveComposerCommand("compact");
+ assert.equal(
+ resolution.status,
+ "unavailable",
+ "a failed source read is not an unknown command",
+ );
+ assert.equal(resolution.error.message, "composer/commands unavailable");
+
+ const decision = resolveSlashDispatch(parseSlashSubmission("/compact"), resolution);
+ assert.equal(decision.action, "blocked");
+ assert.equal(decision.error, resolution.error);
+ },
+ );
+});
+
+test("a failed source read keeps every slash submission retriable", async () => {
+ useWorkspace("/pi-795-source-retry");
+ let attempts = 0;
+ await withCommandSource(
+ async () => {
+ attempts += 1;
+ if (attempts === 1) throw new Error("sidecar RPC timeout: composer.commands");
+ return {
+ commands: [
+ { name: "compact", kind: "builtin", title: "Compact", id: "builtin.agent.compact" },
+ ],
+ };
+ },
+ async () => {
+ // The failed attempt must leave the cache cold, so the retry re-reads.
+ assert.equal((await resolveComposerCommand("compact")).status, "unavailable");
+ const retried = await resolveComposerCommand("compact");
+ assert.equal(retried.status, "resolved");
+ assert.equal(retried.command.id, "builtin.agent.compact");
+ assert.equal(attempts, 2);
+ },
+ );
+});
+
+test("an unknown alias and a template still travel as prompt text", async () => {
+ useWorkspace("/pi-795-unknown");
+ await withCommandSource(
+ async () => ({
+ commands: [
+ { name: "review", kind: "skill", title: "Review", id: "skill.review" },
+ { name: "plan", kind: "template", title: "Plan" },
+ ],
+ }),
+ async () => {
+ const unknown = await resolveComposerCommand("not-a-command");
+ assert.equal(unknown.status, "unknown");
+ assert.equal(
+ resolveSlashDispatch(parseSlashSubmission("/not-a-command hello"), unknown).action,
+ "prompt",
+ );
+
+ const template = await resolveComposerCommand("plan");
+ assert.equal(template.status, "resolved");
+ assert.equal(
+ resolveSlashDispatch(parseSlashSubmission("/plan a release"), template).action,
+ "prompt",
+ "a prompt template is text, not a control command",
+ );
+ },
+ );
+});
+
+test("a warm source keeps dispatching a builtin through a source blip", async () => {
+ useWorkspace("/pi-795-warm");
+ let calls = 0;
+ await withCommandSource(
+ async () => {
+ calls += 1;
+ return {
+ commands: [
+ { name: "compact", kind: "builtin", title: "Compact", id: "builtin.agent.compact" },
+ ],
+ };
+ },
+ async () => {
+ const resolution = await resolveComposerCommand("compact");
+ assert.equal(resolution.status, "resolved");
+ const decision = resolveSlashDispatch(parseSlashSubmission("/compact now"), resolution);
+ assert.equal(decision.action, "dispatch");
+ assert.equal(decision.command.id, "builtin.agent.compact");
+ assert.equal(decision.body, "now");
+ assert.equal(calls, 1, "the first resolution fetches the source");
+
+ await withCommandSource(
+ async () => {
+ throw new Error("composer/commands unavailable");
+ },
+ async () => {
+ assert.equal((await resolveComposerCommand("compact")).status, "resolved");
+ assert.equal(calls, 1, "a warm cache must not re-fetch per submission");
+ },
+ );
+ },
+ );
+});
+
+test("plain text and a bare slash stay on the prompt path", () => {
+ assert.equal(parseSlashSubmission("hello"), null);
+ assert.equal(parseSlashSubmission(""), null);
+ assert.equal(parseSlashSubmission("/"), null);
+ assert.deepEqual(parseSlashSubmission("/compact"), { name: "compact", body: "" });
+ assert.deepEqual(parseSlashSubmission("/plan a release "), {
+ name: "plan",
+ body: "a release",
+ });
+ assert.equal(resolveSlashDispatch(null, null).action, "prompt");
+});
+
+test("the submit path proves the blocked branch precedes the prompt path", async () => {
+ const submit = await read(
+ "../src/features/chat/composer/hooks/useComposerSubmit.ts",
+ );
+ assert.match(
+ submit,
+ /import \{[\s\S]*?parseSlashSubmission,[\s\S]*?resolveSlashDispatch,[\s\S]*?\} from "\.\.\/slash-dispatch";/,
+ );
+ assert.match(
+ submit,
+ /dispatch\.action === "blocked"[\s\S]*?showToast\(t\("chat\.slashCommandSourceUnavailable"\)[\s\S]*?return;[\s\S]*?if \(dispatch\.action === "dispatch"\)/,
+ );
+ const blocked = submit.indexOf('dispatch.action === "blocked"');
+ const promptPath = submit.indexOf("if (!steering && !modelReady)");
+ assert.ok(
+ blocked > -1 && promptPath > blocked,
+ "the refusal must return before the send path is reached",
+ );
+ assert.doesNotMatch(
+ submit,
+ /serializedContent\.startsWith\("\/"\)/,
+ "slash detection belongs to parseSlashSubmission",
+ );
+});
+
+test("the shipped locales carry the refusal copy", async () => {
+ const [en, zhCN] = await Promise.all([
+ read("../../../packages/i18n/src/locales/en/index.ts"),
+ read("../../../packages/i18n/src/locales/zh-CN/index.ts"),
+ ]);
+ assert.match(en, /slashCommandSourceUnavailable:\s*"[^"]+"/);
+ assert.match(zhCN, /slashCommandSourceUnavailable:\s*"[^"]+"/);
+});
diff --git a/scripts/e2e/composer-submission.tsx b/scripts/e2e/composer-submission.tsx
index 550f05980..8aabc8275 100644
--- a/scripts/e2e/composer-submission.tsx
+++ b/scripts/e2e/composer-submission.tsx
@@ -4,6 +4,7 @@ import type { i18n } from "i18next";
import { I18nextProvider } from "react-i18next";
import { Composer } from "../../apps/desktop/src/components/Composer";
import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+import { api } from "../../apps/desktop/src/lib/api";
import { writeComposerDraft, deleteComposerDraft } from "../../apps/desktop/src/lib/composer-draft-cache";
import type { ComposerDraftSnapshot } from "../../apps/desktop/src/lib/composer-smart-stop";
@@ -72,6 +73,44 @@ export async function verifyComposerSubmission(imagePath: string, i18n: i18n) {
"last image must be reachable by scrolling");
flushSync(() => last.querySelector<HTMLButtonElement>(".composer-image-attachment-remove")!.click());
assert(tray.children.length === 19 && !sendButton().disabled, "scrolled attachment removal must preserve other images");
+
+ // Issue #795: a command source that cannot be read must refuse the
+ // submission, instead of handing `/compact` to the model as prompt text.
+ const toasts: string[] = [];
+ const originalComposerCommands = api.composerCommands;
+ const originalShowToast = useAppStore.getState().showToast;
+ api.composerCommands = async () => {
+ throw new Error("composer/commands unavailable");
+ };
+ useAppStore.setState({
+ showToast: (message) => {
+ toasts.push(String(message));
+ },
+ });
+ try {
+ prefill("/compact", []);
+ await painted();
+ const attempted = sent.length;
+ sendButton().click();
+ await painted();
+ await painted();
+ await painted();
+ assert(
+ sent.length === attempted,
+ `a refused slash submission must not reach the send path: ${JSON.stringify(sent.map((entry) => entry.content))}`,
+ );
+ assert(
+ editor().textContent === "/compact",
+ `a refused submission must keep the draft: ${JSON.stringify(editor().textContent)}`,
+ );
+ assert(
+ toasts.includes(i18n.t("chat.slashCommandSourceUnavailable")),
+ `the refusal must be visible: ${JSON.stringify(toasts)}`,
+ );
+ } finally {
+ api.composerCommands = originalComposerCommands;
+ useAppStore.setState({ showToast: originalShowToast });
+ }
} finally {
flushSync(() => root.unmount());
host.remove();