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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/reference/plugin-authoring.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,8 @@ To show the workspace's agents, list them once with `agents.list` (`agent:read`)
`workspace.readContext` lists (with each terminal's `title`) and `terminal.sendText` takes; an
event's `paneKey` is Orca's own pane id. `workspace.changed` (`workspace:read`) carries the new
`workspace.readContext` answer whenever focus moves to another workspace or its terminals open,
close or are renamed, so a panel never polls.
close or are renamed, and once right when a panel or worker subscribes, so a panel never polls
and never starts out stale.

```ts
import { atom, host, on, read, set, update } from 'orca'
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/plugin-host-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ A worker receives the events its manifest lists in `contributes.events` through
| `workspace.created` | `{ workspaceId: string; kind: "worktree" \| "folder"; path: string; branch: string }` | A worktree workspace was created. |
| `workspace.removed` | `{ workspaceId: string; kind: "worktree" \| "folder"; path: string }` | A worktree workspace was removed. |
| `agent.status.changed` | `{ workspaceId: string \| null; paneKey: string; terminalId?: string; title?: string; state: "working" \| "blocked" \| "waiting" \| "done"; receivedAt: number; mainAgent?: { state: "working" \| "blocked" \| "waiting" \| "done"; outcome?: "success" \| "failure" \| "cancellation" \| "superseded" \| "interruption" \| "unconfirmed"; stateStartedAt: number } }` | An agent in a terminal pane changed status; `workspaceId` is null when Orca cannot tie the pane to a workspace, and `terminalId` names its terminal when Orca lists it. |
| `workspace.changed` | `{ context: { branch: string; displayName: string; terminals: { id: string; title?: string }[] } \| null }` | The focused workspace changed, or its terminals were opened, closed or renamed; `context` is what `workspace.readContext` now answers. |
| `workspace.changed` | `{ context: { branch: string; displayName: string; terminals: { id: string; title?: string }[] } \| null }` | The focused workspace changed, or its terminals were opened, closed or renamed; `context` is what `workspace.readContext` now answers. Each new subscriber first gets the current context. |

## Errors

Expand Down
2 changes: 1 addition & 1 deletion resources/plugins/declarative/orca-testing.mjs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion resources/plugins/declarative/orca.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ declare module 'orca' {
"workspace.removed": { workspaceId: string; kind: "worktree" | "folder"; path: string }
/** An agent in a terminal pane changed status; `workspaceId` is null when Orca cannot tie the pane to a workspace, and `terminalId` names its terminal when Orca lists it. */
"agent.status.changed": { workspaceId: string | null; paneKey: string; terminalId?: string; title?: string; state: "working" | "blocked" | "waiting" | "done"; receivedAt: number; mainAgent?: { state: "working" | "blocked" | "waiting" | "done"; outcome?: "success" | "failure" | "cancellation" | "superseded" | "interruption" | "unconfirmed"; stateStartedAt: number } }
/** The focused workspace changed, or its terminals were opened, closed or renamed; `context` is what `workspace.readContext` now answers. */
/** The focused workspace changed, or its terminals were opened, closed or renamed; `context` is what `workspace.readContext` now answers. Each new subscriber first gets the current context. */
"workspace.changed": { context: { branch: string; displayName: string; terminals: { id: string; title?: string }[] } | null }
}
// </generated>
Expand Down
2 changes: 1 addition & 1 deletion resources/plugins/types/orca-host.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ declare module 'orca/host' {
"workspace.removed": { workspaceId: string; kind: "worktree" | "folder"; path: string }
/** An agent in a terminal pane changed status; `workspaceId` is null when Orca cannot tie the pane to a workspace, and `terminalId` names its terminal when Orca lists it. */
"agent.status.changed": { workspaceId: string | null; paneKey: string; terminalId?: string; title?: string; state: "working" | "blocked" | "waiting" | "done"; receivedAt: number; mainAgent?: { state: "working" | "blocked" | "waiting" | "done"; outcome?: "success" | "failure" | "cancellation" | "superseded" | "interruption" | "unconfirmed"; stateStartedAt: number } }
/** The focused workspace changed, or its terminals were opened, closed or renamed; `context` is what `workspace.readContext` now answers. */
/** The focused workspace changed, or its terminals were opened, closed or renamed; `context` is what `workspace.readContext` now answers. Each new subscriber first gets the current context. */
"workspace.changed": { context: { branch: string; displayName: string; terminals: { id: string; title?: string }[] } | null }
}
export type PluginEventName = keyof PluginEvents
Expand Down
2 changes: 1 addition & 1 deletion skill-guides/orca-plugin-authoring/references/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ List each in `contributes.events` (`{ "on": "<event>" }`), with `main`, the `tru
`{ workspaceId: string; kind: "worktree" | "folder"; path: string }`
- `agent.status.changed` (capability `agent:read`; since 1.4.160): An agent in a terminal pane changed status; `workspaceId` is null when Orca cannot tie the pane to a workspace, and `terminalId` names its terminal when Orca lists it.
`{ workspaceId: string | null; paneKey: string; terminalId?: string; title?: string; state: "working" | "blocked" | "waiting" | "done"; receivedAt: number; mainAgent?: { state: "working" | "blocked" | "waiting" | "done"; outcome?: "success" | "failure" | "cancellation" | "superseded" | "interruption" | "unconfirmed"; stateStartedAt: number } }`
- `workspace.changed` (capability `workspace:read`; since 1.4.246): The focused workspace changed, or its terminals were opened, closed or renamed; `context` is what `workspace.readContext` now answers.
- `workspace.changed` (capability `workspace:read`; since 1.4.246): The focused workspace changed, or its terminals were opened, closed or renamed; `context` is what `workspace.readContext` now answers. Each new subscriber first gets the current context.
`{ context: { branch: string; displayName: string; terminals: { id: string; title?: string }[] } | null }`

## Frame events (`orca.on(event, handler)` in HTML panels and custom editors)
Expand Down
5 changes: 3 additions & 2 deletions skill-guides/orca-plugin-authoring/references/recipes.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ agent events with `on(...)` (frames: `orca.on`) without `contributes.events`.
2. Push `on('agent.status.changed', ({ terminalId, title, state }) => ...)` into
`ctx.subscriptions` and update the row with that `terminalId` (the id `workspace.readContext`
lists and `terminal.sendText` takes; `paneKey` is Orca's own id).
3. Push `on('workspace.changed', ...)` too and re-run `agents.list`: it fires when focus moves or
terminals open, close or are renamed, with the new `readContext` answer in `context`.
3. Push `on('workspace.changed', ...)` too and re-run `agents.list`: it fires once with the
current context as you subscribe, then when focus moves or terminals open, close or are
renamed, with the new `readContext` answer in `context`.
4. Keep the rows in an atom and render them as a `Table` (or `List`/`ListItem`); show "since" with
a `{ type: 'relative', at: stateStartedAt }` cell, which Orca keeps current. Never poll.
5. Test it with `mockHost({ results: { 'agents.list': { agents: [...] } } })` and
Expand Down
7 changes: 4 additions & 3 deletions src/cli/bundled-skill-guides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2817,7 +2817,7 @@ const ORCA_PLUGIN_AUTHORING_EVENTS_REFERENCE_MARKDOWN = [
" `{ workspaceId: string; kind: \"worktree\" | \"folder\"; path: string }`",
"- `agent.status.changed` (capability `agent:read`; since 1.4.160): An agent in a terminal pane changed status; `workspaceId` is null when Orca cannot tie the pane to a workspace, and `terminalId` names its terminal when Orca lists it.",
" `{ workspaceId: string | null; paneKey: string; terminalId?: string; title?: string; state: \"working\" | \"blocked\" | \"waiting\" | \"done\"; receivedAt: number; mainAgent?: { state: \"working\" | \"blocked\" | \"waiting\" | \"done\"; outcome?: \"success\" | \"failure\" | \"cancellation\" | \"superseded\" | \"interruption\" | \"unconfirmed\"; stateStartedAt: number } }`",
"- `workspace.changed` (capability `workspace:read`; since 1.4.246): The focused workspace changed, or its terminals were opened, closed or renamed; `context` is what `workspace.readContext` now answers.",
"- `workspace.changed` (capability `workspace:read`; since 1.4.246): The focused workspace changed, or its terminals were opened, closed or renamed; `context` is what `workspace.readContext` now answers. Each new subscriber first gets the current context.",
" `{ context: { branch: string; displayName: string; terminals: { id: string; title?: string }[] } | null }`",
"",
"## Frame events (`orca.on(event, handler)` in HTML panels and custom editors)",
Expand Down Expand Up @@ -3173,8 +3173,9 @@ const ORCA_PLUGIN_AUTHORING_RECIPES_REFERENCE_MARKDOWN = [
"2. Push `on('agent.status.changed', ({ terminalId, title, state }) => ...)` into",
" `ctx.subscriptions` and update the row with that `terminalId` (the id `workspace.readContext`",
" lists and `terminal.sendText` takes; `paneKey` is Orca's own id).",
"3. Push `on('workspace.changed', ...)` too and re-run `agents.list`: it fires when focus moves or",
" terminals open, close or are renamed, with the new `readContext` answer in `context`.",
"3. Push `on('workspace.changed', ...)` too and re-run `agents.list`: it fires once with the",
" current context as you subscribe, then when focus moves or terminals open, close or are",
" renamed, with the new `readContext` answer in `context`.",
"4. Keep the rows in an atom and render them as a `Table` (or `List`/`ListItem`); show \"since\" with",
" a `{ type: 'relative', at: stateStartedAt }` cell, which Orca keeps current. Never poll.",
"5. Test it with `mockHost({ results: { 'agents.list': { agents: [...] } } })` and",
Expand Down
76 changes: 76 additions & 0 deletions src/main/plugins/panels/plugin-panel-bridge-replay.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { describe, expect, it, vi } from 'vitest'
import type { PluginCapabilityKind } from '../../../shared/plugins/capabilities/plugin-capabilities'
import type { PluginRuntimeDelegate } from '../workers/plugin-host-service-bindings'
import { PluginPanelBridge } from './plugin-panel-bridge'

const caller = { id: 'panel-a', surface: 'panel' as const, contributionId: 'board' }
const LEAF = '11111111-1111-4111-8111-111111111111'

function setup(capabilities: PluginCapabilityKind[] = ['workspace:read']) {
let active: string | null = 'repo::/w'
const delegate: PluginRuntimeDelegate = {
resolveActiveWorktreeContext: async () =>
active
? { worktreeId: active, path: '/w', branch: 'refs/heads/main', displayName: 'w' }
: null,
listTerminals: async () => ({
terminals: [{ handle: 'term_a', title: 'zsh', tabId: 'tab0', leafId: LEAF }]
}),
sendTerminal: vi.fn(),
dispatchPluginNotification: vi.fn()
}
const bridge = new PluginPanelBridge({
findApprovedPlugin: () => null,
grantedCapabilities: () => capabilities,
ensureWorker: vi.fn(),
runningWorker: () => null,
log: () => vi.fn(),
runtimeDelegate: () => delegate
})
return { bridge, unfocus: () => (active = null) }
}

const context = { branch: 'main', displayName: 'w', terminals: [{ id: 'term_a', title: 'zsh' }] }

describe('workspace.changed replay on subscribe', () => {
it('gives a panel the current context as soon as it subscribes', async () => {
const { bridge } = setup()
const deliver = vi.fn()
bridge.open(caller, 'acme.board', deliver)
bridge.subscribe('acme.board', caller.id, 'workspace.changed')
await vi.waitFor(() =>
expect(deliver).toHaveBeenCalledWith({
kind: 'event',
event: 'workspace.changed',
payload: { context }
})
)
})

it('holds the replay until the channel opens, when the frame subscribed first', async () => {
const { bridge, unfocus } = setup()
unfocus()
bridge.subscribe('acme.board', caller.id, 'workspace.changed')
const deliver = vi.fn()
bridge.open(caller, 'acme.board', deliver)
await vi.waitFor(() =>
expect(deliver).toHaveBeenCalledWith({
kind: 'event',
event: 'workspace.changed',
payload: { context: null }
})
)
expect(deliver).toHaveBeenCalledOnce()
})

it('replays nothing for other events, or once the panel has closed', async () => {
const { bridge } = setup(['workspace:read', 'agent:read'])
const deliver = vi.fn()
bridge.subscribe('acme.board', caller.id, 'workspace.changed')
bridge.close(caller.id)
bridge.open(caller, 'acme.board', deliver)
bridge.subscribe('acme.board', caller.id, 'agent.status.changed')
await new Promise((resolve) => setTimeout(resolve, 0))
expect(deliver).not.toHaveBeenCalled()
})
})
37 changes: 37 additions & 0 deletions src/main/plugins/panels/plugin-panel-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ const PLUGIN_JSON_VALUE = z.json()
import type { ValidDiscoveredPlugin } from '../plugin-discovery'
import type { PluginWorkerHandle } from '../workers/plugin-host-process'
import { PluginHostCallError } from '../workers/plugin-host-call-scope'
import type { PluginRuntimeDelegate } from '../workers/plugin-host-service-bindings'
import { readPluginWorkspaceChange } from '../plugin-runtime-binding'

type PushChannel = {
pluginKey: string
Expand All @@ -37,6 +39,8 @@ export type PluginPanelBridgeDependencies = {
ensureWorker: (plugin: ValidDiscoveredPlugin) => Promise<PluginWorkerHandle>
runningWorker: (pluginKey: string) => PluginWorkerHandle | null
log: (pluginKey: string) => (line: string) => void
/** For replaying the current workspace to a panel that subscribes to `workspace.changed`. */
runtimeDelegate?: () => PluginRuntimeDelegate | null
now?: () => number
}

Expand All @@ -61,13 +65,16 @@ export class PluginPanelBridge {
private readonly postBudgets = new Map<string, PanelMessageBudget>()
// By panel, not channel: a frame may subscribe before its renderer opens the channel.
private readonly subscriptions = new Map<string, Set<PluginEventName>>()
// Subscriptions still owed their current state, delivered once the panel's channel is open.
private readonly replays = new Map<string, Set<PluginEventName>>()

constructor(private readonly deps: PluginPanelBridgeDependencies) {}

/** A renderer listens to one open panel; the returned function stops it. */
open(caller: PluginPanelCaller, pluginKey: string, deliver: PushChannel['deliver']): () => void {
const channel: PushChannel = { pluginKey, deliver }
this.channels.set(caller.id, channel)
void this.replay(caller.id)
return () => {
if (this.channels.get(caller.id) === channel) {
this.channels.delete(caller.id)
Expand All @@ -79,6 +86,7 @@ export class PluginPanelBridge {
close(panelId: string): void {
this.channels.delete(panelId)
this.subscriptions.delete(panelId)
this.replays.delete(panelId)
this.lifetimes.get(panelId)?.abort()
this.lifetimes.delete(panelId)
}
Expand All @@ -94,6 +102,35 @@ export class PluginPanelBridge {
const events = this.subscriptions.get(panelId) ?? new Set<PluginEventName>()
events.add(event)
this.subscriptions.set(panelId, events)
// Why: a panel that subscribes after the last change (or before Orca focused a workspace)
// would otherwise show nothing until the next one.
if (event === 'workspace.changed') {
const owed = this.replays.get(panelId) ?? new Set<PluginEventName>()
owed.add(event)
this.replays.set(panelId, owed)
void this.replay(panelId)
}
}

/** Delivers the current state for each subscription still owed it, once the channel is open. */
private async replay(panelId: string): Promise<void> {
const channel = this.channels.get(panelId)
const owed = this.replays.get(panelId)
const delegate = this.deps.runtimeDelegate?.()
if (!channel || !owed || !delegate) {
return
}
this.replays.delete(panelId)
for (const event of owed) {
const payload = await readPluginWorkspaceChange(delegate)
if (
this.channels.get(panelId) === channel &&
this.subscriptions.get(panelId)?.has(event) &&
this.deps.grantedCapabilities(channel.pluginKey)?.includes(PLUGIN_EVENT_CAPABILITY[event])
) {
channel.deliver({ kind: 'event', event, payload })
}
}
}

/** Whether an open panel subscribed to `event`. */
Expand Down
22 changes: 15 additions & 7 deletions src/main/plugins/plugin-runtime-binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
projectPluginWorkspaceContext,
terminalForPane,
type PluginAgentStatusRow,
type PluginWorkspaceContext,
type PluginWorkspaceTerminal
} from './workers/plugin-workspace-projection'

Expand Down Expand Up @@ -80,6 +81,17 @@ export function createPluginAgentStatusForwarder(
}
}

/** The `workspace.changed` payload for the context as it is now. */
export async function readPluginWorkspaceChange(
delegate: PluginRuntimeDelegate
): Promise<{ context: PluginWorkspaceContext }> {
const context = await delegate.resolveActiveWorktreeContext().catch(() => null)
const terminals = context
? await listWorkspaceTerminals(delegate, context.worktreeId).catch(() => [])
: []
return { context: projectPluginWorkspaceContext(context, terminals) }
}

/**
* `workspace.changed`: after workspace session writes settle (focus moves, terminals open, close
* or are renamed), re-read the context and emit when it differs from the last one sent.
Expand All @@ -98,15 +110,11 @@ export function watchPluginWorkspaceContext(input: {
last = null
return
}
const context = await input.delegate.resolveActiveWorktreeContext().catch(() => null)
const terminals = context
? await listWorkspaceTerminals(input.delegate, context.worktreeId).catch(() => [])
: []
const projected = projectPluginWorkspaceContext(context, terminals)
const signature = JSON.stringify(projected)
const change = await readPluginWorkspaceChange(input.delegate)
const signature = JSON.stringify(change)
if (signature !== last) {
last = signature
input.events.emitEvent('workspace.changed', { context: projected })
input.events.emitEvent('workspace.changed', change)
}
}
const stop = input.onSessionWritten(() => {
Expand Down
3 changes: 2 additions & 1 deletion src/main/plugins/plugin-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ export class PluginService {
grantedCapabilities: (pluginKey) => this.getGrantedCapabilities(pluginKey),
ensureWorker: (plugin) => this.workerController.ensure(plugin),
runningWorker: (pluginKey) => this.workerController.runningHandle(pluginKey),
log: (pluginKey) => this.installed.captureLog(pluginKey, 'warn')
log: (pluginKey) => this.installed.captureLog(pluginKey, 'warn'),
runtimeDelegate: () => this.runtimeDelegate
})
this.hostCall = createPluginServiceHostCall((pluginKey, caller) =>
resolvePluginServiceHostCallPolicy({
Expand Down
20 changes: 20 additions & 0 deletions src/main/plugins/workers/plugin-worker-panel-requests.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,23 @@ describe('worker entry', () => {
)
})
})

describe('workspace.changed in workers', () => {
it('replays the current context to a handler as it subscribes', async () => {
let orca!: PluginWorkerOrcaApi
const { send, runtime } = await activate((api) => (orca = api))
const handler = vi.fn()
const disposed = vi.fn()
orca.events.on('workspace.changed', handler)
orca.events.on('workspace.changed', disposed).dispose()
const reads = send.mock.calls
.map(([message]) => message)
.filter((message) => message.method === 'workspace.readContext')
expect(reads).toHaveLength(2)
for (const read of reads) {
await runtime.handleMessage({ orca: 1, kind: 'res', id: read.id, result: { branch: 'main' } })
}
await vi.waitFor(() => expect(handler).toHaveBeenCalledWith({ context: { branch: 'main' } }))
expect(disposed).not.toHaveBeenCalled()
})
})
2 changes: 1 addition & 1 deletion src/shared/plugins/events/plugin-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export const PLUGIN_EVENT_SUMMARIES: Record<PluginEventName, string> = {
'agent.status.changed':
'An agent in a terminal pane changed status; `workspaceId` is null when Orca cannot tie the pane to a workspace, and `terminalId` names its terminal when Orca lists it.',
'workspace.changed':
'The focused workspace changed, or its terminals were opened, closed or renamed; `context` is what `workspace.readContext` now answers.'
'The focused workspace changed, or its terminals were opened, closed or renamed; `context` is what `workspace.readContext` now answers. Each new subscriber first gets the current context.'
}

export type PluginEventPayload<E extends PluginEventName> = z.infer<
Expand Down
Loading
Loading