Plugin panels talk to their worker; panel storage, settings and agent events (#37013)

* feat(plugins): panels talk to their own worker, read storage, settings and events

- plugin.request (host API 1.2): a panel or editor asks its plugin's worker, which answers with
  orca.panels.handle(name); the worker pushes with orca.panels.post. Same plugin only, JSON
  checked, 1 MiB answers, 256 KiB/200-per-10s posts, a deadline and the panel's lifetime.
- Panels and editors get storage.*, settings.* and secrets.* behind the same capabilities, and
  storage/settings onDidChange on every surface; events.subscribe delivers workspace and agent
  events to panels that hold the read capability.
- contributes.settings: typed settings (a JSON Schema subset) with defaults and value checks.
- Frames get orca.plugin/storage/settings/secrets; components panels import plugin, storage,
  settings, secrets from 'orca', and atom(key, init, { persist: 'storage' }) shares a value with
  the worker. Workers get orca.panels/storage/settings/secrets sugar.
- One typed contract: declare module 'orca' { interface PluginRequests / PluginPanelEvents }.
- Desktop push channel per open panel session (plugins:openPanelPush).

* feat(plugins): Orca Settings shows and edits a plugin's contributes.settings

The plugin page lists declared settings with Orca's own controls (switch, picker, text and
number fields, Reset to default). Edits are checked against the declaration in main, written to
the plugin's settings, and reach open panels and the running worker through onDidChange.

* docs(plugins): hello-tsx talks to its worker; authoring guide covers panels, workers and data

The example now uses one of each: plugin.request answered by orca.panels.handle, a worker post
heard with plugin.on, a persist: 'storage' atom the worker watches, two contributes.settings and
agent.status.changed in the panel, all typed by one src/protocol.ts. The build-less TSX e2e
drives the whole loop.

* fix(plugins): typed bridge overloads, panel call budget, settings IPC and catalog keys

- PluginBridgeApi/PanelsApi use overloads: declared names are typed (and complete), any other
  name carries JSON; no never-unions for the type-aware lint.
- The per-plugin panel call budget is 120 per 10 s, since a panel loading storage atoms,
  settings and its first requests makes a burst; the hostile fixture floods past it.
- Settings IPC builds its host per call; the settings section's strings are in en.json.

* test(plugins): the example's declared settings show under the plugin with the person's value

* refactor(plugins): keep hello-tsx the minimal starter; the bridge demo is hello-worker-panel

hello-tsx goes back to a sandboxed-ui panel with no worker or capabilities. The worker, protocol,
storage atom, settings and events move to examples/plugins/hello-worker-panel, with their own
e2e (plugin-worker-panel) and PR route.

* feat(plugins): test kit covers the panel bridge and plugin data

mockHost keeps the plugin's storage, settings and secrets in memory (seeded with storage,
settings, secrets; read with host.data()) and fakes the worker with requests, so plugin.request,
storage/settings/secrets and persist: 'storage' atoms work under mount(), writes reach
onDidChange, and panel.post(event, payload) is what plugin.on hears. Typed by PluginRequests and
PluginPanelEvents.

* test(plugins): focusInGuest waits for the guest and retries focusing as one step

Under load the custom-editor guest could still be attaching, so executeJavaScript threw
'dom-ready' before the focus poll began. Wait for waitForGuestReady, then retry focusing the
webview and the element together, tolerating a guest that is still attaching or remounts.

* docs(plugins): the authoring skill covers panels, workers and data; persistence leaves the renderer

- skill-guides/orca-plugin-authoring.md gains Panels, workers and data (plugin.request/on,
  orca.panels.handle/post, persist: 'storage', contributes.settings, panel events, test kit), and
  its generated references read orca-services.d.ts for shell, files, on and the bridge types.
- After the dev-loop rebase, persisted-atom wiring (queue plus storage sync) moves to
  createDeclarativePersistence so the renderer stays under max-lines.

* feat(plugins): panels show agents: agents.list, terminal ids on agent events, workspace.changed

- agents.list (agent:read, every surface): the focused workspace's agents with terminalId,
  title, agent kind, state and stateStartedAt, from the hook server's store.
- agent.status.changed carries terminalId and title: paneKey mapped through the runtime's
  terminal list (tabId:leafId) or the status's terminal handle; looked up only while a plugin
  listens, in arrival order.
- workspace.readContext terminals carry title; workspace.changed (workspace:read) fires after
  workspace session writes when the focused workspace or its terminals change.
- Event subscriptions are kept per panel session, so one made before the push channel opens
  still counts.
