Skip to content
Merged
24 changes: 12 additions & 12 deletions docs/hooks/plugins.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -150,21 +150,21 @@ In an MCP name, Xum replaces each character other than `[A-Za-z0-9_]` with `_`.

The hook's MCP tool returns its output as JSON text. Xum joins the text blocks of the result. If the result has no text, Xum reads `structuredContent`.

| Event | Output | Effect |
| ------------------ | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `PreToolUse` | `hookSpecificOutput.permissionDecision: "deny"`, or `decision: "block"` | Xum blocks the call. The model sees the reason as the tool error. |
| `PreToolUse` | `hookSpecificOutput.permissionDecision: "allow"` with `hookSpecificOutput.updatedInput` | Xum runs the call with the new input. |
| `PostToolUse` | `decision: "block"`, or `continue: false` | Xum replaces the tool result with the hook's feedback. |
| `UserPromptSubmit` | `decision: "block"` with `reason`, or `continue: false` | Xum does not send a message you wrote. See the note below the table. |
| `UserPromptSubmit` | Plain text that does not start with `{` or `[` | Xum adds the text as context. |
| `Stop` | `decision: "block"` with `reason` | The turn continues with `reason` as the next prompt, at most 3 times per message. See the note below the table. |
| `Stop` | `continue: false` | Xum ends the turn and shows `stopReason` to you. |
| All but `Stop` | `hookSpecificOutput.additionalContext` | Xum adds the text for the model. On tool events, it goes on the result as `hook_output`. |
| Any event | `systemMessage` | Xum shows the message to you. The model never sees it. |
| Event | Output | Effect |
| ------------------ | --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `PreToolUse` | `hookSpecificOutput.permissionDecision: "deny"`, or `decision: "block"` | Xum blocks the call. The model sees the reason as the tool error. |
| `PreToolUse` | `hookSpecificOutput.permissionDecision: "allow"` with `hookSpecificOutput.updatedInput` | Xum runs the call with the new input. |
| `PostToolUse` | `decision: "block"`, or `continue: false` | Xum replaces the tool result with the hook's feedback. |
| `UserPromptSubmit` | `decision: "block"` with `reason`, or `continue: false` | Xum does not send a message you wrote. See the note below the table. |
| `UserPromptSubmit` | Plain text that does not start with `{` or `[` | Xum adds the text as context. |
| `Stop` | `decision: "block"` with `reason` | The turn continues with `reason` as the next prompt, at most 3 times per message for each hook. See the note below the table. |
| `Stop` | `continue: false` | Xum ends the turn and shows `stopReason` to you. |
| All but `Stop` | `hookSpecificOutput.additionalContext` | Xum adds the text for the model. On tool events, it goes on the result as `hook_output`. |
| Any event | `systemMessage` | Xum shows the message to you. The model never sees it. |

A `UserPromptSubmit` block applies only to a message you send (typed, edited, queued, or plan-review feedback). Automatic sends (goal and task continuations, wakes, follow-ups) ignore every block, because their sender would retry the same message in a loop. They keep the context of the other hooks. A hook whose output both blocks and adds context loses its own context. The prompt that a `Stop` block queues is different: no `UserPromptSubmit` hook runs for it at all, as in Codex. A `UserPromptSubmit` guard cannot check it.

After 3 `Stop` continuations for one message, Xum logs that the cap was reached and ends the turn. For a turn that an ACP client or `xum run` owns, Xum runs the `Stop` hooks but never continues the turn. For a goal turn, Xum continues only while the goal can take another turn: not after it is paused or replaced, or after it reaches its turn, cost, or budget limit.
Each `Stop` hook continues one message at most 3 times, and all hooks together at most 50 times. Each continuation shows the notice "plugin continued turn n of 50". For a turn that an ACP client or `xum run` owns, Xum runs the `Stop` hooks but never continues the turn. For a goal turn, Xum continues only while the goal can take another turn: not after it is paused or replaced, or after it reaches its turn, cost, or budget limit.

`hookSpecificOutput` must have `hookEventName` set to the event name. `Stop` has no `hookSpecificOutput`.

Expand Down
42 changes: 41 additions & 1 deletion src/browser/utils/chatErrorToasts.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
dismissChatError,
peekChatError,
publishChatError,
publishChatInfo,
useChatErrorToasts,
} from "./chatErrorToasts";

