feat(cli): dispatch du callback plugin slash-command vers le runtime registry — #166 (QA verte)

Boucle le gap end-to-end de #165 : à l'exécution d'une commande slash plugin
depuis le composer custom, l'UI traite l'effet pluginCallback et le dispatche
au PluginRuntimeRegistry pour que la callback du plugin s'exécute réellement.

- runtime/registry: runCommandStrict (échec explicite si handler absent) +
  propagation de la valeur de retour ; élargit les types de retour (unknown).
- runtime/loader: chargement de contributes.slashCommands au registre +
  propagation du retour du handler.
- features/plugins/usePluginMenus: runCommand retourne unknown.
- features/agents/CustomAgentChatView: handler de l'effet pluginCallback ->
  pluginRuntime.registry.runCommandStrict, avec retour utilisateur en cas
  d'échec (commande indisponible / callback absente).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-08-06 15:47:04 +02:00
parent fbaca9d5cc
commit b0be5f04e4
6 changed files with 341 additions and 10 deletions

View File

@ -4,6 +4,13 @@ import { describe, expect, it, vi } from "vitest";
import { DIProvider } from "@/app/di"; import { DIProvider } from "@/app/di";
import type { AgentProfile } from "@/domain"; import type { AgentProfile } from "@/domain";
import { PluginRuntimeProvider } from "@/features/plugins";
import {
PluginCommandRegistry,
PluginLayoutRegistry,
PluginMenuRegistry,
PluginRuntimeRegistry,
} from "@/plugins/runtime";
import type { Gateways } from "@/ports"; import type { Gateways } from "@/ports";
import { CustomAgentChatView } from "./CustomAgentChatView"; import { CustomAgentChatView } from "./CustomAgentChatView";
@ -18,6 +25,27 @@ const profile: AgentProfile = {
structuredAdapter: "codex", structuredAdapter: "codex",
}; };
function addPluginCommand(
registry: PluginRuntimeRegistry,
pluginId: string,
commandId: string,
handler: (...args: unknown[]) => unknown | Promise<unknown>,
) {
const commands = new PluginCommandRegistry(pluginId, new Set([commandId]));
commands.register(commandId, handler);
registry.add({
pluginId,
displayName: "Acme Plugin",
contributes: {
commands: [{ id: commandId, title: "Explain", shortDescription: "Explain selection" }],
},
commands,
layouts: new PluginLayoutRegistry(pluginId, new Set()),
menu: new PluginMenuRegistry(pluginId),
dispose: async () => {},
});
}
describe("CustomAgentChatView", () => { describe("CustomAgentChatView", () => {
it("cancels only the current turn and keeps the structured session alive", async () => { it("cancels only the current turn and keeps the structured session alive", async () => {
const agent = { const agent = {
@ -522,6 +550,173 @@ describe("CustomAgentChatView", () => {
expect(screen.queryByRole("listbox", { name: "suggestions commandes slash" })).toBeNull(); expect(screen.queryByRole("listbox", { name: "suggestions commandes slash" })).toBeNull();
}); });
it("dispatches plugin slash-command callback effects through the plugin runtime", async () => {
const commandHandler = vi.fn(async () => {});
const registry = new PluginRuntimeRegistry();
addPluginCommand(
registry,
"dev.acme.explain",
"dev.acme.explain.run",
commandHandler,
);
const agent = {
launchAgentChat: vi.fn(),
reattachAgentChat: vi.fn(async (sessionId: string) => ({
sessionId,
scrollback: [],
})),
sendAgentChat: vi.fn(async () => {}),
executeSlashCommand: vi.fn(async (_name: string, options) => ({
command: {
name: "/explain",
shortDescription: "Explain selection",
requiresConfirmation: false,
availability: { status: "available" as const },
source: { plugin: { pluginId: "dev.acme.explain" } },
plugin: {
pluginId: "dev.acme.explain",
commandId: "dev.acme.explain.run",
},
},
effect: {
kind: "pluginCallback" as const,
pluginId: "dev.acme.explain",
commandId: "dev.acme.explain.run",
sessionId: options.sessionId,
arguments: options.arguments ?? [],
},
})),
cancelAgentChat: vi.fn(async () => {}),
closeAgentChat: vi.fn(async () => {}),
};
render(
<DIProvider
gateways={{
agent,
system: { pickFile: vi.fn(async () => null) },
} as unknown as Gateways}
>
<PluginRuntimeProvider
value={{ registry, failures: [], pending: [], loading: false }}
>
<CustomAgentChatView
projectId="project-1"
agentId="agent-1"
agentName="Worker"
profile={profile}
cwd="/repo"
nodeId="node-1"
sessionId="chat-session-1"
conversationId="conversation-1"
onSessionId={vi.fn()}
onConversationId={vi.fn()}
/>
</PluginRuntimeProvider>
</DIProvider>,
);
await waitFor(() =>
expect(agent.reattachAgentChat).toHaveBeenCalledWith(
"chat-session-1",
expect.any(Function),
),
);
const composer = screen.getByLabelText(/message CLI custom/) as HTMLTextAreaElement;
fireEvent.change(composer, { target: { value: "/explain focus this" } });
fireEvent.keyDown(composer, { key: "Enter" });
await waitFor(() =>
expect(agent.executeSlashCommand).toHaveBeenCalledWith("/explain", {
sessionId: "chat-session-1",
arguments: ["focus this"],
}),
);
await waitFor(() => expect(commandHandler).toHaveBeenCalledWith("focus this"));
expect(agent.sendAgentChat).not.toHaveBeenCalled();
expect(
await screen.findByText("Commande plugin /explain exécutée."),
).toBeTruthy();
expect(composer.value).toBe("");
});
it("shows feedback when a plugin slash-command callback cannot be dispatched", async () => {
const registry = new PluginRuntimeRegistry();
const agent = {
launchAgentChat: vi.fn(),
reattachAgentChat: vi.fn(async (sessionId: string) => ({
sessionId,
scrollback: [],
})),
sendAgentChat: vi.fn(async () => {}),
executeSlashCommand: vi.fn(async () => ({
command: {
name: "/explain",
shortDescription: "Explain selection",
requiresConfirmation: false,
availability: { status: "available" as const },
source: { plugin: { pluginId: "dev.acme.missing" } },
plugin: {
pluginId: "dev.acme.missing",
commandId: "dev.acme.missing.run",
},
},
effect: {
kind: "pluginCallback" as const,
pluginId: "dev.acme.missing",
commandId: "dev.acme.missing.run",
arguments: [],
},
})),
cancelAgentChat: vi.fn(async () => {}),
closeAgentChat: vi.fn(async () => {}),
};
render(
<DIProvider
gateways={{
agent,
system: { pickFile: vi.fn(async () => null) },
} as unknown as Gateways}
>
<PluginRuntimeProvider
value={{ registry, failures: [], pending: [], loading: false }}
>
<CustomAgentChatView
projectId="project-1"
agentId="agent-1"
agentName="Worker"
profile={profile}
cwd="/repo"
nodeId="node-1"
sessionId="chat-session-1"
conversationId="conversation-1"
onSessionId={vi.fn()}
onConversationId={vi.fn()}
/>
</PluginRuntimeProvider>
</DIProvider>,
);
await waitFor(() =>
expect(agent.reattachAgentChat).toHaveBeenCalledWith(
"chat-session-1",
expect.any(Function),
),
);
const composer = screen.getByLabelText(/message CLI custom/);
fireEvent.change(composer, { target: { value: "/explain" } });
fireEvent.keyDown(composer, { key: "Enter" });
const alert = await screen.findByRole("alert");
expect(alert.textContent).toContain("Commande /explain échouée");
expect(alert.textContent).toContain('plugin "dev.acme.missing" is not loaded');
expect(screen.getAllByText(/Commande \/explain échouée/)).toHaveLength(2);
expect(agent.sendAgentChat).not.toHaveBeenCalled();
});
it("executes /profile as a confirmed profile-switch flow that resets the current session", async () => { it("executes /profile as a confirmed profile-switch flow that resets the current session", async () => {
const agent = { const agent = {
launchAgentChat: vi.fn(async () => ({ launchAgentChat: vi.fn(async () => ({

View File

@ -26,6 +26,7 @@ import type {
SlashCommand, SlashCommand,
} from "@/domain"; } from "@/domain";
import { useGateways } from "@/app/di"; import { useGateways } from "@/app/di";
import { usePluginRuntime } from "@/features/plugins/PluginRuntimeProvider";
import { Button, Spinner, cn } from "@/shared"; import { Button, Spinner, cn } from "@/shared";
import type { ChatAttachmentInput } from "@/ports"; import type { ChatAttachmentInput } from "@/ports";
@ -66,6 +67,11 @@ interface ProfileCommandDialogState {
error: string | null; error: string | null;
} }
interface SlashCommandInvocation {
name: string;
arguments: unknown[];
}
function describe(e: unknown): string { function describe(e: unknown): string {
if (e && typeof e === "object" && "message" in e) { if (e && typeof e === "object" && "message" in e) {
return String((e as GatewayError).message); return String((e as GatewayError).message);
@ -274,6 +280,17 @@ function slashCommandPrefix(draft: string): string | null {
return draft; return draft;
} }
function slashCommandInvocation(text: string): SlashCommandInvocation | null {
if (!text.startsWith("/")) return null;
const [name, ...argumentParts] = text.split(/\s+/);
if (!name) return null;
const rawArguments = argumentParts.join(" ").trim();
return {
name,
arguments: rawArguments ? [rawArguments] : [],
};
}
function isSlashCommandAvailable(command: SlashCommand): boolean { function isSlashCommandAvailable(command: SlashCommand): boolean {
return command.availability.status === "available"; return command.availability.status === "available";
} }
@ -328,6 +345,7 @@ export function CustomAgentChatView({
onConversationId, onConversationId,
}: CustomAgentChatViewProps) { }: CustomAgentChatViewProps) {
const { agent, profile: profileGateway, system } = useGateways(); const { agent, profile: profileGateway, system } = useGateways();
const pluginRuntime = usePluginRuntime();
const [turns, setTurns] = useState<ChatTurn[]>([]); const [turns, setTurns] = useState<ChatTurn[]>([]);
const [currentSession, setCurrentSession] = useState(sessionId); const [currentSession, setCurrentSession] = useState(sessionId);
const [externalSessionId, setExternalSessionId] = useState(sessionId); const [externalSessionId, setExternalSessionId] = useState(sessionId);
@ -756,6 +774,45 @@ export function CustomAgentChatView({
} }
} }
async function executeSlashCommand(invocation: SlashCommandInvocation) {
if (!agent.executeSlashCommand) {
setError(`Commande ${invocation.name} indisponible dans ce runtime.`);
return;
}
setDraft("");
setError(null);
try {
const sid =
currentSession ??
(await recoverStructuredSession({
applyScrollback: false,
retryAttachNotFound: true,
}));
const result = await agent.executeSlashCommand(invocation.name, {
sessionId: sid,
arguments: invocation.arguments,
});
if (result.effect.kind !== "pluginCallback") {
throw new Error(
`La commande ${invocation.name} n'a pas renvoyé d'effet pluginCallback.`,
);
}
await pluginRuntime.registry.runCommandStrict(
result.effect.pluginId,
result.effect.commandId,
...result.effect.arguments,
);
setTurns((prev) => [
...prev,
{ role: "tool", label: `Commande plugin ${result.command.name} exécutée.` },
]);
} catch (e) {
const message = `Commande ${invocation.name} échouée: ${describe(e)}`;
setError(message);
setTurns((prev) => [...prev, { role: "error", text: message }]);
}
}
async function pickAttachment() { async function pickAttachment() {
const path = await system.pickFile(); const path = await system.pickFile();
if (path) { if (path) {
@ -804,6 +861,11 @@ export function CustomAgentChatView({
await openProfileCommandFlow(); await openProfileCommandFlow();
return; return;
} }
const slashInvocation = slashCommandInvocation(text);
if (slashInvocation) {
await executeSlashCommand(slashInvocation);
return;
}
const outgoingAttachments = attachments; const outgoingAttachments = attachments;
const attachmentInputs = outgoingAttachments.map((item) => item.input); const attachmentInputs = outgoingAttachments.map((item) => item.input);
const attachmentLabels = outgoingAttachments.map((item) => item.label); const attachmentLabels = outgoingAttachments.map((item) => item.label);

View File

@ -23,7 +23,7 @@ export interface UsePluginMenusResult {
topLevelMenus: MenuBarMenu[]; topLevelMenus: MenuBarMenu[];
/** Resolved+ordered `MenuBarItem`s to append to a native menu's items. */ /** Resolved+ordered `MenuBarItem`s to append to a native menu's items. */
itemsFor: (targetMenuId: MenuTargetId) => MenuBarItem[]; itemsFor: (targetMenuId: MenuTargetId) => MenuBarItem[];
runCommand: (pluginId: string, commandId: string) => Promise<void>; runCommand: (pluginId: string, commandId: string) => Promise<unknown>;
} }
function describeError(e: unknown): string { function describeError(e: unknown): string {

View File

@ -98,7 +98,7 @@ describe("loadPlugins", () => {
); );
expect(failures).toEqual([]); expect(failures).toEqual([]);
expect((globalThis as Record<string, unknown>).__registerError).toMatch( expect((globalThis as Record<string, unknown>).__registerError).toMatch(
/not declared by any menu item/, /not declared by any command contribution/,
); );
}); });
@ -591,6 +591,13 @@ describe("loadPlugins", () => {
command: "hello-plugin", command: "hello-plugin",
}, },
], ],
slashCommands: [
{
name: "/hello",
shortDescription: "Run the hello-plugin callback",
command: "hello-plugin",
},
],
layouts: [ layouts: [
{ {
type: "hello-plugin.hello-world", type: "hello-plugin.hello-world",
@ -613,6 +620,13 @@ describe("loadPlugins", () => {
}, },
]); ]);
expect(registry.get("com.example.hello-plugin")?.contributes.mcpServers).toEqual([]); expect(registry.get("com.example.hello-plugin")?.contributes.mcpServers).toEqual([]);
expect(registry.get("com.example.hello-plugin")?.contributes.slashCommands).toEqual([
{
name: "/hello",
shortDescription: "Run the hello-plugin callback",
command: "hello-plugin",
},
]);
await registry.runCommand("com.example.hello-plugin", "hello-plugin"); await registry.runCommand("com.example.hello-plugin", "hello-plugin");
expect((globalThis as Record<string, unknown>).__helloArchiveCommandRan).toBe(true); expect((globalThis as Record<string, unknown>).__helloArchiveCommandRan).toBe(true);
const Layout = registry.layoutComponent( const Layout = registry.layoutComponent(
@ -623,6 +637,39 @@ describe("loadPlugins", () => {
expect((Layout as unknown as () => string)()).toBe("hello-world"); expect((Layout as unknown as () => string)()).toBe("hello-world");
}); });
it("allows command callbacks declared only by slashCommands", async () => {
const bundle = dataUrl(`
export function activate(ctx) {
ctx.commands.registerCommand("dev.acme.explain", () => {
globalThis.__slashOnlyCommandRan = true;
});
}
`);
const { registry, failures } = await loadPlugins(
[
entry({
id: "dev.acme.slash",
displayName: "Slash",
bundleUrl: bundle,
contributes: {
slashCommands: [
{
name: "/explain",
shortDescription: "Explain selection",
command: "dev.acme.explain",
},
],
} as unknown as PluginContributionDto,
}),
],
gateways,
);
expect(failures).toEqual([]);
await registry.runCommand("dev.acme.slash", "dev.acme.explain");
expect((globalThis as Record<string, unknown>).__slashOnlyCommandRan).toBe(true);
});
it("confines a malformed runtime catalog entry and still loads healthy plugins", async () => { it("confines a malformed runtime catalog entry and still loads healthy plugins", async () => {
const bundle = dataUrl(` const bundle = dataUrl(`
export function activate(ctx) { export function activate(ctx) {

View File

@ -151,7 +151,7 @@ function createCommandContext(commands: PluginCommandRegistry): PluginCommandCon
register: (commandId, handler) => commands.register(commandId, handler), register: (commandId, handler) => commands.register(commandId, handler),
registerCommand: (commandId, handler) => registerCommand: (commandId, handler) =>
commands.register(commandId, async (...args) => { commands.register(commandId, async (...args) => {
await handler(...args); return await handler(...args);
}), }),
}; };
} }
@ -195,7 +195,10 @@ function safePluginId(entry: unknown): string {
function commandIdsFromContributes(contributes: PluginContributionDto): Set<string> { function commandIdsFromContributes(contributes: PluginContributionDto): Set<string> {
return new Set<string>( return new Set<string>(
contributes.menuItems.flatMap<string>((item) => { [
...arrayOrEmpty(contributes.menuItems),
...arrayOrEmpty(contributes.slashCommands),
].flatMap<string>((item) => {
const command = nonEmptyString(objectOrEmpty(item).command); const command = nonEmptyString(objectOrEmpty(item).command);
return command ? [command] : []; return command ? [command] : [];
}), }),
@ -216,6 +219,7 @@ function normalizeContributes(entry: PluginRuntimePlugin): PluginContributionDto
return { return {
menus: arrayOrEmpty(contributes?.menus), menus: arrayOrEmpty(contributes?.menus),
menuItems: arrayOrEmpty(contributes?.menuItems), menuItems: arrayOrEmpty(contributes?.menuItems),
slashCommands: arrayOrEmpty(contributes?.slashCommands),
layouts: arrayOrEmpty(contributes?.layouts), layouts: arrayOrEmpty(contributes?.layouts),
mcpServers: arrayOrEmpty(contributes?.mcpServers), mcpServers: arrayOrEmpty(contributes?.mcpServers),
}; };

View File

@ -59,7 +59,7 @@ export interface Disposable {
dispose(): void; dispose(): void;
} }
export type PluginCommandHandler = (...args: unknown[]) => void | Promise<void>; export type PluginCommandHandler = (...args: unknown[]) => unknown | Promise<unknown>;
/** Commands a plugin registers in `activate(ctx)`, dispatched by menu items. */ /** Commands a plugin registers in `activate(ctx)`, dispatched by menu items. */
export class PluginCommandRegistry { export class PluginCommandRegistry {
@ -74,7 +74,7 @@ export class PluginCommandRegistry {
if (!this.declaredCommandIds.has(commandId)) { if (!this.declaredCommandIds.has(commandId)) {
throw new Error( throw new Error(
`plugin "${this.pluginId}" tried to register command "${commandId}" ` + `plugin "${this.pluginId}" tried to register command "${commandId}" ` +
"which is not declared by any menu item in its manifest", "which is not declared by any command contribution in its manifest",
); );
} }
this.handlers.set(commandId, handler); this.handlers.set(commandId, handler);
@ -86,11 +86,11 @@ export class PluginCommandRegistry {
} }
/** Runs a registered command; a no-op (never throws) if none is registered. */ /** Runs a registered command; a no-op (never throws) if none is registered. */
async run(commandId: string, ...args: unknown[]): Promise<void> { async run(commandId: string, ...args: unknown[]): Promise<unknown> {
const handler = this.handlers.get(commandId); const handler = this.handlers.get(commandId);
if (!handler) return; if (!handler) return;
try { try {
await handler(...args); return await handler(...args);
} catch (e) { } catch (e) {
console.error( console.error(
`[plugin:${this.pluginId}] command "${commandId}" failed`, `[plugin:${this.pluginId}] command "${commandId}" failed`,
@ -99,6 +99,17 @@ export class PluginCommandRegistry {
} }
} }
/** Runs a registered command and surfaces failures to the caller. */
async runStrict(commandId: string, ...args: unknown[]): Promise<unknown> {
const handler = this.handlers.get(commandId);
if (!handler) {
throw new Error(
`plugin "${this.pluginId}" has no registered command handler "${commandId}"`,
);
}
return await handler(...args);
}
has(commandId: string): boolean { has(commandId: string): boolean {
return this.handlers.has(commandId); return this.handlers.has(commandId);
} }
@ -256,7 +267,19 @@ export class PluginRuntimeRegistry {
); );
} }
async runCommand(pluginId: string, commandId: string, ...args: unknown[]): Promise<void> { async runCommand(pluginId: string, commandId: string, ...args: unknown[]): Promise<unknown> {
await this.loaded.get(pluginId)?.commands.run(commandId, ...args); return await this.loaded.get(pluginId)?.commands.run(commandId, ...args);
}
async runCommandStrict(
pluginId: string,
commandId: string,
...args: unknown[]
): Promise<unknown> {
const plugin = this.loaded.get(pluginId);
if (!plugin) {
throw new Error(`plugin "${pluginId}" is not loaded`);
}
return await plugin.commands.runStrict(commandId, ...args);
} }
} }