Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

Allow conflict-safe private storage from plugin panels (#36273)

Jinjing5b505a6e9447
diff --git a/docs/reference/plugin-host-api.md b/docs/reference/plugin-host-api.md
index 0ca76671dc6..00c7f4e107d 100644
--- a/docs/reference/plugin-host-api.md
+++ b/docs/reference/plugin-host-api.md
@@ -2,7 +2,7 @@
<!-- Generated by `pnpm generate:plugin-schemas` from src/shared/plugins. Do not edit. -->
-Host API 1.0 (`"pluginApi": 1`). Workers call a method with `await orca.host.call(name, params)`; panels and custom editors call the same methods through `window.orca.host.call(name, params)`. Each method lists the surfaces allowed to call it; any other surface gets `not_permitted`. `orca.host.has(name)` answers synchronously whether this Orca offers a method on the current surface, and `orca.api` is `{ major, minor }`. See [Plugin authoring](./plugin-authoring.md) for the frame API.
+Host API 1.1 (`"pluginApi": 1`). Workers call a method with `await orca.host.call(name, params)`; panels and custom editors call the same methods through `window.orca.host.call(name, params)`. Each method lists the surfaces allowed to call it; any other surface gets `not_permitted`. `orca.host.has(name)` answers synchronously whether this Orca offers a method on the current surface, and `orca.api` is `{ major, minor }`. See [Plugin authoring](./plugin-authoring.md) for the frame API.
Every call is checked against the capabilities the user approved, and params are validated before Orca runs anything: params are strict, so a field this Orca does not know is refused with `invalid_params` instead of being dropped. Mutations are recorded in the audit log as `plugin:<publisher>.<id>`.
@@ -13,7 +13,8 @@ Every call is checked against the capabilities the user approved, and params are
| [`workspace.readContext`](#workspacereadcontext) | `workspace:read` | worker, panel, editor | no | 1.0 | Branch, name and terminal ids of the focused workspace, or null when none is focused. |
| [`terminal.sendText`](#terminalsendtext) | `terminal:send` | worker | yes | 1.0 | Types text into one terminal named by id, optionally pressing Enter. |
| [`notifications.show`](#notificationsshow) | `notifications:show` | worker, panel, editor | yes | 1.0 | Shows a desktop notification. |
-| [`storage.get`](#storageget) | `storage:own` | worker | no | 1.0 | Reads a JSON value from the plugin's private store; null when absent. |
+| [`storage.get`](#storageget) | `storage:own` | worker, panel, editor | no | 1.0 | Reads a JSON value from the plugin's private store; null when absent. |
+| [`storage.compareAndSet`](#storagecompareandset) | `storage:own` | worker, panel, editor | yes | 1.1 | Atomically writes a private JSON value only if it still matches expected; absent keys compare as null. |
| [`storage.set`](#storageset) | `storage:own` | worker | yes | 1.0 | Writes a JSON value to the plugin's private store. |
| [`storage.delete`](#storagedelete) | `storage:own` | worker | yes | 1.0 | Removes a key from the plugin's private store. |
| [`storage.keys`](#storagekeys) | `storage:own` | worker | no | 1.0 | Lists the keys in the plugin's private store. |
@@ -55,6 +56,14 @@ Reads a JSON value from the plugin's private store; null when absent.
(params: { key: string }) => { value: JSON }
```
+### `storage.compareAndSet`
+
+Atomically writes a private JSON value only if it still matches expected; absent keys compare as null.
+
+```ts
+(params: { key: string; expected: JSON; value: JSON }) => { swapped: boolean }
+```
+
### `storage.set`
Writes a JSON value to the plugin's private store.
diff --git a/src/main/plugins/plugin-storage-store.test.ts b/src/main/plugins/plugin-storage-store.test.ts
index 44d54b249b2..d59acec196b 100644
--- a/src/main/plugins/plugin-storage-store.test.ts
+++ b/src/main/plugins/plugin-storage-store.test.ts
@@ -25,3 +25,12 @@ describe('PluginKvStore limits', () => {
expect(store.get('large')).toBeUndefined()
})
})
+
+it('reads only stored keys, including names inherited by plain objects', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'orca-plugin-storage-'))
+ roots.push(root)
+ const store = new PluginKvStore(root, 'samples.demo', 'storage.json')
+ expect(store.get('toString')).toBeUndefined()
+ expect(store.set('toString', 'saved')).toEqual({ ok: true })
+ expect(new PluginKvStore(root, 'samples.demo', 'storage.json').get('toString')).toBe('saved')
+})
diff --git a/src/main/plugins/plugin-storage-store.ts b/src/main/plugins/plugin-storage-store.ts
index b0010391510..9d141c8b55c 100644
--- a/src/main/plugins/plugin-storage-store.ts
+++ b/src/main/plugins/plugin-storage-store.ts
@@ -57,7 +57,8 @@ export class PluginKvStore {
}
get(key: string): PluginJsonValue | undefined {
- return this.read()?.[key]
+ const settings = this.read()
+ return settings && Object.hasOwn(settings, key) ? settings[key] : undefined
}
getAll(): Record<string, PluginJsonValue> {
diff --git a/src/main/plugins/workers/plugin-host-method-bindings.ts b/src/main/plugins/workers/plugin-host-method-bindings.ts
index bedd08f3c6d..1235b1a01ea 100644
--- a/src/main/plugins/workers/plugin-host-method-bindings.ts
+++ b/src/main/plugins/workers/plugin-host-method-bindings.ts
@@ -1,3 +1,4 @@
+import { isDeepStrictEqual } from 'node:util'
import type { z } from 'zod'
import {
isPluginHostMethodName,
@@ -142,6 +143,16 @@ const HANDLERS: Record<PluginHostMethodName, BoundPluginHostMethod> = {
'storage.get': bind(api['storage.get'], async ({ key }, { pluginId, services }) => ({
value: services.storage.get(pluginId, key) ?? null
})),
+ 'storage.compareAndSet': bind(
+ api['storage.compareAndSet'],
+ async ({ key, expected, value }, { pluginId, services }) => {
+ if (!isDeepStrictEqual(services.storage.get(pluginId, key) ?? null, expected)) {
+ return { swapped: false }
+ }
+ okOrThrow(services.storage.set(pluginId, key, value))
+ return { swapped: true }
+ }
+ ),
'storage.set': bind(api['storage.set'], async ({ key, value }, { pluginId, services }) =>
okOrThrow(services.storage.set(pluginId, key, value))
),
diff --git a/src/main/plugins/workers/plugin-host-methods.ts b/src/main/plugins/workers/plugin-host-methods.ts
index d1e4c098b82..7f218dfacd6 100644
--- a/src/main/plugins/workers/plugin-host-methods.ts
+++ b/src/main/plugins/workers/plugin-host-methods.ts
@@ -120,6 +120,7 @@ function summarizeParams(method: string, params: unknown): string {
const title = typeof record.title === 'string' ? record.title : ''
return `titleChars=${title.length}`
}
+ case 'storage.compareAndSet':
case 'storage.set':
case 'storage.delete':
case 'secrets.set':
diff --git a/src/main/plugins/workers/plugin-host-runtime.test.ts b/src/main/plugins/workers/plugin-host-runtime.test.ts
index 03b9a8693b7..ee24baf62b3 100644
--- a/src/main/plugins/workers/plugin-host-runtime.test.ts
+++ b/src/main/plugins/workers/plugin-host-runtime.test.ts
@@ -87,7 +87,7 @@ describe('worker orca API parity with frames', () => {
it('exposes api and a synchronous has() for worker methods', async () => {
let orca!: PluginWorkerOrcaApi
await activateWith((api) => (orca = api))
- expect(orca.api).toEqual({ major: 1, minor: 0 })
+ expect(orca.api).toEqual({ major: 1, minor: 1 })
expect(orca.host.has('storage.get')).toBe(true)
expect(orca.host.has('editor.applyEdit')).toBe(false)
expect(Object.isFrozen(orca)).toBe(true)
diff --git a/src/main/plugins/workers/plugin-panel-storage.test.ts b/src/main/plugins/workers/plugin-panel-storage.test.ts
new file mode 100644
index 00000000000..6e99d9d4a7a
--- /dev/null
+++ b/src/main/plugins/workers/plugin-panel-storage.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it, vi } from 'vitest'
+import { executePluginHostCall, type PluginHostServices } from './plugin-host-methods'
+
+function createServices(storageSet: PluginHostServices['storage']['set']): PluginHostServices {
+ return {
+ resolveActiveWorktreeContext: vi.fn().mockResolvedValue(null),
+ listWorktreeTerminals: vi.fn().mockResolvedValue([]),
+ sendTerminalText: vi.fn().mockResolvedValue({ accepted: true }),
+ dispatchPluginNotification: vi.fn().mockResolvedValue({ delivered: true }),
+ storage: {
+ get: vi.fn(),
+ set: storageSet,
+ delete: vi.fn(),
+ keys: vi.fn().mockReturnValue([])
+ },
+ secrets: {
+ get: vi.fn().mockReturnValue({ ok: true, value: null }),
+ set: vi.fn().mockReturnValue({ ok: true }),
+ delete: vi.fn()
+ },
+ settings: {
+ getAll: vi.fn().mockReturnValue({}),
+ set: vi.fn().mockReturnValue({ ok: true })
+ }
+ }
+}
+
+describe('panel private storage', () => {
+ it('requires consent and prevents stale concurrent writes', async () => {
+ let value: string | null = null
+ const services = createServices(
+ vi.fn<PluginHostServices['storage']['set']>((_pluginId, _key, next) => {
+ value = typeof next === 'string' ? next : null
+ return { ok: true }
+ })
+ )
+ vi.mocked(services.storage.get).mockImplementation(() => value)
+ const request = (
+ expected: null,
+ next: string | null,
+ capabilities: 'storage:own'[] = ['storage:own']
+ ) =>
+ executePluginHostCall({
+ pluginId: 'samples.demo',
+ method: 'storage.compareAndSet',
+ params: { key: 'notes', expected, value: next },
+ surface: 'panel',
+ grantedCapabilities: capabilities,
+ services,
+ audit: { record: vi.fn().mockResolvedValue(undefined) }
+ })
+ expect(await request(null, 'denied', [])).toMatchObject({ ok: false })
+ expect(value).toBeNull()
+ expect(await request(null, null)).toEqual({ ok: true, value: { swapped: true } })
+ const results = await Promise.all([request(null, 'first'), request(null, 'second')])
+ expect(results).toContainEqual({ ok: true, value: { swapped: true } })
+ expect(results).toContainEqual({ ok: true, value: { swapped: false } })
+ expect(value).toBe('first')
+ expect(
+ await executePluginHostCall({
+ pluginId: 'samples.demo',
+ method: 'storage.get',
+ params: { key: 'notes' },
+ surface: 'panel',
+ grantedCapabilities: ['storage:own'],
+ services,
+ audit: { record: vi.fn().mockResolvedValue(undefined) }
+ })
+ ).toMatchObject({ ok: true, value: { value: 'first' } })
+ })
+})
diff --git a/src/renderer/src/components/right-sidebar/plugin-frame-host.test.ts b/src/renderer/src/components/right-sidebar/plugin-frame-host.test.ts
index 139ab5b2268..01d70da5b7c 100644
--- a/src/renderer/src/components/right-sidebar/plugin-frame-host.test.ts
+++ b/src/renderer/src/components/right-sidebar/plugin-frame-host.test.ts
@@ -93,12 +93,13 @@ describe('createPluginFrameMessageHandler', () => {
payload: {
protocol: 1,
surface: 'editor',
- api: { major: 1, minor: 0 },
+ api: { major: 1, minor: 1 },
theme: { colorScheme: 'dark', tokens: '--orca-background:#000' }
}
})
expect(hello.payload.methods).toContain('notifications.show')
- expect(hello.payload.methods).not.toContain('storage.get')
+ expect(hello.payload.methods).toContain('storage.get')
+ expect(hello.payload.methods).toContain('storage.compareAndSet')
expect(onReady).toHaveBeenCalledOnce()
})
diff --git a/src/shared/plugins/frames/plugin-frame-api.test.ts b/src/shared/plugins/frames/plugin-frame-api.test.ts
index d197e7ac080..a718204d745 100644
--- a/src/shared/plugins/frames/plugin-frame-api.test.ts
+++ b/src/shared/plugins/frames/plugin-frame-api.test.ts
@@ -53,7 +53,7 @@ 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: 1 })
expect(orca.host.has('workspace.readContext')).toBe(true)
expect(orca.host.has('terminal.sendText')).toBe(false)
expect(orca.document).toBeUndefined()
diff --git a/src/shared/plugins/workers/plugin-host-api.ts b/src/shared/plugins/workers/plugin-host-api.ts
index 5a4f44a799e..6c65745843c 100644
--- a/src/shared/plugins/workers/plugin-host-api.ts
+++ b/src/shared/plugins/workers/plugin-host-api.ts
@@ -159,10 +159,25 @@ export const PLUGIN_HOST_API = {
scope: 'plugin-private',
capability: 'storage:own',
mutation: false,
- surfaces: WORKER_ONLY,
+ surfaces: ALL_SURFACES,
params: storageGetParams,
result: storageGetResult
}),
+ 'storage.compareAndSet': spec({
+ summary:
+ 'Atomically writes a private JSON value only if it still matches expected; absent keys compare as null.',
+ since: 1,
+ scope: 'plugin-private',
+ capability: 'storage:own',
+ mutation: true,
+ surfaces: ALL_SURFACES,
+ params: z.strictObject({
+ key: storageKeySchema,
+ expected: pluginJsonValueSchema,
+ value: pluginJsonValueSchema
+ }),
+ result: z.object({ swapped: z.boolean() })
+ }),
'storage.set': spec({
summary: "Writes a JSON value to the plugin's private store.",
since: 0,