Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(skills): support multiple explicit composer invocations
zszz37b77ee3392ab
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.tsindex 2da6385dd..e889b6914 100644--- a/apps/desktop/electron/main/ipc/agent-ipc.ts+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts@@ -1,4 +1,4 @@-import { IPC, ErrorCodes, compactionRecordId, isGlobalPermissionMode, isRpcTimeoutError, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type PromptEnhancementRequest, type SessionSummarizeTitleRequest, canonicalThinkingLevel, type ThinkingLevel } from "@pi-desktop/shared";+import { IPC, ErrorCodes, compactionRecordId, findSkillMentions, isGlobalPermissionMode, isRpcTimeoutError, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type PromptEnhancementRequest, type SessionSummarizeTitleRequest, canonicalThinkingLevel, type ThinkingLevel } from "@pi-desktop/shared";import type { FinishTurn } from "../runtime/plans";import { expandSlashInvocation, enhancePromptDraft, summarizeSessionTitle, visionFromModelConfig, type ComposerTemplate, type RuntimeProviderConfig } from "@pi-desktop/agent-runtime";import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";@@ -442,28 +442,42 @@ export function registerAgentIpc({// /names stay literal text.let promptContent = sessionMessage?.content ?? req.content;let slashCommand: string | undefined;- if (!sessionMessage && req.content.startsWith("/")) {+ let skillMentions: UiMessage["skillMentions"];+ if (!sessionMessage && /(^|\s)\/\S/.test(req.content)) {try {const root = await optionalWorkspaceRoot();const commandEnd = req.content.search(/\s/);- const commandName = req.content.slice(- 1,- commandEnd === -1 ? undefined : commandEnd,- );+ const commandName = req.content.startsWith("/")+ ? req.content.slice(1, commandEnd === -1 ? undefined : commandEnd)+ : "";const commands = await composerCommandService.buildComposerCommands(launch.projectPath ?? root,);const command = commands.find((item) => item.name === commandName);- if (command?.kind === "skill" && command.skillId) {- const body = commandEnd === -1 ? "" : req.content.slice(commandEnd).trim();+ const activeSkills = new Map(+ commands.flatMap((item) => item.kind === "skill" && item.skillId+ ? [[item.name, item.skillId] as const]+ : []),+ );+ const mentions = findSkillMentions(req.content, activeSkills);+ if (mentions.length > 0 && (!command || command.kind === "skill")) {+ let body = "";+ let end = 0;+ for (const mention of mentions) {+ body += req.content.slice(end, mention.start);+ end = mention.end;+ }+ body = (body + req.content.slice(end)).trim();+ const ids = [...new Set(mentions.map((mention) => mention.id))];promptContent = [- `Call the \`Skill\` tool with id ${JSON.stringify(command.skillId)} before answering this request. Follow the loaded skill instructions.`,+ `Call the \`Skill\` tool with each of these ids before answering this request, in order: ${ids.map((id) => JSON.stringify(id)).join(", ")}. Follow the loaded skill instructions.`,body,].filter(Boolean).join("\n\n");slashCommand = req.content;- } else {+ skillMentions = mentions;+ } else if (req.content.startsWith("/")) {const templates = await loadComposerTemplatesCached(root);const expansion = expandSlashInvocation(req.content, templates);if (expansion) {@@ -531,6 +545,7 @@ export function registerAgentIpc({? { attachments: preparedAttachments.map((attachment) => attachment.message) }: {}),...(slashCommand ? { command: slashCommand } : {}),+ ...(skillMentions ? { skillMentions } : {}),...(revisionMeta?.revisionCount? {revisionRootId: revisionMeta.rootUserId,diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsxindex 71eeae060..c9078af31 100644--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx@@ -5,6 +5,7 @@ import {useRef,useState,type MouseEvent as ReactMouseEvent,+ type ReactNode,} from "react";import { useTranslation } from "react-i18next";import type { UiMessage } from "@pi-desktop/shared";@@ -33,6 +34,37 @@ import {useTranscriptMenu,} from "./TranscriptMenu";+function SkillInvocationText({ message }: { message: UiMessage }) {+ const command = message.command ?? "";+ const mentions = message.skillMentions ?? [];+ const parts: ReactNode[] = [];+ let cursor = 0;+ for (const mention of mentions) {+ if (+ !Number.isInteger(mention.start) ||+ !Number.isInteger(mention.end) ||+ mention.start < cursor ||+ mention.end > command.length ||+ !command.slice(mention.start, mention.end).startsWith("/")+ ) {+ return <LinkifiedText text={command} attachments={message.attachments} />;+ }+ if (mention.start > cursor) {+ parts.push(<LinkifiedText key={`text-${cursor}`} text={command.slice(cursor, mention.start)} attachments={message.attachments} />);+ }+ parts.push(+ <code key={`skill-${mention.start}`} className="chat-command-chip" title={mention.id}>+ {command.slice(mention.start, mention.end)}+ </code>,+ );+ cursor = mention.end;+ }+ if (cursor < command.length) {+ parts.push(<LinkifiedText key={`text-${cursor}`} text={command.slice(cursor)} attachments={message.attachments} />);+ }+ return <>{parts}</>;+}+export const MessageRow = memo(function MessageRow({message,isRunning,@@ -247,17 +279,19 @@ export const MessageRow = memo(function MessageRow({{message.content ? (<div className="message-user-text selectable">{editableUserMessage && message.command ? (- // Slash invocations show the typed form as a chip; the- // expanded template body lives in `content` (hover reveals- // it) and is what regenerate/reseed replay (D123).- <code- className="chat-command-chip"- data-source-start={0}- data-source-end={message.content.length}- title={String(message.content || "")}- >- {message.command}- </code>+ message.skillMentions?.length ? (+ <SkillInvocationText message={message} />+ ) : (+ // Templates retain the existing whole-invocation chip.+ <code+ className="chat-command-chip"+ data-source-start={0}+ data-source-end={message.content.length}+ title={String(message.content || "")}+ >+ {message.command}+ </code>+ )) : (<LinkifiedText text={String(message.content || "")} attachments={message.attachments} />)}diff --git a/apps/desktop/src/hooks/use-composer-autocomplete.ts b/apps/desktop/src/hooks/use-composer-autocomplete.tsindex 8e7cb4132..0b19f7702 100644--- a/apps/desktop/src/hooks/use-composer-autocomplete.ts+++ b/apps/desktop/src/hooks/use-composer-autocomplete.ts@@ -52,6 +52,7 @@ const COMMAND_GROUP_ORDER = {function filterCommands(commands: ComposerCommand[],query: string,+ skillsOnly = false,): AutocompleteItem[] {const matched: Array<{command: ComposerCommand;@@ -59,6 +60,7 @@ function filterCommands(sortText: string;}> = [];for (const command of commands) {+ if (skillsOnly && command.kind !== "skill") continue;const byName = fuzzyMatchCommand(query, command.name);if (byName) {matched.push({ command, match: byName, sortText: command.name });@@ -251,7 +253,7 @@ export function useComposerAutocomplete({const items = useMemo<AutocompleteItem[]>(() => {if (!trigger || dismissed) return [];if (trigger.mode === "slash") {- return commands ? filterCommands(commands, trigger.query) : [];+ return commands ? filterCommands(commands, trigger.query, trigger.tokenStart > 0) : [];}return files ? filterFiles(files.entries, trigger.query) : [];}, [trigger, dismissed, commands, files]);diff --git a/crates/host-core/src/plugin_sessions.rs b/crates/host-core/src/plugin_sessions.rsindex fd09e435a..30ec0c973 100644--- a/crates/host-core/src/plugin_sessions.rs+++ b/crates/host-core/src/plugin_sessions.rs@@ -231,6 +231,8 @@ fn parse_message(id: Uuid::new_v4().to_string(),role: role.to_string(),content: input.content.clone(),+ command: None,+ skill_mentions: None,attachments: None,steering: None,created_at,diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex bd2eaae55..21e51693c 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -148,6 +148,12 @@ pub struct UiMessage {pub id: String,pub role: String,pub content: String,+ /// Original text for a slash template or Skill invocation.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub command: Option<String>,+ /// Validated Skill tokens in `command`, with UTF-16 offsets for the renderer.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub skill_mentions: Option<Vec<SkillMention>>,/// Host-authenticated agent-to-agent origin, never a human authorization.#[serde(default, skip_serializing_if = "Option::is_none")]pub session_message: Option<Value>,@@ -215,6 +221,14 @@ pub struct UiMessage {pub hosted_search: Option<Value>,}+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SkillMention {+ pub start: usize,+ pub end: usize,+ pub id: String,+}+#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct SessionDetail {@@ -284,6 +298,12 @@ fn is_default_title(title: &str) -> bool {/// the search index row (None for tool rows, matching the FTS triggers).pub(crate) fn ui_to_record(message: &UiMessage) -> (MessageRecord, Option<String>) {let mut meta_obj = serde_json::Map::new();+ if let Some(command) = &message.command {+ meta_obj.insert("command".into(), json!(command));+ }+ if let Some(mentions) = &message.skill_mentions {+ meta_obj.insert("skillMentions".into(), json!(mentions));+ }if let Some(origin) = &message.session_message {meta_obj.insert("sessionMessage".into(), origin.clone());}@@ -431,6 +451,13 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {_ => Vec::new(),};let meta = record.meta.unwrap_or(Value::Null);+ let command = meta+ .get("command")+ .and_then(Value::as_str)+ .map(str::to_string);+ let skill_mentions = meta+ .get("skillMentions")+ .and_then(|value| serde_json::from_value(value.clone()).ok());let session_message = meta.get("sessionMessage").cloned();let steering = meta.get("steering").and_then(Value::as_bool);let status = meta@@ -533,6 +560,8 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {id: record.id,role: record.role,content: text,+ command: command.clone(),+ skill_mentions: skill_mentions.clone(),session_message,attachments: None,steering,@@ -582,6 +611,8 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {id: record.id,role: record.role,content,+ command,+ skill_mentions,session_message,attachments,steering,@@ -3823,6 +3854,8 @@ mod tests {id: id.into(),role: "user".into(),content: content.into(),+ command: None,+ skill_mentions: None,attachments: None,steering: None,created_at: ts.into(),@@ -4467,6 +4500,8 @@ mod tests {id: "m2".into(),role: "tool".into(),content: "ok".into(),+ command: None,+ skill_mentions: None,attachments: None,steering: None,created_at: "2025-05-01T00:00:02Z".into(),@@ -4896,6 +4931,8 @@ mod tests {id: "assistant-1".into(),role: "assistant".into(),content: "final answer".into(),+ command: None,+ skill_mentions: None,attachments: None,steering: None,created_at: "2025-05-01T00:00:01Z".into(),@@ -4979,6 +5016,8 @@ mod tests {id: "assistant-search-1".into(),role: "assistant".into(),content: "answer with sources".into(),+ command: None,+ skill_mentions: None,attachments: None,steering: None,created_at: "2025-05-01T00:00:01Z".into(),diff --git a/docs/adr/0219-user-invoked-skills-in-composer.md b/docs/adr/0219-user-invoked-skills-in-composer.mdindex f7bdad665..bdb74734f 100644--- a/docs/adr/0219-user-invoked-skills-in-composer.md+++ b/docs/adr/0219-user-invoked-skills-in-composer.md@@ -24,16 +24,19 @@ the renderer, prompt, or host protocol.commands; the group is always last. The exact skill id is the slash name.Existing command names win collisions, so a Skill cannot shadow a template,builtin, plugin, or extension command.-2. Selecting a Skill inserts `/<skill-id> `. Sending follows the ordinary+2. Selecting a Skill inserts `/<skill-id> `. Later slash tokens can select+ further Skills without opening app commands. Sending follows the ordinaryprompt path. Electron main resolves the command against the current sessionproject, revalidates its active scope and permissions at send time, andkeeps the typed slash form for the transcript chip.3. Main persists a model-facing instruction asking the model to call the local- `Skill` tool with the validated id, followed by any user body text. The Skill+ `Skill` tool with each validated id, followed by the remaining user text. The Skillbody is still loaded on demand by that tool; it is not sent to the rendereror injected directly into the prompt. `agent.prompt.inject` and existinguser-Skill activation rules remain authoritative.-4. No host protocol or storage schema changes are required. The additive+4. No host protocol version or SQL migration is required. The optional+ `command` and `skillMentions` transcript metadata preserve the user's typed+ text and each validated token across session reloads. The additivecommand contract permits `kind: "skill"` and `skillId`, and the existingcomposer-command IPC response carries the extra entries. Skill catalog,body-size, path, and runtime-reuse boundaries remain those of D174 anddiff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex 30f94b88c..8ac585d15 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -149,7 +149,11 @@ name matches a loaded pi prompt template, the main-process handler expandsthe invocation (`parseCommandArgs` + `substituteArgs`) before persisting.The persisted user message stores `content = expanded text` plus an optional`command: string` field carrying the typed invocation for transcript-display. Reseed replays `content`, so the agent context is identical across+display. Explicit Skill invocations also persist validated `skillMentions`+with UTF-16 offsets into `command`, allowing the transcript to show each+Skill separately from the user's remaining text after reopening a session.+These optional transcript metadata fields do not alter the model-facing+`content`. Reseed replays `content`, so the agent context is identical acrossrestarts. Builtin/plugin slash aliases never reach this channel — therenderer executes them locally. Unknown `/foo` passes through as literalcontent. Ordinary `@path` tokens are not transformed anywhere in the pipelinediff --git a/docs/spec/04-ux/04-builtin-commands.md b/docs/spec/04-ux/04-builtin-commands.mdindex 3edb54b04..751a14e2c 100644--- a/docs/spec/04-ux/04-builtin-commands.md+++ b/docs/spec/04-ux/04-builtin-commands.md@@ -112,12 +112,14 @@ name and description, and form a separate **Skills** group after extensioncommands. This group is always last; a Skill never shadows a command ortemplate with the same name.-Selecting a Skill inserts `/<skill-id> `. Sending `/<skill-id>` with optional-prompt text keeps that typed form as the visible transcript chip and asks the-model to call the existing `Skill` tool with the validated id before answering.+Selecting a Skill inserts `/<skill-id> `. After the first token, typing `/`+offers Skills only; app commands and templates remain first-token actions.+Multiple Skills may be selected in one message. Sending keeps each validated+Skill as its own transcript chip, with ordinary prompt text between chips, and+asks the model to call the existing `Skill` tool for each id before answering.Only Skills active for the current project are listed or accepted, so projectscope and plugin activation remain enforced at send time. If the Skill is no-longer active, the text follows the normal unknown-slash prompt path.+longer active, its token remains literal prompt text.## 9. Ideographic comma opens the slash menu (D405)diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 8b14ef60f..8dce05c62 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -3105,6 +3105,9 @@ Anatomy:user-global), app commands (builtin slash aliases), plugin commands.The core aliases remain `/new`, `/compact`, `/agent-mode`, `/plan-mode`, and`/goal-mode`; matched characters highlight in accent.+- A whitespace-delimited `/` later in the draft offers active Skills only.+ Completion replaces only the token under the cursor, so several Skills and+ ordinary text can coexist in one prompt.- Command descriptions use the space left after the slash name and optionaltitle/argument hints. A long description truncates before it can squeeze ashort command name to an ellipsis, including in narrow composers. Names anddiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 209d68879..1f74ae544 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -13583,12 +13583,16 @@ plugin-form fixtures in an isolated temporary directory at runtime.3. Confirm the model calls `Skill` with the exact id without calling`ToolSearch` first, and that the returned document is the skill body.4. Send `/<skill-id>` from the composer and inspect the following turn.+ 4a. Add a second active Skill with `/` after the first token, submit the+ prompt, switch away from the session, and reopen it.5. Switch the session to Plan mode and inspect the tool list again.6. Disable or remove every Skill and start another Agent turn.- **Expected**: Whenever the skill catalog is non-empty, `Skill` ships with thefirst request and never appears under `# On-demand tools`, so both a matchingtask and a `/skill-id` invocation load the body without a discovery round- trip. `ToolSearch` still exists for the other on-demand capabilities and+ trip. Both explicit Skills load in their selected order; after reopening,+ each remains a separate transcript chip beside the user's prompt text.+ `ToolSearch` still exists for the other on-demand capabilities andnever returns `Skill`. Plan mode omits the tool and the `# Skills` section,and an empty catalog registers no `Skill` tool at all.- **Specs linked**: `03-runtime/02-agent-runtime.md` (§7.1),diff --git a/packages/shared/src/composer-trigger.test.ts b/packages/shared/src/composer-trigger.test.tsindex bed6d9a01..5c69f7581 100644--- a/packages/shared/src/composer-trigger.test.ts+++ b/packages/shared/src/composer-trigger.test.ts@@ -44,9 +44,10 @@ describe("detectTrigger — slash mode", () => {});});- it("never triggers mid-draft or on later lines", () => {- expect(detectTrigger("hi /cmd", 7)).toBeNull();- expect(detectTrigger("hi\n/cmd", 7)).toBeNull();+ it("targets later slash tokens independently", () => {+ expect(detectTrigger("hi /cmd", 7)).toMatchObject({ tokenStart: 3, query: "cmd" });+ expect(detectTrigger("hi\n/cmd", 7)).toMatchObject({ tokenStart: 3, query: "cmd" });+ expect(detectTrigger("https://example.com", 8)).toBeNull();});});diff --git a/packages/shared/src/composer-trigger.ts b/packages/shared/src/composer-trigger.tsindex 913774e5c..a3f6d8917 100644--- a/packages/shared/src/composer-trigger.ts+++ b/packages/shared/src/composer-trigger.ts@@ -4,8 +4,8 @@* tested away from React and IME timing.** Grammar mirrors the pi CLI editor:- * - "/" opens command mode only as the very first character of the draft,- * while the cursor is still inside that first whitespace-free token.+ * - "/" opens all commands in the first token. Later whitespace-delimited+ * slash tokens offer Skills only; app commands still require the first token.* - "@" opens file mode when the token containing the cursor starts with* "@" and the character before it is start-of-input, whitespace, or one* of the pi delimiters (" ' =). A `@"` prefix starts a quoted token that@@ -73,19 +73,21 @@ export function detectTrigger(): ComposerTrigger | null {if (cursor < 0 || cursor > value.length) return null;- // Slash mode: draft starts with "/", cursor inside the first token.- if (value.startsWith("/") && cursor >= 1) {- const head = value.slice(1, cursor);- let hasWhitespace = false;- for (const ch of head) {- if (WHITESPACE.has(ch)) {- hasWhitespace = true;- break;- }- }- if (!hasWhitespace) {- return { mode: "slash", query: head, tokenStart: 0, tokenEnd: cursor };+ // Only the token under the cursor can open the menu. A later slash is a+ // Skill reference, not a second app command.+ let slashStart = cursor;+ while (slashStart > 0 && !WHITESPACE.has(value[slashStart - 1])) slashStart -= 1;+ if (value[slashStart] === "/" && cursor > slashStart) {+ let tokenEnd = cursor;+ if (slashStart > 0) {+ while (tokenEnd < value.length && !WHITESPACE.has(value[tokenEnd])) tokenEnd += 1;}+ return {+ mode: "slash",+ query: value.slice(slashStart + 1, cursor),+ tokenStart: slashStart,+ tokenEnd,+ };}// File mode, quoted form first: @"query with spaces@@ -127,6 +129,23 @@ export function detectTrigger(return null;}+export type SkillMention = { start: number; end: number; id: string };++/** Resolve complete slash tokens against the active Skill catalog at send time. */+export function findSkillMentions(+ content: string,+ skillIds: ReadonlyMap<string, string>,+): SkillMention[] {+ const mentions: SkillMention[] = [];+ for (const match of content.matchAll(/(^|\s)\/([^\s]+)/g)) {+ const id = skillIds.get(match[2]);+ if (!id) continue;+ const start = match.index + match[1].length;+ mentions.push({ start, end: start + match[2].length + 1, id });+ }+ return mentions;+}+/** Insertion text for an accepted slash command: `/name ` ready for args. */export function formatCommandInsert(name: string): string {return `/${name} `;diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.tsindex 2ba3d124f..fd396f12b 100644--- a/packages/shared/src/types/messages.ts+++ b/packages/shared/src/types/messages.ts@@ -97,11 +97,12 @@ export type UiMessage = {/** 1-based active variant index for this user root turn. */activeRevision?: number;/**- * Typed slash invocation ("/name args") when this user message was- * produced by a prompt-template command; `content` holds the expanded- * text the model sees (D123). Transcript renders this as a chip.+ * Original text for an expanded slash template or explicit Skill invocation;+ * `content` holds the expanded text the model sees (D123, ADR 0219).*/command?: string;+ /** Validated Skill tokens in `command`, using UTF-16 offsets. */+ skillMentions?: Array<{ start: number; end: number; id: string }>;toolName?: string;toolCallId?: string;toolStatus?: "running" | "success" | "error" | "denied";