Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/plugin-authoring-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ Each line is the main call. Read the types for every field.
| `decisions` | Typed judgments about text | `await ctx.decisions.decide({ state, questions, community })`. It never rejects. |
| `browser` | An embedded website (macOS) | `ctx.browser.View` inside a panel |
| `notices` (optional) | A notice on any page, with up to three buttons | `await ctx.reflect.get("notices")?.show({ title, description?, actions? }, { signal? })` resolves with the picked action's `id`, or `undefined` if dismissed or aborted. Proceed only on an allow `id`. Pass a tool call's `client.signal` to ask the owner before it runs. |
| `ui` (optional) | The host's own controls | `Button`, `Input`, `Field`, `Switch`, `Dialog`. Fall back to plain elements when missing. |
| `ui` (optional) | The host's own controls | `Button`, `Input`, `Field`, `Switch`, `Dialog`, and `Menu` (newer hosts: check `ui.Menu`). `Menu` takes `items` (`label`, `onSelect`, `tone: "destructive"`, `disabled`), a `label` or `aria-label`, `icon` and `align`. Fall back to plain elements when missing. |
| `host` | Commands, HTTPS, processes, files | Needs `manifest.host`, below |

Agent tool names match `/^[a-z][a-z0-9_]{0,63}$/` and are unique across plugins; prefix them with your plugin. Changing a tool's name, description or schema restarts some agent sessions. `addInstructions` text is sent on every turn, so keep it short.
Expand Down Expand Up @@ -136,7 +136,7 @@ Other grants (`mcp`, `managedFiles`, `publicImages`, `publicPages`, `agentHooks`
## UI

- The host supplies the shell, navigation, error boundaries, and the outer surface of panels and Settings. Don't add your own page frame, overlays, global styles or theme. Panels sit in a host card, so render only the body. Pages own their padding and scrolling.
- Use the `ui` controls for buttons, fields, switches and dialogs. Use `className="ui-card"` for a card, `var(--space-panel-inset)` and `var(--space-2)` for spacing, and inline styles for layout. Plain `h1`–`h3`, `p` and `button` get host styling.
- Use the `ui` controls for buttons, fields, switches, dialogs and action menus. Use `className="ui-card"` for a card, `var(--space-panel-inset)` and `var(--space-2)` for spacing, and inline styles for layout. Plain `h1`–`h3`, `p` and `button` get host styling.
- Use host color tokens (`var(--...)`) so light and dark themes both work. Rely only on the `core` roles in `src/shared/design-system/tokens/registry.ts`; other custom properties, classes and `data-*` attributes are internal.
- Avoid fixed widths; pages can be narrow.
- For `ctx.agents.ui.Transcript`, set `endedAt` on a finished turn, or supply `outcome` if its end time is unknown. Use `at: 0` for an unknown item timestamp. Omit `completedAt` when a tool's start time is unknown.
Expand Down
2 changes: 1 addition & 1 deletion examples/plugins/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ All example plugins live here with `manifest.json` and prebuilt `plugin.js` file
- `shortcut-counter`: offline keyboard-shortcut consumer; Command+Shift+G /
Control+Shift+G increments through the injected host service. Requires `shortcuts`.
- `broken-page`: intentionally fails when its page renders to exercise error handling.
- `host-controls`: offline switch and name dialog built from the host's `ui` controls, with a
- `host-controls`: offline switch, name dialog and actions menu built from the host's `ui` controls, with a
notice on hosts without them.

## Try the offline playgrounds
Expand Down
21 changes: 20 additions & 1 deletion examples/plugins/host-controls/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,26 @@ export function apply(ctx) {
checked: alerts,
onCheckedChange: setAlerts,
}),
h(ui.Button, { variant: "prominent", onClick: edit }, "Edit name"),
h(
"div",
{ style: { display: "flex", gap: "var(--space-2)" } },
h(ui.Button, { variant: "prominent", onClick: edit }, "Edit name"),
// Newer hosts only; the Edit button still works without it.
ui.Menu &&
h(ui.Menu, {
"aria-label": "Name actions",
items: [
{ label: "Edit name", onSelect: edit },
{ label: "Use “Ada”", onSelect: () => setName("Ada") },
{
label: "Clear name",
tone: "destructive",
disabled: !name,
onSelect: () => setName(""),
},
],
}),
),
h(
ui.Dialog,
{
Expand Down
31 changes: 31 additions & 0 deletions src/features/plugin-ui/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,43 @@ export type PluginDialogProps = Readonly<{
preventClose?: boolean | undefined;
}>;

export type PluginMenuItem = Readonly<{
/** Unique within the menu. Typeahead matches it. */
label: string;
/** Called with no arguments. The menu closes, so it can open a `Dialog`. */
onSelect: () => void;
/** Default `default`. `destructive` is for an item that deletes or discards. */
tone?: "default" | "destructive" | undefined;
disabled?: boolean | undefined;
}>;

/**
* An action menu on its own trigger. The host owns the popup above clipping
* containers, highlight, arrow keys, typeahead, Escape and focus return.
*/
export type PluginMenuProps = Readonly<
{
items: readonly PluginMenuItem[];
/** Shown before `label`, or alone. Default the host's More icon. */
icon?: ReactElement | undefined;
disabled?: boolean | undefined;
/** Default `start`. `end` lines the menu up with the trigger's end edge. */
align?: "start" | "end" | undefined;
} & (
| { label: string; "aria-label"?: string | undefined }
/** Without a visible `label`, the trigger is an icon button with this name and hint. */
| { label?: undefined; "aria-label": string }
)
>;

export type PluginUi = Readonly<{
Button: (props: PluginButtonProps) => ReactElement;
Input: (props: PluginInputProps) => ReactElement;
Field: (props: PluginFieldProps) => ReactElement;
Switch: (props: PluginSwitchProps) => ReactElement;
Dialog: (props: PluginDialogProps) => ReactElement;
/** Absent on hosts from before it was added; fall back when it is missing. */
Menu?: ((props: PluginMenuProps) => ReactElement) | undefined;
}>;

declare module "@deepseek-ai/cordis" {
Expand Down
95 changes: 95 additions & 0 deletions src/features/plugin-ui/service.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import { pluginUi } from "./service";

afterEach(cleanup);

const fail = (message: string): never => {
throw new Error(message);
};

/** Reads `ui` the way a plugin does: optionally, from its own context. */
async function readUi(host: Context) {
let ui: PluginUi | undefined;
Expand Down Expand Up @@ -168,6 +172,83 @@ it("lets a plugin build a form in a dialog from host controls", async () => {
await vi.waitFor(() => expect(document.body.style.overflowY).toBe(""));
});

it("lets a plugin offer actions in a host menu that leads to a dialog", async () => {
const { Dialog, Button } = pluginUi;
const Menu = pluginUi.Menu ?? fail("Menu was not provided");
const snoozed = vi.fn();
const user = userEvent.setup();
function Card() {
const [confirming, setConfirming] = useState(false);
return h(
// A card that clips its overflow, like a scrolling sheet.
"article",
{ "data-testid": "card", style: { overflow: "hidden", height: 24 } },
h(Menu, {
"aria-label": "More",
align: "end",
items: [
{ label: "Snooze", onSelect: snoozed },
{ label: "Archive", onSelect: snoozed, disabled: true },
{
label: "Dismiss without answering",
tone: "destructive",
onSelect: () => setConfirming(true),
},
],
}),
h(
Dialog,
{
open: confirming,
onOpenChange: setConfirming,
title: "Dismiss item?",
actions: h(Button, { onClick: () => setConfirming(false) }, "Cancel"),
},
"The agent will see you chose not to answer.",
),
);
}
render(h(Card));
const trigger = screen.getByRole("button", { name: "More" });

// Keyboard: open, move with the arrows, and choose by typeahead.
trigger.focus();
await user.keyboard("{Enter}");
const menu = await screen.findByRole("menu", { name: "More" });
// Rendered outside the card, so the card's overflow cannot clip it.
expect(screen.getByTestId("card")).not.toContainElement(menu);
const item = (name: string) => screen.getByRole("menuitem", { name });
await vi.waitFor(() => expect(item("Snooze")).toHaveFocus());
await user.keyboard("{ArrowDown}");
await vi.waitFor(() => expect(item("Snooze")).not.toHaveFocus());
await user.keyboard("s");
await vi.waitFor(() => expect(item("Snooze")).toHaveFocus());
// A disabled item does nothing and keeps the menu open.
await user.click(item("Archive"));
expect(snoozed).not.toHaveBeenCalled();
expect(menu).toBeInTheDocument();
await user.keyboard("s");
await vi.waitFor(() => expect(item("Snooze")).toHaveFocus());
await user.keyboard("{Enter}");
expect(snoozed).toHaveBeenCalledExactlyOnceWith();
await vi.waitFor(() => expect(screen.queryByRole("menu")).toBeNull());
expect(trigger).toHaveFocus();

// A destructive item opens a confirmation; Escape returns to the trigger.
await user.click(trigger);
await user.click(
await screen.findByRole("menuitem", { name: "Dismiss without answering" }),
);
await screen.findByRole("dialog", { name: "Dismiss item?" });
await vi.waitFor(() =>
expect(screen.getByRole("button", { name: "Cancel" })).toHaveFocus(),
);
await user.keyboard("{Escape}");
await vi.waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
expect(screen.queryByRole("menu")).toBeNull();
expect(trigger).toHaveFocus();
});

it("treats plain-JS values of the wrong type as absent", async () => {
const loose = pluginUi as unknown as Record<
keyof PluginUi,
Expand All @@ -182,6 +263,15 @@ it("treats plain-JS values of the wrong type as absent", async () => {
h(loose.Input, { "aria-label": "Name", disabled: 1, maxLength: "4" }),
h(loose.Switch, { label: "Alerts", disabled: 1, checked: "yes" }),
h(loose.Switch, { label: null, "aria-label": "Sync" }),
h(loose.Menu, {
label: "Actions",
icon: "x",
items: [
null,
{ label: 5 },
{ label: "Go", onSelect: "x", disabled: 1 },
],
}),
),
);
const go = screen.getByRole("button", { name: "Go" });
Expand All @@ -194,4 +284,9 @@ it("treats plain-JS values of the wrong type as absent", async () => {
expect(alerts).not.toHaveAttribute("aria-disabled");
expect(alerts).not.toBeChecked();
expect(screen.getByRole("switch", { name: "Sync" })).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Actions" }));
const item = await screen.findByRole("menuitem");
expect(item).toHaveAccessibleName("Go");
expect(item).not.toHaveAttribute("aria-disabled");
await user.click(item);
});
70 changes: 69 additions & 1 deletion src/features/plugin-ui/service.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
// Hands plugins the host's own controls. Each wrapper forwards only the props in
// `contract.ts`, so plugins (usually plain JS) cannot come to depend on internal
// variants or on Base UI's event details.
import { type RefObject, useRef } from "react";
import { isValidElement, type RefObject, useRef } from "react";
import { DotsThreeIcon } from "../../shared/design-system/icons";
import { Button } from "../../shared/design-system/ui/Button";
import { Dialog } from "../../shared/design-system/ui/Dialog";
import { Field } from "../../shared/design-system/ui/Field";
import { IconButton } from "../../shared/design-system/ui/IconButton";
import { Input } from "../../shared/design-system/ui/Input";
import {
MenuItem,
MenuPopup,
MenuRoot,
MenuTrigger,
} from "../../shared/design-system/ui/Menu";
import { Switch } from "../../shared/design-system/ui/Switch";
import type {
PluginButtonProps,
PluginDialogProps,
PluginFieldProps,
PluginInputProps,
PluginMenuProps,
PluginSwitchProps,
PluginUi,
} from "./contract";
Expand Down Expand Up @@ -177,4 +186,63 @@ export const pluginUi: PluginUi = Object.freeze({
</Dialog>
);
},
Menu: (props: PluginMenuProps) => {
const label = str(props.label);
const name = str(props["aria-label"]);
const disabled = props.disabled === true;
const icon = isValidElement(props.icon) ? props.icon : undefined;
const items = Array.isArray(props.items) ? props.items : [];
return (
<MenuRoot>
<MenuTrigger
render={
label === undefined ? (
<IconButton
aria-label={name ?? ""}
title={name}
icon={icon ?? <DotsThreeIcon size={16} aria-hidden="true" />}
disabled={disabled}
/>
) : (
<Button
variant="ghost"
size="sm"
aria-label={name}
disabled={disabled}
>
{icon}
{label}
</Button>
)
}
/>
<MenuPopup
size="compact"
align={oneOf(props.align, ["start", "end"]) ?? "start"}
aria-label={name ?? label}
>
{items.map((item: unknown) => {
if (typeof item !== "object" || item === null) return null;
const { label, onSelect, tone, disabled } = item as Record<
string,
unknown
>;
const text = str(label);
const select = fn(onSelect);
if (text === undefined) return null;
return (
<MenuItem
key={text}
tone={tone === "destructive" ? "danger" : "default"}
disabled={disabled === true}
onClick={select && (() => select())}
>
{text}
</MenuItem>
);
})}
</MenuPopup>
</MenuRoot>
);
},
});
5 changes: 5 additions & 0 deletions src/plugins/author.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ export function apply(ctx: Context) {
void createElement(ui.Switch, { label: "Alerts", onCheckedChange: (checked: boolean) => void checked });
// @ts-expect-error Internal and legacy variants are not part of the plugin contract.
void createElement(ui.Button, { variant: "glass", children: "Glass" });
// @ts-expect-error Menu is missing on hosts from before it was added and must be checked.
void createElement(ui.Menu, { "aria-label": "More", items: [] });
if (ui.Menu)
void createElement(ui.Menu, { "aria-label": "More", align: "end",
items: [{ label: "Dismiss", tone: "destructive", onSelect: () => {} }] });
}
const unread: UnreadCapability = ctx.relay.snapshot().session.unread;
const conversations: ReturnType<UnreadCapability["inbox"]> = unread.inbox();
Expand Down
2 changes: 2 additions & 0 deletions src/plugins/author.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export type {
PluginDialogProps,
PluginFieldProps,
PluginInputProps,
PluginMenuItem,
PluginMenuProps,
PluginSwitchProps,
PluginUi,
} from "../features/plugin-ui/contract";
Expand Down
Loading