Expand All @@ -31,8 +32,10 @@ describe("useChatErrorToasts", () => {
/** A chat input whose single toast slot the test drives: `show` renders a toast, `dismiss` clears it. */
function mountInput(workspaceId: string | null, options?: { strict?: boolean }) {
const shown: string[] = [];
const pushToast = (toast: { message: string }) => {
const pushed: Array<{ type: string; message: string }> = [];
const pushToast = (toast: { type: "error" | "info"; message: string }) => {
shown.push(toast.message);
pushed.push({ type: toast.type, message: toast.message });
};
const initialProps: Props = { workspaceId, visible: null };
const rendered = renderHook(
Expand All @@ -41,6 +44,7 @@ describe("useChatErrorToasts", () => {
);
return {
shown,
pushed,
...rendered,
show: (message: string) => rendered.rerender({ workspaceId, visible: message }),
dismiss: () => rendered.rerender({ workspaceId, visible: null }),
Expand Down Expand Up @@ -169,6 +173,42 @@ describe("useChatErrorToasts", () => {
expect(peekChatError("ws-j")).toBeUndefined();
});

test("an info notice shows as an info toast, and a newer one replaces one still waiting", () => {
publishChatError("ws-k", "Stop could not be recorded");
publishChatInfo("ws-k", "Plugin ralph: plugin continued turn 1 of 50");
publishChatInfo("ws-k", "Plugin ralph: plugin continued turn 2 of 50");

const input = mountInput("ws-k");
input.show("Stop could not be recorded");
input.dismiss();
input.show("Plugin ralph: plugin continued turn 2 of 50");
input.dismiss();

expect(input.pushed).toEqual([
{ type: "error", message: "Stop could not be recorded" },
{ type: "info", message: "Plugin ralph: plugin continued turn 2 of 50" },
]);
expect(peekChatError("ws-k")).toBeUndefined();
});

test("info notices published while one shows leave only the newest to show next", () => {
const input = mountInput("ws-l");
act(() => {
publishChatInfo("ws-l", "turn 1");
});
input.show("turn 1");
act(() => {
publishChatInfo("ws-l", "turn 2");
publishChatInfo("ws-l", "turn 3");
});
input.dismiss();
input.show("turn 3");
input.dismiss();

expect(input.shown).toEqual(["turn 1", "turn 3"]);
expect(peekChatError("ws-l")).toBeUndefined();
});

test("StrictMode's replayed effect re-pushes the same error instead of consuming the next one", () => {
publishChatError("ws-i", "first");
publishChatError("ws-i", "second");
Expand Down
49 changes: 37 additions & 12 deletions src/browser/utils/chatErrorToasts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,52 @@
* Error toasts addressed to a workspace's chat input (a child exhausting the parent's goal budget,
* a Stop the backend could not record). Retained until that input has shown and dismissed them: the
* error can land after the user switched workspaces (a Stop settles asynchronously), when no input
* for that workspace is mounted, and the input renders a single toast at a time.
* for that workspace is mounted, and the input renders a single toast at a time. Info notices
* (publishChatInfo) share this queue.
*/
const pendingByWorkspace = new Map<string, string[]>();
interface PendingChatToast {
type: "error" | "info";
message: string;
}
const pendingByWorkspace = new Map<string, PendingChatToast[]>();
const listenersByWorkspace = new Map<string, Set<() => void>>();

export function publishChatError(workspaceId: string, message: string): void {
const pending = pendingByWorkspace.get(workspaceId) ?? [];
pending.push(message);
pendingByWorkspace.set(workspaceId, pending);
publish(workspaceId, (pending) => [...pending, { type: "error", message }]);
}

/**
* A routine notice (a plugin's Stop continuation), shown as a non-error toast. It replaces any info
* notice still waiting, so a loop of 50 continuations leaves one notice to show, not 50.
*/
export function publishChatInfo(workspaceId: string, message: string): void {
publish(workspaceId, (pending) => [
...pending.filter((toast) => toast.type !== "info"),
{ type: "info", message },
]);
}

function publish(
workspaceId: string,
update: (pending: PendingChatToast[]) => PendingChatToast[]
): void {
pendingByWorkspace.set(workspaceId, update(pendingByWorkspace.get(workspaceId) ?? []));

Check warning on line 36 in src/browser/utils/chatErrorToasts.ts

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: ?? -> ||

No unit test failed when publish had ?? -> ||. Add a test that tells them apart, or say why they are equivalent.
for (const listener of listenersByWorkspace.get(workspaceId) ?? []) {

Check warning on line 37 in src/browser/utils/chatErrorToasts.ts

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: ?? -> ||

No unit test failed when publish had ?? -> ||. Add a test that tells them apart, or say why they are equivalent.
listener();
}
}

export function peekChatError(workspaceId: string): string | undefined {
function peekChatToast(workspaceId: string): PendingChatToast | undefined {
return pendingByWorkspace.get(workspaceId)?.[0];
}

export function peekChatError(workspaceId: string): string | undefined {
return peekChatToast(workspaceId)?.message;
}

export function dismissChatError(workspaceId: string, message: string): void {
const pending = pendingByWorkspace.get(workspaceId);
const index = pending?.indexOf(message) ?? -1;
const index = pending?.findIndex((toast) => toast.message === message) ?? -1;

Check warning on line 52 in src/browser/utils/chatErrorToasts.ts

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: ?. -> .

No unit test failed when dismissChatError had ?. -> .. Add a test that tells them apart, or say why they are equivalent.

Check warning on line 52 in src/browser/utils/chatErrorToasts.ts

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: 1 -> 0

No unit test failed when dismissChatError had 1 -> 0. Add a test that tells them apart, or say why they are equivalent.

Check warning on line 52 in src/browser/utils/chatErrorToasts.ts

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: delete -

No unit test failed when dismissChatError had delete -. Add a test that tells them apart, or say why they are equivalent.
if (pending == null || index < 0) return;
pending.splice(index, 1);
if (pending.length === 0) pendingByWorkspace.delete(workspaceId);
Expand All @@ -40,7 +65,7 @@
export function useChatErrorToasts(
workspaceId: string | null,
visibleToastMessage: string | null,
pushToast: (toast: { type: "error"; message: string }) => void
pushToast: (toast: PendingChatToast) => void
): void {
const pushedRef = useRef<{ message: string; displayed: boolean } | null>(null);
useEffect(() => {
Expand All @@ -56,18 +81,18 @@
pushedRef.current = null;
const showNext = () => {
if (pushedRef.current != null) return;
const message = peekChatError(workspaceId);
if (message == null) return;
pushedRef.current = { message, displayed: false };
pushToast({ type: "error", message });
const next = peekChatToast(workspaceId);
if (next == null) return;
pushedRef.current = { message: next.message, displayed: false };
pushToast(next);
};
const listeners = listenersByWorkspace.get(workspaceId) ?? new Set<() => void>();

Check warning on line 89 in src/browser/utils/chatErrorToasts.ts

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: ?? -> ||

No unit test failed when useChatErrorToasts had ?? -> ||. Add a test that tells them apart, or say why they are equivalent.
listenersByWorkspace.set(workspaceId, listeners);
listeners.add(showNext);
showNext();
return () => {
listeners.delete(showNext);
if (listeners.size === 0) {

Check warning on line 95 in src/browser/utils/chatErrorToasts.ts

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: === -> !==

No unit test failed when useChatErrorToasts had === -> !==. Add a test that tells them apart, or say why they are equivalent.

Check warning on line 95 in src/browser/utils/chatErrorToasts.ts

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: 0 -> 1

No unit test failed when useChatErrorToasts had 0 -> 1. Add a test that tells them apart, or say why they are equivalent.
listenersByWorkspace.delete(workspaceId);
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,36 @@ describe("applyWorkspaceChatEventToAggregator", () => {
expect(peekChatError("ws-notice")).toBeUndefined();
});

test("a continuation notice (info) replaces the one still waiting, unlike a warning", () => {
const notice = (message: string, severity?: "info"): WorkspaceChatMessage => ({
type: "plugin-hook-notice",
workspaceId: "ws-info-notice",
plugin: "ralph",
message,
...(severity != null ? { severity } : {}),
});
const aggregator = new StubAggregator();

applyWorkspaceChatEventToAggregator(
aggregator,
notice("plugin continued turn 1 of 50", "info")
);
applyWorkspaceChatEventToAggregator(
aggregator,
notice("plugin continued turn 2 of 50", "info")
);
expect(peekChatError("ws-info-notice")).toBe("Plugin ralph: plugin continued turn 2 of 50");
dismissChatError("ws-info-notice", "Plugin ralph: plugin continued turn 2 of 50");
expect(peekChatError("ws-info-notice")).toBeUndefined();

applyWorkspaceChatEventToAggregator(aggregator, notice("first warning"));
applyWorkspaceChatEventToAggregator(aggregator, notice("second warning"));
expect(peekChatError("ws-info-notice")).toBe("Plugin ralph: first warning");
dismissChatError("ws-info-notice", "Plugin ralph: first warning");
expect(peekChatError("ws-info-notice")).toBe("Plugin ralph: second warning");
dismissChatError("ws-info-notice", "Plugin ralph: second warning");
});

test("a long plugin hook notice is cut to a toast-safe length", () => {
const long = "x".repeat(16 * 1024);
applyWorkspaceChatEventToAggregator(new StubAggregator(), {
Expand Down
20 changes: 13 additions & 7 deletions src/browser/utils/messages/applyWorkspaceChatEventToAggregator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import assert from "@/common/utils/assert";
import { CUSTOM_EVENTS } from "@/common/constants/events";
import { publishChatError } from "@/browser/utils/chatErrorToasts";
import type { DeleteMessage, StreamErrorMessage, WorkspaceChatMessage } from "@/common/orpc/types";
import { publishChatError, publishChatInfo } from "@/browser/utils/chatErrorToasts";
import type {
DeleteMessage,
PluginHookNoticeEvent,
StreamErrorMessage,
WorkspaceChatMessage,
} from "@/common/orpc/types";
import {
isBashOutputEvent,
isCaughtUpMessage,
Expand Down Expand Up @@ -126,14 +131,19 @@
return `${Array.from(message).slice(0, PLUGIN_HOOK_NOTICE_MAX_CHARS).join("").trimEnd()}…`;
}

function publishPluginHookNotice(event: PluginHookNoticeEvent): void {
const publish = event.severity === "info" ? publishChatInfo : publishChatError;
publish(event.workspaceId, `Plugin ${event.plugin}: ${boundPluginHookNotice(event.message)}`);
}

export function applyWorkspaceChatEventToAggregator(
aggregator: WorkspaceChatEventAggregator,
event: WorkspaceChatMessage,
options?: ApplyWorkspaceChatEventToAggregatorOptions
): WorkspaceChatEventUpdateHint {
assert(aggregator, "applyWorkspaceChatEventToAggregator requires aggregator");
assert(
event && typeof event === "object",

Check warning on line 146 in src/browser/utils/messages/applyWorkspaceChatEventToAggregator.ts

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: && -> ||

No unit test failed when applyWorkspaceChatEventToAggregator had && -> ||. Add a test that tells them apart, or say why they are equivalent.
"applyWorkspaceChatEventToAggregator requires event object"
);

Expand Down Expand Up @@ -190,7 +200,7 @@
aggregator.handleToolCallEnd(event);

if (
allowSideEffects &&

Check warning on line 203 in src/browser/utils/messages/applyWorkspaceChatEventToAggregator.ts

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: && -> ||

No unit test failed when applyWorkspaceChatEventToAggregator had && -> ||. Add a test that tells them apart, or say why they are equivalent.
event.replay !== true &&
(event.toolName === "agent_skill_read" ||
event.toolName === "agent_skill_list" ||
Expand All @@ -215,11 +225,7 @@

if (isPluginHookNoticeEvent(event)) {
// A plugin hook's systemMessage: a toast for the user, never a transcript row.
if (allowSideEffects)
publishChatError(
event.workspaceId,
`Plugin ${event.plugin}: ${boundPluginHookNotice(event.message)}`
);
if (allowSideEffects) publishPluginHookNotice(event);
return "ignored";
}

Expand Down
5 changes: 5 additions & 0 deletions src/common/orpc/schemas/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -700,6 +700,11 @@ export const PluginHookNoticeEventSchema = z.object({
workspaceId: z.string(),
plugin: z.string(),
message: z.string(),
/**
* `info`: a routine notice (a Stop continuation), shown as an info toast that a newer one replaces
* while it waits. Absent: a hook's systemMessage, shown as an error toast.
*/
severity: z.literal("info").optional(),
});

/** Wire shape of ArtifactInteractionMetadata (Artifacts M5b), for queued-message projections. */
Expand Down
5 changes: 5 additions & 0 deletions src/constants/pluginHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
export const HOOK_DEFAULT_TIMEOUT_SECONDS = 10;
export const HOOK_MAX_TIMEOUT_SECONDS = 30;

/** A Stop hook without its own `loop_limit` continues one user turn at most this many times. */
export const MAX_STOP_HOOK_CONTINUATIONS = 3;
/** Stop-hook continuations of one user turn, all hooks together, even with `loop_limit: null`. */
export const MAX_PLUGIN_CONTINUATIONS_PER_USER_TURN = 50;

/** The timeout a hook call runs with: its declared timeout (or the default), capped. */
export function effectiveHookTimeoutSeconds(declaredSeconds: number | undefined): number {
return Math.min(declaredSeconds ?? HOOK_DEFAULT_TIMEOUT_SECONDS, HOOK_MAX_TIMEOUT_SECONDS);
Expand Down
Loading
Loading