- shell.openExternal never prompts on a hidden or minimized window: it settles
  { opened: false, reason: 'consent-unavailable' } and says so in the plugin log, which also
  notes 'waiting for the person to confirm' while a prompt is up; the rate budget is spent only
  when Orca acts. e2e launches never open a real browser or mail client.
- A worker may export activate as default or by name; docs, typings and the authoring skill
  document the entry, the agent events and a live agent status recipe.

* fix(plugins): the plugin page names the workspace.changed subscription

* fix(plugins): workers activate only by default export, and say so when it is named

Orca calls the worker module's default export. A module with a named `activate` and no default
now fails to start with an error naming the fix (`export default function activate(orca)`),
instead of being called by a fallback; docs, typings and the skill say default export.
hello-worker-panel gains a picker setting (suggestionOrder) the worker reads.
This commit is contained in:
Neil
2026-11-01 04:40:17 -08:00
committed by GitHub
parent 3a983d06fd
commit ec0d3cedd1
141 changed files with 6049 additions and 735 deletions
@@ -19,6 +19,8 @@ type FrameOrca = {
}
on: (event: string, handler: (payload: unknown) => unknown) => { dispose: () => void }
locale: string
plugin: object
storage: object
shell?: { openExternal: (url: string) => Promise<unknown> }
files?: {
saveAs: (options: {
@@ -90,12 +92,15 @@ describe('window.orca', () => {
expect(Object.isFrozen(orca)).toBe(true)
expect(Object.isFrozen(orca.host)).toBe(true)
expect(posted()).toEqual([{ orca: 1, kind: 'evt', event: 'ready', payload: { protocol: 1 } }])
expect(orca.api).toEqual({ major: 1, minor: 0 })
expect(orca.api).toEqual({ major: 1, minor: 2 })
expect(orca.shell).toBeUndefined()
expect(orca.files).toBeUndefined()
expect(orca.host.has('shell.openExternal')).toBe(false)
expect(orca.host.has('workspace.readContext')).toBe(true)
expect(orca.host.has('terminal.sendText')).toBe(false)
expect(orca.host.has('plugin.request')).toBe(true)
expect(Object.isFrozen(orca.plugin)).toBe(true)
expect(Object.isFrozen(orca.storage)).toBe(true)
expect(orca.document).toBeUndefined()
})
@@ -24,7 +24,9 @@ export const FRAME_EVENTS = {
/** frame → host: a modifier chord, so Orca's save shortcut works inside an editor. */
editorKeydown: 'editor.keydown',
/** host → frame: the document, on ready and whenever it changes outside the frame. */
editorDocument: 'editor.document'
editorDocument: 'editor.document',
/** host → frame, payload `PluginPanelPush`: a worker post, an event or a data change. */
push: 'plugin.push'
} as const
/** Frame-local methods a custom editor handles or calls on the same envelope. */
@@ -47,9 +49,10 @@ export type PluginFrameHello = {
locale?: string
}
/** Per-plugin bridge budgets, enforced host-side. */
/** Per-plugin bridge budgets, enforced host-side. Why 120: a panel loading its storage atoms,
* settings and first worker requests makes a burst of small calls. */
export const PANEL_MESSAGE_MAX_BYTES = 64 * 1024
export const PANEL_MESSAGE_RATE_LIMIT = { maxMessages: 30, perMs: 10_000 }
export const PANEL_MESSAGE_RATE_LIMIT = { maxMessages: 120, perMs: 10_000 }
/** Size-only liveness lane: count limits let a panel’s pongs exhaust the budget and starve genuine replies.
* Pongs also spend the data budget, bounding aggregate cost; walks are capped here. */
@@ -0,0 +1,105 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { buildPluginPanelShellHtml } from './plugin-panel-shell'
type Disposable = { dispose: () => void }
type FrameOrca = {
on: (event: string, handler: (payload: unknown) => unknown) => Disposable
plugin: {
request: (name: string, input?: unknown, options?: { timeoutMs?: number }) => Promise<unknown>
on: (event: string, handler: (payload: unknown) => unknown) => Disposable
}
storage: {
get: (key: string) => Promise<unknown>
set: (key: string, value: unknown) => Promise<void>
onDidChange: (handler: (change: { key: string }) => void) => Disposable
}
settings: { get: (key?: string) => Promise<unknown> }
}
const realParent = window.parent
afterEach(() => {
Object.defineProperty(window, 'parent', { value: realParent, configurable: true })
})
function mountShell() {
const parent = { postMessage: vi.fn() }
Object.defineProperty(window, 'parent', { value: parent, configurable: true })
const script = buildPluginPanelShellHtml('<main></main>').match(
/<script>\n([\s\S]*?)<\/script>/
)?.[1]
window.eval(script!.replaceAll('configurable: false', 'configurable: true'))
const orca: FrameOrca = Object.getOwnPropertyDescriptor(window, 'orca')?.value
const fromHost = (data: unknown) =>
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the shim only compares source identity.
window.dispatchEvent(new MessageEvent('message', { data, source: parent as never as Window }))
const requests = () =>
parent.postMessage.mock.calls
.map(([message]) => message)
.filter((message) => message.kind === 'req')
const answer = (id: number, result: unknown) => fromHost({ orca: 1, kind: 'res', id, result })
const push = (payload: unknown) =>
fromHost({ orca: 1, kind: 'evt', event: 'plugin.push', payload })
return { orca, requests, answer, push }
}
describe('window.orca.plugin', () => {
it('asks the worker through plugin.request and resolves with its output', async () => {
const { orca, requests, answer } = mountShell()
const todos = orca.plugin.request('todos.list', { done: false }, { timeoutMs: 999_999 })
const [sent] = requests()
expect(sent).toMatchObject({
method: 'plugin.request',
params: { name: 'todos.list', input: { done: false }, timeoutMs: 120_000 }
})
answer(sent.id, { output: [{ id: '1' }] })
await expect(todos).resolves.toEqual([{ id: '1' }])
})
it('hands worker posts to plugin.on by event name', () => {
const { orca, push } = mountShell()
const changed = vi.fn()
const other = vi.fn()
orca.plugin.on('todos.changed', changed)
orca.plugin.on('other', other)
push({ kind: 'message', event: 'todos.changed', payload: { count: 3 } })
expect(changed).toHaveBeenCalledWith({ count: 3 })
expect(other).not.toHaveBeenCalled()
})
})
describe('window.orca events and data', () => {
it('subscribes to a workspace or agent event once, on the first listener', () => {
const { orca, requests, push } = mountShell()
const first = vi.fn()
orca.on('agent.status.changed', first)
orca.on('agent.status.changed', vi.fn())
orca.on('theme', vi.fn())
expect(requests()).toEqual([
expect.objectContaining({
method: 'events.subscribe',
params: { event: 'agent.status.changed' }
})
])
push({ kind: 'event', event: 'agent.status.changed', payload: { state: 'done' } })
expect(first).toHaveBeenCalledWith({ state: 'done' })
})
it('reads storage and settings, and hears which key changed', async () => {
const { orca, requests, answer, push } = mountShell()
const value = orca.storage.get('todos')
const setting = orca.settings.get('apiUrl')
const [get, settings] = requests()
answer(get.id, { value: null })
answer(settings.id, { settings: { apiUrl: 'https://x' } })
await expect(value).resolves.toBeNull()
await expect(setting).resolves.toBe('https://x')
const changed = vi.fn()
orca.storage.onDidChange(changed)
push({ kind: 'changed', area: 'settings', key: 'apiUrl' })
push({ kind: 'changed', area: 'storage', key: 'todos' })
expect(changed).toHaveBeenCalledOnce()
expect(changed).toHaveBeenCalledWith({ key: 'todos' })
})
})
@@ -0,0 +1,85 @@
import { PLUGIN_EVENT_NAMES } from '../contributions/plugin-event-contribution'
import { PLUGIN_PANEL_REQUEST_MAX_TIMEOUT_MS } from '../workers/plugin-panel-bridge-protocol'
/**
* Part of the frame shell's IIFE (plugin-panel-shell.ts), after `orca` exists: `orca.plugin`
* (requests to and posts from the plugin's worker), `orca.storage`, `orca.settings`,
* `orca.secrets`, and `orca.on` for workspace and agent events. Uses the shell's `call`, `on`,
* `emit` and `failure`; `receivePush` handles the host's `plugin.push` event.
*/
export const PLUGIN_FRAME_FACADES_SCRIPT = `
var domainEvents = ${JSON.stringify(PLUGIN_EVENT_NAMES)}
var subscribed = new Set()
var pluginListeners = new Map()
var dataListeners = new Map()
function listen(map, name, fn) {
if (typeof fn !== 'function') throw new TypeError('a listener must be a function')
var set = map.get(name) || new Set()
map.set(name, set)
var entry = function (payload) { return fn(payload) }
set.add(entry)
return Object.freeze({ dispose: function () { set.delete(entry) } })
}
function fire(map, name, payload) {
var set = map.get(name)
if (set) Array.from(set).forEach(function (fn) {
try { Promise.resolve(fn(payload)).catch(function (e) { console.error(e) }) } catch (e) { console.error(e) }
})
}
function onEvent(name, fn) {
var subscription = on(name, fn)
if (domainEvents.indexOf(name) >= 0 && !subscribed.has(name)) {
subscribed.add(name)
call('events.subscribe', { event: name }).catch(function (e) {
subscribed.delete(name)
console.warn('[orca] cannot receive ' + name + ': ' + (e && e.message))
})
}
return subscription
}
function receivePush(p) {
if (!p) return
if (p.kind === 'message') fire(pluginListeners, String(p.event), p.payload)
else if (p.kind === 'event') emit(String(p.event), p.payload)
else if (p.kind === 'changed') fire(dataListeners, String(p.area), Object.freeze({ key: String(p.key) }))
}
function pick(name) { return function (result) { return result ? result[name] : undefined } }
function done() { return undefined }
orca.on = onEvent
orca.plugin = Object.freeze({
request: function (name, input, options) {
var o = options || {}
var params = { name: String(name) }
if (input !== undefined) params.input = input
if (typeof o.timeoutMs === 'number' && o.timeoutMs > 0) {
params.timeoutMs = Math.min(Math.ceil(o.timeoutMs), ${PLUGIN_PANEL_REQUEST_MAX_TIMEOUT_MS})
}
return call('plugin.request', params, { signal: o.signal }).then(pick('output'))
},
on: function (event, fn) { return listen(pluginListeners, String(event), fn) }
})
orca.storage = Object.freeze({
get: function (key) {
return call('storage.get', { key: String(key) }).then(pick('value')).then(function (v) { return v === undefined ? null : v })
},
set: function (key, value) { return call('storage.set', { key: String(key), value: value }).then(done) },
delete: function (key) { return call('storage.delete', { key: String(key) }).then(done) },
keys: function () { return call('storage.keys').then(pick('keys')) },
onDidChange: function (fn) { return listen(dataListeners, 'storage', fn) }
})
orca.settings = Object.freeze({
get: function (key) {
return call('settings.get').then(function (result) {
var all = (result && result.settings) || {}
return key === undefined ? all : (Object.prototype.hasOwnProperty.call(all, key) ? all[key] : undefined)
})
},
set: function (key, value) { return call('settings.set', { key: String(key), value: value }).then(done) },
onDidChange: function (fn) { return listen(dataListeners, 'settings', fn) }
})
orca.secrets = Object.freeze({
get: function (key) { return call('secrets.get', { key: String(key) }).then(pick('value')) },
set: function (key, value) { return call('secrets.set', { key: String(key), value: String(value) }).then(done) },
delete: function (key) { return call('secrets.delete', { key: String(key) }).then(done) }
})
`
@@ -2,6 +2,7 @@ import { EDITOR_METHODS, FRAME_EVENTS, type PluginFrameTheme } from './plugin-fr
import { PLUGIN_ERROR_CODES, PLUGIN_PROTOCOL_VERSION } from './plugin-protocol'
import { PLUGIN_DECLARATIVE_POST_GLOBAL, PLUGIN_FRAME_TRANSPORT_GLOBAL } from './plugin-frame-guest'
import { PLUGIN_HOST_API_MAJOR } from '../workers/plugin-host-api-major'
import { PLUGIN_FRAME_FACADES_SCRIPT } from './plugin-panel-shell-facades'
import {
PLUGIN_FRAME_USER_METHODS,
pluginFrameMethodsFor,
@@ -170,6 +171,8 @@ function frameApiScript(surface: PluginFrameSurface, transport: FrameTransport):
applyTheme(m.payload.theme)
} else if (m.kind === 'evt' && m.event === E.theme) {
applyTheme(m.payload)
} else if (m.kind === 'evt' && m.event === E.push) {
receivePush(m.payload)
} else if (m.kind === 'evt' && m.event === E.editorDocument && C.surface === 'editor') {
latest = Object.freeze(m.payload)
waiting.splice(0).forEach(function (resolve) { resolve(latest) })
@@ -191,7 +194,7 @@ function frameApiScript(surface: PluginFrameSurface, transport: FrameTransport):
}),
on: on
}
if (C.user) {
${PLUGIN_FRAME_FACADES_SCRIPT} if (C.user) {
orca.shell = Object.freeze({
openExternal: function (url) { return userCall(C.user.openExternal, { url: String(url) }) }
})