diff --git a/docs/buzz-help.md b/docs/buzz-help.md index dc25305f43..f6731c720f 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -2332,5 +2332,6 @@ Plugins can add actions to your avatar menu. Profile-related actions may appear Desktop toast notifications appear at the top right, 12px from the top on Mac and below the app headers on Windows/Linux. Hover the stack to expand it and pause timed notifications; F6 focuses notifications for keyboard access. Tab and Shift+Tab also expand the stack, which stays expanded while it -contains keyboard focus. Dismissible notices show their close button on hover or keyboard focus. +contains keyboard focus. While a dialog such as Settings is open, F6 reaches a +plugin's notice that asks you to choose, and F6 again returns to the dialog. Dismissible notices show their close button on hover or keyboard focus. Recovery notices remain until resolved or dismissed where allowed. diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 7dc4ad38e7..5568656165 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -1139,11 +1139,15 @@ lowercase and cannot be a Buzz tool's. The tool is removed when its plugin's scope ends, so safe mode removes installed plugins' tools. `call(client, context, args)` can read `client.signal`, a host-owned -`AbortSignal` captured for that call. Native Claude, Codex and Goose cancel it on -Stop. Goose captures the current ACP work burst: steers share its signal, and +`AbortSignal` captured for that call. Native Claude, Codex, Goose and Pi cancel it on +Stop. Claude and Codex also cancel it when the turn that made the call ends, +whether it finished or failed. A Codex watch or timer run doesn't: its calls +aren't cancelled when the run ends. Goose captures the current ACP work burst: steers share its signal, and Stop, eligible final-message settlement, normal completion, failure or session close abort it. Calls before a Goose session starts work or while idle receive an aborted -signal; agent retirement also aborts captured calls. Keep that exact signal across waits. Pass it to work that supports +signal; agent retirement also aborts captured calls. An external MCP connection cancels it when the app sends +`notifications/cancelled` for that call, or when the connection closes. A +harness built on `ctx.agents.harness` gives none. Keep that exact signal across waits. Pass it to work that supports cancellation, then call `signal.throwIfAborted()` before an external write. A new turn does not restore a canceled call. The supplied client also checks cancellation before it publishes. Stop cannot undo a write already sent. @@ -1941,6 +1945,78 @@ flow while `.shell-header` has `data-compact-pages`), `.shell-body`, and the outermost `.panel` elements inside it (nested panels are content). On macOS the native window controls sit in the header's leading inset, outside these roles. +### Shell notices + +A plugin can show a notice in the app's notice stack, on whatever page the +person is on, with `ctx.reflect.get("notices")`. It is `undefined` on older +hosts. It needs no manifest grant, since a notice is only UI. Do not list it +in `inject`: `apply` would then never run on a host without it. + +`show(content, { signal })` takes a `title`, an optional `description`, and at +most three `actions`, each `{ id, label, prominent? }` with its own `id`. It +resolves once the notice closes: with the `id` of the action the person +picked, or `undefined` when they dismissed it (its Dismiss button, Escape or a +sideways swipe), `signal` aborted or the plugin's scope ended. To take a +notice down, abort its `signal`. A signal that has already aborted shows +nothing. It rejects a notice with an empty title, more than three actions, +two actions with one `id`, or an action without a label. + +The host owns placement, stacking, the Dismiss button and naming the plugin: +below the words it shows "From" and the name in the plugin's manifest. The +buttons keep the order of `actions`. Each is a default button, and +`prominent` makes one the prominent button, so mark one at most. The title and +description have no length limit, and the host neither cuts nor rejects long +text: it wraps, breaking long words anywhere, and the expanded notice stack +scrolls within the window's height, so the buttons stay reachable. The plugin +owns everything it says and what each action means. Name the agent and the +action in the title. + +A tool can ask the owner before it runs. Pass the call's `client.signal`, so +the notice goes away when the call is cancelled, which includes the end of its +turn where the harness cancels calls then (see `client.signal` above). Proceed only +on an allow `id`: Dismiss, Escape and an aborted signal all resolve +`undefined`. Keep any policy, such as Always allow, in the plugin: + +```js +ctx.agents.addTool({ + name: "notes_clear", + description: "Clear this plugin's saved notes, once the owner allows it.", + inputSchema: { type: "object" }, + async call(client) { + const always = "example.notes.always-clear"; + if (localStorage.getItem(always) !== "yes") { + const notices = ctx.reflect.get("notices"); + if (!notices) throw new Error("This Buzz can't ask the owner first"); + const agent = ctx.agents + .snapshot() + .running.find((item) => item.key === client.key); + const answer = await notices.show( + { + title: `Let ${agent?.name ?? "your agent"} clear your notes?`, + actions: [ + { id: "once", label: "Allow once", prominent: true }, + { id: "always", label: "Always allow" }, + { id: "deny", label: "Deny" }, + ], + }, + { signal: client.signal }, + ); + client.signal?.throwIfAborted(); + if (answer !== "once" && answer !== "always") + throw new Error("The owner did not allow this"); + if (answer === "always") localStorage.setItem(always, "yes"); + } + localStorage.removeItem("example.notes"); + return "Cleared the notes"; + }, +}); +``` + +A throw is a tool error for the agent, so Deny and Dismiss both refuse the +call. The plugin decides how many asks may wait, whether Always allow also +answers the others waiting, and where the owner can take Always allow back, +such as its Settings card. + ### Discovery metadata Plugin manifests may include display-only discovery metadata: diff --git a/docs/plugin-authoring-guide.md b/docs/plugin-authoring-guide.md index 29c771c34c..4c76405ab2 100644 --- a/docs/plugin-authoring-guide.md +++ b/docs/plugin-authoring-guide.md @@ -46,7 +46,7 @@ export function apply(ctx) { - Plugin `id`: starts with a lowercase letter, then lowercase letters, digits, `.` and `-` only, at most 80 bytes, no empty segments (no `..`, `-.`, trailing `.`). No underscores. Ids of bundled plugins are reserved. `name`: 1-80 bytes. Updates match on `id`. - Contribution ids (page, panel, shortcut, settings card, sidebar section and its actions): `/^[a-z0-9][a-z0-9._-]*$/`, unique within the plugin. Hosts add the plugin identity, so ids are local. - Module evaluation must be pure: no work at top level. Do everything in `apply`. Enabled plugins activate even if their page is never opened. -- Declare every service you use in `inject` (for example `["react", "pages", "shortcuts"]`). `apply` runs only once all are available. `sidebarSections`, `subjectLift`, `pluginInstaller`, `seen` and `ui` are optional services: read them with `ctx.reflect.get("name")` (returns `undefined` on older hosts) instead of listing them in `inject`. +- Declare every service you use in `inject` (for example `["react", "pages", "shortcuts"]`). `apply` runs only once all are available. `sidebarSections`, `subjectLift`, `notices`, `pluginInstaller`, `seen` and `ui` are optional services: read them with `ctx.reflect.get("name")` (returns `undefined` on older hosts) instead of listing them in `inject`. - Own every timer, listener, subscription or process with `ctx.effect(() => { start(); return () => stop(); })`. Cleanup runs on disable, replacement and app teardown. React effects inside components clean up when the page unmounts. - Everything you register is owned by the plugin and removed when it is disabled or replaced. A `register` call that throws on invalid fields fails activation; the error appears in Settings and `plugin_status`. - React state resets when the revision changes (a reload remounts the selected page). The module is evaluated once per revision per app session, so module-level variables survive a disable and enable of the same revision. Use [Seen](plugin-architecture.md#remembering-one-time-experiences) to remember a one-time experience. `ctx.artifactStorage` is a structured IndexedDB store for synced artifacts. @@ -62,7 +62,7 @@ export function apply(ctx) { | `settingsCards` | A Settings destination | `ctx.settingsCards.register({ id, title, component, group?, personal?, identityRow? })`. `component` receives `{ active(), community?, navigation? }`; `navigation.target.route` can carry bounded, versioned presentation data for the card. Opening a route must never submit an operation. Optional `identityRow` receives `{ active() }` and contributes a compact account-status link inside Identity. Reuse the plugin’s existing session; check `active()` before navigation or an action. The row retires with its owning registration. Omit `icon` (it is a host icon component). The host supplies navigation and the content column, not a heading. | | `sidebarSections` (optional) | A section in the Team sidebar | `ctx.reflect.get("sidebarSections")?.register({ version: 1, id, title, icon, rows: { snapshot, subscribe }, select, actions? })`. `snapshot()` returns a stable array of `{ id, label, icon?, badge?, count?, status? }` until data changes, then notify subscribers. `select(row)` returns an open target such as `{ version: 1, kind: "home" }`. Actions: `{ id, label, icon: ReactElement, onSelect }`. | | `conversation` | Composer/message UI | `registerAccessory({ id, title, component, order?, placement? })` (read-only UI above the composer; props `{ session, scope, channelId, threadRootId?, canOpen, open, onFocusedRemoval? }`; `placement`: `"composer"`, `"message"`, `"response"`; see [Composer accessories](plugin-architecture.md#composer-accessories)). `registerSendGate({ id, hold })` holds or refuses a message the composer is about to publish, and `publish(session, message)` publishes a held one later; see [Send gates](plugin-architecture.md#send-gates). `registerMessage({ id, title, matches(message), component })`, `registerMessageAction({ id, title, matches(message, session), component })`, `registerIdentityMark({ id, title, component })` (presentation after a person's name in @mention suggestions; props `{ pubkey, profiles }`, where `profiles.snapshot().get(pubkey)?.verified` carries community verification), `registerLink({ id, title, matches(url), component })`, `registerLinkPreview({ id, title, matches(url), order?, component })` (a card below the message for one of its HTTPS links; props `{ url, messageId, open, opener }`, where `opener` opens other targets such as your panel; lowest `order` wins, so claim your URLs below the default web card's `100`), `registerTool({ id, title, component })`. | -| `agents` | Tools and hooks for agents | `ctx.agents.addTool({ name, description, inputSchema, call })`. `name` matches `/^[a-z][a-z0-9_]{0,63}$/`, is unique across plugins and not a Buzz tool name (prefix it with your plugin: `notes_get`). `inputSchema` is a JSON-serializable object with `type: "object"`. `async call(client, context, args)` resolves to a string (or `{ data, type, text? }`) and runs as the agent; a throw is shown to the agent as a tool error. Changing a tool's name, description or schema restarts some agent sessions, so edit deliberately. `ctx.agents.addInstructions({ id, text, when? })` gives every turn of the agents this copy runs, or those `when(agent)` accepts, a `` section with `text` (at most 4096 UTF-8 bytes after trimming); it is sent with every turn, so keep it short. `ctx.agents.registerHook({ id, harness, event, run })` needs `host.agentHooks`. `ctx.agents.wake(agentKey, { channel, root?, topLevel?, text })` wakes a local agent (`root` is a 64-hex event id; `topLevel: true` instead wakes it at a channel's top level). With `host.files`, `ctx.agents.assignConversationFolder(agentKey, { channelId, root? }, path)` gives one conversation of a local Claude, Codex, Goose or Pi agent its own working folder before its first turn; see [Agents](agents.md). `ctx.agents.setConversationInstructions(agentKey, { channelId, root? }, text)` gives a local agent standing instructions in one conversation, shown on each of its turns there in an `` section (at most 8192 UTF-8 bytes after trimming; `""` clears them); `ctx.agents.conversationInstructions(agentKey, place)` resolves with the text. With `host.agentPromptSections`, `ctx.agents.setConversationSections(agentKey, { channelId, root? }, { "working-location": text })` replaces declared sections of a local Claude, Codex, Goose or Pi agent's base instructions in one conversation, which your plugin then manages (each text 1 to 4096 UTF-8 bytes after trimming, the set at most 12 KiB; `{}` clears it); `ctx.agents.conversationSections(agentKey, place)` resolves with `{ text, applied, reason? }` per section, or undefined when your plugin holds none there. Check that both are functions on older hosts. | +| `agents` | Tools and hooks for agents | `ctx.agents.addTool({ name, description, inputSchema, call })`. `name` matches `/^[a-z][a-z0-9_]{0,63}$/`, is unique across plugins and not a Buzz tool name (prefix it with your plugin: `notes_get`). `inputSchema` is a JSON-serializable object with `type: "object"`. `async call(client, context, args)` resolves to a string (or `{ data, type, text? }`) and runs as the agent; a throw is shown to the agent as a tool error. Read `client.signal` to stop waiting when the call is cancelled; to ask the owner first, show a notice (below) with that signal. Changing a tool's name, description or schema restarts some agent sessions, so edit deliberately. `ctx.agents.addInstructions({ id, text, when? })` gives every turn of the agents this copy runs, or those `when(agent)` accepts, a `` section with `text` (at most 4096 UTF-8 bytes after trimming); it is sent with every turn, so keep it short. `ctx.agents.registerHook({ id, harness, event, run })` needs `host.agentHooks`. `ctx.agents.wake(agentKey, { channel, root?, topLevel?, text })` wakes a local agent (`root` is a 64-hex event id; `topLevel: true` instead wakes it at a channel's top level). With `host.files`, `ctx.agents.assignConversationFolder(agentKey, { channelId, root? }, path)` gives one conversation of a local Claude, Codex, Goose or Pi agent its own working folder before its first turn; see [Agents](agents.md). `ctx.agents.setConversationInstructions(agentKey, { channelId, root? }, text)` gives a local agent standing instructions in one conversation, shown on each of its turns there in an `` section (at most 8192 UTF-8 bytes after trimming; `""` clears them); `ctx.agents.conversationInstructions(agentKey, place)` resolves with the text. With `host.agentPromptSections`, `ctx.agents.setConversationSections(agentKey, { channelId, root? }, { "working-location": text })` replaces declared sections of a local Claude, Codex, Goose or Pi agent's base instructions in one conversation, which your plugin then manages (each text 1 to 4096 UTF-8 bytes after trimming, the set at most 12 KiB; `{}` clears it); `ctx.agents.conversationSections(agentKey, place)` resolves with `{ text, applied, reason? }` per section, or undefined when your plugin holds none there. Check that both are functions on older hosts. | | `shortcuts` | In-app key bindings | `ctx.shortcuts.register({ id, title, binding, run, when?, order?, allowInEditable?, allowInModal?, repeat? })`. `binding` is `{ key, mod?, shift?, alt?, ctrl? }` or an array; `mod` is Command on macOS, Control elsewhere. `key` is the logical key, case-insensitive (Space is `" "`). Skipped in text fields and modals unless opted in. | | `navigation` | Open destinations | `await ctx.navigation.open(target)` returns `{ status: "opened" \| "failed" \| "superseded" \| "cancelled" }`. Targets: `{ version: 1, kind: "plugin", pluginId, pageId?, params? }`, `{ version: 1, kind: "home" }`, `{ version: 1, kind: "settings", section? }`. | | `communityJoin` (optional) | Join a community the person chose in your UI | `ctx.reflect.get("communityJoin")?.open(address)` with a `wss://` or `https://` community address, for example one your plugin just created. It opens the app's join dialog, which connects at once; the person still completes admission and the profile step there, and nothing is saved before they do. An address already saved just selects that community. It returns `false` when the address is not a community origin (for example it has a path or credentials) or no identity is ready to join with (hand the address off another way), otherwise `true`; it reports no completion. Call it only from a live, user-initiated action. | @@ -72,6 +72,7 @@ export function apply(ctx) { | `seen` (optional) | One-time experiences for the current identity | Use `const seen = ctx.reflect.get("seen")`. Show a hint only when `seen?.has(key) === false`. Call `seen?.mark(key)` when the experience happens and `seen?.subscribe(listener)` to observe changes. | | `host` | Commands, HTTPS, processes, files | Requires `manifest.host` grants; see below. | | `ui` (optional) | The host's own controls | `const ui = ctx.reflect.get("ui")`, then, if `ui?.Button`, `React.createElement(ui.Button, { variant: "prominent", onClick }, "Save")`. `Button` (`variant`: `prominent`, `subtle`, `ghost`, `destructive`; `size`: `sm`, `md`; `loading`, `disabled`, `type`, `form`, `title`, `aria-label`), `Input` (`value`, `defaultValue`, `onValueChange(value)`, `type`: `text`, `password`; `placeholder`, `name`, `id`, `disabled`, `readOnly`, `maxLength`, `aria-label`), `Field` (`label`, `description?`, `error?`, `optional?`; labels the one `Input` inside it), `Switch` (`checked`, `defaultChecked`, `onCheckedChange(checked)`, `disabled`, `name`, `id`, and `label` or `aria-label`; it applies immediately, so never put it behind Save) and `Dialog` (`open`, `onOpenChange(open)`, `title`, `description?`, `actions?`, `size`: `compact`, `default`; `dismissOnOutsideClick?`, set `false` for a form holding a draft; `preventClose?`; it opens on its first body control, else its first action, and returns focus to the opener on close). For a form, put the fields in a `form` with an `id` and give the Save action `type: "submit"` and `form` set to that `id`, so Save and Enter both submit. Validate in the submit handler and show a `Field` error after a Save attempt, not on open. Other props and values are ignored. Like other services, it is a preview. Fall back to plain host-styled elements when `ui` or a component is missing. | +| `notices` (optional) | A notice on any page, with your buttons | `const answer = await ctx.reflect.get("notices")?.show({ title, description?, actions? }, { signal? })`, with at most three actions `{ id, label, prominent? }`, shown in that order. No manifest grant. It resolves with the picked action's `id`, or `undefined` once the person dismisses it, `signal` aborts (abort it to take the notice down) or your plugin stops, so proceed only on an allow `id`. Buzz shows your plugin's name below your words; your title names the agent and the action. Long text wraps and the notice stack scrolls; nothing is cut. See the plugin architecture's Shell notices. | | `subjectLift` (optional) | Lift a message image's subject | `const lift = ctx.reflect.get("subjectLift")`. `lift?.supports(source)`, then `await lift.lift(source, signal?)` resolves a transparent PNG `File` ready for `session.emoji.upload`, or rejects with a reason. `source` is `session.media(attachment.url)`. macOS 14+ only; see the plugin architecture's Subject lift contract. | | `pluginInstaller` (optional) | Ask the owner to install another plugin, compare a listed release, check installation status, or access retained update reviews | `requestInstall(...)` resolves `"installed" \| "updated" \| "cancelled" \| "unavailable"` and never installs silently. Status and release-comparison methods are described below. `updates` is an optional, host-retained capability; see [Plugin architecture](plugin-architecture.md#plugin-installer). | @@ -422,7 +423,7 @@ show an upgrade explanation if supporting older hosts. ## Common mistakes - Adding `import ... from "react"` or any runtime import, or compiling JSX with the automatic runtime (`react/jsx-runtime`). Use `ctx.react` and classic `React.createElement`. -- Forgetting a service in `inject` (`ctx.pages` is undefined and activation fails) or listing optional services (`sidebarSections`, `subjectLift`, `pluginInstaller`, `ui`) there instead of using `ctx.reflect.get`. +- Forgetting a service in `inject` (`ctx.pages` is undefined and activation fails) or listing optional services (`sidebarSections`, `subjectLift`, `notices`, `pluginInstaller`, `ui`) there instead of using `ctx.reflect.get`. - Doing work at module top level (it must be pure) or using `ctx.react` outside `apply`. - Starting timers, listeners or subscriptions without `ctx.effect` cleanup, so they leak across reloads. - A bundler emitting several chunks, CSS, or asset files. Only one `plugin.js` is loaded. diff --git a/patches/sonner@2.0.8.patch b/patches/sonner@2.0.8.patch index e4d11f357a..e519eba101 100644 --- a/patches/sonner@2.0.8.patch +++ b/patches/sonner@2.0.8.patch @@ -131,8 +131,8 @@ index 394dbc2272f43b84642b0f9d5cc7eb1eacb0ffb3..0fcb2ea0432847dac77ef6b950139cc3 - lastFocusedElementRef.current = null; + const previous = lastFocusedElementRef.current; + lastFocusedElementRef.current = null; -+ // Tab, pointer and action-driven focus moves already have a destination. -+ if (previous && (!event.relatedTarget || event.relatedTarget === document.body)) { ++ // Tab, pointer and action-driven focus moves keep their destination unless it is hidden, as behind a modal. ++ if (previous && (!event.relatedTarget || event.relatedTarget === document.body || event.relatedTarget.closest?.('[aria-hidden="true"]'))) { + previous.focus?.({ preventScroll: true }); } } @@ -316,8 +316,8 @@ index c124f821a68f7070647a5a04441d0caa53689662..27f2fb1bed2607477a790e5d7c182b6c - lastFocusedElementRef.current = null; + const previous = lastFocusedElementRef.current; + lastFocusedElementRef.current = null; -+ // Tab, pointer and action-driven focus moves already have a destination. -+ if (previous && (!event.relatedTarget || event.relatedTarget === document.body)) { ++ // Tab, pointer and action-driven focus moves keep their destination unless it is hidden, as behind a modal. ++ if (previous && (!event.relatedTarget || event.relatedTarget === document.body || event.relatedTarget.closest?.('[aria-hidden="true"]'))) { + previous.focus?.({ preventScroll: true }); } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 224e7a06aa..1f94ecf0ed 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7,7 +7,7 @@ settings: patchedDependencies: '@base-ui/react@1.9.0': 958237d028ca73b236150c1367b09699dd0d42738be177382595af9b5fd91709 '@dnd-kit/core@6.3.1': 5574bf49bcc2d7dedd0b2b177d78447eaefecccddd2097929a7a6ecb42450623 - sonner@2.0.8: 8681d29d772a4e0298fa11354cc8c373866fe16d16368011712e7fa448db973f + sonner@2.0.8: 2de84edd37b041ac6b7a813b160a49bddd798063b4661c20c52194c929904753 virtua@0.54.2: 552a4046fabf69256b2cbe3d56d1ba6bbc6574134168c763b0c60c01e0620642 importers: @@ -166,7 +166,7 @@ importers: version: 4.0.1 sonner: specifier: 2.0.8 - version: 2.0.8(patch_hash=8681d29d772a4e0298fa11354cc8c373866fe16d16368011712e7fa448db973f)(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) + version: 2.0.8(patch_hash=2de84edd37b041ac6b7a813b160a49bddd798063b4661c20c52194c929904753)(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) virtua: specifier: 0.54.2 version: 0.54.2(patch_hash=552a4046fabf69256b2cbe3d56d1ba6bbc6574134168c763b0c60c01e0620642)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) @@ -4257,7 +4257,7 @@ snapshots: signal-exit@4.1.0: {} - sonner@2.0.8(patch_hash=8681d29d772a4e0298fa11354cc8c373866fe16d16368011712e7fa448db973f)(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8): + sonner@2.0.8(patch_hash=2de84edd37b041ac6b7a813b160a49bddd798063b4661c20c52194c929904753)(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8): dependencies: react: 19.2.8 react-dom: 19.2.8(react@19.2.8) diff --git a/src/app/App.tsx b/src/app/App.tsx index 305ee9cfaa..a8c2cce4d4 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -36,6 +36,7 @@ import { UpdateReview } from "../bundled/agents/UpdateReview"; import { TeamUpdateReview } from "../bundled/agents/TeamUpdateReview"; import { AppOverlays } from "../features/pages/AppOverlays"; import { InterruptedNotice } from "../features/agents/InterruptedNotice"; +import { ShellNotices } from "../features/notices/ShellNotices"; import { useCallback, useEffect, @@ -831,6 +832,7 @@ function ConnectedAppContent({ services }: { services: AppServices }) { relay={services.relay} /> + diff --git a/src/app/services.ts b/src/app/services.ts index cd08a3ea3f..4e1643c9ac 100644 --- a/src/app/services.ts +++ b/src/app/services.ts @@ -64,6 +64,7 @@ import { import { createUpdates } from "../features/updates/updates"; import { PanelsService } from "../features/panels/service"; import { BackdropsService } from "../features/backdrops/service"; +import { NoticesService } from "../features/notices/service"; import { SubjectLiftService } from "../features/messages/subject-lift"; import { pluginUi } from "../features/plugin-ui/service"; import { Context } from "@deepseek-ai/cordis"; @@ -129,6 +130,7 @@ export function createServices() { const sidebarRows = new SidebarRowsService(ctx); const panels = new PanelsService(ctx); const backdrops = new BackdropsService(ctx); + const notices = new NoticesService(ctx); new SubjectLiftService(ctx); ctx.provide("ui", pluginUi); const accountActions = new AccountActionsService(ctx); @@ -464,6 +466,7 @@ export function createServices() { sidebarRows, panels, backdrops, + notices, plugins, federatedIdentity, firstRunFederatedIdentity, diff --git a/src/bundled/claude-code/claude.test.ts b/src/bundled/claude-code/claude.test.ts index 9c3fc2df74..9f6c459aa8 100644 --- a/src/bundled/claude-code/claude.test.ts +++ b/src/bundled/claude-code/claude.test.ts @@ -5,6 +5,7 @@ import type { AgentHandle } from "../../features/agents/service"; import { ClaudeProcess, stepLabel } from "./claude"; import { backgroundTasks, + type FakeClaude, fakeSpawn, flush, sessionState, @@ -897,6 +898,125 @@ it("allows tool use and acknowledges hooks it is asked about", async () => { ]); }); +it("cancels a Buzz tool still running when its turn settles, failed or not, and serves the next turn's", async () => { + const { spawn, processes } = fakeSpawn(); + const signals: AbortSignal[] = []; + let called = () => {}; + const tools = vi.fn( + (_conversation: unknown, _message: unknown, signal: AbortSignal) => { + signals.push(signal); + called(); + return new Promise(() => {}); + }, + ); + const claude = await ClaudeProcess.start(spawn, { + ...launch, + sessionId: "s1", + tools, + }); + const fake = processes[0]; + if (!fake) throw new Error("no process"); + fake.hold = true; + const call = (id: string) => { + const reached = new Promise((resolve) => { + called = resolve; + }); + fake.emit({ + type: "control_request", + request_id: id, + request: { + subtype: "mcp_message", + server_name: "buzz", + message: { jsonrpc: "2.0", id: 3, method: "tools/call" }, + }, + }); + return reached; + }; + const taken = (text: string) => { + let submitted = () => {}; + const written = new Promise((resolve) => { + submitted = resolve; + }); + return { settled: claude.send(text, { submitted }), written }; + }; + const failed = taken("first"); + await failed.written; + await call("r1"); + expect(signals).toHaveLength(1); + expect(signals[0]?.aborted).toBe(false); + fake.finish({ error: "Credit balance is too low" }); + await expect(failed.settled).resolves.toMatchObject({ ok: false }); + expect(signals[0]?.aborted).toBe(true); + const ok = taken("second"); + await ok.written; + await call("r2"); + expect(signals).toHaveLength(2); + expect(signals[1]?.aborted).toBe(false); + fake.finish(); + await expect(ok.settled).resolves.toEqual({ ok: true }); + expect(signals[1]?.aborted).toBe(true); +}); + +it.each([ + [ + "reports its state", + (fake: FakeClaude) => sessionState(fake, "running"), + (fake: FakeClaude) => sessionState(fake, "idle"), + ], + [ + "is too old to report its state", + () => {}, + (fake: FakeClaude) => + fake.emit({ type: "result", subtype: "success", is_error: false }), + ], +])( + "cancels a Buzz tool called in a turn of its own when that turn ends, on a claude that %s", + async (_, start, end) => { + const { spawn, processes } = fakeSpawn(); + const signals: AbortSignal[] = []; + let called = () => {}; + const tools = vi.fn( + (_conversation: unknown, _message: unknown, signal: AbortSignal) => { + signals.push(signal); + called(); + return new Promise(() => {}); + }, + ); + await ClaudeProcess.start(spawn, { + ...launch, + sessionId: "s1", + tools, + }); + const fake = processes[0]; + if (!fake) throw new Error("no process"); + const call = (id: string) => { + const reached = new Promise((resolve) => { + called = resolve; + }); + fake.emit({ + type: "control_request", + request_id: id, + request: { + subtype: "mcp_message", + server_name: "buzz", + message: { jsonrpc: "2.0", id: 3, method: "tools/call" }, + }, + }); + return reached; + }; + start(fake); + await call("r1"); + expect(signals).toHaveLength(1); + expect(signals[0]?.aborted).toBe(false); + end(fake); + expect(signals[0]?.aborted).toBe(true); + start(fake); + await call("r2"); + expect(signals).toHaveLength(2); + expect(signals[1]?.aborted).toBe(false); + }, +); + it("cancels a Buzz tool that is still running when its process stops", async () => { const { spawn, processes } = fakeSpawn(); const signals: AbortSignal[] = []; diff --git a/src/bundled/claude-code/claude.ts b/src/bundled/claude-code/claude.ts index 4cd1e98e4d..19860db511 100644 --- a/src/bundled/claude-code/claude.ts +++ b/src/bundled/claude-code/claude.ts @@ -240,6 +240,7 @@ export class ClaudeProcess { * starts anew, so a stopped turn's tool calls stay stopped. */ private workLifetime = new AbortController(); private callEpoch = 0; + private turnLifetime = new AbortController(); /** The owner's Stop awaiting Claude's answer, for the work it stopped; * another Stop of that work shares it. */ private stopRequest: @@ -933,7 +934,6 @@ export class ClaudeProcess { return this.readingEffort; } private settle(settled: Settled) { - this.callEpoch++; this.pending = 0; this.receipts.clear(); this.activeReceipts.clear(); @@ -941,9 +941,15 @@ export class ClaudeProcess { this.stopping = false; this.stopped = false; this.compacting = false; + this.endTurn(); for (const resolve of this.waiters.splice(0)) resolve(settled); if (!this.alive) this.releaseIdle(); } + private endTurn() { + this.callEpoch++; + this.turnLifetime.abort(new Error("The Claude turn has ended")); + this.turnLifetime = new AbortController(); + } private readError(data: string) { this.stderr = (this.stderr + data).slice(-STDERR_LIMIT); @@ -1010,10 +1016,9 @@ export class ClaudeProcess { this.continuation = "running"; if (!this.working && (this.continuation === "running" || this.stopping)) this.continuation = undefined; - if (!this.working) this.callEpoch++; // A turn of its own, such as a background task's, is new work. if (starts) this.renew(); - if (!this.working && this.pending) this.done(); + if (!this.working) this.done(); this.edge(active); return; } @@ -1109,12 +1114,12 @@ export class ClaudeProcess { if (!this.reportsState) { const active = this.active; this.continuation = undefined; - this.callEpoch++; - if (this.pending) this.done(); + this.done(); this.edge(active); } } private done() { + if (!this.pending) return this.endTurn(); const error = this.lastError; this.settle( error @@ -1143,7 +1148,11 @@ export class ClaudeProcess { mcp_response: await this.tools( this.conversation, request.message, - AbortSignal.any([this.protectionLifetime.signal, work.signal]), + AbortSignal.any([ + this.protectionLifetime.signal, + work.signal, + this.turnLifetime.signal, + ]), () => { work.signal.throwIfAborted(); if ( diff --git a/src/buzz-mcp/external.ts b/src/buzz-mcp/external.ts index 3729234460..feccae1f58 100644 --- a/src/buzz-mcp/external.ts +++ b/src/buzz-mcp/external.ts @@ -10,6 +10,8 @@ const required = { "buzz/requiredScopes": ["agent"] }; const instructions = "Act as the agent selected by the owner in Buzz, with all of its Buzz tools. There is no current conversation: supply explicit channel or message IDs. Keys stay in Buzz. Use saved approval to restore a closed connection. Revoked or expired approval needs owner consent. Never repeat a post after a lost response. Read its destination first."; +const inflight = new WeakMap>(); + /** An approved external app acts as the selected agent: it lists and calls * the tools that agent's sessions get, plugins' included, through the same * dispatcher, without an implicit conversation. Only full-agent approval @@ -32,7 +34,14 @@ export async function respondExternal( method?: string; params?: Record; }; - if (id === undefined || id === null) return undefined; + if (id === undefined || id === null) { + if (method === "notifications/cancelled") + inflight + .get(client) + ?.get((params as { requestId?: unknown } | null)?.requestId) + ?.abort(new Error("The agent cancelled this request")); + return undefined; + } if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error("params must be an object."); const error = (message: string) => ({ @@ -83,5 +92,20 @@ export async function respondExternal( }, }, }; - return respond(client, {}, input, added(), { instructions }); + if (method !== "tools/call") + return respond(client, {}, input, added(), { instructions }); + const calls = inflight.get(client) ?? new Map(); + inflight.set(client, calls); + const cancelled = new AbortController(); + calls.set(id, cancelled); + const signal = client.signal + ? AbortSignal.any([client.signal, cancelled.signal]) + : cancelled.signal; + try { + return await respond({ ...client, signal }, {}, input, added(), { + instructions, + }); + } finally { + if (calls.get(id) === cancelled) calls.delete(id); + } } diff --git a/src/features/agents/service.test.ts b/src/features/agents/service.test.ts index 2b07c1f6ed..7c162850f2 100644 --- a/src/features/agents/service.test.ts +++ b/src/features/agents/service.test.ts @@ -125,6 +125,7 @@ import { TEAM_MOVES_KEY, TeamMoves } from "./team-migration"; import { NoTeamChannel, type TeamSent } from "./team-ops"; import { importedTeamId } from "./config-channels"; import { STANDALONE_DEADLINE_MS } from "../agent-harness/standalone"; +import { NoticesService, type ShownNotice } from "../notices/service"; import { readTeams, writeTeams, type AgentRecord } from "./store"; import { createPluginRequests } from "../../plugins/requests"; import { @@ -20980,6 +20981,8 @@ describe("full external agent access", () => { return { ...f, write, + send, + server, message, names, call: (name: string, args: object) => @@ -21064,6 +21067,126 @@ describe("full external agent access", () => { } }); + it("ends a plugin tool's wait when the agent cancels that call or the connection closes", async () => { + const f = await fixture(); + try { + const started = runnerGate(); + let waiting = 0; + const tasks = f.ctx.extend({ + pluginOwner: Object.freeze({ id: "buzz.tasks", revision: "one" }), + }); + await tasks.plugin({ + inject: ["agents"], + apply: (plugin: Context) => + plugin.agents.addTool({ + name: "tasks_wait", + description: "Wait for its call to end.", + inputSchema: { type: "object" }, + call: (client) => + new Promise((_, reject) => { + const { signal } = client; + if (!signal) reject(new Error("no signal")); + else + signal.addEventListener("abort", () => reject(signal.reason)); + if (++waiting === 2) started.resolve(); + }), + }), + }); + const wait = (id: number) => + f.send({ + id, + method: "tools/call", + params: { name: "tasks_wait", arguments: {} }, + }); + const cancel = (requestId: number) => + f.send({ method: "notifications/cancelled", params: { requestId } }); + const first = wait(101); + const second = wait(102); + await started.promise; + await cancel(999); + await cancel(101); + expect(await first).toMatchObject({ + id: 101, + result: { + isError: true, + content: [{ text: "The agent cancelled this request" }], + }, + }); + await f.server.close(); + await expect(second).rejects.toThrow("This agent connection has closed"); + } finally { + await f.cleanup(); + } + }); + + it("lets a plugin's tool wait for its owner's answer to a notice, which the agent's cancel withdraws", async () => { + const f = await fixture(); + try { + const notices = new NoticesService(f.ctx); + const files = f.ctx.extend({ + pluginOwner: Object.freeze({ id: "example.files", revision: "one" }), + }); + await files.plugin({ + inject: ["agents"], + apply: (plugin: Context) => + plugin.agents.addTool({ + name: "files_delete", + description: "Delete a file, once the owner allows it.", + inputSchema: { type: "object" }, + async call(client) { + const answer = await plugin.reflect.get("notices")?.show( + { + title: "Let Echo delete a.txt?", + actions: [{ id: "once", label: "Allow once" }], + }, + { signal: client.signal }, + ); + return `answered ${answer}`; + }, + }), + }); + const shown = () => + new Promise((resolve) => { + const stop = notices.subscribe(() => { + const [notice] = notices.snapshot(); + if (notice) { + stop(); + resolve(notice); + } + }); + }); + const asked = shown(); + const call = f.call("files_delete", {}); + const notice = await asked; + expect(notices.snapshot()).toHaveLength(1); + expect(notice).toMatchObject({ + title: "Let Echo delete a.txt?", + plugin: "example.files", + }); + notice.pick("once"); + expect((await call).result).toMatchObject({ + content: [{ text: "answered once" }], + }); + expect(notices.snapshot()).toEqual([]); + const reasked = shown(); + const cancelled = f.send({ + id: 901, + method: "tools/call", + params: { name: "files_delete", arguments: {} }, + }); + await reasked; + expect(notices.snapshot()).toHaveLength(1); + await f.send({ + method: "notifications/cancelled", + params: { requestId: 901 }, + }); + expect(notices.snapshot()).toEqual([]); + await cancelled; + } finally { + await f.cleanup(); + } + }); + it("neither lists nor runs the retired owner-read tools", async () => { vi.stubEnv("VITE_BUZZ_OWNER_MCP_COMMUNITIES", "https://relay.example.test"); const f = await fixture(["agent"], { revision: "bundled" }); diff --git a/src/features/notices/ShellNotices.test.tsx b/src/features/notices/ShellNotices.test.tsx new file mode 100644 index 0000000000..a4c0b43fa4 --- /dev/null +++ b/src/features/notices/ShellNotices.test.tsx @@ -0,0 +1,92 @@ +// @vitest-environment jsdom +import "@testing-library/jest-dom/vitest"; +import { Context } from "@deepseek-ai/cordis"; +import { + act, + cleanup, + fireEvent, + render, + screen, +} from "@testing-library/react"; +import { afterEach, expect, it } from "vitest"; +import type { PluginManager } from "../../plugins/manager"; +import type { PluginManifest } from "../../plugins/api"; +import { ToastProvider } from "../../shared/design-system/ui/Toast"; +import { NoticesService } from "./service"; +import { ShellNotices } from "./ShellNotices"; + +afterEach(cleanup); + +const manifest: PluginManifest = { + id: "example.plugin", + name: "Example drafts", + apiVersion: 1, +}; +const plugins: Pick = (() => { + const snapshot = { + configuration: { + status: "ready" as const, + catalog: { + profile: "", + location: "", + plugins: [ + { + manifest, + source: "external" as const, + enabled: true, + revision: "one", + previous: null, + reloadable: false, + error: null, + }, + ], + }, + externalPluginsPaused: false, + }, + activation: {}, + busy: false, + error: null, + refreshError: null, + }; + return { subscribe: () => () => {}, snapshot: () => snapshot }; +})(); + +it("draws a plugin's notice with its buttons and the plugin's name, and answers with the button clicked or none when dismissed", async () => { + const root = new Context(); + const notices = new NoticesService(root); + const plugin = root.extend({ + pluginOwner: { id: manifest.id, revision: "one" }, + }); + render( + + + , + ); + const content = { + title: "Publish the draft?", + actions: [ + { id: "yes", label: "Publish", prominent: true }, + { id: "no", label: "Not now" }, + ], + }; + const show = () => { + let closed: Promise | undefined; + act(() => { + closed = plugin.notices?.show(content); + }); + return closed; + }; + const picked = show(); + const notice = await screen.findByRole("dialog", { + name: "Publish the draft?", + }); + expect(notice).toHaveTextContent("From Example drafts"); + fireEvent.click(screen.getByRole("button", { name: "Not now" })); + await expect(picked).resolves.toBe("no"); + const dismissed = show(); + await screen.findByRole("dialog", { name: "Publish the draft?" }); + fireEvent.click(screen.getByRole("button", { name: "Dismiss notification" })); + await expect(dismissed).resolves.toBeUndefined(); + expect(notices.snapshot()).toEqual([]); + await root.fiber.dispose(); +}); diff --git a/src/features/notices/ShellNotices.tsx b/src/features/notices/ShellNotices.tsx new file mode 100644 index 0000000000..ed3cd9699f --- /dev/null +++ b/src/features/notices/ShellNotices.tsx @@ -0,0 +1,58 @@ +import { useSyncExternalStore } from "react"; +import type { PluginManager } from "../../plugins/manager"; +import { Button } from "../../shared/design-system/ui/Button"; +import { ToastNotice } from "../../shared/design-system/ui/Toast"; +import type { NoticesService } from "./service"; + +/** Plugins' notices, one toast each, in the order they were shown, each + * saying which plugin shows it. The person can always dismiss one; an action + * button closes it with that answer. */ +export function ShellNotices({ + notices, + plugins, +}: { + notices: NoticesService; + /** Display names come from the catalog. */ + plugins: Pick; +}) { + const shown = useSyncExternalStore(notices.subscribe, notices.snapshot); + const { configuration } = useSyncExternalStore( + plugins.subscribe, + plugins.snapshot, + ); + const name = (id: string) => + (configuration.status === "ready" + ? configuration.catalog.plugins.find( + (plugin) => plugin.manifest.id === id, + )?.manifest.name + : undefined) ?? id; + return shown.map((notice) => ( + + From {name(notice.plugin)} + + } + tone="info" + onDismiss={notice.dismiss} + reachableOverModal={!!notice.actions?.length} + > + {notice.actions?.length + ? notice.actions.map((action) => ( + + )) + : undefined} + + )); +} diff --git a/src/features/notices/service.test.ts b/src/features/notices/service.test.ts new file mode 100644 index 0000000000..618dae421f --- /dev/null +++ b/src/features/notices/service.test.ts @@ -0,0 +1,108 @@ +import { Context } from "@deepseek-ai/cordis"; +import { expect, it } from "vitest"; +import { + type NoticeContent, + NoticesService, + type ShownNotice, +} from "./service"; + +const ask: NoticeContent = { + title: "Publish the draft?", + description: "Ampy wants to publish it.", + actions: [ + { id: "yes", label: "Publish", prominent: true }, + { id: "no", label: "Not now" }, + ], +}; + +async function setup() { + const root = new Context(); + const notices = new NoticesService(root); + let plugin!: Context; + const fiber = root + .extend({ pluginOwner: { id: "example.plugin", revision: "one" } }) + .plugin((ctx: Context) => { + plugin = ctx; + }); + await fiber.await(); + const show = ( + content: NoticeContent = ask, + options?: { signal?: AbortSignal }, + ) => { + const shown = plugin.reflect.get("notices")?.show(content, options); + if (!shown) throw new Error("no notices service"); + return shown; + }; + return { root, notices, fiber, show }; +} + +it("shows a plugin's notice, named for it, until the person picks one of its actions", async () => { + const { root, notices, show } = await setup(); + const closed = show(); + expect(notices.snapshot()).toMatchObject([ + { ...ask, plugin: "example.plugin" }, + ]); + const [shown] = notices.snapshot(); + shown?.pick("missing"); + expect(notices.snapshot()).toHaveLength(1); + shown?.pick("yes"); + await expect(closed).resolves.toBe("yes"); + expect(notices.snapshot()).toEqual([]); + shown?.pick("no"); + expect(notices.snapshot()).toEqual([]); + await root.fiber.dispose(); +}); + +it.each([ + ["the person dismisses it", (n: Shown) => n.entry.dismiss()], + ["its signal aborts", (n: Shown) => n.controller.abort()], + ["the plugin's scope ends", (n: Shown) => n.fiber.dispose()], +])( + "closes without an answer when %s, and ignores a later pick", + async (_, close) => { + const { root, notices, fiber, show } = await setup(); + const controller = new AbortController(); + const closed = show(ask, { signal: controller.signal }); + const entry = notices.snapshot()[0]; + if (!entry) throw new Error("not shown"); + await close({ controller, fiber, entry }); + entry.pick("yes"); + await expect(closed).resolves.toBeUndefined(); + expect(notices.snapshot()).toEqual([]); + await root.fiber.dispose(); + }, +); +type Shown = Readonly<{ + controller: AbortController; + fiber: ReturnType; + entry: ShownNotice; +}>; + +it("never shows a notice whose signal already aborted, or one from an ended plugin", async () => { + const { root, notices, fiber, show } = await setup(); + await expect( + show(ask, { signal: AbortSignal.abort() }), + ).resolves.toBeUndefined(); + expect(notices.snapshot()).toEqual([]); + await fiber.dispose(); + await expect(show()).rejects.toThrow(); + expect(notices.snapshot()).toEqual([]); + await root.fiber.dispose(); +}); + +it("refuses a notice without a title, an anonymous caller and more than three actions", async () => { + const { root, notices, show } = await setup(); + const action = (id: string) => ({ id, label: id }); + for (const bad of [ + { title: " " }, + { title: "T", actions: ["a", "b", "c", "d"].map(action) }, + { title: "T", actions: [action("a"), action("a")] }, + { title: "T", actions: [{ id: "a", label: "" }] }, + ]) + await expect(show(bad)).rejects.toThrow("A notice needs a title"); + await expect(notices.show(ask)).rejects.toThrow( + "Notices must be shown by an installed plugin", + ); + expect(notices.snapshot()).toEqual([]); + await root.fiber.dispose(); +}); diff --git a/src/features/notices/service.ts b/src/features/notices/service.ts new file mode 100644 index 0000000000..17c4dca4a5 --- /dev/null +++ b/src/features/notices/service.ts @@ -0,0 +1,122 @@ +import { Service, type Context } from "@deepseek-ai/cordis"; + +export type NoticeAction = Readonly<{ + id: string; + label: string; + prominent?: boolean; +}>; +export type NoticeContent = Readonly<{ + title: string; + description?: string; + /** At most three buttons. Picking one closes the notice. */ + actions?: readonly NoticeAction[]; +}>; +export type Notices = Readonly<{ + /** Shows a notice until it closes, then resolves with the id of the action + * the person picked, or `undefined` when they dismissed it, `signal` + * aborted or the plugin's scope ended. */ + show( + content: NoticeContent, + options?: Readonly<{ signal?: AbortSignal | undefined }>, + ): Promise; +}>; +/** A notice as the host renders it. `plugin` is the id of the plugin that + * shows it. */ +export type ShownNotice = NoticeContent & + Readonly<{ + key: string; + plugin: string; + pick(action: string): void; + dismiss(): void; + }>; + +declare module "@deepseek-ai/cordis" { + interface Context { + /** Read with `ctx.reflect.get("notices")` for old-host compatibility. */ + notices?: Notices; + } +} + +const text = (value: unknown) => typeof value === "string" && !!value.trim(); +function checked(content: NoticeContent) { + const actions = content?.actions ?? []; + if ( + !text(content?.title) || + (content.description !== undefined && + typeof content.description !== "string") || + !Array.isArray(actions) || + actions.length > 3 || + !actions.every((action) => text(action?.id) && text(action?.label)) || + new Set(actions.map((action) => action.id)).size !== actions.length + ) + throw new Error( + "A notice needs a title and at most three actions, each with its own id and a label", + ); + return { + title: content.title, + ...(content.description ? { description: content.description } : {}), + actions: actions.map(({ id, label, prominent }) => ({ + id, + label, + ...(prominent ? { prominent: true } : {}), + })), + }; +} + +export class NoticesService extends Service implements Notices { + private entries: readonly ShownNotice[] = []; + private readonly listeners = new Set<() => void>(); + constructor(ctx: Context) { + super(ctx, "notices"); + } + snapshot = () => this.entries; + subscribe = (listener: () => void) => { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + }; + private publish(entries: readonly ShownNotice[]) { + this.entries = entries; + for (const listener of this.listeners) listener(); + } + + async show( + content: NoticeContent, + { signal }: Readonly<{ signal?: AbortSignal | undefined }> = {}, + ) { + const ctx = this.ctx; + const owner = ctx.pluginOwner; + if (!owner) throw new Error("Notices must be shown by an installed plugin"); + const value = checked(content); + if (signal?.aborted) return undefined; + const key = `${owner.id}/${crypto.randomUUID()}`; + return new Promise((resolve) => { + let shown = true; + const settle = (outcome: string | undefined) => { + if (!shown) return false; + shown = false; + signal?.removeEventListener("abort", dismiss); + this.publish(this.entries.filter((item) => item !== entry)); + resolve(outcome); + return true; + }; + const ended = ctx.effect(() => () => void settle(undefined), key); + const close = (outcome: string | undefined) => { + if (settle(outcome)) void ended(); + }; + const dismiss = () => close(undefined); + const entry: ShownNotice = Object.freeze({ + ...value, + key, + plugin: owner.id, + pick: (action: string) => { + if (value.actions?.some((item) => item.id === action)) close(action); + }, + dismiss, + }); + signal?.addEventListener("abort", dismiss, { once: true }); + this.publish([...this.entries, entry]); + }); + } +} diff --git a/src/plugins/author.test.mjs b/src/plugins/author.test.mjs index b371e41abb..e33dd7dbdc 100644 --- a/src/plugins/author.test.mjs +++ b/src/plugins/author.test.mjs @@ -33,7 +33,7 @@ test("generated author package exposes shared messages, captured-read Undo, host join(dir, "consumer.ts"), ` import { createElement } from "react"; -import type { Context, DocumentEditorProps, DocumentEditorHandle, DocumentEditorSelection, ChannelMembersDialogProps, ChannelGeneralAccessProps, GeneralAccessPolicy, MemberChange, Delivery, HarnessConversation, McpHandler, StandaloneTurn, TurnResult, DecisionResult, Host, HostRequestOnceOptions, AddedTool, AddedToolContext, AddedToolReply, BuzzClient, Media, HostByteUpload, HostByteRequest, HostByteResponse, HostSavedBytes, PluginManifest, NamingPolicy, PagePreviewProps, PageSidebarProps, SidebarSectionContribution, SidebarSections, SidebarRowContribution, SidebarRows, ReadMutationResult, UnreadCapability, Backdrops, PluginUi, OutgoingMessage, SendGate, Seen } from "@buzz/author"; +import type { Context, DocumentEditorProps, DocumentEditorHandle, DocumentEditorSelection, ChannelMembersDialogProps, ChannelGeneralAccessProps, GeneralAccessPolicy, MemberChange, Delivery, HarnessConversation, McpHandler, StandaloneTurn, TurnResult, DecisionResult, Host, HostRequestOnceOptions, AddedTool, AddedToolContext, AddedToolReply, BuzzClient, Media, HostByteUpload, HostByteRequest, HostByteResponse, HostSavedBytes, PluginManifest, NamingPolicy, PagePreviewProps, PageSidebarProps, SidebarSectionContribution, SidebarSections, SidebarRowContribution, SidebarRows, ReadMutationResult, UnreadCapability, Backdrops, PluginUi, OutgoingMessage, SendGate, Seen, Notices } from "@buzz/author"; export const manifest: PluginManifest = { id: "example.plugin", name: "Example", apiVersion: 1, host: { @@ -235,6 +235,11 @@ export function apply(ctx: Context) { backdrops?.register({ id: "glow", component: () => null }); // @ts-expect-error A backdrop must be a React component. backdrops?.register({ id: "bad-glow", component: "div" }); + const notices: Notices | undefined = ctx.reflect.get("notices"); + const picked: Promise | undefined = notices?.show({ title: "Allow?", actions: [{ id: "yes", label: "Allow", prominent: true }] }, { signal: new AbortController().signal }); + void picked; + // @ts-expect-error A notice needs a title. + void notices?.show({ description: "No title" }); const sidebar: SidebarSections | undefined = ctx.reflect.get("sidebarSections"); sidebar?.register(section); // @ts-expect-error Sidebar contribution versions are explicit. diff --git a/src/plugins/author.ts b/src/plugins/author.ts index 42a034c70d..8cec2c0463 100644 --- a/src/plugins/author.ts +++ b/src/plugins/author.ts @@ -32,6 +32,7 @@ export type { } from "../features/pages/service"; export type { Seen } from "../features/seen/service"; export type { Backdrop, Backdrops } from "../features/backdrops/service"; +export type { Notices } from "../features/notices/service"; export type { SubjectLift } from "../features/messages/subject-lift"; export type { PluginButtonProps, diff --git a/src/shared/design-system/DESIGN.md b/src/shared/design-system/DESIGN.md index a2bd18a62a..597c04a02f 100644 --- a/src/shared/design-system/DESIGN.md +++ b/src/shared/design-system/DESIGN.md @@ -452,6 +452,7 @@ Sign in, Cancel, and Sign out at narrow widths with enlarged text. | Settings card/destination | Settings navigation, content column, contribution lifetime/error boundary | Content Header/grouping and controls; registration title is navigation metadata, not rendered content hierarchy | | Channel launcher or menu contribution | Placement, surrounding header/menu, target selection | The supported launcher/item only; preserve host action sizing and lifecycle | | Message/link/attachment renderer | Surrounding message and navigation contracts | Content inside that boundary; no duplicate author/actions or nested interactive target where the contract forbids it | +| Notice (`ctx.notices`) | Placement in the toast stack on every page, the info ToastNotice, its buttons and Dismiss, and the plugin's name | The title, an optional description and up to three actions, and what each answer means; anything but an allow is a refusal | Source plugins can import the shared components directly. External plugins must use the actual supported author contract and exposed CSS roles; source paths are @@ -1531,6 +1532,11 @@ keeps only the fade. ToastProvider mounts one headless [Sonner](https://sonner.emilkowal.ski) Toaster in the host, portaled outside the app layout to the top right. Features and plugins use the shared Toast API, never their own Toaster or direct Sonner calls. +Installed plugins reach the stack through `ctx.notices` +([shell notices](../../../docs/plugin-architecture.md#shell-notices)): they +supply the words and up to three actions, and the host draws them as an info +ToastNotice that the person can always dismiss, with the plugin's name in +`text-caption` below the words. Toast cards reuse `floating-surface`, including its `--shadow-panel` elevation; the scrollable viewport leaves room for the shadow and keyboard focus. Buzz owns the floating surface, semantic colors, type roles, Button and IconButton; @@ -1553,12 +1559,15 @@ Sonner is the toast behavior owner; other matching controls use Base UI. ToastNo owns its state and recovery: unmounting the source removes its notification, without reporting user dismissal. Gate notices from hidden Settings sections explicitly; portals do not inherit a hidden ancestor. Keep form errors and -blocked-page recovery inline. Relay connection recovery is the exception: it +blocked-page recovery inline. Relay connection recovery is one exception: it retries on its own, so after a 30-second quiet delay it shows one buttonless notice in the toast stack on every page, and other surfaces do not repeat it. -A community's refusal of the account is the other exception: it affects every +A community's refusal of the account is another exception: it affects every page, so its one notice stays in the toast stack with the actions that -fixes it, and pages it leaves empty only say why. +fixes it, and pages it leaves empty only say why. A plugin's notice is the +third: it asks the person about work that waits on their answer, wherever they +are. It belongs to the plugin's request: the plugin takes it down when the +request ends, and it closes when the plugin stops. Channel LiveStatus keeps failures that recovery does not retry in the conversation flow immediately above the composer, with bounded overflow, so Send and companion-panel controls remain usable. Its retry policy and diagnostics @@ -1581,7 +1590,7 @@ height on non-Mac shells. Mac uses a 12px top inset and an 8px right inset. Inte chrome aligns the card with the room/content divider. On touch, notices form a bounded scrolling list. Trailing actions wrap below the message when their intrinsic width cannot fit beside it. -F6 enters notifications, Tab reaches actions. Modals remain above the stack. Content updates do not restart expiry; timeout changes do. +F6 enters notifications, Tab reaches actions. Modals remain above the stack. While a modal is open, F6 moves only through notices that set `reachableOverModal` (a plugin's notice with actions), then back into the modal. Tab past a notice's last control, or Shift+Tab out of it, also returns to the modal. Keyboard focus that returns to the modal shows its focus ring. If a notice covers that control or its ring, focus moves to the modal's first visible control that no notice covers. Content updates do not restart expiry; timeout changes do. Tabs with content use renderPanel, which lets Base UI connect each tab and panel. Route navigation uses NavigationItem with aria-current instead, except for the diff --git a/src/shared/design-system/ui/Toast.tsx b/src/shared/design-system/ui/Toast.tsx index 34be380f5d..c96ddd9c30 100644 --- a/src/shared/design-system/ui/Toast.tsx +++ b/src/shared/design-system/ui/Toast.tsx @@ -14,6 +14,7 @@ import { import { createPortal } from "react-dom"; import { Toaster, toast } from "sonner"; import { XIcon } from "../icons"; +import { focusWithKeyboard } from "../useKeyboardFocusVisibility"; import { Button } from "./Button"; import { IconButton } from "./IconButton"; @@ -50,6 +51,26 @@ const attachViewport = (viewport: HTMLElement | null) => { }; }; +const tabbable = + 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'; +const focusRing = 4; +const underToast = (control: Element) => { + const box = control.getBoundingClientRect(); + return [ + ...document.querySelectorAll( + '[data-sonner-toast]:not([data-removed="true"])', + ), + ].some((card) => { + const rect = card.getBoundingClientRect(); + return ( + rect.left < box.right + focusRing && + rect.right > box.left - focusRing && + rect.top < box.bottom + focusRing && + rect.bottom > box.top - focusRing + ); + }); +}; + /** Keeps the stack below a mounted top-edge surface, such as the shell header. * Hidden surfaces take no room. */ export function useToastClearance(ref: RefObject) { @@ -93,17 +114,86 @@ export function ToastProvider({ globalThis.navigator?.platform?.startsWith("Linux") && navigator.vendor === "Apple Computer, Inc."; useEffect(() => { + const modalOpen = () => + [ + ...document.querySelectorAll( + '[aria-modal="true"]:not([data-ending-style])', + ), + ].at(-1); // Sonner's global hotkey must not bypass the host's modal focus boundary. const guardModal = (event: KeyboardEvent) => { + if (event.code !== "F6" || !modalOpen()) return; + event.stopPropagation(); + const cards = [ + ...document.querySelectorAll( + "[data-reachable-over-modal]:not([inert])", + ), + ].map((card) => card.closest("[data-sonner-toast]")); + const active = document.activeElement; + const current = cards.findIndex((card) => card?.contains(active)); + const next = cards[current + 1]; + if (next) focusWithKeyboard(next); + else if (current >= 0 && active instanceof HTMLElement) active.blur(); + }; + const keepModal = (event: FocusEvent) => { + const { target, relatedTarget } = event; if ( - event.code === "F6" && - document.querySelector('[aria-modal="true"]:not([data-ending-style])') - ) { - event.stopPropagation(); - } + !(target instanceof HTMLElement) || + !(relatedTarget instanceof Element) + ) + return; + const card = target.closest("[data-sonner-toast]"); + const from = relatedTarget.closest("[data-sonner-toast]"); + if ( + !card || + card === from || + card.querySelector("[data-reachable-over-modal]") || + !from?.querySelector("[data-reachable-over-modal]") || + document.documentElement.dataset.keyboardNavigation === undefined || + !modalOpen() + ) + return; + event.stopPropagation(); + target.blur(); + }; + let noticeOver: Element | undefined; + const revealReturn = async (target: HTMLElement, modal: Element) => { + await new Promise(requestAnimationFrame); + if ( + document.activeElement !== target || + document.documentElement.dataset.keyboardNavigation === undefined + ) + return; + const control = underToast(target) + ? [...modal.querySelectorAll(tabbable)].find( + (candidate) => + !underToast(candidate) && + !candidate.closest('[hidden], [inert], [aria-hidden="true"]') && + candidate.getClientRects().length > 0, + ) + : target; + if (control) focusWithKeyboard(control); + }; + const trackReturn = ({ target }: FocusEvent) => { + if (!(target instanceof HTMLElement)) return; + const card = target.closest("[data-sonner-toast]"); + if (card) + noticeOver = card.querySelector("[data-reachable-over-modal]") + ? modalOpen() + : undefined; + if (card) return; + const modal = target.closest('[aria-modal="true"]'); + if (modal && modal === noticeOver) void revealReturn(target, modal); + noticeOver = undefined; }; window.addEventListener("keydown", guardModal, true); - return () => window.removeEventListener("keydown", guardModal, true); + document.addEventListener("focusin", keepModal, true); + document.addEventListener("focusin", trackReturn, true); + return () => { + window.removeEventListener("keydown", guardModal, true); + document.removeEventListener("focusin", keepModal, true); + document.removeEventListener("focusin", trackReturn, true); + }; }, []); useEffect( () => () => { @@ -141,6 +231,7 @@ export function ToastProvider({ type ToastCardProps = { exiting?: boolean; + reachableOverModal?: boolean | undefined; title: string; description?: string | undefined; /** Optional supporting detail between the message and its actions. */ @@ -154,6 +245,7 @@ type ToastCardProps = { function ToastCard({ exiting, + reachableOverModal, title, description, details, @@ -165,8 +257,15 @@ function ToastCard({ }: ToastCardProps) { const titleId = useId(); const descriptionId = useId(); + const card = useRef(null); + useEffect(() => { + const item = card.current?.closest("[data-sonner-toast]"); + if (exiting && reachableOverModal && item === document.activeElement) + item?.blur(); + }, [exiting, reachableOverModal]); return (
{navigation && ( @@ -259,6 +359,7 @@ export function ToastNotice({ timeout = 0, tone = "error", navigation, + reachableOverModal, }: { title: string; description?: string; @@ -270,6 +371,7 @@ export function ToastNotice({ timeout?: number; tone?: Tone; navigation?: ToastCardProps["navigation"]; + reachableOverModal?: boolean; }) { const id = useId(); const toasterId = useContext(ToastHost); @@ -320,6 +422,7 @@ export function ToastNotice({ children, closeLabel, navigation, + reachableOverModal, onClose: dismissible ? () => { toast.dismiss(id); @@ -338,6 +441,7 @@ export function ToastNotice({ closeLabel, dismissible, navigation, + reachableOverModal, ]); return null; } diff --git a/tests/browser/plugin-fixtures.tsx b/tests/browser/plugin-fixtures.tsx index 9bd89e879a..169096d0a5 100644 --- a/tests/browser/plugin-fixtures.tsx +++ b/tests/browser/plugin-fixtures.tsx @@ -140,6 +140,31 @@ const fill = (background: string, zIndex?: number) => () => ( export const fixturePlugins: readonly BundledPlugin[] = [ soloRegionFixture, + { + manifest: { + id: "fixture.notices", + name: "Notice fixture", + apiVersion: 1, + }, + enabledByDefault: false, + module: { + apply(ctx) { + const notices = ctx.reflect.get("notices"); + void notices + ?.show({ + title: "Let Fixture delete a.txt?", + actions: [ + { id: "once", label: "Allow once", prominent: true }, + { id: "deny", label: "Deny" }, + ], + }) + .then((answer) => + notices.show({ title: `Answered ${answer ?? "nothing"}` }), + ); + void notices?.show({ title: "Fixture is waiting" }); + }, + }, + }, { manifest: { id: "fixture.backdrops", diff --git a/tests/browser/shell-notices.spec.mjs b/tests/browser/shell-notices.spec.mjs new file mode 100644 index 0000000000..82c2691bfb --- /dev/null +++ b/tests/browser/shell-notices.spec.mjs @@ -0,0 +1,241 @@ +import { + openSettings, + selectSettingsSection, + settingsDialog, +} from "./navigation.mjs"; +import { test, expect } from "./fixture.mjs"; +import { open } from "./timeline.mjs"; + +test.use({ pluginFixtures: true, enabledPlugins: ["fixture.notices"] }); + +const tabKey = (browserName) => + browserName === "webkit" && process.platform === "darwin" ? "Alt+Tab" : "Tab"; + +const question = (page) => + page.getByRole("dialog", { name: "Let Fixture delete a.txt?" }); + +test("a plugin's notice shows on any page and takes the owner's answer over Settings", async ({ + page, + app, +}) => { + await open(page, app); + const ask = question(page); + await expect(ask).toBeVisible(); + await expect(ask).toContainText("From Notice fixture"); + await openSettings(page); + await expect(ask).toBeVisible(); + const close = settingsDialog(page).getByRole("button", { + name: "Close Settings", + exact: true, + }); + await expect(close).toBeFocused(); + await page.getByRole("dialog", { name: "Fixture is waiting" }).hover(); + await ask.getByRole("button", { name: "Allow once" }).click(); + await expect(ask).toHaveCount(0); + await returnedFocus(page); + await expect(close).toBeFocused(); + await expect(page.locator("html")).not.toHaveAttribute( + "data-keyboard-navigation", + ); + const answered = page.getByRole("dialog", { name: "Answered once" }); + await expect(answered).toBeVisible(); + await settingsDialog(page).press("Escape"); + await expect(settingsDialog(page)).toHaveCount(0); + await expect(answered).toBeVisible(); +}); + +async function returnedFocus(page) { + await expect(settingsDialog(page).locator(":focus")).toHaveCount(1); + return page.evaluate(async () => { + const frame = () => new Promise(requestAnimationFrame); + const toaster = document.querySelector("[data-sonner-toaster]"); + const settle = async () => { + await frame(); + const moving = toaster.getAnimations({ subtree: true }); + if (!moving.length) return; + await Promise.allSettled(moving.map((animation) => animation.finished)); + await settle(); + }; + await settle(); + await frame(); + const cards = [ + ...document.querySelectorAll( + '[data-sonner-toast]:not([data-removed="true"])', + ), + ].map((card) => card.getBoundingClientRect()); + const meets = (box, pad) => + cards.filter( + (card) => + card.left < box.right + pad && + card.right > box.left - pad && + card.top < box.bottom + pad && + card.bottom > box.top - pad, + ).length; + const settings = document.querySelector('[aria-modal="true"]'); + const close = settings.querySelector('[aria-label="Close Settings"]'); + const focused = document.activeElement; + const style = getComputedStyle(focused); + const ring = + Number.parseFloat(style.outlineWidth) + + Number.parseFloat(style.outlineOffset); + const box = focused.getBoundingClientRect(); + const corners = [ + [box.left - ring, box.top - ring], + [box.right + ring - 1, box.top - ring], + [box.left - ring, box.bottom + ring - 1], + [box.right + ring - 1, box.bottom + ring - 1], + ]; + return { + closeUnderToast: meets(close.getBoundingClientRect(), 4) > 0, + inSettings: settings.contains(focused), + ring: `${style.outlineStyle} ${style.outlineWidth} ${style.outlineOffset}`, + toastsOverRing: meets(box, ring), + centreOnFocus: focused.contains( + document.elementFromPoint( + box.left + box.width / 2, + box.top + box.height / 2, + ), + ), + ringCornersOnToast: corners.filter(([x, y]) => + document.elementFromPoint(x, y)?.closest("[data-sonner-toast]"), + ).length, + }; + }); +} + +const visibleInSettings = { + closeUnderToast: true, + inSettings: true, + ring: "solid 2px 2px", + toastsOverRing: 0, + centreOnFocus: true, + ringCornersOnToast: 0, +}; + +async function reachOverSettings(page, app) { + await open(page, app); + const ask = question(page); + await expect(ask).toBeVisible(); + await openSettings(page); + const close = settingsDialog(page).getByRole("button", { + name: "Close Settings", + exact: true, + }); + await close.focus(); + const card = page.locator("[data-sonner-toast]", { has: ask }); + const [noticeBox, closeBox] = [ + await card.boundingBox(), + await close.boundingBox(), + ]; + expect(noticeBox.x).toBeLessThan(closeBox.x); + expect(noticeBox.x + noticeBox.width).toBeGreaterThan( + closeBox.x + closeBox.width, + ); + expect(noticeBox.y).toBeLessThan(closeBox.y); + expect(noticeBox.y + noticeBox.height).toBeGreaterThan( + closeBox.y + closeBox.height, + ); + await page.keyboard.press("F6"); + await expect(card).toBeFocused(); + await expect(card).toHaveCSS("outline-style", "solid"); + return { ask, card }; +} + +test("F6 reaches a waiting notice over Settings, and Enter on an action answers it", async ({ + page, + app, + browserName, +}) => { + const tab = tabKey(browserName); + const { ask } = await reachOverSettings(page, app); + await page.keyboard.press(tab); + await page.keyboard.press(tab); + await expect(ask.getByRole("button", { name: "Allow once" })).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(ask).toHaveCount(0); + await expect( + page.getByRole("dialog", { name: "Answered once" }), + ).toBeVisible(); + await expect(settingsDialog(page)).toBeVisible(); + expect(await returnedFocus(page)).toEqual(visibleInSettings); +}); + +test("F6 and Tab keep focus between a waiting notice and Settings, and Escape on the notice refuses it", async ({ + page, + app, + browserName, +}) => { + const tab = tabKey(browserName); + const { ask, card } = await reachOverSettings(page, app); + await page.keyboard.press(`Shift+${tab}`); + expect(await returnedFocus(page)).toEqual(visibleInSettings); + await page.keyboard.press("F6"); + await expect(card).toBeFocused(); + await page.keyboard.press(tab); + await page.keyboard.press(tab); + await page.keyboard.press(tab); + await expect(ask.getByRole("button", { name: "Deny" })).toBeFocused(); + await page.keyboard.press(tab); + expect(await returnedFocus(page)).toEqual(visibleInSettings); + await page.keyboard.press("F6"); + await expect(card).toBeFocused(); + await page.keyboard.press("F6"); + expect(await returnedFocus(page)).toEqual(visibleInSettings); + await page.keyboard.press("F6"); + await expect(card).toBeFocused(); + await page.keyboard.press("Escape"); + await expect(ask).toHaveCount(0); + await expect( + page.getByRole("dialog", { name: "Answered nothing" }), + ).toBeVisible(); + await expect(settingsDialog(page)).toBeVisible(); + expect(await returnedFocus(page)).toEqual(visibleInSettings); +}); + +test("over Settings, a notice without choices keeps its Tab order and the focus a click gives it", async ({ + page, + app, + browserName, +}) => { + const tab = tabKey(browserName); + await open(page, app); + await expect(question(page)).toBeVisible(); + await openSettings(page); + await selectSettingsSection(page, "Appearance"); + await page.evaluate(() => { + const setItem = Storage.prototype.setItem; + Storage.prototype.setItem = function (key, value) { + if (key === "buzz-clock.v1") + throw new DOMException("Full", "QuotaExceededError"); + return setItem.call(this, key, value); + }; + }); + await page.getByRole("switch", { name: "Show seconds" }).click(); + const unsaved = page.getByRole("dialog", { + name: "Clock preference wasn’t saved", + }); + await unsaved.getByText("Clock preference wasn’t saved").click(); + await expect( + page.locator("[data-sonner-toast]", { has: unsaved }), + ).toBeFocused(); + await page.keyboard.press(tab); + await expect( + unsaved.getByRole("button", { name: "Retry saving clock preference" }), + ).toBeFocused(); + await page.keyboard.press(tab); + await expect( + page.locator("[data-sonner-toast]", { + has: page.getByRole("dialog", { name: "Fixture is waiting" }), + }), + ).toBeFocused(); + await question(page).getByText("Let Fixture delete a.txt?").click(); + await expect( + page.locator("[data-sonner-toast]", { has: question(page) }), + ).toBeFocused(); + const retry = unsaved.getByRole("button", { + name: "Retry saving clock preference", + }); + await unsaved.hover(); + await retry.click(); + await expect(retry).toBeFocused(); +});