Skip to content

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

feat(composer): route @agent mentions to a named subagent

vastsa841b64461f93
diff --git a/apps/desktop/electron/main/agent-mentions.ts b/apps/desktop/electron/main/agent-mentions.ts
new file mode 100644
index 000000000..5622cdb94
--- /dev/null
+++ b/apps/desktop/electron/main/agent-mentions.ts
@@ -0,0 +1,43 @@
+import { stat } from "node:fs/promises";
+import { join } from "node:path";
+import { findAgentMentions, type AgentMention, type Mode } from "@pi-desktop/shared";
+
+/**
+ * Send-time resolution of `@agent` mentions (ADR 0346).
+ *
+ * A token is a delegation only when the turn runs in Agent mode (the only mode
+ * that may execute `Task`), it names a subagent in the catalog this launch
+ * hands the runtime, and the workspace holds no file or folder of that name —
+ * a project that really has an `explorer` file keeps its file reference.
+ */
+export async function resolvePromptAgentMentions({
+ content,
+ mode,
+ subagentNames,
+ workspaceRoot,
+}: {
+ content: string;
+ mode: Mode | undefined;
+ subagentNames: readonly string[];
+ /** Local workspace root; `null` for a remote or project-less session. */
+ workspaceRoot: string | null;
+}): Promise<AgentMention[]> {
+ if (mode !== "agent" || subagentNames.length === 0 || !content.includes("@")) return [];
+ const mentions = findAgentMentions(content, new Set(subagentNames));
+ if (!mentions.length || !workspaceRoot) return mentions;
+ const shadowed = new Set<string>();
+ for (const name of new Set(mentions.map((mention) => mention.name))) {
+ // Catalog names match /^[a-z0-9][a-z0-9-]*$/, so the join stays inside root.
+ if (await pathExists(join(workspaceRoot, name))) shadowed.add(name);
+ }
+ return mentions.filter((mention) => !shadowed.has(mention.name));
+}
+
+async function pathExists(path: string): Promise<boolean> {
+ try {
+ await stat(path);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.ts
index cac93579b..07faeb1f7 100644
--- a/apps/desktop/electron/main/ipc/agent-ipc.ts
+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts
@@ -1,9 +1,10 @@
import { expandMcpInvocation } from "../composer-mcp";
-import { IPC, ErrorCodes, compactionRecordId, findSkillMentions, isGlobalPermissionMode, isRpcTimeoutError, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AgentStopSubagentsRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PendingInteractiveRequests, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type VoiceOrigin } from "@pi-desktop/shared";
+import { IPC, ErrorCodes, compactionRecordId, composeMentionPrompt, findSkillMentions, isGlobalPermissionMode, isRpcTimeoutError, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AgentStopSubagentsRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PendingInteractiveRequests, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type VoiceOrigin } from "@pi-desktop/shared";
import type { FinishTurn } from "../runtime/plans";
import { expandSlashInvocation, visionFromModelConfig, type ComposerTemplate } from "@pi-desktop/agent-runtime";
import { appendPromptFallbackPaths, durableUserMessageId, preparePromptAttachments, type PreparedPromptAttachment } from "../prompt-attachments";
import { resolveSessionReferences } from "../session-references";
+import { resolvePromptAgentMentions } from "../agent-mentions";
import { executionFromResponse, resolveSessionMessageInput } from "@pi-desktop/host-runtime";
import type { AgentExtensionBridge } from "../agent-extensions";
import type { AgentHostBridge } from "../agent-host-bridge";
@@ -351,52 +352,64 @@ export function registerAgentIpc({
// as `command` for transcript display. Skill aliases are converted into a
// short model instruction that makes the existing Skill tool call
// explicit, while the typed form remains the visible transcript chip.
+ // `@agent` mentions (ADR 0346) take the same shape with the `Task` tool.
// Builtin/plugin slash aliases never reach this channel, and unknown
// /names stay literal text.
let promptContent = mcpExpansion?.expanded ?? sessionMessage?.content ?? req.content;
let slashCommand: string | undefined = mcpExpansion?.command;
let skillMentions: UiMessage["skillMentions"];
- if (!sessionMessage && !mcpExpansion && /(^|\s)\/\S/.test(req.content)) {
+ let agentMentions: UiMessage["agentMentions"];
+ const hasSlashToken = /(^|\s)\/\S/.test(req.content);
+ if (!sessionMessage && !mcpExpansion && (hasSlashToken || req.content.includes("@"))) {
try {
- const root = await optionalWorkspaceRoot();
- const commandEnd = req.content.search(/\s/);
- const commandName = req.content.startsWith("/")
- ? req.content.slice(1, commandEnd === -1 ? undefined : commandEnd)
- : "";
- const commands = await composerCommandService.buildComposerCommands(
- session.remoteWorkspace ? null : launch.projectPath ?? root,
- { remote: Boolean(session.remoteWorkspace) },
- );
- const command = commands.find((item) => item.name === commandName);
- 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;
+ const foundAgents = await resolvePromptAgentMentions({
+ content: req.content,
+ mode: launch.sidecarParams?.mode,
+ subagentNames: Array.isArray(launch.sidecarParams?.subagents)
+ ? launch.sidecarParams.subagents.map((definition: { name: string }) => definition.name)
+ : [],
+ workspaceRoot: session.remoteWorkspace
+ ? null
+ : (launch.workspaceRoot ?? launch.projectPath ?? null),
+ });
+ if (!hasSlashToken) {
+ if (foundAgents.length > 0) {
+ promptContent = composeMentionPrompt(req.content, [], foundAgents);
+ slashCommand = req.content;
+ agentMentions = foundAgents;
}
- body = (body + req.content.slice(end)).trim();
- const ids = [...new Set(mentions.map((mention) => mention.id))];
- promptContent = [
- `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;
- skillMentions = mentions;
- } else if (req.content.startsWith("/")) {
- const templates = await loadComposerTemplatesCached(root);
- const expansion = expandSlashInvocation(req.content, templates);
- if (expansion) {
- promptContent = expansion.expanded;
- slashCommand = expansion.command;
+ } else {
+ const root = await optionalWorkspaceRoot();
+ const commandEnd = req.content.search(/\s/);
+ const commandName = req.content.startsWith("/")
+ ? req.content.slice(1, commandEnd === -1 ? undefined : commandEnd)
+ : "";
+ const commands = await composerCommandService.buildComposerCommands(
+ session.remoteWorkspace ? null : launch.projectPath ?? root,
+ { remote: Boolean(session.remoteWorkspace) },
+ );
+ const command = commands.find((item) => item.name === commandName);
+ const activeSkills = new Map(
+ commands.flatMap((item) => item.kind === "skill" && item.skillId
+ ? [[item.name, item.skillId] as const]
+ : []),
+ );
+ const mentions = findSkillMentions(req.content, activeSkills);
+ // A leading template keeps its expansion; agent mentions ride along
+ // only on a draft whose first token is no app or template command.
+ const mentionable = !command || command.kind === "skill";
+ if (mentionable && (mentions.length > 0 || foundAgents.length > 0)) {
+ promptContent = composeMentionPrompt(req.content, mentions, foundAgents);
+ slashCommand = req.content;
+ if (mentions.length > 0) skillMentions = mentions;
+ if (foundAgents.length > 0) agentMentions = foundAgents;
+ } else if (req.content.startsWith("/")) {
+ const templates = await loadComposerTemplatesCached(root);
+ const expansion = expandSlashInvocation(req.content, templates);
+ if (expansion) {
+ promptContent = expansion.expanded;
+ slashCommand = expansion.command;
+ }
}
}
} catch (error) {
@@ -482,6 +495,7 @@ export function registerAgentIpc({
...(voiceOrigin ? { voiceOrigin } : {}),
...(slashCommand ? { command: slashCommand } : {}),
...(skillMentions ? { skillMentions } : {}),
+ ...(agentMentions ? { agentMentions } : {}),
...(revisionMeta?.revisionCount
? {
revisionRootId: revisionMeta.rootUserId,
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsx
index 33b4ebd52..5928aa425 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -489,6 +489,7 @@ export function Composer({
cursor,
composing,
enabled: !inputBlocked && localToolsAllowed,
+ agentsEnabled: mode === "agent",
referenceSessionId,
fileReferencesRef,
applyEditorDraft,
diff --git a/apps/desktop/src/components/ComposerAutocomplete.tsx b/apps/desktop/src/components/ComposerAutocomplete.tsx
index b28811c83..a02c61ea5 100644
--- a/apps/desktop/src/components/ComposerAutocomplete.tsx
+++ b/apps/desktop/src/components/ComposerAutocomplete.tsx
@@ -7,6 +7,7 @@ import type {
} from "../features/chat/composer/hooks/useComposerCompletions";
import {
IconBookOpen,
+ IconBot,
IconFileText,
IconFolder,
IconPlug,
@@ -88,9 +89,11 @@ export function ComposerAutocomplete({
key:
item.kind === "command"
? `c:${item.command.kind}:${item.command.name}`
- : item.kind === "plugin"
- ? `pl:${item.pluginId}:${index}`
- : `p:${item.entry.path}`,
+ : item.kind === "agent"
+ ? `a:${item.agent.name}`
+ : item.kind === "plugin"
+ ? `pl:${item.pluginId}:${index}`
+ : `p:${item.entry.path}`,
type: "button" as const,
role: "option" as const,
"aria-selected": active,
@@ -124,6 +127,21 @@ export function ComposerAutocomplete({
</button>
);
}
+ if (item.kind === "agent") {
+ return (
+ <button {...commonProps} aria-label={`@${item.agent.name}`} title={item.agent.description}>
+ <span className="composer-ac-icon">
+ <IconBot size={14} />
+ </span>
+ <span className="composer-ac-name">
+ @<Highlighted text={item.agent.name} ranges={item.match.ranges} />
+ </span>
+ {item.agent.description ? (
+ <span className="composer-ac-desc">{item.agent.description}</span>
+ ) : null}
+ </button>
+ );
+ }
if (item.kind === "plugin") {
return (
<button {...commonProps} title={item.row.detail}>
@@ -155,8 +173,18 @@ export function ComposerAutocomplete({
const rows: React.ReactNode[] = [];
let lastGroup: string | null = null;
+ // Files carry a heading only beside an Agents group (ADR 0346); a plain
+ // `@` file list stays as it was.
+ const hasAgents = ac.items.some((item) => item.kind === "agent");
ac.items.forEach((item, index) => {
- if (item.kind === "command") {
+ if ((item.kind === "agent" || (item.kind === "path" && hasAgents)) && lastGroup !== item.kind) {
+ lastGroup = item.kind;
+ rows.push(
+ <div key={`g:${item.kind}`} className="composer-model-group-label">
+ {t(item.kind === "agent" ? "chat.mentionGroupAgents" : "chat.mentionGroupFiles")}
+ </div>,
+ );
+ } else if (item.kind === "command") {
const group = item.command.kind;
if (group !== lastGroup) {
lastGroup = group;
diff --git a/apps/desktop/src/features/chat/composer/editor.ts b/apps/desktop/src/features/chat/composer/editor.ts
index 8734a474e..b344fc3d9 100644
--- a/apps/desktop/src/features/chat/composer/editor.ts
+++ b/apps/desktop/src/features/chat/composer/editor.ts
@@ -39,7 +39,7 @@ export function createFileReference(
preferredName?: string,
sessionId = "",
metadata?: {
- kind?: "image" | "file" | "session" | "directory";
+ kind?: "image" | "file" | "session" | "directory" | "agent";
mimeType?: string;
token?: string;
plugin?: ComposerPluginPart;
@@ -54,7 +54,7 @@ export function createFileReference(
// A plugin mark's label is shown as given, and a session reference is
// named by its conversation; neither is a path.
name:
- isPluginMark(metadata) || metadata?.kind === "session"
+ isPluginMark(metadata) || metadata?.kind === "session" || metadata?.kind === "agent"
? (preferredName ?? "")
: fileReferenceLabel(path, preferredName),
kind: metadata?.kind ?? (isImageFilePath(path) ? "image" : "file"),
@@ -254,6 +254,8 @@ const CHIP_ICON_SVG: Record<string, string> = {
x: '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
plugin:
'<path d="M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z"/>',
+ agent:
+ '<path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/><path d="M2 14h2"/><path d="M20 14h2"/><path d="M15 13v2"/><path d="M9 13v2"/>',
fold: '<rect width="14" height="14" x="8" y="8" rx="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
};
@@ -261,6 +263,7 @@ function chipIconKey(reference: ComposerFileReference): string {
if (reference.plugin?.kind === "mark") return "plugin";
if (reference.plugin?.kind === "fold") return "fold";
if (reference.kind === "session") return "session";
+ if (reference.kind === "agent") return "agent";
if (reference.kind === "directory") return "dir";
const mime = reference.mimeType ?? "";
if (reference.kind === "image" || mime.startsWith("image/")) return "image";
@@ -280,7 +283,7 @@ function chipSvg(key: string, size = 13): string {
}
export function isEditableTextReference(reference: ComposerFileReference): boolean {
- if (isPluginMark(reference) || reference.kind === "directory") return false;
+ if (isPluginMark(reference) || reference.kind === "directory" || reference.kind === "agent") return false;
return reference.mimeType?.toLowerCase() === "text/plain" || /\.txt$/i.test(reference.name);
}
@@ -299,8 +302,13 @@ function buildChipElement(
chip.contentEditable = "false";
chip.dataset.token = token;
// A mark names the plugin that put it there where a file names its path.
- const origin = isPluginMark(reference) ? (reference.plugin?.pluginId ?? "") : reference.path;
+ const origin = isPluginMark(reference)
+ ? (reference.plugin?.pluginId ?? "")
+ : reference.kind === "agent"
+ ? `@${reference.path}`
+ : reference.path;
if (isPluginMark(reference)) chip.dataset.pluginMark = reference.plugin?.kind;
+ if (reference.kind === "agent") chip.dataset.agent = reference.path;
chip.title = origin;
// An image keeps the compact chip and opens its preview, a session chip opens
// that conversation, and only plain text expands into editable draft text.
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerCompletions.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerCompletions.ts
index 0777df7a7..5cacc31f7 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerCompletions.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerCompletions.ts
@@ -67,6 +67,7 @@ export function useComposerCompletions({
cursor,
composing,
enabled,
+ agentsEnabled = false,
referenceSessionId,
fileReferencesRef,
applyEditorDraft,
@@ -77,13 +78,15 @@ export function useComposerCompletions({
cursor: number;
composing: boolean;
enabled: boolean;
+ /** Whether the `@` menu offers subagents (Agent mode only, ADR 0346). */
+ agentsEnabled?: boolean;
referenceSessionId: string;
fileReferencesRef: RefObject<ComposerFileReference[]>;
applyEditorDraft: (text: string, references: ComposerFileReference[], caret: number) => void;
handleInput: (source: string, caret: number, composing?: boolean) => string;
invalidateComposerTransforms: () => void;
}) {
- const host = useComposerAutocomplete({ value, cursor, composing, enabled });
+ const host = useComposerAutocomplete({ value, cursor, composing, enabled, agentsEnabled });
const { triggers } = useSyncExternalStore(
slotRegistry.subscribe,
slotRegistry.getSnapshot,
@@ -195,6 +198,24 @@ export function useComposerCompletions({
const result = host.accept(index);
if (!result) return;
invalidateComposerTransforms();
+ const acceptedAgent = result.agentReference;
+ if (acceptedAgent) {
+ // The same atomic chip a file gets: it displays and deletes as one
+ // thing, and serializes to `@name` only at send time.
+ const token = nextChipToken();
+ applyEditorDraft(
+ result.value.slice(0, result.cursor) + token + result.value.slice(result.cursor),
+ [
+ ...fileReferencesRef.current,
+ createFileReference(acceptedAgent.name, acceptedAgent.name, referenceSessionId, {
+ kind: "agent",
+ token,
+ }),
+ ],
+ result.cursor + token.length,
+ );
+ return;
+ }
// File accept strips the @ token (empty insert) and used to store a
// token-less chip above the textarea. Inline chips only paint when a
// sentinel is in the draft, so Enter looked like the reference vanished.
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
index 50a45ad4b..a6cd31b64 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
@@ -499,11 +499,13 @@ export function useComposerDraft({
compositionRef.current = null;
previousWorkspacePathRef.current = workspacePath;
const current = fileReferencesRef.current;
- // Plugin marks carry their text, not a workspace path, and a session
- // reference names a conversation rather than a file in this project.
+ // Plugin marks carry their text, not a workspace path, a session
+ // reference names a conversation and an agent chip names a subagent
+ // rather than a file in this project.
const survives = (fileReference: ComposerFileReference) =>
Boolean(fileReference.plugin) ||
fileReference.kind === "session" ||
+ fileReference.kind === "agent" ||
isPersistedScratchReference(fileReference.path);
const kept = current.filter(survives);
if (kept.length === current.length) return;
diff --git a/apps/desktop/src/features/chat/composer/model.ts b/apps/desktop/src/features/chat/composer/model.ts
index b56bce388..bf6ebdd8c 100644
--- a/apps/desktop/src/features/chat/composer/model.ts
+++ b/apps/desktop/src/features/chat/composer/model.ts
@@ -61,7 +61,7 @@ export type ComposerFileReference = {
sessionId: string;
path: string;
name: string;
- kind: "image" | "file" | "session" | "directory";
+ kind: "image" | "file" | "session" | "directory" | "agent";
mimeType?: string;
token?: string;
plugin?: ComposerPluginPart;
diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsx
index 2528f4bc0..35cb8bfb6 100644
--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx
+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx
@@ -40,9 +40,16 @@ import {
} from "./TranscriptMenu";
import { getExtraMessageAttachments } from "./extra-attachments";
-function SkillInvocationText({ message }: { message: UiMessage }) {
+/**
+ * The typed form of a Skill or `@agent` invocation (ADR 0346): each validated
+ * mention is a chip, and the text around it stays text.
+ */
+function MentionInvocationText({ message }: { message: UiMessage }) {
const command = message.command ?? "";
- const mentions = message.skillMentions ?? [];
+ const mentions = [
+ ...(message.skillMentions ?? []).map((mention) => ({ ...mention, sigil: "/", title: mention.id, agent: false })),
+ ...(message.agentMentions ?? []).map((mention) => ({ ...mention, sigil: "@", title: `@${mention.name}`, agent: true })),
+ ].sort((a, b) => a.start - b.start);
const parts: ReactNode[] = [];
let cursor = 0;
for (const mention of mentions) {
@@ -51,7 +58,7 @@ function SkillInvocationText({ message }: { message: UiMessage }) {
!Number.isInteger(mention.end) ||
mention.start < cursor ||
mention.end > command.length ||
- !command.slice(mention.start, mention.end).startsWith("/")
+ !command.slice(mention.start, mention.end).startsWith(mention.sigil)
) {
return <LinkifiedText text={command} attachments={message.attachments} />;
}
@@ -59,7 +66,12 @@ function SkillInvocationText({ message }: { message: UiMessage }) {
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}>
+ <code
+ key={`mention-${mention.start}`}
+ className="chat-command-chip"
+ title={mention.title}
+ {...(mention.agent ? { "data-agent-mention": "" } : {})}
+ >
{command.slice(mention.start, mention.end)}
</code>,
);
@@ -328,8 +340,8 @@ export const MessageRow = memo(function MessageRow({
<div className="message-user-text selectable">
{editableUserMessage && message.command ? (
<>
- {message.skillMentions?.length ? (
- <SkillInvocationText message={message} />
+ {message.skillMentions?.length || message.agentMentions?.length ? (
+ <MentionInvocationText message={message} />
) : (
// Templates retain the existing whole-invocation chip.
<code
diff --git a/apps/desktop/src/hooks/use-composer-autocomplete.ts b/apps/desktop/src/hooks/use-composer-autocomplete.ts
index bdc1ed26e..260ab9ed5 100644
--- a/apps/desktop/src/hooks/use-composer-autocomplete.ts
+++ b/apps/desktop/src/hooks/use-composer-autocomplete.ts
@@ -36,8 +36,11 @@ const SOURCE_TTL_MS = 10_000;
/** Typing pause before a query searches past a truncated file index. */
const FILE_SEARCH_DEBOUNCE_MS = 150;
+export type AutocompleteAgent = { name: string; description: string };
+
export type AutocompleteItem =
| { kind: "command"; command: ComposerCommand; match: FuzzyMatch }
+ | { kind: "agent"; agent: AutocompleteAgent; match: FuzzyMatch }
| { kind: "path"; entry: FsIndexEntry; match: FuzzyMatch };
/**
@@ -52,6 +55,9 @@ let filesCache: {
truncated: boolean;
} | null = null;
+/** The delegation catalog `Task` offers, for the `@` menu's Agents group (ADR 0346). */
+let agentsCache: { key: string; at: number; agents: AutocompleteAgent[] } | null = null;
+
const COMMAND_GROUP_ORDER = {
template: 0,
builtin: 1,
@@ -104,6 +110,34 @@ function filterCommands(
return matched.map(({ command, match }) => ({ kind: "command", command, match }));
}
+/**
+ * Agents matching the `@` query, by name or description. A root entry of the
+ * same name hides its agent: send-time resolution gives that token to the
+ * file, so the menu must not offer a delegation it would not perform.
+ */
+function filterAgents(
+ agents: readonly AutocompleteAgent[],
+ query: string,
+ entries: readonly FsIndexEntry[],
+): AutocompleteItem[] {
+ const shadowed = new Set(entries.map((entry) => entry.path));
+ const matched: Array<{ agent: AutocompleteAgent; match: FuzzyMatch }> = [];
+ for (const agent of agents) {
+ if (shadowed.has(agent.name)) continue;
+ const byName = fuzzyMatchCommand(query, agent.name);
+ const byDescription = byName ? null : fuzzyMatchCommand(query, agent.description);
+ const match = byName ?? (byDescription ? { score: Math.max(0, byDescription.score - 20), ranges: [] } : null);
+ if (match) matched.push({ agent, match });
+ }
+ matched.sort((a, b) =>
+ compareMatches(
+ { score: a.match.score, text: a.agent.name },
+ { score: b.match.score, text: b.agent.name },
+ ),
+ );
+ return matched.map(({ agent, match }) => ({ kind: "agent", agent, match }));
+}
+
function filterFiles(entries: FsIndexEntry[], query: string): AutocompleteItem[] {
const matched: Array<{ entry: FsIndexEntry; match: FuzzyMatch }> = [];
// Rows found by the main-process search may repeat index entries.
@@ -177,11 +211,14 @@ export function useComposerAutocomplete({
cursor,
composing,
enabled,
+ agentsEnabled = false,
}: {
value: string;
cursor: number;
composing: boolean;
enabled: boolean;
+ /** Offer subagents in the `@` menu; only Agent mode may delegate (ADR 0346). */
+ agentsEnabled?: boolean;
}) {
const sessionId = useAppStore((s) => s.activeSessionId);
const remoteSession = useAppStore(activeSessionHasRemoteWorkspace);
@@ -198,6 +235,7 @@ export function useComposerAutocomplete({
entries: FsIndexEntry[];
truncated: boolean;
} | null>(null);
+ const [agents, setAgents] = useState<AutocompleteAgent[] | null>(null);
const [highlight, setHighlight] = useState(0);
const [dismissedKey, setDismissedKey] = useState<string | null>(null);
const frozenRef = useRef<ComposerTrigger | null>(null);
@@ -275,6 +313,35 @@ export function useComposerAutocomplete({
};
}, [trigger?.mode, dismissed, workspaceKey, hasWorkspace, sessionId]);
+ // The Agents group reads the same catalog `Task` is built from. A failed
+ // read leaves the group empty; the file rows still answer.
+ const wantAgents = agentsEnabled && trigger?.mode === "file" && !dismissed;
+ useEffect(() => {
+ if (!wantAgents) return;
+ if (
+ agentsCache &&
+ agentsCache.key === workspaceKey &&
+ Date.now() - agentsCache.at < SOURCE_TTL_MS
+ ) {
+ setAgents(agentsCache.agents);
+ return;
+ }
+ let cancelled = false;
+ void api
+ .subagentCatalog()
+ .then((catalog) => {
+ const next = catalog.subagents.map(({ name, description }) => ({ name, description }));
+ agentsCache = { key: workspaceKey, at: Date.now(), agents: next };
+ if (!cancelled) setAgents(next);
+ })
+ .catch(() => {
+ if (!cancelled) setAgents([]);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [wantAgents, workspaceKey]);
+
// A truncated index keeps only the shallowest entries, so a deep file of a
// large tree matches nothing in it. Once typing pauses, the query also
// searches the main process's full listing (D669); the answer belongs to
@@ -331,11 +398,16 @@ export function useComposerAutocomplete({
: [];
}
if (!files) return [];
- return filterFiles(
- foundHere ? [...foundHere.entries, ...files.entries] : files.entries,
- trigger.query,
- );
- }, [trigger, dismissed, commands, remoteSession, files, foundHere]);
+ const agentItems =
+ agentsEnabled && agents ? filterAgents(agents, trigger.query, files.entries) : [];
+ return [
+ ...agentItems,
+ ...filterFiles(
+ foundHere ? [...foundHere.entries, ...files.entries] : files.entries,
+ trigger.query,
+ ),
+ ];
+ }, [trigger, dismissed, commands, remoteSession, files, foundHere, agentsEnabled, agents]);
// New query or mode restarts keyboard navigation at the top hit.
const itemsKey = trigger ? `${trigger.mode}:${trigger.query}` : "";
@@ -360,11 +432,18 @@ export function useComposerAutocomplete({
value: string;
cursor: number;
fileReference?: { path: string; name: string };
+ agentReference?: { name: string };
}
| null => {
if (!trigger) return null;
const item = items[index];
if (!item) return null;
+ if (item.kind === "agent") {
+ return {
+ ...applyCompletion(value, trigger, ""),
+ agentReference: { name: item.agent.name },
+ };
+ }
if (item.kind === "path" && item.entry.kind === "file") {
return {
...applyCompletion(value, trigger, ""),
diff --git a/apps/desktop/src/lib/composer-draft-cache.ts b/apps/desktop/src/lib/composer-draft-cache.ts
index 8362b10ca..a6ea2df11 100644
--- a/apps/desktop/src/lib/composer-draft-cache.ts
+++ b/apps/desktop/src/lib/composer-draft-cache.ts
@@ -24,7 +24,7 @@ export type ComposerDraftFileInput = {
sessionId?: string;
path: string;
name: string;
- kind?: "image" | "file" | "session" | "directory";
+ kind?: "image" | "file" | "session" | "directory" | "agent";
mimeType?: string;
token?: string;
plugin?: ComposerPluginPart;
diff --git a/apps/desktop/src/lib/composer-smart-stop.ts b/apps/desktop/src/lib/composer-smart-stop.ts
index 24d5becfc..f90bbcaaa 100644
--- a/apps/desktop/src/lib/composer-smart-stop.ts
+++ b/apps/desktop/src/lib/composer-smart-stop.ts
@@ -25,7 +25,7 @@ export type ComposerPluginPart =
export type ComposerDraftFileReference = {
path: string;
name: string;
- kind?: "image" | "file" | "session" | "directory";
+ kind?: "image" | "file" | "session" | "directory" | "agent";
mimeType?: string;
/** Visible inline token for a generated large-text paste reference. */
token?: string;
@@ -44,6 +44,8 @@ export type ComposerPrefill = ComposerDraftSnapshot & {
type AbortMessage = {
role: string;
content: string;
+ /** The typed form of a rewritten prompt (template, Skill, `@agent`). */
+ command?: string;
thinking?: string;
steering?: boolean;
};
@@ -86,8 +88,13 @@ export function resolveComposerSmartStop<T extends AbortMessage>(
return {
kind: "restore",
kept: lastUserIndex >= 0 ? messages.slice(0, lastUserIndex) : [...messages],
+ // Without a local snapshot the row is the source; its `content` is what
+ // the model was given, so the typed `command` is what the user gets back.
draft: submitted?.draft ?? {
- text: lastUserIndex >= 0 ? messages[lastUserIndex].content : "",
+ text:
+ lastUserIndex >= 0
+ ? (messages[lastUserIndex].command ?? messages[lastUserIndex].content)
+ : "",
fileReferences: [],
},
};
diff --git a/apps/desktop/src/lib/session-transcript.ts b/apps/desktop/src/lib/session-transcript.ts
index a13984106..c893d30bf 100644
--- a/apps/desktop/src/lib/session-transcript.ts
+++ b/apps/desktop/src/lib/session-transcript.ts
@@ -11,7 +11,7 @@ import {
type OptimisticFileReference = {
path: string;
name: string;
- kind?: "image" | "file" | "session" | "directory";
+ kind?: "image" | "file" | "session" | "directory" | "agent";
mimeType?: string;
/** Large-text paste tokens travel inline in the text, not as attachments. */
token?: string;
@@ -37,7 +37,7 @@ export function optimisticUserMessage(
// an image chip is one: it also records where its path sits, so the row shows
// the image in place before the durable echo arrives (D288).
const rendered = fileReferences.flatMap((reference) => {
- if (reference.kind === "directory") return [];
+ if (reference.kind === "directory" || reference.kind === "agent") return [];
const kind =
reference.kind ??
(IMAGE_PATH_PATTERN.test(reference.path) ? ("image" as const) : ("file" as const));
diff --git a/apps/desktop/src/stores/helpers/store-helpers.ts b/apps/desktop/src/stores/helpers/store-helpers.ts
index b9dc108ee..7feefee74 100644
--- a/apps/desktop/src/stores/helpers/store-helpers.ts
+++ b/apps/desktop/src/stores/helpers/store-helpers.ts
@@ -27,7 +27,8 @@ export function promptAttachmentsFromDraft(
return references.flatMap((reference) => {
// A session link is prompt text: main resolves it into a conversation
// reference, and it never travels as a structured attachment.
- if (reference.kind === "session" || reference.kind === "directory") return [];
+ // An `@agent` chip is prompt text too (ADR 0346).
+ if (reference.kind === "session" || reference.kind === "directory" || reference.kind === "agent") return [];
const kind =
reference.kind ??
(/\.(avif|bmp|gif|heic|jpe?g|png|tiff?|webp)$/i.test(reference.path)
diff --git a/apps/desktop/test/composer-agent-mention-user-path.test.mjs b/apps/desktop/test/composer-agent-mention-user-path.test.mjs
new file mode 100644
index 000000000..29077cad5
--- /dev/null
+++ b/apps/desktop/test/composer-agent-mention-user-path.test.mjs
@@ -0,0 +1,217 @@
+/**
+ * ADR 0346: `@agent` in the composer. Drives the real draft, completions,
+ * input and menu against a stubbed delegation catalog and file index, then
+ * checks the accepted chip serializes to a token the send-time resolver reads.
+ */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { repositoryRoot, resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";
+
+const root = repositoryRoot();
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+
+const fixture = String.raw`
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { initReactI18next } from "react-i18next";
+import { catalogs, flattenCatalog } from "@pi-desktop/i18n";
+import { findAgentMentions, serializeComposerFileReferences } from "@pi-desktop/shared";
+import { useComposerDraft } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerDraft";
+import { useComposerCompletions } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerCompletions";
+import { ComposerInput } from "../../apps/desktop/src/features/chat/composer/ComposerInput";
+import { ComposerAutocomplete } from "../../apps/desktop/src/components/ComposerAutocomplete";
+import { setEditorCaret } from "../../apps/desktop/src/features/chat/composer/editor";
+import { api } from "../../apps/desktop/src/lib/api";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+
+let catalogReads = 0;
+api.fsIndex = async () => ({ entries: [{ path: "README.md", kind: "file" }, { path: "fixer", kind: "file" }], truncated: false });
+api.subagentCatalog = async () => {
+ catalogReads += 1;
+ return {
+ subagents: [
+ { name: "explorer", description: "Fast codebase search" },
+ { name: "fixer", description: "Implements a change" },
+ ],
+ builtins: [], diagnostics: [], projectPath: "/repo",
+ };
+};
+
+await i18n.use(initReactI18next).init({ lng: "en", keySeparator: false,
+ resources: { en: { translation: flattenCatalog(catalogs.en) } },
+ interpolation: { escapeValue: false } });
+useAppStore.setState({ activeSessionId: "s1", workspace: { path: "/repo", name: "repo" } });
+
+const noop = () => {};
+let draft;
+function Fixture({ agentsEnabled }) {
+ draft = useComposerDraft({
+ variant: "docked", activeSessionId: "s1", workspacePath: "/repo",
+ sessions: [{ id: "s1" }], composerPrefill: null, clearComposerPrefill: noop,
+ t: (key) => key, invalidateComposerTransforms: noop, inputBlocked: false,
+ });
+ const completions = useComposerCompletions({
+ value: draft.value, cursor: draft.cursor, composing: draft.composing, enabled: true,
+ agentsEnabled,
+ referenceSessionId: "s1", fileReferencesRef: draft.fileReferencesRef,
+ applyEditorDraft: draft.applyEditorDraft, handleInput: draft.handleInput,
+ invalidateComposerTransforms: noop,
+ });
+ return <>
+ <ComposerInput inputRef={draft.ref} value={draft.value} placeholderText="" placeholderKey="fixture"
+ inputBlocked={false} pasting={false} enterToSend={false} runActive={false}
+ composerAc={completions.ac} onPaste={noop} onAcceptCompletion={completions.acceptCompletion}
+ onSubmit={noop} onInsertNewline={noop} onHistoryNavigate={() => false}
+ onInput={(source, caret, composing) => completions.handleInput(source, caret, composing)}
+ onCompositionStart={() => draft.setComposing(true)}
+ onCompositionEnd={() => draft.setComposing(false)}
+ onSettledInput={() => draft.setComposing(false)} onFocus={noop} onBlur={noop} />
+ <ComposerAutocomplete anchorRef={draft.ref} ac={completions.ac} onAccept={completions.acceptCompletion} />
+ </>;
+}
+
+const rootNode = createRoot(document.getElementById("root"));
+const settle = async () => {
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ await new Promise((resolve) => setTimeout(resolve, 40));
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+};
+const editor = () => document.querySelector(".composer-input");
+const options = () => [...document.querySelectorAll('[role="option"]')].map((row) => row.getAttribute("aria-label"));
+const headings = () => [...document.querySelectorAll(".composer-model-group-label")].map((row) => row.textContent);
+function check(condition, message) {
+ if (!condition) throw new Error(message + " options=" + JSON.stringify(options()) + " headings=" + JSON.stringify(headings()));
+}
+async function until(predicate, message) {
+ for (let n = 0; n < 300; n += 1) {
+ if (predicate()) return;
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ check(false, message);
+}
+async function type(text) {
+ const el = editor();
+ el.textContent = text;
+ setEditorCaret(el, text.length);
+ await settle();
+ el.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: text }));
+ await settle();
+}
+
+window.agentMentionProbe = async () => {
+ // Plan / Goal: no Agents group, the file menu is unchanged.
+ flushSync(() => rootNode.render(<Fixture agentsEnabled={false} />));
+ await settle();
+ editor().focus();
+ await type("@");
+ await until(() => options().includes("README.md"), "the @ menu did not open");
+ check(!options().includes("@explorer"), "Plan mode must not offer agents");
+ check(headings().length === 0, "a plain file list carries no headings");
+ check(catalogReads === 0, "Plan mode must not read the delegation catalog");
+
+ // Agent mode: an Agents group above the files; a root file shadows its agent.
+ flushSync(() => rootNode.render(<Fixture agentsEnabled />));
+ await type("");
+ await type("@");
+ await until(() => options().includes("@explorer"), "Agent mode did not offer the explorer");
+ check(JSON.stringify(headings()) === JSON.stringify(["Agents", "Files"]), "Agents and Files headings");
+ check(!options().includes("@fixer"), "a root file named fixer must hide that agent");
+ check(options().indexOf("@explorer") < options().indexOf("README.md"), "agents list above files");
+
+ // Mid-sentence accept → one atomic chip that serializes to a resolvable token.
+ await type("look @expl");
+ await until(() => options()[0] === "@explorer", "the query did not rank the explorer first");
+ editor().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ await settle();
+ const chips = [...editor().querySelectorAll(".composer-chip[data-agent]")];
+ check(chips.length === 1 && chips[0].dataset.agent === "explorer", "accepting did not place one agent chip");
+ check(chips[0].textContent.includes("explorer"), "the chip must show the agent name");
+ const references = draft.fileReferencesRef.current;
+ check(references.length === 1 && references[0].kind === "agent", "the chip must be an agent reference");
+ const text = draft.value + "where the retry policy lives";
+ const serialized = serializeComposerFileReferences(text, references);
+ check(findAgentMentions(serialized, new Set(["explorer"])).length === 1, "the serialized prompt lost the mention");
+
+ flushSync(() => rootNode.unmount());
+ return { passed: true, serialized };
+};
+`;
+
+test("the @ menu offers subagents in Agent mode and accepts one as an atomic chip", {
+ skip: process.platform === "linux" && !process.env.DISPLAY ? "Electron requires a display" : false,
+}, async () => {
+ const temp = await mkdtemp(join(tmpdir(), "pi-agent-mention-ui-"));
+ try {
+ await build({
+ stdin: { contents: fixture, resolveDir: join(root, "scripts/e2e"), loader: "tsx" },
+ outfile: join(temp, "renderer.js"),
+ bundle: true,
+ platform: "browser",
+ format: "esm",
+ jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"' },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src"),
+ "@pi-desktop/shared": join(root, "packages/shared/src"),
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ i18next: join(root, "apps/desktop/node_modules/i18next"),
+ "react-i18next": join(root, "apps/desktop/node_modules/react-i18next"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ await writeFile(join(temp, "index.html"),
+ '<!doctype html><meta charset="utf-8"><div id="root"></div><script type="module" src="renderer.js"></script>');
+ await writeFile(join(temp, "main.cjs"), `
+const { app, BrowserWindow } = require("electron");
+const path = require("node:path");
+app.setPath("userData", path.join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ // Hidden Windows windows need offscreen painting to advance animation frames.
+ const win = new BrowserWindow({ show: false, width: 900, height: 700,
+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false,
+ offscreen: process.platform === "win32" } });
+ win.webContents.on("console-message", (event) => console.error(event.message));
+ try {
+ await win.loadFile(path.join(__dirname, "index.html"));
+ console.log("AGENT_MENTION_PROBE " + JSON.stringify(await win.webContents.executeJavaScript("window.agentMentionProbe()")));
+ app.exit(0);
+ } catch (error) { console.error(error?.stack ?? error); app.exit(1); }
+});`);
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], {
+ env,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) {
+ stream.setEncoding("utf8");
+ stream.on("data", (chunk) => { output += chunk; });
+ }
+ const timer = setTimeout(() => child.kill("SIGKILL"), 60_000);
+ let code;
+ try {
+ code = await new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+ } finally {
+ clearTimeout(timer);
+ }
+ assert.equal(code, 0, output.slice(-6000));
+ const line = output.split(/\r?\n/).find((item) => item.startsWith("AGENT_MENTION_PROBE "));
+ assert.ok(line, output.slice(-6000));
+ const result = JSON.parse(line.slice("AGENT_MENTION_PROBE ".length));
+ assert.equal(result.passed, true);
+ assert.equal(result.serialized, "look @explorer where the retry policy lives");
+ } finally {
+ await rm(temp, { recursive: true, force: true });
+ }
+});
diff --git a/apps/desktop/test/composer-agent-mention.test.mjs b/apps/desktop/test/composer-agent-mention.test.mjs
new file mode 100644
index 000000000..0111cc8af
--- /dev/null
+++ b/apps/desktop/test/composer-agent-mention.test.mjs
@@ -0,0 +1,119 @@
+import assert from "node:assert/strict";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { register } from "node:module";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+
+const { registerAgentIpc } = await import("../electron/main/ipc/agent-ipc.ts");
+const { IPC, serializeInlineComposerFileReferences } = await import("@pi-desktop/shared");
+
+/** Drive the real prompt channel; only host, sidecar and launch are stubbed. */
+function promptFixture({ mode = "agent", projectPath = null, skills = [], templates = [] } = {}) {
+ const handlers = new Map();
+ const calls = [];
+ const sidecarCalls = [];
+ const host = { async call(method, params) {
+ calls.push({ method, params });
+ if (method === "settings.get") return {};
+ if (method === "session.get") return { session: { id: "s", projectPath, messages: [] } };
+ if (method === "session.beginTurn") return { turnId: "turn-1" };
+ if (method === "session.appendMessage") return {};
+ assert.fail(`unexpected RPC ${method}`);
+ } };
+ registerAgentIpc({
+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
+ getHost: () => host,
+ getSidecar: () => ({ setProjectInstructionRoot() {}, async call(method, params) {
+ sidecarCalls.push({ method, params });
+ return { accepted: true, turnId: "turn-1" };
+ } }),
+ getAgentHostBridge: () => null,
+ isTurnDispatchable: () => true,
+ logger: { app() {} }, agentExtensions: {}, cancelSessionTools() {},
+ persistenceOutbox: {}, dataDir: "/unused-for-no-attachments",
+ activeTurns: new Map(), activeTurnUsages: new Map(), approvedExecutionIdsBySession: new Map(), claimedExecutionSessions: new Map(),
+ recordTurnStart() {},
+ resolveAgentRuntimeLaunch: async () => ({
+ projectPath, providerId: "provider", modelId: "model",
+ sidecarParams: {
+ sessionId: "s", mode,
+ subagents: [{ name: "explorer" }, { name: "code-reviewer" }],
+ provider: { modelConfig: { input: ["text"] } },
+ },
+ }),
+ acquireSessionOperation: async () => () => {},
+ finishTurn: async () => { assert.fail("no turn failure expected"); },
+ emitAgentEvent() {}, setNotificationViewingSessionId() {},
+ optionalWorkspaceRoot: async () => projectPath,
+ composerCommandService: { buildComposerCommands: async () => skills },
+ loadComposerTemplatesCached: async () => templates,
+ });
+ return {
+ async prompt(content) {
+ await handlers.get(IPC.invoke.agentPrompt)({ sessionId: "s", content });
+ return calls.find((call) => call.method === "session.appendMessage").params.message;
+ },
+ sidecarCalls,
+ };
+}
+
+test("an accepted agent chip mid-sentence becomes an explicit Task instruction", async () => {
+ // The composer serializes the chip; the leading space is what lets the
+ // send-time resolver see `@explorer` after "look".
+ const content = serializeInlineComposerFileReferences("look\ue020where the retry policy lives", [
+ { path: "explorer", kind: "agent", token: "\ue020" },
+ ]);
+ const fixture = promptFixture();
+ const row = await fixture.prompt(content);
+ assert.equal(row.command, "look @explorer where the retry policy lives");
+ assert.deepEqual(row.agentMentions, [{ start: 5, end: 14, name: "explorer" }]);
+ assert.match(row.content, /^The user explicitly delegated.*`Task`.*"explorer"/);
+ assert.match(row.content, /look @explorer where the retry policy lives$/);
+ assert.equal(fixture.sidecarCalls.at(-1).params.content, row.content);
+});
+
+test("Plan mode, unknown names and e-mail-like text stay literal", async () => {
+ for (const [mode, content] of [
+ ["plan", "@explorer find it"],
+ ["goal", "@explorer find it"],
+ ["agent", "@nobody find it"],
+ ["agent", "mail me at user@explorer"],
+ ]) {
+ const row = await promptFixture({ mode }).prompt(content);
+ assert.equal(row.content, content, `${mode}: ${content}`);
+ assert.equal(row.command, undefined);
+ assert.equal(row.agentMentions, undefined);
+ }
+});
+
+test("a workspace file of the same name wins over the agent", async () => {
+ const root = await mkdtemp(join(tmpdir(), "agent-mention-"));
+ try {
+ await writeFile(join(root, "explorer"), "a real file");
+ const row = await promptFixture({ projectPath: root }).prompt("@explorer @code-reviewer check");
+ assert.deepEqual(row.agentMentions, [{ start: 10, end: 24, name: "code-reviewer" }]);
+ assert.doesNotMatch(row.content.split("\n\n")[0], /"explorer"/);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("Skill and agent mentions combine; a leading template keeps its expansion", async () => {
+ const skills = [{ name: "skill:review", kind: "skill", skillId: "review" }];
+ const row = await promptFixture({ skills }).prompt("/skill:review @code-reviewer check this");
+ assert.deepEqual(row.skillMentions, [{ start: 0, end: 13, id: "review" }]);
+ assert.deepEqual(row.agentMentions, [{ start: 14, end: 28, name: "code-reviewer" }]);
+ const [skill, agent, body] = row.content.split("\n\n");
+ assert.match(skill, /`Skill`.*"review"/);
+ assert.match(agent, /`Task`.*"code-reviewer"/);
+ assert.equal(body, "@code-reviewer check this");
+
+ const templated = await promptFixture({
+ skills: [{ name: "fix", kind: "template" }],
+ templates: [{ name: "fix", body: "Fix: $ARGUMENTS", description: "" }],
+ }).prompt("/fix @explorer it");
+ assert.equal(templated.agentMentions, undefined);
+ assert.doesNotMatch(templated.content, /`Task`/);
+});
diff --git a/apps/desktop/test/composer-file-reference-display.test.mjs b/apps/desktop/test/composer-file-reference-display.test.mjs
index 9540a364a..f9ced8813 100644
--- a/apps/desktop/test/composer-file-reference-display.test.mjs
+++ b/apps/desktop/test/composer-file-reference-display.test.mjs
@@ -77,7 +77,10 @@ test("composer renders atomic inline chips and serializes paths on send", () =>
assert.match(composer, /composer-chip-name/);
assert.match(composer, /nameSpan\.textContent = reference\.name/);
// A file chip's title is its path; a plugin mark's is its plugin.
- assert.match(composer, /isPluginMark\(reference\) \? \(reference\.plugin\?\.pluginId \?\? ""\) : reference\.path/);
+ assert.match(
+ composer,
+ /isPluginMark\(reference\)\s*\? \(reference\.plugin\?\.pluginId \?\? ""\)\s*: reference\.kind === "agent"\s*\? `@\$\{reference\.path\}`\s*: reference\.path/,
+ );
assert.match(composer, /chip\.title = origin/);
assert.match(
composer,
diff --git a/apps/desktop/test/composer-smart-stop.test.mjs b/apps/desktop/test/composer-smart-stop.test.mjs
index a961ac3f1..80485df5c 100644
--- a/apps/desktop/test/composer-smart-stop.test.mjs
+++ b/apps/desktop/test/composer-smart-stop.test.mjs
@@ -60,3 +60,17 @@ test("legacy sends without a snapshot keep the text-only fallback", () => {
draft: { text: "plain prompt", fileReferences: [] },
});
});
+
+test("a stop without a local snapshot restores the typed form of a rewritten prompt", () => {
+ // An `@agent` (or template / Skill) turn stores the model instruction in
+ // `content`; the composer must get back what the user typed.
+ const sent = {
+ role: "user",
+ content: "The user explicitly delegated this request with @mentions. Call the `Task` tool…\n\n@explorer find it",
+ command: "@explorer find it",
+ };
+ const result = resolveComposerSmartStop([sent]);
+ assert.equal(result.kind, "restore");
+ assert.equal(result.draft.text, "@explorer find it");
+ assert.equal(resolveComposerSmartStop([message("user", "plain")]).draft.text, "plain");
+});
diff --git a/apps/desktop/test/plugin-skills.test.mjs b/apps/desktop/test/plugin-skills.test.mjs
index c97709212..1fa672d0b 100644
--- a/apps/desktop/test/plugin-skills.test.mjs
+++ b/apps/desktop/test/plugin-skills.test.mjs
@@ -94,7 +94,9 @@ test("the composer lists active skills last and routes slash skills to the Skill
/\.\.\.extensionCommands,\s*\.\.\.mcpCommands,\s*\.\.\.skillCommands,/,
);
assert.match(mainSrc, /findSkillMentions\(req\.content, activeSkills\)/);
- assert.match(mainSrc, /Call the \\`Skill\\` tool with each of these ids/);
+ // The Skill instruction text lives in shared `composeMentionPrompt`
+ // (ADR 0346); its exact wording is pinned in composer-trigger.test.ts.
+ assert.match(mainSrc, /composeMentionPrompt\(req\.content, mentions, foundAgents\)/);
assert.match(composerAutocompleteSrc, /item\.command\.kind === "skill"/);
});
diff --git a/apps/desktop/test/session-message-presentation.test.mjs b/apps/desktop/test/session-message-presentation.test.mjs
index 71b088156..ccfe7ef3a 100644
--- a/apps/desktop/test/session-message-presentation.test.mjs
+++ b/apps/desktop/test/session-message-presentation.test.mjs
@@ -170,3 +170,24 @@ test("an image without a recorded position still follows the body", () => {
const image = html.indexOf('data-image="b.png"');
assert.ok(text >= 0 && image > text, html);
});
+
+test("an @agent turn shows the typed text with the named delegate chipped (ADR 0346)", () => {
+ const html = render({
+ ...userMessage,
+ content: "The user explicitly delegated this request with @mentions. Call the `Task` tool…",
+ command: "look @explorer where /skill:review runs",
+ agentMentions: [{ start: 5, end: 14, name: "explorer" }],
+ skillMentions: [{ start: 21, end: 34, id: "review" }],
+ });
+ assert.match(html, /look <code class="chat-command-chip" title="@explorer" data-agent-mention="">@explorer<\/code> where <code class="chat-command-chip" title="review">\/skill:review<\/code> runs/);
+ assert.doesNotMatch(html, /Call the `Task` tool/);
+
+ // Offsets that do not point at an @token fall back to plain text.
+ const forged = render({
+ ...userMessage,
+ command: "look explorer here",
+ agentMentions: [{ start: 5, end: 13, name: "explorer" }],
+ });
+ assert.doesNotMatch(forged, /chat-command-chip/);
+ assert.match(forged, /look explorer here/);
+});
diff --git a/crates/host-core/src/plugin_sessions.rs b/crates/host-core/src/plugin_sessions.rs
index 00d8e1ebe..741584e2c 100644
--- a/crates/host-core/src/plugin_sessions.rs
+++ b/crates/host-core/src/plugin_sessions.rs
@@ -281,6 +281,7 @@ fn parse_message(
content: input.content.clone(),
command: None,
skill_mentions: None,
+ agent_mentions: None,
attachments: None,
voice_origin: None,
steering: None,
diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rs
index 834a6d483..86b684154 100644
--- a/crates/host-core/src/sessions.rs
+++ b/crates/host-core/src/sessions.rs
@@ -204,6 +204,9 @@ pub struct UiMessage {
/// 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>>,
+ /// Validated `@agent` tokens in `command`, with UTF-16 offsets for the renderer.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub agent_mentions: Option<Vec<AgentMention>>,
/// Host-authenticated agent-to-agent origin, never a human authorization.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_message: Option<Value>,
@@ -292,6 +295,14 @@ pub struct SkillMention {
pub id: String,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentMention {
+ pub start: usize,
+ pub end: usize,
+ pub name: String,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionDetail {
@@ -407,6 +418,9 @@ pub(crate) fn ui_to_record(message: &UiMessage) -> (MessageRecord, Option<String
if let Some(mentions) = &message.skill_mentions {
meta_obj.insert("skillMentions".into(), json!(mentions));
}
+ if let Some(mentions) = &message.agent_mentions {
+ meta_obj.insert("agentMentions".into(), json!(mentions));
+ }
if let Some(origin) = &message.session_message {
meta_obj.insert("sessionMessage".into(), origin.clone());
}
@@ -565,6 +579,9 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {
let skill_mentions = meta
.get("skillMentions")
.and_then(|value| serde_json::from_value(value.clone()).ok());
+ let agent_mentions: Option<Vec<AgentMention>> = meta
+ .get("agentMentions")
+ .and_then(|value| serde_json::from_value(value.clone()).ok());
let session_message = meta.get("sessionMessage").cloned();
let voice_origin = meta.get("voiceOrigin").cloned();
let steering = meta.get("steering").and_then(Value::as_bool);
@@ -698,6 +715,7 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {
content: text,
command: command.clone(),
skill_mentions: skill_mentions.clone(),
+ agent_mentions: agent_mentions.clone(),
session_message,
voice_origin: voice_origin.clone(),
attachments: None,
@@ -753,6 +771,7 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {
content,
command,
skill_mentions,
+ agent_mentions,
session_message,
voice_origin,
attachments,
@@ -4428,6 +4447,28 @@ mod tests {
Database::open(&dir.join("test.sqlite")).unwrap()
}
+ #[test]
+ fn agent_mentions_round_trip_through_record_meta() {
+ let mut message = user_msg("u1", "Call the `Task` tool", "2026-01-01T00:00:00Z");
+ message.command = Some("look @explorer here".into());
+ message.agent_mentions = Some(vec![AgentMention {
+ start: 5,
+ end: 14,
+ name: "explorer".into(),
+ }]);
+ let (record, _) = ui_to_record(&message);
+ let restored = record_to_ui(record);
+ let mentions = restored.agent_mentions.expect("agent mentions survive");
+ assert_eq!(mentions.len(), 1);
+ assert_eq!((mentions[0].start, mentions[0].end), (5, 14));
+ assert_eq!(mentions[0].name, "explorer");
+ assert_eq!(restored.command.as_deref(), Some("look @explorer here"));
+
+ // A row written before the field existed reads back without it.
+ let (legacy, _) = ui_to_record(&user_msg("u2", "plain", "2026-01-01T00:00:00Z"));
+ assert!(record_to_ui(legacy).agent_mentions.is_none());
+ }
+
fn user_msg(id: &str, content: &str, ts: &str) -> UiMessage {
UiMessage {
id: id.into(),
@@ -4435,6 +4476,7 @@ mod tests {
content: content.into(),
command: None,
skill_mentions: None,
+ agent_mentions: None,
attachments: None,
voice_origin: None,
steering: None,
@@ -5399,6 +5441,7 @@ mod tests {
content: "ok".into(),
command: None,
skill_mentions: None,
+ agent_mentions: None,
attachments: None,
voice_origin: None,
steering: None,
@@ -6194,6 +6237,7 @@ mod tests {
content: "final answer".into(),
command: None,
skill_mentions: None,
+ agent_mentions: None,
attachments: None,
voice_origin: None,
steering: None,
@@ -6342,6 +6386,7 @@ mod tests {
content: "answer with sources".into(),
command: None,
skill_mentions: None,
+ agent_mentions: None,
attachments: None,
voice_origin: None,
steering: None,
diff --git a/docs/adr/0346-composer-agent-mentions.md b/docs/adr/0346-composer-agent-mentions.md
new file mode 100644
index 000000000..e5f4b4849
--- /dev/null
+++ b/docs/adr/0346-composer-agent-mentions.md
@@ -0,0 +1,68 @@
+# ADR 0346: `@agent` mentions route a turn to a named subagent
+
+- Status: Accepted
+- Date: 2026-11-06
+- Deciders: PI-Desktop core
+- Related: [ADR 0024](0024-composer-commands-and-file-references.md) ·
+ [ADR 0062](0062-bounded-subagents-behind-a-task-tool.md) ·
+ [04-ux/08-component-spec §11.8](../spec/04-ux/08-component-spec.md) ·
+ issue #986 · prior design in PR #1101 (@f4ct0r)
+
+## Context
+
+A subagent was reachable only when the model decided to call `Task`. Work the
+user already knows is separable — "ask the explorer where the retry policy
+lives" — had no entry point. Everything downstream of delegation (Task cards,
+topology, the permission queue, `TaskWait`, the context budget) keys off "this
+turn contains a `Task` call" and does not care who initiated it, so the
+missing piece is an entry point, not a second execution path.
+
+`/skill:<id>` already solved the same shape: the composer offers a catalog,
+main rewrites the typed draft into an explicit tool instruction at send time,
+and the user's own words stay in the transcript as `command` with chips.
+
+## Decision
+
+1. **Trigger.** `@` already means "reference an entity", so the `@` menu gains
+ an **Agents** group above the file rows (each group with its own heading),
+ listing the same catalog `Task` is built from (`subagentCatalog`). Accepting
+ a row inserts an atomic inline chip, the same sentinel-backed chip a file
+ gets; it serializes to `@name` only at send time, with a space on either
+ side when a neighbor is not whitespace, because the send-time resolver reads
+ an `@token` only at a word boundary (that is what keeps `user@host` text).
+2. **Resolution at send.** Main resolves `@name` tokens against the launch's
+ subagent catalog. A token is a delegation only when
+ - the turn runs in **Agent mode** — the only mode that may execute `Task`
+ (ADR 0062 §4); Plan and Goal omit the group and leave a hand-typed
+ mention as literal text;
+ - it names a catalog subagent; and
+ - the local workspace root holds **no file or folder of that name** — a
+ project that really has an `explorer` file keeps the file. The menu hides
+ such an agent for the same reason.
+3. **Prompt.** The model receives a short instruction to call `Task` with the
+ named agents, followed by the unchanged draft (the `@name` tokens stay so
+ each brief can be written from the part addressed to it). Skill and agent
+ mentions combine: Skills load first, then delegation. A leading template or
+ app command keeps its existing behavior and mentions are not rewritten.
+4. **Persistence.** The user row stores `command` (typed text) and
+ `agentMentions: [{ start, end, name }]` (UTF-16 offsets) in record meta
+ beside `skillMentions`. No SQL migration; old rows read back without the
+ field and render as before; older builds ignore it.
+5. **Transcript.** The typed form renders with each validated mention as a
+ chip and the surrounding text as text. Offsets that do not point at an
+ `@token` fall back to plain text.
+6. **Smart stop.** Without a local draft snapshot, Stop restores a row's
+ `command` instead of its `content`, so the composer never receives the
+ model instruction. This also corrects the same pre-existing gap for
+ templates and Skills.
+
+## Consequences
+
+- This is a strong prompt, not an enforced dispatch — the same trade-off
+ `/skill` accepts. Enforcing it would need a public runtime entry point for a
+ private tool, a new RPC and a synthetic parent row, and would hand the parent
+ a report it never asked for. Out of scope.
+- The `@` menu reads the delegation catalog with the same short TTL as the
+ file index; a failed read only empties the Agents group.
+- No IPC, Plugin SDK or schema-version change. One optional field is added to
+ the persisted user message.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index a0e800290..b4664fab6 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -408,3 +408,4 @@ Each ADR includes:
| 0343 | [The plugin launcher enumerates and opens local applications](0343-plugin-launcher-local-apps.md) | Accepted (issue #2085) |
| 0344 | [Computer use grants the whole desktop automatically, and Stop is the boundary](0344-computer-use-whole-desktop-grant.md) | Accepted (D682; amends ADR 0342 §4 and §6) |
| 0345 | [One settings destination owns one subject](0345-one-settings-destination-one-subject.md) | Accepted (D684; amends D143, D166, D678) |
+| 0346 | [`@agent` mentions route a turn to a named subagent](0346-composer-agent-mentions.md) | Accepted (issue #986; extends 0024 / 0062) |
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index ccd45782d..d719f966e 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -3565,7 +3565,7 @@ See [Live Voice](../03-runtime/live-voice.md) and
[Live Work](../03-runtime/live-work-session.md) for the unchanged ownership,
permission, and call-scoped work contracts.
-### 11.8 Slash commands, @ file references, and clipboard files (D123–D125, D197, D209, D262, D362, D397, ADR 0024, ADR 0059, ADR 0070, ADR 0131, ADR 0221, ADR 0222)
+### 11.8 Slash commands, @ file references, and clipboard files (D123–D125, D197, D209, D262, D362, D397, ADR 0024, ADR 0059, ADR 0070, ADR 0131, ADR 0221, ADR 0222, ADR 0346)
The composer owns an inline autocomplete menu — one component serving two
modes. Focus never leaves the textarea (D125).
@@ -3649,6 +3649,20 @@ Anatomy:
may be incomplete — the bare `@`, until the first search for the token
answers, and when a search is itself capped or unavailable, as in remote
sessions; without a workspace the menu shows an "open a project" empty state.
+- `@agent` mentions (ADR 0346): in Agent mode the `@` menu lists an
+ **Agents** group above the files — the catalog `Task` is built from, each
+ row `@name` + description with the bot glyph — and the file rows gain a
+ **Files** heading only beside it. Plan and Goal omit the group. An agent
+ whose name matches a workspace-root entry is hidden, because that token
+ belongs to the file. Accepting an agent inserts an atomic inline chip that
+ serializes to `@name`, with a separating space before and after when a
+ neighbor is not whitespace. At send, main rewrites a draft whose `@name`
+ tokens name catalog subagents (Agent mode, no same-named root entry) into an
+ explicit `Task` instruction followed by the unchanged draft; the typed text
+ persists as `command` with `agentMentions` offsets, and the transcript chips
+ each mention. Skill and agent mentions combine; a leading template or app
+ command is not rewritten. Stop restores the typed `command`, never the
+ rewritten `content`.
- Accepting commands and directories inserts text (`/name ` / `@dir/`);
accepting a completed file inserts the inline chip rather than deleting the
trigger. Immediately
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 7a36ba428..7dbdc8ad4 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -9529,6 +9529,30 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
Electron renderer. The full desktop journey against a large real tree is
Draft (run only in a capable environment when this surface changes).
+#### E2E-102k: `@agent` mention delegates to a named subagent
+
+- **Preconditions**: An Agent session in a project with the builtin
+ `explorer` subagent enabled and no workspace-root entry named `explorer`.
+- **Steps**: Type `look @expl`, accept the `@explorer` row from the **Agents**
+ group, finish the sentence and send. Repeat in Plan mode. Add a root file
+ named `explorer` and type `@` again.
+- **Expected**: The chip is atomic; the user row shows the typed text with
+ `@explorer` chipped; the model is instructed to call `Task` with
+ `explorer` and a Task card appears. Plan mode lists no Agents group and sends
+ the text literally. A same-named root file hides the agent row. Stop before
+ any reply restores the typed text, not the model instruction.
+- **Spec**: `04-ux/08-component-spec.md` §11.8, ADR 0346
+- **Acceptance**: C (conversation & stream)
+- **Milestone**: M5
+- **Status**: The renderer journey (group, shadowing, Plan omission, chip,
+ serialization) runs in `apps/desktop/test/composer-agent-mention-user-path.test.mjs`
+ in a real Electron renderer; send-time rewriting, mode gating, file
+ precedence and Skill composition in `composer-agent-mention.test.mjs`;
+ transcript chips in `session-message-presentation.test.mjs`; persistence in
+ `host-core` `agent_mentions_round_trip_through_record_meta`; Stop restoration
+ in `composer-smart-stop.test.mjs`. The live Task card against a real
+ provider is Draft (requires a configured model).
+
#### E2E-102b: Unanswered Stop restores compact file-reference drafts
- **Preconditions**: An Agent session can delay its first assistant event. The
diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.md
index 7c5539e33..4e7af8b91 100644
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@ -2308,7 +2308,7 @@ Live Voice 受现有开发者模式和开发构建门控约束,包含四种展
[Live Voice](../03-runtime/live-voice.md) 和
[Live Work](../03-runtime/live-work-session.md);这些约定保持不变。
-### 11.8 斜线命令、@ 文件引用和剪贴板文件(D123–D125、D197、D209、D262、D362、ADR 0024、ADR 0059、ADR 0070、ADR 0131)
+### 11.8 斜线命令、@ 文件引用和剪贴板文件(D123–D125、D197、D209、D262、D362、ADR 0024、ADR 0059、ADR 0070、ADR 0131、ADR 0346)
输入框拥有一个内联自动完成菜单——一个组件服务两个组件
模式。焦点永远不会离开文本区域 (D125)。
@@ -2340,6 +2340,15 @@ Live Voice 受现有开发者模式和开发构建门控约束,包含四种展
- 命令描述使用斜杠名称及可选标题、参数提示之后的剩余空间。在窄输入框中,
长描述也应优先省略,不能把短命令名称挤成省略号。名称或提示自身超过行宽时
仍可省略;命令行和文件行都不得溢出菜单。
+- `@agent` 提及(ADR 0346):Agent 模式下 `@` 菜单在文件上方列出 **Agents**
+ 分组(即 `Task` 使用的子代理目录,每行 `@name` + 描述 + 机器人图标),仅在
+ 该分组存在时文件行才带 **Files** 标题;Plan / Goal 模式不显示该分组。与工作区
+ 根目录条目同名的代理被隐藏,因为该标记属于文件。接受代理会插入原子内联芯片,
+ 发送时序列化为 `@name`,相邻字符非空白时前后补空格。发送时,main 把指向目录
+ 中子代理的 `@name`(Agent 模式且根目录无同名条目)改写为显式 `Task` 指令并附上
+ 原始草稿;输入原文作为 `command` 与 `agentMentions` 偏移持久化,转录中每个提及
+ 渲染为芯片。Skill 与代理提及可组合;以模板或应用命令开头的草稿不改写。停止
+ 恢复的是输入原文 `command`,而非改写后的 `content`。
- 文件模式(光标处的 `@` 标记,边界之前):行持续显示
叶文件或目录名称,并在其后以弱化的等宽样式显示该条目完整的
工作区相对路径;目录叶名带尾随 `/`,接受后继续完成,
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index d0281757e..1dfe7181d 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -390,6 +390,8 @@ export const de = {
"pluginTriggerMenu": "Plugin-Vorschläge",
"messageAttachments": "Anhänge in dieser Nachricht",
"fileEmpty": "Keine übereinstimmenden Dateien",
+ "mentionGroupAgents": "Agenten",
+ "mentionGroupFiles": "Dateien",
"fileNoWorkspace": "Öffnen Sie ein Projekt, um auf Dateien zu verweisen",
"fileTruncated": "Das erste wird angezeigt 8000 passende Dateien",
"acHint": "↑↓ auswählen · Eingabe bestätigen · Esc schließen",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 3313faca4..66cbe23d1 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -390,6 +390,8 @@ export const en = {
slashCommandSourceUnavailable: "Command list unavailable, so nothing was sent. Try again.",
sessionTranscriptEmpty: "This session's history could not be read. Reopen the session to try again.",
fileMenu: "File references",
+ mentionGroupAgents: "Agents",
+ mentionGroupFiles: "Files",
removeFileReference: "Remove file reference {{name}}",
directoryReference: "Folder",
directoryPasteUnavailable: "The copied folder's full path is unavailable. Drag the folder into the composer instead.",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 3105621e1..9c7d7e86b 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -390,6 +390,8 @@ export const es = {
"pluginTriggerMenu": "Sugerencias de plugins",
"messageAttachments": "Archivos adjuntos en este mensaje",
"fileEmpty": "No hay archivos coincidentes",
+ "mentionGroupAgents": "Agentes",
+ "mentionGroupFiles": "Archivos",
"fileNoWorkspace": "Abrir un proyecto para hacer referencia a archivos",
"fileTruncated": "Mostrando el primero 8000 archivos coincidentes",
"acHint": "↑↓ seleccionar · Ingresar confirmar · Esc cerrar",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 53e03e382..b31bdce62 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -390,6 +390,8 @@ export const fr = {
"pluginTriggerMenu": "Suggestions de plugins",
"messageAttachments": "Pièces jointes à ce message",
"fileEmpty": "Aucun fichier correspondant",
+ "mentionGroupAgents": "Agents",
+ "mentionGroupFiles": "Fichiers",
"fileNoWorkspace": "Ouvrir un projet pour référencer les fichiers",
"fileTruncated": "Afficher le premier 8000 fichiers correspondants",
"acHint": "↑↓ sélectionner · Entrer confirmer · Esc fermer",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index b434412fd..0f046af0a 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -399,6 +399,8 @@ export const ko = {
pluginTriggerMenu: "플러그인 제안",
messageAttachments: "이 메시지의 첨부 파일",
fileEmpty: "일치하는 파일 없음",
+ mentionGroupAgents: "에이전트",
+ mentionGroupFiles: "파일",
fileNoWorkspace: "파일을 참조하려면 프로젝트를 여세요",
fileTruncated: "일치하는 파일 중 처음 8000개 표시",
acHint: "↑↓ 선택 · Enter 확인 · Esc 닫기",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 07e6e49d6..fe9e3bf75 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -389,6 +389,8 @@ export const ptBR = {
pluginTriggerMenu: "Sugestões de plugins",
messageAttachments: "Anexos desta mensagem",
fileEmpty: "Nenhum arquivo correspondente",
+ mentionGroupAgents: "Agentes",
+ mentionGroupFiles: "Arquivos",
fileNoWorkspace: "Abra um projeto para referenciar arquivos",
fileTruncated: "Exibindo os primeiros 8.000 arquivos correspondentes",
acHint: "↑↓ para selecionar · Enter para confirmar · Esc para fechar",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 7b3ff32eb..1a38f0c7f 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -399,6 +399,8 @@ export const tr = {
pluginTriggerMenu: "Eklenti önerileri",
messageAttachments: "Bu iletideki ekler",
fileEmpty: "Eşleşen dosya yok",
+ mentionGroupAgents: "Ajanlar",
+ mentionGroupFiles: "Dosyalar",
fileNoWorkspace: "Dosyalara başvurmak için bir proje açın",
fileTruncated: "İlk 8000 eşleşen dosya gösteriliyor",
acHint: "↑↓ seç · Enter onayla · Esc kapat",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 78950e598..36ba247d3 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -385,6 +385,8 @@ export const zhCN = {
slashCommandSourceUnavailable: "指令列表不可用,消息未发送。请重试。",
sessionTranscriptEmpty: "无法读取该会话的记录,请重新打开会话后重试。",
fileMenu: "引用文件",
+ mentionGroupAgents: "智能体",
+ mentionGroupFiles: "文件",
removeFileReference: "移除文件引用 {{name}}",
directoryReference: "文件夹",
directoryPasteUnavailable: "无法获取所复制文件夹的完整路径,请将文件夹拖入输入框。",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 566ea120a..c37e7b4cb 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -385,6 +385,8 @@ export const zhTW = {
slashCommandSourceUnavailable: "指令清單無法載入,訊息未傳送。請重試。",
sessionTranscriptEmpty: "無法讀取此工作階段的記錄,請重新開啟後再試一次。",
fileMenu: "引用檔案",
+ mentionGroupAgents: "智慧體",
+ mentionGroupFiles: "檔案",
removeFileReference: "移除檔案引用 {{name}}",
directoryReference: "資料夾",
directoryPasteUnavailable: "無法取得所複製資料夾的完整路徑,請將資料夾拖入輸入框。",
diff --git a/packages/shared/src/composer-trigger.test.ts b/packages/shared/src/composer-trigger.test.ts
index 67928f537..81ea7eccf 100644
--- a/packages/shared/src/composer-trigger.test.ts
+++ b/packages/shared/src/composer-trigger.test.ts
@@ -1,7 +1,10 @@
import { describe, expect, it } from "vitest";
import {
applyCompletion,
+ composeMentionPrompt,
detectTrigger,
+ findAgentMentions,
+ findSkillMentions,
fileReferenceLabel,
formatCommandInsert,
formatFileInsert,
@@ -323,3 +326,60 @@ describe("compact file references", () => {
expect(serializeComposerFileReferences("", [{ path: id, kind: "session" }])).toBe("");
});
});
+
+describe("agent mentions (ADR 0346)", () => {
+ const agents = new Set(["explorer", "code-reviewer"]);
+
+ it("reads @name only at a word start and only for a catalog name", () => {
+ expect(findAgentMentions("@explorer 帮我查找一下是否存在沙箱", agents)).toEqual([
+ { start: 0, end: 9, name: "explorer" },
+ ]);
+ expect(findAgentMentions("ask @code-reviewer, then @nobody", agents)).toEqual([
+ { start: 4, end: 18, name: "code-reviewer" },
+ ]);
+ expect(findAgentMentions("mail user@explorer now", agents)).toEqual([]);
+ expect(findAgentMentions("open @explorer.ts and @explorer/x", agents)).toEqual([]);
+ expect(findAgentMentions("end with @explorer.", agents)).toEqual([
+ { start: 9, end: 18, name: "explorer" },
+ ]);
+ });
+
+ it("an agent chip serializes to a resolvable @name even mid-word", () => {
+ const reference = { path: "explorer", kind: "agent", token: "\ue010" };
+ const content = serializeInlineComposerFileReferences("look\ue010where", [reference]);
+ expect(content).toBe("look @explorer where");
+ expect(findAgentMentions(content, agents).map((m) => m.name)).toEqual(["explorer"]);
+ // A chip-less agent reference never leaks into the trailing path list.
+ expect(serializeComposerFileReferences("hi", [{ path: "explorer", kind: "agent" }])).toBe("hi");
+ });
+
+ it("keeps the file serialization byte-for-byte unchanged", () => {
+ const file = { path: "src/a.ts", kind: "file", token: "\ue011" };
+ expect(serializeInlineComposerFileReferences("see\ue011now", [file])).toBe("see@src/a.ts now");
+ });
+
+ it("prompts a Task call and keeps the addressed body", () => {
+ const content = "@explorer find the sandbox";
+ const prompt = composeMentionPrompt(content, [], findAgentMentions(content, agents));
+ expect(prompt).toMatch(/^The user explicitly delegated.*`Task`.*"explorer"/);
+ expect(prompt.endsWith("\n\n@explorer find the sandbox")).toBe(true);
+ });
+
+ it("is unchanged for a Skill-only draft and orders Skills before agents", () => {
+ const skills = new Map([["skill:review", "review"]]);
+ const skillOnly = "/skill:review check this";
+ expect(composeMentionPrompt(skillOnly, findSkillMentions(skillOnly, skills), [])).toBe(
+ 'Call the `Skill` tool with each of these ids before answering this request, in order: "review". Follow the loaded skill instructions.\n\ncheck this',
+ );
+ const both = "/skill:review @code-reviewer check this";
+ const prompt = composeMentionPrompt(
+ both,
+ findSkillMentions(both, skills),
+ findAgentMentions(both, agents),
+ );
+ const [skill, agent, body] = prompt.split("\n\n");
+ expect(skill).toMatch(/`Skill`/);
+ expect(agent).toMatch(/"code-reviewer"/);
+ expect(body).toBe("@code-reviewer check this");
+ });
+});
diff --git a/packages/shared/src/composer-trigger.ts b/packages/shared/src/composer-trigger.ts
index f790a494d..6f7cfbf58 100644
--- a/packages/shared/src/composer-trigger.ts
+++ b/packages/shared/src/composer-trigger.ts
@@ -148,6 +148,62 @@ export function findSkillMentions(
return mentions;
}
+export type AgentMention = { start: number; end: number; name: string };
+
+/**
+ * Resolve complete `@name` tokens against the delegation catalog at send time
+ * (ADR 0346). A token counts only at the start or after whitespace, so
+ * `user@host` stays text, and only when it ends at whitespace, punctuation or
+ * the end of the draft, so `@explorer.ts` stays a file reference.
+ */
+export function findAgentMentions(
+ content: string,
+ agentNames: ReadonlySet<string>,
+): AgentMention[] {
+ const mentions: AgentMention[] = [];
+ for (const match of content.matchAll(
+ /(^|\s)@([a-z0-9][a-z0-9-]*)(?=$|\s|[,;:!?)\],。;:!?、)]|\.(?:\s|$))/g,
+ )) {
+ if (!agentNames.has(match[2])) continue;
+ const start = match.index + match[1].length;
+ mentions.push({ start, end: start + match[2].length + 1, name: match[2] });
+ }
+ return mentions;
+}
+
+/**
+ * The model-facing prompt for a draft that names Skills (`/skill:…`) or
+ * subagents (`@agent`). Skill tokens are removed from the body because the
+ * instruction already loads them; agent tokens stay, because the body is what
+ * each delegate's brief is written from and `@name` says which part is whose.
+ */
+export function composeMentionPrompt(
+ content: string,
+ skillMentions: readonly SkillMention[],
+ agentMentions: readonly AgentMention[],
+): string {
+ let body = "";
+ let end = 0;
+ for (const mention of skillMentions) {
+ body += content.slice(end, mention.start);
+ end = mention.end;
+ }
+ body = (body + content.slice(end)).trim();
+ const skillIds = [...new Set(skillMentions.map((mention) => mention.id))];
+ const agentNames = [...new Set(agentMentions.map((mention) => mention.name))];
+ return [
+ skillIds.length
+ ? `Call the \`Skill\` tool with each of these ids before answering this request, in order: ${skillIds.map((id) => JSON.stringify(id)).join(", ")}. Follow the loaded skill instructions.`
+ : "",
+ agentNames.length
+ ? `The user explicitly delegated this request with @mentions. Call the \`Task\` tool with \`agent\` set to each of these subagents: ${agentNames.map((name) => JSON.stringify(name)).join(", ")}. Write each \`task\` as a complete brief built from the request below; there, @name marks the part addressed to that subagent. Converge with TaskWait and answer from the reports.`
+ : "",
+ body,
+ ]
+ .filter(Boolean)
+ .join("\n\n");
+}
+
/** Insertion text for an accepted slash command: `/name ` ready for args. */
export function formatCommandInsert(name: string): string {
return `/${name} `;
@@ -186,7 +242,7 @@ export function serializeComposerFileReferences(
): string {
const content = serializeInlineComposerFileReferences(draft, references);
const paths = references
- .filter((reference) => !reference.token && reference.kind !== "session" && reference.kind !== "directory")
+ .filter((reference) => !reference.token && reference.kind !== "session" && reference.kind !== "directory" && reference.kind !== "agent")
.map((reference) => formatFileInsert(reference.path, "file"))
.join("")
.trim();
@@ -238,6 +294,8 @@ function directoryPromptReference(path: string): string {
* separating space so adjacent chips never fuse their @paths together. A
* plugin mark's token resolves to the text it sends (`plugin.send`) instead
* of a path, and a session reference resolves to its `pi-desktop://` link.
+ * An agent chip resolves to `@name` and also keeps a space before it, because
+ * the send-time resolver reads an `@token` only after whitespace (ADR 0346).
*/
export function serializeInlineComposerFileReferences(
draft: string,
@@ -248,23 +306,29 @@ export function serializeInlineComposerFileReferences(
const token = reference.token?.trim();
if (!token || !content.includes(token)) continue;
const send = reference.plugin?.send;
+ const agent = reference.kind === "agent";
const insert = typeof send === "string"
? send
- : reference.kind === "session"
- ? formatSessionLink(reference.path)
- : reference.kind === "directory"
- ? directoryPromptReference(reference.path)
- : formatFileInsert(reference.path, "file").trim();
+ : agent
+ ? `@${reference.path}`
+ : reference.kind === "session"
+ ? formatSessionLink(reference.path)
+ : reference.kind === "directory"
+ ? directoryPromptReference(reference.path)
+ : formatFileInsert(reference.path, "file").trim();
let index = content.indexOf(token);
while (index !== -1) {
const nextChar = content[index + token.length];
const separator = nextChar && !/\s/.test(nextChar) ? " " : "";
+ const previousChar = content[index - 1];
+ const lead = agent && previousChar && !/\s/.test(previousChar) ? " " : "";
content =
content.slice(0, index) +
+ lead +
insert +
separator +
content.slice(index + token.length);
- index = content.indexOf(token, index + insert.length + separator.length);
+ index = content.indexOf(token, index + lead.length + insert.length + separator.length);
}
}
const directories = references.filter(reference => reference.kind === "directory" &&
diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.ts
index 0ee958184..5a25639df 100644
--- a/packages/shared/src/types/messages.ts
+++ b/packages/shared/src/types/messages.ts
@@ -140,6 +140,8 @@ export type UiMessage = {
command?: string;
/** Validated Skill tokens in `command`, using UTF-16 offsets. */
skillMentions?: Array<{ start: number; end: number; id: string }>;
+ /** Validated `@agent` tokens in `command`, using UTF-16 offsets (ADR 0346). */
+ agentMentions?: Array<{ start: number; end: number; name: string }>;
toolName?: string;
toolCallId?: string;
toolStatus?: "running" | "success" | "error" | "denied";