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
@@ -0,0 +1,97 @@
import { afterEach, describe, expect, it } from 'vitest'
import { atom, read, set } from '../runtime/declarative-atoms'
import { h } from '../runtime/declarative-elements'
import { plugin, settings, storage } from '../runtime/orca-module'
import { hostError, mockHost, mount, type TestPanel } from './orca-testing'
let panel: TestPanel | null = null
afterEach(async () => {
await panel?.unmount()
panel = null
})
const todos = atom<string[]>('testing.todos', [], { persist: 'storage' })
const message = atom('')
const Todos = () =>
h(
'Stack',
null,
h('Text', null, `${read(todos).length} todos ${read(message)}`),
h(
'Button',
{
onPress: async () => {
const answer = await plugin.request('todos.suggest', { taken: read(todos) })
set(todos, [...read(todos), String(answer)])
}
},
'Suggest'
),
h(
'Button',
{
onPress: () =>
plugin.request('todos.fail').catch((error: { code: string }) => set(message, error.code))
},
'Fail'
)
)
describe('orca/testing and the plugin bridge', () => {
it("answers plugin.request from `requests`, and keeps storage atoms in the host's storage", async () => {
const host = mockHost({
capabilities: ['storage:own'],
storage: { 'testing.todos': ['seeded'] },
requests: {
'todos.suggest': (input: unknown) => `idea ${JSON.stringify(input)}`,
'todos.fail': () => {
throw hostError('conflict', 'taken')
}
}
})
panel = await mount(Todos, { host })
expect(panel.find({ role: 'text' })?.text).toBe('1 todos')
await panel.press({ text: 'Suggest' })
expect(host.callsOf('plugin.request')).toEqual([
{ name: 'todos.suggest', input: { taken: ['seeded'] } }
])
expect(panel.persisted.storage['testing.todos']).toEqual([
'seeded',
'idea {"taken":["seeded"]}'
])
await panel.press({ text: 'Fail' })
expect(panel.find({ role: 'text' })?.text).toBe('2 todos conflict')
})
it('hears worker posts, and storage and settings changes', async () => {
const heard: unknown[] = []
const host = mockHost({
capabilities: ['storage:own', 'settings:own'],
settings: { theme: 'dark' }
})
panel = await mount(
{
setup: (ctx) => {
ctx.subscriptions.push(
plugin.on('todos.changed', (payload) => heard.push(payload)),
storage.onDidChange(({ key }) => heard.push(`storage:${key}`))
)
},
default: () => h('Text', null, 'x')
},
{ host }
)
await panel.post('todos.changed', { count: 2 })
await storage.set('filter', 'open')
await panel.settled()
expect(heard).toEqual([{ count: 2 }, 'storage:filter'])
await expect(settings.get('theme')).resolves.toBe('dark')
expect(host.data().storage).toEqual({ filter: 'open' })
})
it('refuses storage without the capability, as Orca would', async () => {
panel = await mount(() => h('Text', null, 'x'), { host: mockHost({ capabilities: [] }) })
await expect(storage.get('k')).rejects.toMatchObject({ code: 'capability_denied' })
})
})
@@ -0,0 +1,13 @@
/** A host API rejection, as plugin code sees it from `host.call`. */
export type MockHostError = Error & { code: string; retryable: boolean; retryAfterMs?: number }
const RETRYABLE = new Set(['rate_limited', 'unavailable', 'timeout', 'conflict'])
/** The error `host.call` rejects with for `code`, e.g. `hostError('rate_limited', 'slow down', 500)`. */
export function hostError(code: string, message = code, retryAfterMs?: number): MockHostError {
return Object.assign(new Error(message), {
code,
retryable: RETRYABLE.has(code),
...(retryAfterMs === undefined ? {} : { retryAfterMs })
})
}
@@ -5,28 +5,24 @@ import {
} from '../../workers/plugin-host-api'
import { PLUGIN_HOST_API_MAJOR } from '../../workers/plugin-host-api-major'
/** A host API rejection, as plugin code sees it from `host.call`. */
export type MockHostError = Error & { code: string; retryable: boolean; retryAfterMs?: number }
import { hostError } from './testing-host-error'
import {
createMockPluginData,
type MockPluginDataOptions,
type MockPluginDataSnapshot
} from './testing-plugin-data'
export { hostError, type MockHostError } from './testing-host-error'
export type MockHostCall = { method: string; params: unknown }
export type MockHostOptions = {
export type MockHostOptions = MockPluginDataOptions & {
/** Granted capabilities; defaults to the ones the plugin's orca-plugin.json declares. */
capabilities?: readonly string[]
/** What each method answers: a value, or a function of the params (it may throw `hostError`). */
/** What each method answers: a value, or a function of the params (it may throw `hostError`).
* Overrides the built-in storage, settings, secrets and `requests`. */
results?: Record<string, unknown>
}
const RETRYABLE = new Set(['rate_limited', 'unavailable', 'timeout', 'conflict'])
/** The error `host.call` rejects with for `code`, e.g. `hostError('rate_limited', 'slow down', 500)`. */
export function hostError(code: string, message = code, retryAfterMs?: number): MockHostError {
return Object.assign(new Error(message), {
code,
retryable: RETRYABLE.has(code),
...(retryAfterMs === undefined ? {} : { retryAfterMs })
})
}
function isResultFunction(value: unknown): value is (params: unknown) => unknown {
return typeof value === 'function'
}
@@ -36,7 +32,8 @@ const DEFAULT_RESULTS: Record<string, unknown> = {
'workspace.readContext': null,
'notifications.show': { delivered: true },
'shell.openExternal': { opened: true },
'files.saveAs': { status: 'saved' }
'files.saveAs': { status: 'saved' },
'agents.list': { agents: [] }
}
export type MockHost = {
@@ -49,6 +46,10 @@ export type MockHost = {
grantGesture(): void
/** Resolves when every call made so far has answered. */
idle(): Promise<void>
/** The plugin's storage, settings and secrets as they are now. */
data(): MockPluginDataSnapshot
/** Hears each storage or settings write, as Orca tells the plugin's open panels. */
onDataChange(listener: (area: 'storage' | 'settings', key: string) => void): () => void
readonly bridge: {
api: { major: number; minor: number }
call(method: string, params?: unknown): Promise<unknown>
@@ -67,6 +68,7 @@ export function createMockHost(
): MockHost {
const capabilities = new Set(options.capabilities ?? declaredCapabilities)
const results = new Map<string, unknown>(Object.entries(options.results ?? {}))
const data = createMockPluginData(options)
const methods = pluginFrameMethodsFor('panel', true)
const calls: MockHostCall[] = []
const pending = new Set<Promise<unknown>>()
@@ -93,11 +95,16 @@ export function createMockHost(
if (!parsedParams.success) {
throw hostError('invalid_params', parsedParams.error.issues[0]?.message ?? 'invalid params')
}
if (!results.has(method) && !Object.hasOwn(DEFAULT_RESULTS, method)) {
const builtIn = !results.has(method) && data.handles(method)
if (!results.has(method) && !builtIn && !Object.hasOwn(DEFAULT_RESULTS, method)) {
throw hostError('unavailable', `the test configured no result for ${method}`)
}
const configured: unknown = results.has(method) ? results.get(method) : DEFAULT_RESULTS[method]
const value = isResultFunction(configured) ? await configured(parsedParams.data) : configured
const value = builtIn
? await data.answer(method, parsedParams.data)
: isResultFunction(configured)
? await configured(parsedParams.data)
: configured
const parsedResult = spec.result.safeParse(value)
if (!parsedResult.success) {
// The test's mock is wrong, not the plugin: fail loudly instead of rejecting the call.
@@ -118,6 +125,8 @@ export function createMockHost(
// Single-use, like a press: an unused grant does not pile up.
gestures = 1
},
data: () => data.snapshot(),
onDataChange: (listener) => data.onChange(listener),
async idle() {
while (pending.size > 0) {
await Promise.allSettled(pending)
@@ -0,0 +1,79 @@
import type { OrcaBridge, OrcaDisposable } from '../runtime/declarative-runtime-types'
type Listener = (payload: unknown) => void
/**
* The frame shell's `plugin`, `storage`, `settings` and `secrets` for a mounted test panel, over
* the mock host's calls: what plugin-panel-shell-facades.ts gives a real guest. `post` stands in
* for the worker's `orca.panels.post`; `changed` for Orca telling the panel a key changed.
*/
export function createTestingPanelFacades(
call: (method: string, params?: unknown) => Promise<unknown>
) {
const listeners = new Map<string, Set<Listener>>()
const listen = (channel: string, handler: Listener): OrcaDisposable => {
const set = listeners.get(channel) ?? new Set()
set.add(handler)
listeners.set(channel, set)
return { dispose: () => set.delete(handler) }
}
const fire = (channel: string, payload: unknown): void => {
for (const handler of listeners.get(channel) ?? []) {
handler(payload)
}
}
const pick =
(name: string) =>
(result: unknown): unknown =>
typeof result === 'object' && result !== null && name in result
? Object.getOwnPropertyDescriptor(result, name)?.value
: undefined
const done = (): void => undefined
const facades: Required<Pick<OrcaBridge, 'plugin' | 'storage' | 'settings' | 'secrets'>> = {
plugin: {
request: (name, input, options) => {
const timeoutMs =
typeof options === 'object' && options !== null && 'timeoutMs' in options
? options.timeoutMs
: undefined
return call('plugin.request', {
name,
...(input === undefined ? {} : { input }),
...(typeof timeoutMs === 'number' ? { timeoutMs } : {})
}).then(pick('output'))
},
on: (event, handler) => listen(`message:${event}`, handler)
},
storage: {
get: (key) => call('storage.get', { key }).then((result) => pick('value')(result) ?? null),
set: (key, value) => call('storage.set', { key, value }).then(done),
delete: (key) => call('storage.delete', { key }).then(done),
keys: async () => {
const keys = pick('keys')(await call('storage.keys'))
return Array.isArray(keys) ? keys.map(String) : []
},
onDidChange: (handler) => listen('changed:storage', (key) => handler({ key: String(key) }))
},
settings: {
get: async (key) => {
const all = pick('settings')(await call('settings.get'))
return key === undefined ? all : pick(key)(all)
},
set: (key, value) => call('settings.set', { key, value }).then(done),
onDidChange: (handler) => listen('changed:settings', (key) => handler({ key: String(key) }))
},
secrets: {
get: async (key) => {
const value = pick('value')(await call('secrets.get', { key }))
return typeof value === 'string' ? value : null
},
set: (key, value) => call('secrets.set', { key, value }).then(done),
delete: (key) => call('secrets.delete', { key }).then(done)
}
}
return {
facades,
post: (event: string, payload: unknown): void => fire(`message:${event}`, payload),
changed: (area: 'storage' | 'settings', key: string): void => fire(`changed:${area}`, key)
}
}
@@ -19,21 +19,18 @@ import {
type TreeSnapshot
} from './testing-tree'
import { createValueControls } from './testing-value-controls'
import { createTestingPanelFacades } from './testing-panel-facades'
import { seedPersisted } from './testing-persisted'
export { stored, type StoredValue } from './testing-persisted'
export type PanelIssue = { kind: 'plugin' | 'refused'; message: string; stack?: string }
type Stored = { version: number; value: unknown }
export type PersistedState = { plugin: Record<string, unknown>; workspace: Record<string, unknown> }
const STORED = Symbol.for('orca.testing.stored')
export type StoredValue = { readonly [STORED]: true; version: number; value: unknown }
/** A persisted value written by an older version of the panel, for testing `migrate`. */
export function stored(value: unknown, version: number): StoredValue {
return Object.freeze({ [STORED]: true as const, version, value })
}
function isStoredValue(value: unknown): value is StoredValue {
return typeof value === 'object' && value !== null && STORED in value
export type PersistedState = {
plugin: Record<string, unknown>
workspace: Record<string, unknown>
/** The plugin's storage (`persist: 'storage'` atoms and `storage.set`), on the mock host. */
storage: Record<string, unknown>
}
export type MountOptions = {
@@ -80,16 +77,7 @@ export async function mountPanel(
plugin: new Map(),
workspace: new Map()
}
for (const scope of ['plugin', 'workspace'] as const) {
for (const [key, value] of Object.entries(options.persisted?.[scope] ?? {})) {
storage[scope].set(
key,
isStoredValue(value)
? { version: value.version, value: value.value }
: { version: 1, value }
)
}
}
seedPersisted(storage, options.persisted)
let visible = options.visible ?? true
let shown: { document: string; revision: number; tree: PluginDeclarativeNode | null } = {
document: '',
@@ -97,6 +85,8 @@ export async function mountPanel(
tree: null
}
const controls = createValueControls()
const data = createTestingPanelFacades(host.bridge.call)
const stopDataChanges = host.onDataChange(data.changed)
function post(event: string, payload: unknown): void {
if (event === PLUGIN_DECLARATIVE_MESSAGES.ready) {
@@ -160,6 +150,7 @@ export async function mountPanel(
api: host.bridge.api,
locale: options.locale ?? 'en',
host: { call: host.bridge.call, has: host.bridge.has },
...data.facades,
on(event, handler) {
const set = listeners.get(event) ?? new Set()
set.add(handler)
@@ -246,7 +237,7 @@ export async function mountPanel(
get persisted(): PersistedState {
const read = (scope: 'plugin' | 'workspace') =>
Object.fromEntries([...storage[scope]].map(([key, entry]) => [key, entry.value]))
return { plugin: read('plugin'), workspace: read('workspace') }
return { plugin: read('plugin'), workspace: read('workspace'), storage: host.data().storage }
},
settled,
async press(target: Target): Promise<void> {
@@ -298,6 +289,11 @@ export async function mountPanel(
emit(event, payload)
await settled()
},
/** What the plugin's worker posts with `orca.panels.post`; `plugin.on` handlers hear it. */
async post(event: string, payload: unknown): Promise<void> {
data.post(event, payload)
await settled()
},
async setVisible(next: boolean): Promise<void> {
visible = next
emit(PLUGIN_DECLARATIVE_MESSAGES.visibility, { visible: next })
@@ -310,6 +306,7 @@ export async function mountPanel(
async unmount(): Promise<void> {
runtime.dispose()
listeners.clear()
stopDataChanges()
}
}
}
@@ -0,0 +1,30 @@
type Stored = { version: number; value: unknown }
const STORED = Symbol.for('orca.testing.stored')
export type StoredValue = { readonly [STORED]: true; version: number; value: unknown }
/** A persisted value written by an older version of the panel, for testing `migrate`. */
export function stored(value: unknown, version: number): StoredValue {
return Object.freeze({ [STORED]: true as const, version, value })
}
function isStoredValue(value: unknown): value is StoredValue {
return typeof value === 'object' && value !== null && STORED in value
}
/** Values an earlier run persisted: plain values at version 1, `stored()` ones as given. */
export function seedPersisted(
storage: Record<'plugin' | 'workspace', Map<string, Stored>>,
persisted: { plugin?: Record<string, unknown>; workspace?: Record<string, unknown> } | undefined
): void {
for (const scope of ['plugin', 'workspace'] as const) {
for (const [key, value] of Object.entries(persisted?.[scope] ?? {})) {
storage[scope].set(
key,
isStoredValue(value)
? { version: value.version, value: value.value }
: { version: 1, value }
)
}
}
}
@@ -0,0 +1,117 @@
import { hostError } from './testing-host-error'
/** What the stand-in Orca holds for the plugin, and the worker handlers it fakes. */
export type MockPluginDataOptions = {
/** `plugin.request` handlers by name: the answer, or a function of the input (it may throw
* `hostError(...)`, which the panel then sees). An unlisted name is `unknown_method`. */
requests?: Record<string, unknown>
/** The plugin's storage before the panel runs, by key. */
storage?: Record<string, unknown>
/** Its settings, declared defaults included. */
settings?: Record<string, unknown>
secrets?: Record<string, string>
}
export type MockPluginDataArea = 'storage' | 'settings' | 'secrets'
export type MockPluginDataSnapshot = Record<MockPluginDataArea, Record<string, unknown>>
const HANDLED = new Set([
'plugin.request',
'events.subscribe',
'storage.get',
'storage.set',
'storage.delete',
'storage.keys',
'settings.get',
'settings.set',
'secrets.get',
'secrets.set',
'secrets.delete',
'secrets.protection'
])
function field(params: unknown, name: string): unknown {
return typeof params === 'object' && params !== null && name in params
? Object.getOwnPropertyDescriptor(params, name)?.value
: undefined
}
/** In-memory storage, settings and secrets, and the plugin's fake worker, behind the host methods
* Orca answers for them. Writes tell `onChange` listeners, as Orca tells open panels. */
export function createMockPluginData(options: MockPluginDataOptions) {
const areas: Record<MockPluginDataArea, Map<string, unknown>> = {
storage: new Map(Object.entries(options.storage ?? {})),
settings: new Map(Object.entries(options.settings ?? {})),
secrets: new Map(Object.entries(options.secrets ?? {}))
}
const listeners = new Set<(area: 'storage' | 'settings', key: string) => void>()
const write = (area: MockPluginDataArea, key: string, value: unknown): { ok: true } => {
if (value === undefined) {
areas[area].delete(key)
} else {
areas[area].set(key, value)
}
if (area !== 'secrets') {
for (const listener of listeners) {
listener(area, key)
}
}
return { ok: true }
}
async function request(params: unknown): Promise<{ output: unknown }> {
const name = String(field(params, 'name'))
if (!options.requests || !Object.hasOwn(options.requests, name)) {
throw hostError('unknown_method', `no panel handler named ${name}`)
}
const handler: unknown = options.requests[name]
const input = field(params, 'input')
const output = typeof handler === 'function' ? await handler(input) : handler
return { output: output ?? null }
}
return {
handles: (method: string): boolean => HANDLED.has(method),
async answer(method: string, params: unknown): Promise<unknown> {
const key = String(field(params, 'key'))
const value = field(params, 'value')
switch (method) {
case 'plugin.request':
return request(params)
case 'storage.get':
return { value: areas.storage.get(key) ?? null }
case 'storage.keys':
return { keys: [...areas.storage.keys()] }
case 'settings.get':
return { settings: Object.fromEntries(areas.settings) }
case 'secrets.get':
return { value: areas.secrets.get(key) ?? null }
case 'secrets.protection':
return { status: 'os-keyring' }
case 'storage.set':
return write('storage', key, value)
case 'settings.set':
return write('settings', key, value)
case 'secrets.set':
return write('secrets', key, value)
case 'storage.delete':
return write('storage', key, undefined)
case 'secrets.delete':
return write('secrets', key, undefined)
default:
return { ok: true }
}
},
onChange(listener: (area: 'storage' | 'settings', key: string) => void): () => void {
listeners.add(listener)
return () => listeners.delete(listener)
},
snapshot: (): MockPluginDataSnapshot => ({
storage: Object.fromEntries(areas.storage),
settings: Object.fromEntries(areas.settings),
secrets: Object.fromEntries(areas.secrets)
})
}
}
export type MockPluginData = ReturnType<typeof createMockPluginData>