Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(desktop-app): plugin UI SDK with consented context bridge

Andy Pavia8966952983bc
diff --git a/desktop-app/src/__tests__/pluginAuditLog.test.ts b/desktop-app/src/__tests__/pluginAuditLog.test.ts
new file mode 100644
index 000000000..dbc1a66c4
--- /dev/null
+++ b/desktop-app/src/__tests__/pluginAuditLog.test.ts
@@ -0,0 +1,104 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { promises as fs } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { AUDIT_MAX_BYTES, type AuditEntry, PluginAuditLog, shapeOf } from '../pluginAuditLog.js'
+
+const ENV_KEY = 'testenv-0123456789ab'
+
+let tmpDir: string
+let clock: number
+let log: PluginAuditLog
+
+function entry(overrides: Partial<AuditEntry> = {}): AuditEntry {
+ return {
+ ts: '2026-08-06T10:00:00.000Z',
+ userId: 'user-1',
+ pluginId: 'ns/plugin',
+ capability: 'identity.read',
+ outcome: 'allowed',
+ ...overrides,
+ }
+}
+
+beforeEach(async () => {
+ tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-audit-'))
+ clock = 1_700_000_000_000
+ log = new PluginAuditLog(tmpDir, () => clock)
+})
+
+afterEach(async () => {
+ await fs.rm(tmpDir, { recursive: true, force: true })
+})
+
+describe('shapeOf', () => {
+ it('describes an object by field names, never values', () => {
+ expect(shapeOf({ email: '[email protected]', name: 'A' })).toEqual({ fields: ['email', 'name'] })
+ })
+
+ it('describes a wrapped list by count as well as field', () => {
+ expect(shapeOf({ agents: [1, 2, 3] })).toEqual({ fields: ['agents'], count: 3 })
+ })
+
+ it('describes a string by byte length', () => {
+ expect(shapeOf('hello')).toEqual({ bytes: 5 })
+ })
+})
+
+describe('PluginAuditLog', () => {
+ it('appends one JSON line per entry, newest first on read', async () => {
+ await log.append(ENV_KEY, entry({ capability: 'identity.read' }))
+ await log.append(ENV_KEY, entry({ capability: 'org.read' }))
+ const entries = await log.read(ENV_KEY)
+ expect(entries.map(item => item.capability)).toEqual(['org.read', 'identity.read'])
+ })
+
+ it('writes the file 0600', async () => {
+ await log.append(ENV_KEY, entry())
+ const stat = await fs.stat(path.join(tmpDir, `${ENV_KEY}.jsonl`))
+ expect(stat.mode & 0o777).toBe(0o600)
+ })
+
+ it('filters to one user', async () => {
+ await log.append(ENV_KEY, entry({ userId: 'user-1' }))
+ await log.append(ENV_KEY, entry({ userId: 'user-2' }))
+ const entries = await log.read(ENV_KEY, { userId: 'user-1' })
+ expect(entries).toHaveLength(1)
+ })
+
+ it('survives a torn final line instead of failing the whole read', async () => {
+ await log.append(ENV_KEY, entry())
+ // A crash mid-append leaves a partial line; one bad line must not cost the
+ // user their whole activity history.
+ await fs.appendFile(path.join(tmpDir, `${ENV_KEY}.jsonl`), '{"ts":"broken', 'utf8')
+ expect(await log.read(ENV_KEY)).toHaveLength(1)
+ })
+
+ it('rotates once past the size ceiling and keeps a single generation', async () => {
+ const file = path.join(tmpDir, `${ENV_KEY}.jsonl`)
+ await fs.writeFile(file, 'x'.repeat(AUDIT_MAX_BYTES + 1), 'utf8')
+ await log.append(ENV_KEY, entry())
+ const files = await fs.readdir(tmpDir)
+ expect(files.sort()).toEqual([`${ENV_KEY}.jsonl`, `${ENV_KEY}.jsonl.1`])
+ expect(await log.read(ENV_KEY)).toHaveLength(1)
+ })
+
+ it('never throws into the request path when the directory is unusable', async () => {
+ const blocked = new PluginAuditLog(path.join(tmpDir, 'file-not-dir'))
+ await fs.writeFile(path.join(tmpDir, 'file-not-dir'), 'x', 'utf8')
+ // An audit write failure must not turn a legitimate capability call into an
+ // error for the plugin.
+ await expect(blocked.append(ENV_KEY, entry())).resolves.toBeUndefined()
+ })
+
+ it('rejects an envKey that is not the expected shape', async () => {
+ await expect(log.read('../../etc/passwd')).resolves.toEqual([])
+ })
+
+ it('clears both generations', async () => {
+ await log.append(ENV_KEY, entry())
+ await fs.writeFile(path.join(tmpDir, `${ENV_KEY}.jsonl.1`), 'old', 'utf8')
+ await log.clear(ENV_KEY)
+ expect(await fs.readdir(tmpDir)).toEqual([])
+ })
+})
diff --git a/desktop-app/src/__tests__/pluginConsentGate.test.ts b/desktop-app/src/__tests__/pluginConsentGate.test.ts
new file mode 100644
index 000000000..82b1f1f3a
--- /dev/null
+++ b/desktop-app/src/__tests__/pluginConsentGate.test.ts
@@ -0,0 +1,190 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { promises as fs } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import {
+ CONSENT_MAX_PROMPTS_PER_MOUNT,
+ CONSENT_PROMPT_COOLDOWN_MS,
+ CONSENT_PROMPT_TIMEOUT_MS,
+ PluginConsentGate,
+} from '../pluginConsentGate.js'
+import { LocalConsentStore } from '../pluginConsentStore.js'
+import type { PluginConsentRequest } from '../pluginSdkProtocol.js'
+
+const ENV_KEY = 'testenv-0123456789ab'
+const BASE = { envKey: ENV_KEY, userId: 'user-1', pluginId: 'ns/plugin', pluginTitle: 'Plugin' }
+
+let tmpDir: string
+let store: LocalConsentStore
+let prompts: PluginConsentRequest[]
+let cancelled: string[]
+let visibility: boolean[]
+let sleeps: number[]
+let clock: number
+
+type GateOptions = {
+ decide?: (request: PluginConsentRequest) => string[] | null
+ windowReady?: () => boolean
+}
+
+function makeGate(options: GateOptions = {}): PluginConsentGate {
+ const gate = new PluginConsentGate({
+ store,
+ presentPrompt: request => {
+ prompts.push(request)
+ const decision = options.decide
+ ? options.decide(request)
+ : request.rows.map(r => r.capability)
+ // `null` models a user who never answers.
+ if (decision !== null) {
+ setTimeout(() => gate.resolvePrompt(request.promptId, decision), 0)
+ }
+ },
+ cancelPrompt: promptId => cancelled.push(promptId),
+ setSurfaceVisible: async visible => {
+ visibility.push(visible)
+ },
+ isWindowReady: options.windowReady ?? (() => true),
+ now: () => clock,
+ sleep: async ms => {
+ sleeps.push(ms)
+ clock += ms
+ },
+ })
+ return gate
+}
+
+beforeEach(async () => {
+ tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-consent-gate-'))
+ store = new LocalConsentStore(path.join(tmpDir, 'consent'), () => clock)
+ prompts = []
+ cancelled = []
+ visibility = []
+ sleeps = []
+ clock = 1_700_000_000_000
+})
+
+afterEach(async () => {
+ await fs.rm(tmpDir, { recursive: true, force: true })
+})
+
+describe('PluginConsentGate', () => {
+ it('hides the plugin surface for the duration of the prompt and restores it after', async () => {
+ const gate = makeGate()
+ await gate.ensure({ ...BASE, capabilities: ['identity.read'] })
+ // False before the modal, true after — the plugin cannot paint while the
+ // user is deciding (spec §9.4).
+ expect(visibility).toEqual([false, true])
+ })
+
+ it('persists a grant that survives a new gate instance', async () => {
+ const first = makeGate()
+ await first.ensure({ ...BASE, capabilities: ['identity.read'] })
+
+ const second = makeGate()
+ const outcome = await second.ensure({ ...BASE, capabilities: ['identity.read'] })
+ expect(outcome.source['identity.read']).toBe('existing_grant')
+ expect(prompts).toHaveLength(1)
+ })
+
+ it('treats an unanswered prompt as a denial once it times out', async () => {
+ const gate = makeGate({ decide: () => null })
+ const pending = gate.ensure({ ...BASE, capabilities: ['identity.read'] })
+ await new Promise(resolve => setTimeout(resolve, 0))
+ // Fire the real timer the gate armed.
+ await new Promise(resolve => setTimeout(resolve, 0))
+ const promptId = prompts[0]?.promptId as string
+ // Simulate the timeout path directly: resolving with nothing is what the
+ // timer does, and waiting 120 s in a unit test is not a test.
+ gate.resolvePrompt(promptId, [])
+ const outcome = await pending
+ expect(outcome.granted['identity.read']).toBe(false)
+ })
+
+ it('drops a resolve for an unknown or already-answered promptId', async () => {
+ const gate = makeGate()
+ await gate.ensure({ ...BASE, capabilities: ['identity.read'] })
+ const promptId = prompts[0]?.promptId as string
+ // The nonce is what stops a replayed or forged resolve from landing.
+ expect(gate.resolvePrompt(promptId, ['identity.read'])).toBe(false)
+ expect(gate.resolvePrompt('not-a-prompt', ['identity.read'])).toBe(false)
+ })
+
+ it('waits out the cooldown between consecutive prompts', async () => {
+ const gate = makeGate()
+ await gate.ensure({ ...BASE, capabilities: ['identity.read'] })
+ await gate.ensure({ ...BASE, capabilities: ['org.read'] })
+ expect(sleeps).toEqual([CONSENT_PROMPT_COOLDOWN_MS])
+ })
+
+ it('spends one prompt from the budget per batch, not one per capability', async () => {
+ const gate = makeGate()
+ await gate.ensure({
+ ...BASE,
+ capabilities: ['identity.read', 'org.read', 'agents.read', 'gfs.list'],
+ })
+ expect(prompts).toHaveLength(1)
+
+ // Budget is 3 modals; a 4-capability batch must not have exhausted it.
+ await gate.ensure({ ...BASE, capabilities: ['mcp.read'] })
+ expect(prompts).toHaveLength(2)
+ })
+
+ it('stops prompting after the per-mount budget is spent', async () => {
+ const gate = makeGate({ decide: () => [] })
+ const asks = ['identity.read', 'org.read', 'agents.read', 'mcp.read']
+ for (const capability of asks) {
+ await gate.ensure({ ...BASE, capabilities: [capability] })
+ }
+ expect(prompts).toHaveLength(CONSENT_MAX_PROMPTS_PER_MOUNT)
+ })
+
+ it('reports how many times a plugin has already asked this session', async () => {
+ const gate = makeGate()
+ await gate.ensure({ ...BASE, capabilities: ['identity.read'] })
+ await gate.ensure({ ...BASE, capabilities: ['org.read'] })
+ expect(prompts[0]?.priorPromptCount).toBe(0)
+ expect(prompts[1]?.priorPromptCount).toBe(1)
+ })
+
+ it('clears denials and the prompt budget when the plugin unmounts', async () => {
+ const gate = makeGate({ decide: () => [] })
+ await gate.ensure({ ...BASE, capabilities: ['identity.read'] })
+ await gate.ensure({ ...BASE, capabilities: ['identity.read'] })
+ expect(prompts).toHaveLength(1)
+
+ // Reopening the plugin gives it one more chance to ask — a mis-click is not
+ // a permanent lockout (spec §9.3).
+ gate.resetPlugin(BASE.pluginId)
+ await gate.ensure({ ...BASE, capabilities: ['identity.read'] })
+ expect(prompts).toHaveLength(2)
+ })
+
+ it('cancels a pending prompt when its plugin goes away', async () => {
+ const gate = makeGate({ decide: () => null })
+ const pending = gate.ensure({ ...BASE, capabilities: ['identity.read'] })
+ await new Promise(resolve => setTimeout(resolve, 0))
+ gate.resetPlugin(BASE.pluginId)
+ const outcome = await pending
+ expect(cancelled).toHaveLength(1)
+ expect(outcome.granted['identity.read']).toBe(false)
+ })
+
+ it('does not prompt for an ambient capability', async () => {
+ const gate = makeGate()
+ const outcome = await gate.ensure({ ...BASE, capabilities: ['theme.read'] })
+ expect(outcome.source['theme.read']).toBe('not_required')
+ expect(prompts).toHaveLength(0)
+ })
+
+ it('parks rather than prompting onto an unfocused window, and gives up at the timeout', async () => {
+ const gate = makeGate({ windowReady: () => false })
+ const outcome = await gate.ensure({ ...BASE, capabilities: ['identity.read'] })
+ expect(prompts).toHaveLength(0)
+ expect(outcome.granted['identity.read']).toBe(false)
+ // It polled until the deadline instead of spinning forever.
+ expect(sleeps.reduce((total, ms) => total + ms, 0)).toBeGreaterThanOrEqual(
+ CONSENT_PROMPT_TIMEOUT_MS
+ )
+ })
+})
diff --git a/desktop-app/src/__tests__/pluginConsentStore.test.ts b/desktop-app/src/__tests__/pluginConsentStore.test.ts
new file mode 100644
index 000000000..039ea3200
--- /dev/null
+++ b/desktop-app/src/__tests__/pluginConsentStore.test.ts
@@ -0,0 +1,175 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { promises as fs } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { type ConsentGrant, LocalConsentStore } from '../pluginConsentStore.js'
+
+const ENV_A = 'enva-0123456789ab'
+const ENV_B = 'envb-0123456789ab'
+
+let tmpDir: string
+let store: LocalConsentStore
+
+function grant(overrides: Partial<ConsentGrant> = {}): ConsentGrant {
+ return {
+ envKey: ENV_A,
+ userId: 'user-1',
+ pluginId: 'ns/plugin',
+ capability: 'identity.read',
+ grantedAt: '2026-08-06T10:00:00.000Z',
+ lastUsedAt: null,
+ descriptorVersion: 1,
+ revision: 0,
+ ...overrides,
+ }
+}
+
+beforeEach(async () => {
+ tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-consent-store-'))
+ store = new LocalConsentStore(tmpDir)
+})
+
+afterEach(async () => {
+ await fs.rm(tmpDir, { recursive: true, force: true })
+ vi.restoreAllMocks()
+})
+
+describe('LocalConsentStore', () => {
+ it('round-trips a grant through a fresh instance', async () => {
+ await store.put(grant())
+ const reread = new LocalConsentStore(tmpDir)
+ const found = await reread.get({
+ envKey: ENV_A,
+ userId: 'user-1',
+ pluginId: 'ns/plugin',
+ capability: 'identity.read',
+ })
+ expect(found?.capability).toBe('identity.read')
+ expect(found?.revision).toBe(1)
+ })
+
+ it('writes the file 0600 so other local accounts cannot read it', async () => {
+ await store.put(grant())
+ const stat = await fs.stat(path.join(tmpDir, `${ENV_A}.json`))
+ expect(stat.mode & 0o777).toBe(0o600)
+ })
+
+ it('keeps environments apart', async () => {
+ await store.put(grant({ envKey: ENV_A }))
+ const other = await store.get({
+ envKey: ENV_B,
+ userId: 'user-1',
+ pluginId: 'ns/plugin',
+ capability: 'identity.read',
+ })
+ // Cluster A's grants must never answer for cluster B.
+ expect(other).toBeNull()
+ })
+
+ it('keeps users on one machine apart', async () => {
+ await store.put(grant({ userId: 'user-1' }))
+ const other = await store.get({
+ envKey: ENV_A,
+ userId: 'user-2',
+ pluginId: 'ns/plugin',
+ capability: 'identity.read',
+ })
+ expect(other).toBeNull()
+ })
+
+ it('rejects an envKey that is not the expected shape', async () => {
+ await expect(store.list('../../etc', 'user-1')).rejects.toThrow(/envKey/)
+ })
+
+ it('bumps revision on re-grant instead of duplicating the row', async () => {
+ await store.put(grant())
+ await store.put(grant())
+ const rows = await store.list(ENV_A, 'user-1')
+ expect(rows).toHaveLength(1)
+ expect(rows[0]?.revision).toBe(2)
+ })
+
+ it('records last use without disturbing the grant', async () => {
+ await store.put(grant())
+ await store.touch({
+ envKey: ENV_A,
+ userId: 'user-1',
+ pluginId: 'ns/plugin',
+ capability: 'identity.read',
+ })
+ const rows = await store.list(ENV_A, 'user-1')
+ expect(rows[0]?.lastUsedAt).toEqual(expect.any(String))
+ expect(rows[0]?.grantedAt).toBe('2026-08-06T10:00:00.000Z')
+ })
+
+ it('revokes one capability and leaves the rest', async () => {
+ await store.put(grant({ capability: 'identity.read' }))
+ await store.put(grant({ capability: 'org.read' }))
+ await store.revoke({
+ envKey: ENV_A,
+ userId: 'user-1',
+ pluginId: 'ns/plugin',
+ capability: 'identity.read',
+ })
+ const rows = await store.list(ENV_A, 'user-1')
+ expect(rows.map(row => row.capability)).toEqual(['org.read'])
+ })
+
+ it('revokes everything for one plugin without touching another', async () => {
+ await store.put(grant({ pluginId: 'ns/a' }))
+ await store.put(grant({ pluginId: 'ns/a', capability: 'org.read' }))
+ await store.put(grant({ pluginId: 'ns/b' }))
+ await store.revokeAllForPlugin(ENV_A, 'user-1', 'ns/a')
+ const rows = await store.list(ENV_A, 'user-1')
+ expect(rows.map(row => row.pluginId)).toEqual(['ns/b'])
+ })
+
+ it('prunes grants for plugins the user can no longer reach', async () => {
+ await store.put(grant({ pluginId: 'ns/gone' }))
+ await store.put(grant({ pluginId: 'ns/kept' }))
+ await store.pruneToPlugins(ENV_A, 'user-1', new Set(['ns/kept']))
+ const rows = await store.list(ENV_A, 'user-1')
+ expect(rows.map(row => row.pluginId)).toEqual(['ns/kept'])
+ })
+
+ it('fails CLOSED on a corrupt file and moves it aside', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ await fs.writeFile(path.join(tmpDir, `${ENV_A}.json`), '{ not json', 'utf8')
+ // A half-understood grant list is worse than none: every capability
+ // re-prompts rather than being silently mis-read.
+ const rows = await store.list(ENV_A, 'user-1')
+ expect(rows).toEqual([])
+ const files = await fs.readdir(tmpDir)
+ expect(files.some(file => file.includes('.corrupt-'))).toBe(true)
+ })
+
+ it('fails CLOSED on a file from a newer schema version', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ await fs.writeFile(
+ path.join(tmpDir, `${ENV_A}.json`),
+ JSON.stringify({ version: 99, users: { 'user-1': [grant()] } }),
+ 'utf8'
+ )
+ expect(await store.list(ENV_A, 'user-1')).toEqual([])
+ })
+
+ it('serializes concurrent writes without losing one', async () => {
+ await Promise.all([
+ store.put(grant({ capability: 'identity.read' })),
+ store.put(grant({ capability: 'org.read' })),
+ store.put(grant({ capability: 'agents.read' })),
+ ])
+ const rows = await store.list(ENV_A, 'user-1')
+ expect(rows.map(row => row.capability).sort()).toEqual([
+ 'agents.read',
+ 'identity.read',
+ 'org.read',
+ ])
+ })
+
+ it('leaves no temp file behind after a write', async () => {
+ await store.put(grant())
+ const files = await fs.readdir(tmpDir)
+ expect(files.filter(file => file.includes('.tmp-'))).toEqual([])
+ })
+})
diff --git a/desktop-app/src/__tests__/pluginSdkBroker.test.ts b/desktop-app/src/__tests__/pluginSdkBroker.test.ts
new file mode 100644
index 000000000..1fc8d1cd4
--- /dev/null
+++ b/desktop-app/src/__tests__/pluginSdkBroker.test.ts
@@ -0,0 +1,379 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { promises as fs } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { PluginAuditLog } from '../pluginAuditLog.js'
+import { PluginConsentGate } from '../pluginConsentGate.js'
+import { LocalConsentStore } from '../pluginConsentStore.js'
+import { PluginRateLimiter } from '../pluginRateLimiter.js'
+import { PluginSdkBroker } from '../pluginSdkBroker.js'
+import type { PluginSdkDataSource } from '../pluginSdkCapabilities.js'
+import type { PluginConsentRequest } from '../pluginSdkProtocol.js'
+import { _resetPluginSurfacesForTests, pinPluginSurface } from '../pluginSurfaceRegistry.js'
+
+const ENV_KEY = 'testenv-0123456789ab'
+const USER_ID = 'user-1'
+const PLUGIN_ID = 'sandbox-recipes/leadforge'
+const SENDER_ID = 42
+
+let tmpDir: string
+let store: LocalConsentStore
+let audit: PluginAuditLog
+let gate: PluginConsentGate
+let broker: PluginSdkBroker
+let prompts: PluginConsentRequest[]
+/** What the fake user clicks on the next prompt. */
+let nextDecision: (request: PluginConsentRequest) => string[]
+let userId: string | null
+let sleeps: number[]
+
+function fakeSource(overrides: Partial<PluginSdkDataSource> = {}): PluginSdkDataSource {
+ return {
+ getSessionState: async () => ({
+ authenticated: true,
+ me: {
+ id: USER_ID,
+ email: '[email protected]',
+ name: 'Andres',
+ picture: 'https://cdn.example/avatar.png',
+ teamId: 'team-1',
+ teamName: 'Acme',
+ role: 'member',
+ },
+ }),
+ listMyAgents: async () => [
+ {
+ name: 'scout',
+ contextRef: 'context1',
+ provider: 'claude',
+ mcpServers: [{ name: 'search' }],
+ gfsSubject: { type: 'host', id: '1st:ns/scout' },
+ },
+ ],
+ getAccessCatalog: async () =>
+ ({
+ userId: USER_ID,
+ teamId: 'team-1',
+ userContextIds: ['ctx-user'],
+ userAgentNames: [],
+ teamContextIds: ['ctx-team'],
+ teamAgentNames: [],
+ contextIds: [],
+ agentNames: [],
+ mcpServersByAgent: { scout: ['search'] },
+ }) as never,
+ listAccessibleMcpServers: async () =>
+ ({
+ userId: USER_ID,
+ contextIds: [],
+ servers: [{ name: 'search', url: 'http://search.mcp-server.svc.cluster.local:3000' }],
+ }) as never,
+ listAccessibleGfsResources: async () => ({ items: [], nextCursor: null }),
+ listGfsChildren: async () => ({ items: [], nextCursor: null }),
+ downloadGfsUri: async () => {
+ throw new Error('not stubbed')
+ },
+ getPluginTheme: () => 'dark',
+ showPluginNotification: async () => ({ delivered: true }),
+ ...overrides,
+ }
+}
+
+async function build(source = fakeSource()): Promise<void> {
+ prompts = []
+ sleeps = []
+ nextDecision = request => request.rows.map(row => row.capability)
+ userId = USER_ID
+ store = new LocalConsentStore(path.join(tmpDir, 'consent'))
+ audit = new PluginAuditLog(path.join(tmpDir, 'audit'))
+ gate = new PluginConsentGate({
+ store,
+ presentPrompt: request => {
+ prompts.push(request)
+ // Answer on the next tick, the way a real renderer would.
+ setTimeout(() => gate.resolvePrompt(request.promptId, nextDecision(request)), 0)
+ },
+ cancelPrompt: () => undefined,
+ setSurfaceVisible: async () => undefined,
+ isWindowReady: () => true,
+ // Cooldowns are asserted directly in pluginConsentGate.test.ts; spending
+ // ten real seconds per back-to-back prompt here would only slow the suite.
+ sleep: async ms => {
+ sleeps.push(ms)
+ },
+ })
+ broker = new PluginSdkBroker({
+ source,
+ store,
+ gate,
+ limiter: new PluginRateLimiter(),
+ audit,
+ getEnvKey: () => ENV_KEY,
+ getUserId: () => userId,
+ })
+ pinPluginSurface({
+ pluginId: PLUGIN_ID,
+ pluginTitle: 'LeadForge',
+ surface: 'sandbox-ui-embed',
+ webContentsId: SENDER_ID,
+ generation: 1,
+ })
+}
+
+beforeEach(async () => {
+ tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-sdk-broker-'))
+ _resetPluginSurfacesForTests()
+ await build()
+})
+
+afterEach(async () => {
+ _resetPluginSurfacesForTests()
+ await fs.rm(tmpDir, { recursive: true, force: true })
+ vi.restoreAllMocks()
+})
+
+async function auditLines() {
+ return audit.read(ENV_KEY, { limit: 100 })
+}
+
+describe('PluginSdkBroker — caller identity', () => {
+ it('rejects an unpinned sender rather than treating it as an unknown plugin', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ const result = await broker.request(999, { v: 1, capability: 'identity.read' })
+ expect(result).toEqual({
+ ok: false,
+ error: { code: 'internal', message: expect.any(String), retryable: false },
+ })
+ expect(prompts).toHaveLength(0)
+ })
+
+ it('derives the plugin id from the sender, never from the payload', async () => {
+ await broker.request(SENDER_ID, {
+ v: 1,
+ capability: 'identity.read',
+ // A plugin trying to claim someone else's identity gets ignored: the
+ // broker never reads a pluginId off the wire.
+ params: { pluginId: 'sandbox-recipes/other' },
+ })
+ const lines = await auditLines()
+ expect(lines.every(line => line.pluginId === PLUGIN_ID)).toBe(true)
+ })
+})
+
+describe('PluginSdkBroker — request gating', () => {
+ it('rejects an unknown capability', async () => {
+ const result = await broker.request(SENDER_ID, { v: 1, capability: 'identity.readAll' })
+ expect(result).toMatchObject({ ok: false, error: { code: 'unsupported_capability' } })
+ })
+
+ it('rejects an unknown protocol version', async () => {
+ const result = await broker.request(SENDER_ID, { v: 99, capability: 'identity.read' })
+ expect(result).toMatchObject({ ok: false, error: { code: 'unsupported_version' } })
+ })
+
+ it('rejects unexpected params before prompting', async () => {
+ const result = await broker.request(SENDER_ID, {
+ v: 1,
+ capability: 'identity.read',
+ params: { verbose: true },
+ })
+ expect(result).toMatchObject({ ok: false, error: { code: 'invalid_request' } })
+ expect(prompts).toHaveLength(0)
+ })
+
+ it('fails closed when there is no session', async () => {
+ userId = null
+ const result = await broker.request(SENDER_ID, { v: 1, capability: 'identity.read' })
+ expect(result).toMatchObject({ ok: false, error: { code: 'unauthenticated', retryable: true } })
+ })
+
+ it('prompts once, then serves later calls from the stored grant', async () => {
+ const first = await broker.request(SENDER_ID, { v: 1, capability: 'identity.read' })
+ expect(first).toMatchObject({ ok: true, data: { email: '[email protected]' } })
+ expect(prompts).toHaveLength(1)
+
+ const second = await broker.request(SENDER_ID, { v: 1, capability: 'identity.read' })
+ expect(second).toMatchObject({ ok: true })
+ expect(prompts).toHaveLength(1)
+ })
+
+ it('keeps a denial sticky for the rest of the mount', async () => {
+ nextDecision = () => []
+ const first = await broker.request(SENDER_ID, { v: 1, capability: 'identity.read' })
+ expect(first).toMatchObject({ ok: false, error: { code: 'permission_denied' } })
+
+ const second = await broker.request(SENDER_ID, { v: 1, capability: 'identity.read' })
+ expect(second).toMatchObject({ ok: false, error: { code: 'permission_denied' } })
+ // One prompt, not two: a refusal buys silence rather than a second ask.
+ expect(prompts).toHaveLength(1)
+ })
+
+ it('does not prompt for an ambient capability', async () => {
+ const result = await broker.request(SENDER_ID, { v: 1, capability: 'theme.read' })
+ expect(result).toMatchObject({ ok: true, data: { theme: 'dark' } })
+ expect(prompts).toHaveLength(0)
+ })
+
+ it('rate limits and refuses without calling the provider again', async () => {
+ let calls = 0
+ await build(
+ fakeSource({
+ getPluginTheme: () => {
+ calls += 1
+ return 'light'
+ },
+ })
+ )
+ // theme.read allows 60/min.
+ for (let i = 0; i < 60; i += 1) {
+ await broker.request(SENDER_ID, { v: 1, capability: 'theme.read' })
+ }
+ const limited = await broker.request(SENDER_ID, { v: 1, capability: 'theme.read' })
+ expect(limited).toMatchObject({ ok: false, error: { code: 'rate_limited', retryable: true } })
+ expect(calls).toBe(60)
+ })
+
+ it('returns permission_revoked when a grant disappears mid-flight', async () => {
+ await broker.request(SENDER_ID, { v: 1, capability: 'identity.read' })
+ const source = fakeSource({
+ getSessionState: async () => {
+ // Simulate the user revoking in Settings while the provider is working.
+ await store.revoke({
+ envKey: ENV_KEY,
+ userId: USER_ID,
+ pluginId: PLUGIN_ID,
+ capability: 'identity.read',
+ })
+ return {
+ authenticated: true,
+ me: {
+ id: USER_ID,
+ email: '[email protected]',
+ name: 'Andres',
+ picture: null,
+ teamId: null,
+ teamName: null,
+ role: null,
+ },
+ }
+ },
+ })
+ const racing = new PluginSdkBroker({
+ source,
+ store,
+ gate,
+ limiter: new PluginRateLimiter(),
+ audit,
+ getEnvKey: () => ENV_KEY,
+ getUserId: () => USER_ID,
+ })
+ const result = await racing.request(SENDER_ID, { v: 1, capability: 'identity.read' })
+ expect(result).toMatchObject({ ok: false, error: { code: 'permission_revoked' } })
+ })
+})
+
+describe('PluginSdkBroker — batched permissions', () => {
+ it('opens one prompt for the whole batch and returns a per-row map', async () => {
+ nextDecision = request =>
+ request.rows.map(row => row.capability).filter(capability => capability !== 'gfs.list')
+
+ const result = await broker.requestPermissions(SENDER_ID, {
+ v: 1,
+ capabilities: ['identity.read', 'org.read', 'agents.read', 'gfs.list'],
+ })
+
+ expect(prompts).toHaveLength(1)
+ expect(prompts[0]?.rows).toHaveLength(4)
+ expect(result).toEqual({
+ ok: true,
+ data: {
+ granted: {
+ 'identity.read': true,
+ 'org.read': true,
+ 'agents.read': true,
+ 'gfs.list': false,
+ },
+ all: false,
+ },
+ })
+ })
+
+ it('orders rows most-sensitive-first', async () => {
+ await broker.requestPermissions(SENDER_ID, {
+ v: 1,
+ capabilities: ['agents.read', 'identity.read'],
+ })
+ expect(prompts[0]?.rows.map(row => row.capability)).toEqual(['identity.read', 'agents.read'])
+ })
+
+ it('drops already-granted ids from the prompt but keeps them in the answer', async () => {
+ await broker.requestPermissions(SENDER_ID, { v: 1, capabilities: ['identity.read'] })
+ prompts.length = 0
+
+ const result = await broker.requestPermissions(SENDER_ID, {
+ v: 1,
+ capabilities: ['identity.read', 'org.read'],
+ })
+ expect(prompts[0]?.rows.map(row => row.capability)).toEqual(['org.read'])
+ expect(result).toMatchObject({ data: { granted: { 'identity.read': true, 'org.read': true } } })
+ // The second modal waited out the anti-fatigue cooldown before opening.
+ expect(sleeps[0]).toBeGreaterThan(0)
+ })
+
+ it('rejects duplicates, unknown ids, and oversized batches before prompting', async () => {
+ for (const capabilities of [
+ ['identity.read', 'identity.read'],
+ ['identity.read', 'nope.read'],
+ new Array(9).fill('identity.read'),
+ [],
+ ]) {
+ const result = await broker.requestPermissions(SENDER_ID, { v: 1, capabilities })
+ expect(result).toMatchObject({ ok: false, error: { code: 'invalid_request' } })
+ }
+ expect(prompts).toHaveLength(0)
+ })
+
+ it('writes one audit line per row', async () => {
+ nextDecision = () => ['identity.read']
+ await broker.requestPermissions(SENDER_ID, {
+ v: 1,
+ capabilities: ['identity.read', 'org.read'],
+ })
+ const lines = await auditLines()
+ expect(lines.filter(line => line.capability === 'identity.read')[0]?.outcome).toBe('granted')
+ expect(lines.filter(line => line.capability === 'org.read')[0]?.outcome).toBe('denied')
+ })
+})
+
+describe('PluginSdkBroker — permission state', () => {
+ it('reports grant state without prompting', async () => {
+ const before = await broker.permissionState(SENDER_ID, ['identity.read'])
+ expect(before).toMatchObject({ data: { granted: { 'identity.read': false } } })
+ expect(prompts).toHaveLength(0)
+
+ await broker.requestPermissions(SENDER_ID, { v: 1, capabilities: ['identity.read'] })
+ const after = await broker.permissionState(SENDER_ID, ['identity.read'])
+ expect(after).toMatchObject({ data: { granted: { 'identity.read': true } } })
+ })
+})
+
+describe('PluginSdkBroker — audit', () => {
+ it('records the shape of a payload and never its contents', async () => {
+ await broker.request(SENDER_ID, { v: 1, capability: 'identity.read' })
+ const file = path.join(tmpDir, 'audit', `${ENV_KEY}.jsonl`)
+ const raw = await fs.readFile(file, 'utf8')
+
+ // The single most important property of the audit log: reading it must not
+ // hand you the data it is auditing.
+ expect(raw).not.toContain('[email protected]')
+ expect(raw).not.toContain('Andres')
+ expect(raw).toContain('"fields":["email","name","userId"]')
+ })
+
+ it('records denials and rate limits, not just successes', async () => {
+ nextDecision = () => []
+ await broker.request(SENDER_ID, { v: 1, capability: 'identity.read' })
+ const lines = await auditLines()
+ expect(lines[0]).toMatchObject({ outcome: 'denied', consent: 'prompt_denied' })
+ })
+})
diff --git a/desktop-app/src/__tests__/pluginSdkCapabilities.test.ts b/desktop-app/src/__tests__/pluginSdkCapabilities.test.ts
new file mode 100644
index 000000000..5f1fb0628
--- /dev/null
+++ b/desktop-app/src/__tests__/pluginSdkCapabilities.test.ts
@@ -0,0 +1,288 @@
+import { describe, expect, it } from 'vitest'
+import {
+ CAPABILITIES,
+ CapabilityInputError,
+ CapabilityTooLargeError,
+ PLUGIN_GFS_IMAGE_MAX_BYTES,
+ type PluginSdkDataSource,
+ type ProviderContext,
+ detectImageMime,
+ getCapability,
+ sortCapabilitiesForPrompt,
+} from '../pluginSdkCapabilities.js'
+
+const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x01])
+const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10])
+
+function source(overrides: Partial<PluginSdkDataSource> = {}): PluginSdkDataSource {
+ return {
+ getSessionState: async () => ({
+ authenticated: true,
+ me: {
+ id: 'u1',
+ email: '[email protected]',
+ name: 'A',
+ picture: 'https://cdn.example/a.png',
+ teamId: 't1',
+ teamName: 'Acme',
+ role: 'member',
+ },
+ }),
+ listMyAgents: async () => [
+ {
+ name: 'scout',
+ contextRef: 'context1',
+ provider: 'claude',
+ mcpServers: [{ name: 'search' }],
+ gfsSubject: { type: 'host', id: '1st:ns/scout' },
+ },
+ ],
+ getAccessCatalog: async () =>
+ ({
+ userContextIds: ['ctx-user'],
+ teamContextIds: ['ctx-team', 'ctx-user'],
+ mcpServersByAgent: { scout: ['search'] },
+ }) as never,
+ listAccessibleMcpServers: async () =>
+ ({ servers: [{ name: 'search', url: 'http://internal:3000' }] }) as never,
+ listAccessibleGfsResources: async () =>
+ ({
+ items: [
+ {
+ resourceId: 'r1',
+ rid: 'r1',
+ gfsUri: 'gfs://main/a.png',
+ drive: 'main',
+ parentResourceId: null,
+ name: 'a.png',
+ kind: 'file',
+ path: '/a.png',
+ version: 3,
+ bytes: 10,
+ sources: ['grant'],
+ permissions: ['read'],
+ coversDescendants: false,
+ },
+ ],
+ nextCursor: null,
+ }) as never,
+ listGfsChildren: async () => ({ items: [], nextCursor: null }),
+ downloadGfsUri: async () => ({
+ resource: { gfsUri: 'gfs://main/a.png', name: 'a.png' } as never,
+ bytes: PNG.buffer.slice(PNG.byteOffset, PNG.byteOffset + PNG.byteLength) as ArrayBuffer,
+ }),
+ getPluginTheme: () => 'light',
+ showPluginNotification: async () => ({ delivered: true }),
+ ...overrides,
+ }
+}
+
+function ctx(overrides: Partial<PluginSdkDataSource> = {}): ProviderContext {
+ return {
+ source: source(overrides),
+ pluginId: 'ns/plugin',
+ pluginTitle: 'Plugin',
+ userId: 'u1',
+ }
+}
+
+async function run(id: string, params: unknown = undefined, overrides = {}) {
+ const descriptor = getCapability(id)
+ if (!descriptor) throw new Error(`missing ${id}`)
+ return descriptor.run(ctx(overrides), descriptor.validate(params))
+}
+
+describe('capability catalog invariants', () => {
+ it('gives every capability consent copy and limits', () => {
+ for (const [id, descriptor] of Object.entries(CAPABILITIES)) {
+ expect(descriptor.id, id).toBe(id)
+ expect(descriptor.consent.title.length, id).toBeGreaterThan(0)
+ expect(descriptor.consent.dataDescription.length, id).toBeGreaterThan(0)
+ expect(descriptor.limits.perMinute, id).toBeGreaterThan(0)
+ expect(descriptor.limits.maxResponseBytes, id).toBeGreaterThan(0)
+ }
+ })
+
+ it('marks only theme.read as consent-free', () => {
+ const unscoped = Object.values(CAPABILITIES)
+ .filter(descriptor => !descriptor.requiresConsent)
+ .map(descriptor => descriptor.id)
+ // Any addition here is a decision to hand a plugin something without asking.
+ expect(unscoped).toEqual(['theme.read'])
+ })
+
+ it('sorts prompt rows most-sensitive-first', () => {
+ expect(sortCapabilitiesForPrompt(['theme.read', 'agents.read', 'identity.read'])).toEqual([
+ 'identity.read',
+ 'agents.read',
+ 'theme.read',
+ ])
+ })
+})
+
+describe('minimize contracts', () => {
+ it('identity.read returns exactly three fields and drops the avatar URL', async () => {
+ const result = await run('identity.read')
+ expect(Object.keys(result as object).sort()).toEqual(['email', 'name', 'userId'])
+ })
+
+ it('org.read returns exactly the team triple', async () => {
+ const result = await run('org.read')
+ expect(Object.keys(result as object).sort()).toEqual(['role', 'teamId', 'teamName'])
+ })
+
+ it('agents.read flattens MCP servers to names and exposes a stable id', async () => {
+ const result = (await run('agents.read')) as { agents: Array<Record<string, unknown>> }
+ expect(result.agents[0]).toEqual({
+ id: '1st:ns/scout',
+ name: 'scout',
+ contextRef: 'context1',
+ provider: 'claude',
+ mcpServers: ['search'],
+ })
+ })
+
+ it('mcp.read never leaks a server URL', async () => {
+ const result = (await run('mcp.read')) as { servers: Array<Record<string, unknown>> }
+ expect(result.servers[0]).toEqual({ name: 'search', agents: ['scout'] })
+ expect(JSON.stringify(result)).not.toContain('internal')
+ })
+
+ it('contexts.read labels a context present in both lists as the user’s', async () => {
+ const result = (await run('contexts.read')) as {
+ contexts: Array<{ id: string; scope: string }>
+ }
+ expect(result.contexts).toEqual([
+ { id: 'ctx-user', scope: 'user' },
+ { id: 'ctx-team', scope: 'team' },
+ ])
+ })
+
+ it('gfs.list returns metadata only', async () => {
+ const result = (await run('gfs.list', {})) as { items: Array<Record<string, unknown>> }
+ expect(Object.keys(result.items[0] ?? {}).sort()).toEqual([
+ 'bytes',
+ 'gfsUri',
+ 'kind',
+ 'name',
+ 'resourceId',
+ 'version',
+ ])
+ })
+})
+
+describe('gfs.read', () => {
+ it('returns a data: URI, because the embed CSP allows data: and not blob:', async () => {
+ const result = (await run('gfs.read', { uri: 'gfs://main/a.png', as: 'dataUrl' })) as {
+ dataUrl: string
+ mimeType: string
+ }
+ expect(result.mimeType).toBe('image/png')
+ expect(result.dataUrl.startsWith('data:image/png;base64,')).toBe(true)
+ })
+
+ it('refuses a file whose bytes are not the image it claims to be', async () => {
+ const notAnImage = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"></svg>')
+ await expect(
+ run(
+ 'gfs.read',
+ { uri: 'gfs://main/a.png', as: 'dataUrl' },
+ {
+ downloadGfsUri: async () => ({
+ resource: { gfsUri: 'gfs://main/a.png', name: 'a.png' } as never,
+ bytes: notAnImage.buffer.slice(
+ notAnImage.byteOffset,
+ notAnImage.byteOffset + notAnImage.byteLength
+ ) as ArrayBuffer,
+ }),
+ }
+ )
+ ).rejects.toBeInstanceOf(CapabilityInputError)
+ })
+
+ it('refuses an image over the size ceiling', async () => {
+ const huge = Buffer.concat([PNG, Buffer.alloc(PLUGIN_GFS_IMAGE_MAX_BYTES)])
+ await expect(
+ run(
+ 'gfs.read',
+ { uri: 'gfs://main/a.png', as: 'dataUrl' },
+ {
+ downloadGfsUri: async () => ({
+ resource: { gfsUri: 'gfs://main/a.png', name: 'a.png' } as never,
+ bytes: huge.buffer.slice(
+ huge.byteOffset,
+ huge.byteOffset + huge.byteLength
+ ) as ArrayBuffer,
+ }),
+ }
+ )
+ ).rejects.toBeInstanceOf(CapabilityTooLargeError)
+ })
+
+ it('rejects a non-gfs uri and an unknown mode at validation time', () => {
+ const descriptor = getCapability('gfs.read')
+ expect(() => descriptor?.validate({ uri: 'https://evil.example/x', as: 'dataUrl' })).toThrow()
+ expect(() => descriptor?.validate({ uri: 'gfs://main/a', as: 'binary' })).toThrow()
+ expect(() => descriptor?.validate({ uri: 'gfs://main/a', as: 'text', extra: 1 })).toThrow()
+ })
+
+ it('refuses bytes that are not valid UTF-8 in text mode', async () => {
+ const binary = Buffer.from([0xff, 0xfe, 0xfd])
+ await expect(
+ run(
+ 'gfs.read',
+ { uri: 'gfs://main/a.bin', as: 'text' },
+ {
+ downloadGfsUri: async () => ({
+ resource: { gfsUri: 'gfs://main/a.bin', name: 'a.bin' } as never,
+ bytes: binary.buffer.slice(
+ binary.byteOffset,
+ binary.byteOffset + binary.byteLength
+ ) as ArrayBuffer,
+ }),
+ }
+ )
+ ).rejects.toBeInstanceOf(CapabilityInputError)
+ })
+})
+
+describe('detectImageMime', () => {
+ it('identifies renderable formats by magic bytes', () => {
+ expect(detectImageMime(PNG)).toBe('image/png')
+ expect(detectImageMime(JPEG)).toBe('image/jpeg')
+ })
+
+ it('does not identify SVG, which is deliberately unsupported', () => {
+ expect(detectImageMime(Buffer.from('<svg></svg>'))).toBeNull()
+ })
+
+ it('survives a file shorter than any magic prefix', () => {
+ expect(detectImageMime(Buffer.from([0x01]))).toBeNull()
+ })
+})
+
+describe('notifications.notify', () => {
+ it('strips control characters and enforces length caps', () => {
+ const descriptor = getCapability('notifications.notify')
+ const params = descriptor?.validate({ title: 'New\u0000 lead\u001b', body: 'x' })
+ expect(params?.title).toBe('New lead')
+ expect(() => descriptor?.validate({ title: 'x'.repeat(121) })).toThrow()
+ expect(() => descriptor?.validate({ title: 'ok', body: 'x'.repeat(401) })).toThrow()
+ expect(() => descriptor?.validate({ body: 'no title' })).toThrow()
+ })
+
+ it('passes the host-owned plugin title through for attribution', async () => {
+ let seen: { pluginTitle?: string } = {}
+ await run(
+ 'notifications.notify',
+ { title: 'Hello' },
+ {
+ showPluginNotification: async (input: { pluginTitle?: string }) => {
+ seen = input
+ return { delivered: true }
+ },
+ }
+ )
+ expect(seen.pluginTitle).toBe('Plugin')
+ })
+})
diff --git a/desktop-app/src/__tests__/pluginSdkSurface.test.ts b/desktop-app/src/__tests__/pluginSdkSurface.test.ts
new file mode 100644
index 000000000..3a9879cd8
--- /dev/null
+++ b/desktop-app/src/__tests__/pluginSdkSurface.test.ts
@@ -0,0 +1,156 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+import { PLUGIN_GLOBAL_LIMIT, PluginRateLimiter } from '../pluginRateLimiter.js'
+import { CAPABILITY_IDS } from '../pluginSdkCapabilities.js'
+import {
+ PLUGIN_SDK_CAPABILITIES_CHANNEL,
+ PLUGIN_SDK_EVENT_CHANNEL,
+ PLUGIN_SDK_PERMISSIONS_CHANNEL,
+ PLUGIN_SDK_PERMISSION_STATE_CHANNEL,
+ PLUGIN_SDK_PROTOCOL,
+ PLUGIN_SDK_REQUEST_CHANNEL,
+ PLUGIN_SDK_VERSION,
+} from '../pluginSdkProtocol.js'
+import {
+ _resetPluginSurfacesForTests,
+ allPinnedSurfaces,
+ pinPluginSurface,
+ resolvePluginSurface,
+ unpinPluginSurface,
+ unpinPluginSurfacesOfKind,
+} from '../pluginSurfaceRegistry.js'
+
+// `import.meta` is unavailable in this CommonJS build; resolve from cwd, which
+// vitest sets to the desktop-app package root.
+const PRELOAD_PATH = path.join(process.cwd(), 'src', 'sandboxUiEmbedPreload.ts')
+
+describe('PluginRateLimiter', () => {
+ let clock: number
+ let limiter: PluginRateLimiter
+
+ beforeEach(() => {
+ clock = 0
+ limiter = new PluginRateLimiter(() => clock)
+ })
+
+ it('allows up to the per-minute budget then refuses with a retry hint', () => {
+ const spec = { perMinute: 3, perHour: 100 }
+ for (let i = 0; i < 3; i += 1) {
+ expect(limiter.take('p', 'c', spec).allowed).toBe(true)
+ }
+ const denied = limiter.take('p', 'c', spec)
+ expect(denied.allowed).toBe(false)
+ if (!denied.allowed) expect(denied.retryAfterMs).toBeGreaterThan(0)
+ })
+
+ it('refills continuously rather than resetting on a window edge', () => {
+ const spec = { perMinute: 60, perHour: 3600 }
+ for (let i = 0; i < 60; i += 1) limiter.take('p', 'c', spec)
+ expect(limiter.take('p', 'c', spec).allowed).toBe(false)
+ clock += 1_000 // one second buys exactly one token at 60/min
+ expect(limiter.take('p', 'c', spec).allowed).toBe(true)
+ })
+
+ it('stops a plugin round-robining past per-capability budgets', () => {
+ const generous = { perMinute: 1000, perHour: 10_000 }
+ let allowed = 0
+ for (let i = 0; i < PLUGIN_GLOBAL_LIMIT.perMinute + 10; i += 1) {
+ if (limiter.take('p', `cap-${i % 5}`, generous).allowed) allowed += 1
+ }
+ expect(allowed).toBe(PLUGIN_GLOBAL_LIMIT.perMinute)
+ })
+
+ it('refunds the capability token when only the global bucket is exhausted', () => {
+ const generous = { perMinute: 1000, perHour: 10_000 }
+ for (let i = 0; i < PLUGIN_GLOBAL_LIMIT.perMinute; i += 1) limiter.take('p', 'c', generous)
+ expect(limiter.take('p', 'c', generous).allowed).toBe(false)
+ // A globally throttled plugin should not also have burned its per-capability
+ // budget: once the global bucket refills, the capability must be callable.
+ clock += 60_000
+ expect(limiter.take('p', 'c', generous).allowed).toBe(true)
+ })
+
+ it('keeps plugins independent and forgets a plugin on reset', () => {
+ const spec = { perMinute: 1, perHour: 10 }
+ expect(limiter.take('a', 'c', spec).allowed).toBe(true)
+ expect(limiter.take('a', 'c', spec).allowed).toBe(false)
+ expect(limiter.take('b', 'c', spec).allowed).toBe(true)
+ limiter.reset('a')
+ expect(limiter.take('a', 'c', spec).allowed).toBe(true)
+ })
+})
+
+describe('pluginSurfaceRegistry', () => {
+ beforeEach(() => _resetPluginSurfacesForTests())
+ afterEach(() => _resetPluginSurfacesForTests())
+
+ const surface = {
+ pluginId: 'ns/plugin',
+ pluginTitle: 'Plugin',
+ surface: 'sandbox-ui-embed' as const,
+ webContentsId: 7,
+ generation: 1,
+ }
+
+ it('resolves a pinned sender and returns null for anything else', () => {
+ pinPluginSurface(surface)
+ expect(resolvePluginSurface(7)?.pluginId).toBe('ns/plugin')
+ expect(resolvePluginSurface(8)).toBeNull()
+ })
+
+ it('forgets a surface on unpin', () => {
+ pinPluginSurface(surface)
+ unpinPluginSurface(7)
+ expect(resolvePluginSurface(7)).toBeNull()
+ })
+
+ it('clears a whole kind and reports what it dropped', () => {
+ pinPluginSurface(surface)
+ pinPluginSurface({ ...surface, webContentsId: 8, pluginId: 'ns/other' })
+ const dropped = unpinPluginSurfacesOfKind('sandbox-ui-embed')
+ expect(dropped.map(item => item.pluginId).sort()).toEqual(['ns/other', 'ns/plugin'])
+ expect(allPinnedSurfaces()).toEqual([])
+ })
+})
+
+describe('embed preload contract', () => {
+ /**
+ * The embed preload runs with `sandbox: true`, where Electron's `require` is
+ * a polyfill limited to `electron` and a few builtins — it cannot import the
+ * protocol module. The channel names are therefore duplicated as literals in
+ * that file, and this test is what stops the copies from drifting apart.
+ */
+ it('inlines exactly the channel names and version the protocol module defines', async () => {
+ const source = await fs.readFile(PRELOAD_PATH, 'utf8')
+ for (const value of [
+ PLUGIN_SDK_REQUEST_CHANNEL,
+ PLUGIN_SDK_PERMISSIONS_CHANNEL,
+ PLUGIN_SDK_PERMISSION_STATE_CHANNEL,
+ PLUGIN_SDK_CAPABILITIES_CHANNEL,
+ PLUGIN_SDK_EVENT_CHANNEL,
+ PLUGIN_SDK_VERSION,
+ ]) {
+ expect(source, `preload is missing ${value}`).toContain(`'${value}'`)
+ }
+ expect(source).toContain(`const PLUGIN_SDK_PROTOCOL = ${PLUGIN_SDK_PROTOCOL}`)
+ })
+
+ it('never imports a relative module at runtime', async () => {
+ const source = await fs.readFile(PRELOAD_PATH, 'utf8')
+ const relativeValueImports = source
+ .split('\n')
+ .filter(line => /^import\s/.test(line) && line.includes("'./"))
+ .filter(line => !line.includes('import type'))
+ // A value import of a relative module compiles to `require('./…')`, which
+ // throws in a sandboxed preload at runtime — a failure no typecheck catches.
+ expect(relativeValueImports).toEqual([])
+ })
+
+ it('exposes one wrapper per capability the catalog defines', async () => {
+ const source = await fs.readFile(PRELOAD_PATH, 'utf8')
+ for (const id of CAPABILITY_IDS) {
+ expect(source, `preload has no wrapper for ${id}`).toContain(`'${id}'`)
+ }
+ })
+})
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index 19d3d64e3..c93b2f955 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -17,6 +17,7 @@ import { type DelegationAffordances, delegationAffordances } from './gfs/delegat
import { GfsClient, parseSubjectKey } from './gfs/uriHandler.js'
import { ApiError, requestJson } from './httpClient.js'
import { MemberRegistrationServiceClient } from './memberRegistrationServiceClient.js'
+import { tryGetPluginSdkRuntime } from './pluginSdkRuntime.js'
import { RpcProxyClient } from './rpcProxyClient.js'
import { RpcTokenManager } from './rpcTokenManager.js'
import {
@@ -517,6 +518,13 @@ export class AppService {
return matchingEntry?.team.id ?? this.accessCatalog?.teamId ?? null
}
+ /**
+ * Monotonic per sandbox-ui mount. Carried into the SDK surface pin so a
+ * request from a superseded embed can be told apart from the live one
+ * (spec §8.1), mirroring the driver's own `mountGeneration` guard.
+ */
+ private sandboxUiGeneration = 0
+
private enqueueSandboxUiLifecycle<T>(operation: () => Promise<T>): Promise<T> {
const result = this.sandboxUiLifecycleQueue.then(operation)
this.sandboxUiLifecycleQueue = result.then(
@@ -881,6 +889,9 @@ export class AppService {
this.rpcTokenManager.clear()
await this.tokenStore.clearSessionToken(getActiveEnvKey())
unbindChatStore()
+ // Grants survive logout (they are keyed by userId), but every cached SDK
+ // result must not: the next user of this machine gets nothing of this one's.
+ tryGetPluginSdkRuntime()?.notifySessionChanged(false)
}
/** Resolve a gfs:// URI to its current resource via the API (no local mirror). */
@@ -1027,6 +1038,17 @@ export class AppService {
return { authenticated: true, me: this.me }
}
+ /**
+ * Synchronous read of the cached session user id. The plugin SDK broker needs
+ * the current user to key grants and audit lines on every request, and it
+ * cannot await mid-decision without opening a window where a logout races the
+ * consent check. Returns null whenever there is no live session.
+ */
+ getCachedUserId(): string | null {
+ if (!this.sessionToken || !this.me) return null
+ return this.me.id
+ }
+
async listTeams(): Promise<{ currentTeamId: string; items: TeamSummary[] }> {
const token = this.requireSessionToken()
return this.authClient.listTeams(token)
@@ -1454,6 +1476,10 @@ export class AppService {
await this.switchSessionToTeam(targetTeamId)
if (!this.me) throw new Error('Team switch ended without an authenticated session')
this.stopAllStreams()
+ // Grants are keyed by userId, not by team, so they carry over — but every
+ // cached org/agents/contexts answer is now about the wrong team. Drop the
+ // cache and tell mounted plugins to refetch (spec §6.2).
+ tryGetPluginSdkRuntime()?.notifySessionChanged(true)
return { authenticated: true, me: this.me }
}
@@ -2910,6 +2936,7 @@ export class AppService {
openSandboxUi(args: {
recipeNs: string
recipeName: string
+ title?: string
defaultPath?: string
routePath?: string
bounds: import('./sandboxUiDriver.js').SandboxUiBounds
@@ -2924,6 +2951,7 @@ export class AppService {
private async openSandboxUiNow(args: {
recipeNs: string
recipeName: string
+ title?: string
defaultPath?: string
routePath?: string
bounds: import('./sandboxUiDriver.js').SandboxUiBounds
@@ -2935,6 +2963,7 @@ export class AppService {
const recipeNs = String(args.recipeNs || '').trim()
const recipeName = String(args.recipeName || '').trim()
if (!recipeNs || !recipeName) throw new Error('recipeNs and recipeName are required')
+ this.sandboxUiGeneration += 1
const { setCookie } = await this.mintSandboxUiSession(recipeNs, recipeName)
const driver = await import('./sandboxUiDriver.js')
const refreshModule = await import('./sandboxUiSessionRefresh.js')
@@ -2951,6 +2980,10 @@ export class AppService {
// Cancel refresh first so the timer doesn't keep firing against a
// partition we're about to evict on the next mount.
refreshModule.cancelSandboxUiRefresh()
+ // Unpin before anything else can observe a dead surface as pinned:
+ // per-mount SDK state (session denials, prompt budget, rate budget)
+ // dies with the mount.
+ tryGetPluginSdkRuntime()?.unpinAllSandboxUiSurfaces()
args.onClosed?.()
},
onOauthAuthorize: (oauthClientId, background) => {
@@ -2973,6 +3006,14 @@ export class AppService {
// to whichever recipe is active now.
return
}
+ // Pin the surface so the SDK broker can derive this plugin's identity from
+ // `webContents.id` — the plugin never asserts who it is (spec §8.1).
+ tryGetPluginSdkRuntime()?.pinSandboxUiSurface({
+ pluginId: activeView.appRef,
+ pluginTitle: String(args.title || '').trim() || recipeName,
+ webContentsId: activeView.webContentsId,
+ generation: this.sandboxUiGeneration,
+ })
refreshModule.startSandboxUiRefresh({
recipeNs,
recipeName,
@@ -2991,6 +3032,7 @@ export class AppService {
const driver = await import('./sandboxUiDriver.js')
const refreshModule = await import('./sandboxUiSessionRefresh.js')
refreshModule.cancelSandboxUiRefresh()
+ tryGetPluginSdkRuntime()?.unpinAllSandboxUiSurfaces()
await driver.unmountSandboxUiView()
})
}
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index 9dfee7e54..bc3561540 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -12,6 +12,13 @@ import { promises as fs } from 'node:fs'
import path from 'node:path'
import { AppService } from './appService.js'
import { requireChatStore } from './chatStoreBinding.js'
+import {
+ PLUGIN_SDK_CAPABILITIES_CHANNEL,
+ PLUGIN_SDK_CONSENT_RESOLVE_CHANNEL,
+ PLUGIN_SDK_PERMISSIONS_CHANNEL,
+ PLUGIN_SDK_PERMISSION_STATE_CHANNEL,
+ PLUGIN_SDK_REQUEST_CHANNEL,
+} from './pluginSdkProtocol.js'
import {
DesktopRuntimeConfig,
HostActivityStreamEvent,
@@ -1359,6 +1366,10 @@ export function registerIpcHandlers(service: AppService): void {
await service.openSandboxUi({
recipeNs,
recipeName,
+ // Human title from the installed recipe, used verbatim in consent
+ // prompts and notification attribution. Comes from the trusted renderer's
+ // app list — NEVER from anything the plugin itself can set.
+ title: sanitizeString((payload as { title?: unknown })?.title) || undefined,
defaultPath: typeof payload?.defaultPath === 'string' ? payload.defaultPath : undefined,
routePath: typeof payload?.routePath === 'string' ? payload.routePath : undefined,
bounds,
@@ -1421,4 +1432,94 @@ export function registerIpcHandlers(service: AppService): void {
ipcMain.handle('clerum:sandbox-ui:request-refresh', async event => {
await service.requestSandboxUiRefresh(event.sender.id)
})
+
+ // ── Plugin UI SDK ────────────────────────────────────────────────────
+ //
+ // Same trust model as the refresh IPC above and for the same reason: these
+ // four channels are reachable by untrusted plugin JS, so `assertTrustedSender`
+ // cannot be the gate (the embed's origin is rpc-proxy). Identity comes from
+ // the surface pinning map, and every other check — consent, rate limits,
+ // response minimization, audit — happens inside the broker. Nothing is
+ // enforced here; this layer only routes.
+
+ // Lazily imported: `pluginSdkRuntime` pulls in `config`, whose module-level
+ // profile load needs a real Electron `app`. Importing it at the top of this
+ // file would make merely registering IPC handlers depend on an initialized
+ // Electron runtime. Mirrors how `appService` defers `sandboxUiDriver`.
+ const pluginSdk = async () => (await import('./pluginSdkRuntime.js')).getPluginSdkRuntime()
+
+ ipcMain.handle(PLUGIN_SDK_CAPABILITIES_CHANNEL, async event =>
+ (await pluginSdk()).broker.listCapabilities(event.sender.id)
+ )
+
+ ipcMain.handle(PLUGIN_SDK_PERMISSION_STATE_CHANNEL, async (event, payload: unknown) =>
+ (await pluginSdk()).broker.permissionState(event.sender.id, payload)
+ )
+
+ ipcMain.handle(PLUGIN_SDK_PERMISSIONS_CHANNEL, async (event, payload: unknown) =>
+ (await pluginSdk()).broker.requestPermissions(event.sender.id, payload)
+ )
+
+ ipcMain.handle(PLUGIN_SDK_REQUEST_CHANNEL, async (event, payload: unknown) =>
+ (await pluginSdk()).broker.request(event.sender.id, payload)
+ )
+
+ // ── Plugin SDK, trusted-renderer half ────────────────────────────────
+ //
+ // The consent resolve channel IS trusted-sender guarded. That is what stops
+ // an embed from answering its own permission prompt, and it pairs with the
+ // main-generated `promptId` nonce: a resolve for an unknown or already-
+ // answered prompt is dropped inside the gate (spec §9.4).
+
+ ipcMain.handle(
+ PLUGIN_SDK_CONSENT_RESOLVE_CHANNEL,
+ async (event, payload: { promptId?: unknown; allowed?: unknown }) => {
+ assertTrustedSender(event)
+ const promptId = sanitizeString(payload?.promptId)
+ if (!promptId) throw new Error('promptId is required')
+ const allowed = Array.isArray(payload?.allowed)
+ ? payload.allowed.filter((entry): entry is string => typeof entry === 'string')
+ : []
+ return (await pluginSdk()).resolveConsentPrompt(promptId, allowed)
+ }
+ )
+
+ ipcMain.handle('pluginSdk:listGrants', async event => {
+ assertTrustedSender(event)
+ return (await pluginSdk()).listGrants()
+ })
+
+ ipcMain.handle(
+ 'pluginSdk:revoke',
+ async (event, payload: { pluginId?: unknown; capability?: unknown }) => {
+ assertTrustedSender(event)
+ const pluginId = sanitizeString(payload?.pluginId)
+ const capability = sanitizeString(payload?.capability)
+ if (!pluginId) throw new Error('pluginId is required')
+ const runtime = await pluginSdk()
+ if (capability) await runtime.revokeGrant(pluginId, capability)
+ else await runtime.revokeAllForPlugin(pluginId)
+ }
+ )
+
+ ipcMain.handle(
+ 'pluginSdk:activity',
+ async (event, payload: { limit?: unknown; includeAmbient?: unknown }) => {
+ assertTrustedSender(event)
+ return (await pluginSdk()).readAudit({
+ limit: sanitizeOptionalInteger(payload?.limit),
+ includeAmbient: payload?.includeAmbient === true,
+ })
+ }
+ )
+
+ ipcMain.handle('pluginSdk:clearActivity', async event => {
+ assertTrustedSender(event)
+ await (await pluginSdk()).clearAudit()
+ })
+
+ ipcMain.handle('pluginSdk:setTheme', async (event, payload: { theme?: unknown }) => {
+ assertTrustedSender(event)
+ ;(await pluginSdk()).setTheme(payload?.theme)
+ })
}
diff --git a/desktop-app/src/main.ts b/desktop-app/src/main.ts
index d190f540e..8a5fad1d6 100644
--- a/desktop-app/src/main.ts
+++ b/desktop-app/src/main.ts
@@ -5,6 +5,7 @@ import { config } from './config.js'
import { assertTrustedSender, registerIpcHandlers } from './ipc.js'
import { createMainWindowCoordinator, createRetryableInitializer } from './mainWindowCoordinator.js'
import { wireMainWindowRendererReadiness } from './mainWindowReadiness.js'
+import { initPluginSdkRuntime } from './pluginSdkRuntime.js'
import { collectInitialProtocolUrls } from './protocolLaunchArgs.js'
import { SandboxUiDeepLinkQueue } from './sandboxUiDeepLinkQueue.js'
import {
@@ -426,6 +427,10 @@ if (gotSingleInstanceLock) {
.whenReady()
.then(async () => {
wireAdaptiveSystemIcon()
+ // Must precede registerIpcHandlers: the SDK IPC handlers resolve the
+ // runtime eagerly on first call, and a plugin can be mounted the moment
+ // the window paints.
+ initPluginSdkRuntime({ service: appService, getMainWindow: () => mainWindow })
registerIpcHandlers(appService)
mainWindowLifecycleReady = true
wirePowerMonitor()
diff --git a/desktop-app/src/pluginAuditLog.ts b/desktop-app/src/pluginAuditLog.ts
new file mode 100644
index 000000000..a287f7f90
--- /dev/null
+++ b/desktop-app/src/pluginAuditLog.ts
@@ -0,0 +1,149 @@
+/**
+ * Append-only audit trail for plugin SDK activity (spec §10.3).
+ *
+ * Records the SHAPE of what a plugin received, never the content: field names
+ * for objects, counts for lists, byte sizes for blobs. An audit log that
+ * reproduces the data it is auditing is a liability, not a control — the whole
+ * point is that a user can read this file to see that LeadForge got their email
+ * without the file itself becoming a second copy of their email.
+ *
+ * One JSONL file per environment, mode 0600, rotated at 5 MB / 90 days with a
+ * single `.1` generation kept.
+ */
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+
+/** Same shape guard tokenStore.ts applies before interpolating into a path. */
+const ENV_KEY_SHAPE = /^[a-z0-9_]+-[0-9a-f]{12}$/
+
+export const AUDIT_MAX_BYTES = 5 * 1024 * 1024
+export const AUDIT_MAX_AGE_MS = 90 * 24 * 60 * 60 * 1000
+
+export type AuditOutcome =
+ | 'allowed'
+ | 'denied'
+ | 'granted'
+ | 'revoked'
+ | 'revoked_mid_flight'
+ | 'rate_limited'
+ | 'error'
+
+export type AuditConsentSource =
+ | 'existing_grant'
+ | 'prompt_allowed'
+ | 'prompt_denied'
+ | 'not_required'
+ | 'user_revoked'
+
+/** Shape summary — the only description of the payload that is ever written. */
+export type AuditShape = {
+ fields?: string[]
+ count?: number
+ bytes?: number
+}
+
+export type AuditEntry = {
+ ts: string
+ userId: string
+ pluginId: string
+ capability: string
+ outcome: AuditOutcome
+ consent?: AuditConsentSource
+ surface?: string
+ shape?: AuditShape
+ /** Error code for `outcome: error`. Never an upstream message. */
+ code?: string
+}
+
+export class PluginAuditLog {
+ constructor(
+ private readonly baseDir: string,
+ private readonly now: () => number = () => Date.now()
+ ) {}
+
+ private fileFor(envKey: string): string {
+ if (!ENV_KEY_SHAPE.test(envKey)) throw new Error('Invalid envKey: unexpected shape')
+ return path.join(this.baseDir, `${envKey}.jsonl`)
+ }
+
+ /**
+ * Append one line. Never throws into the request path: an audit write failure
+ * must not turn a legitimate capability call into an error for the plugin,
+ * so failures are logged and swallowed. (A silently unwritable audit log is a
+ * real gap; it surfaces as a console warning rather than user-facing noise.)
+ */
+ async append(envKey: string, entry: AuditEntry): Promise<void> {
+ try {
+ const file = this.fileFor(envKey)
+ await fs.mkdir(this.baseDir, { recursive: true, mode: 0o700 })
+ await this.rotateIfNeeded(file)
+ await fs.appendFile(file, `${JSON.stringify(entry)}\n`, { encoding: 'utf8', mode: 0o600 })
+ } catch (err) {
+ console.warn('[PluginSDK] audit append failed:', err)
+ }
+ }
+
+ private async rotateIfNeeded(file: string): Promise<void> {
+ let stat
+ try {
+ stat = await fs.stat(file)
+ } catch {
+ return
+ }
+ const tooBig = stat.size >= AUDIT_MAX_BYTES
+ const tooOld = this.now() - stat.birthtimeMs >= AUDIT_MAX_AGE_MS
+ if (!tooBig && !tooOld) return
+ await fs.rm(`${file}.1`, { force: true })
+ await fs.rename(file, `${file}.1`)
+ }
+
+ /**
+ * Newest-first read for the Settings activity tab. `ambient` capability lines
+ * are on disk but the caller filters them out by default (spec §10.3) — a
+ * `theme.read` per second would drown the entries a user cares about.
+ */
+ async read(envKey: string, options?: { limit?: number; userId?: string }): Promise<AuditEntry[]> {
+ const limit = options?.limit ?? 200
+ let raw: string
+ try {
+ raw = await fs.readFile(this.fileFor(envKey), 'utf8')
+ } catch {
+ return []
+ }
+ const entries: AuditEntry[] = []
+ for (const line of raw.split('\n')) {
+ if (!line.trim()) continue
+ try {
+ const parsed = JSON.parse(line) as AuditEntry
+ if (options?.userId && parsed.userId !== options.userId) continue
+ entries.push(parsed)
+ } catch {
+ // A torn final line (crash mid-append) must not poison the whole read.
+ }
+ }
+ return entries.reverse().slice(0, limit)
+ }
+
+ async clear(envKey: string): Promise<void> {
+ const file = this.fileFor(envKey)
+ await fs.rm(file, { force: true })
+ await fs.rm(`${file}.1`, { force: true })
+ }
+}
+
+/** Describe a payload without copying it. */
+export function shapeOf(value: unknown): AuditShape {
+ if (value === null || value === undefined) return {}
+ if (Array.isArray(value)) return { count: value.length }
+ if (typeof value === 'string') return { bytes: Buffer.byteLength(value, 'utf8') }
+ if (typeof value === 'object') {
+ const record = value as Record<string, unknown>
+ const fields = Object.keys(record).sort()
+ // A single-key wrapper around a list ({ agents: [...] }) is much more
+ // useful reported as a count than as the field name alone.
+ const only = fields.length === 1 ? record[fields[0] as string] : undefined
+ if (Array.isArray(only)) return { fields, count: only.length }
+ return { fields }
+ }
+ return {}
+}
diff --git a/desktop-app/src/pluginConsentGate.ts b/desktop-app/src/pluginConsentGate.ts
new file mode 100644
index 000000000..b30245a8b
--- /dev/null
+++ b/desktop-app/src/pluginConsentGate.ts
@@ -0,0 +1,350 @@
+/**
+ * The consent gate (spec §9).
+ *
+ * Owns everything between "a plugin wants a capability" and "the broker may
+ * call the provider": grant lookup, session-sticky denials, the prompt budget,
+ * the single-prompt-at-a-time queue, and the modal round-trip to the trusted
+ * renderer.
+ *
+ * Two asymmetries are deliberate:
+ * - A GRANT is permanent until revoked (decision D4).
+ * - A DENIAL is in-memory and dies with the mount, so a mis-click is not a
+ * permanent lockout — reopening the plugin gives it one more chance to ask.
+ *
+ * The prompt itself renders in the trusted renderer while the plugin surface is
+ * HIDDEN, because a WebContentsView paints above renderer DOM regardless of
+ * z-index (spec §9.4). Hiding it is the only way to guarantee the plugin can
+ * neither fake a modal nor paint over the real one.
+ */
+import { randomUUID } from 'node:crypto'
+import type { ConsentGrant, ConsentStore } from './pluginConsentStore.js'
+import { getCapability, sortCapabilitiesForPrompt } from './pluginSdkCapabilities.js'
+import type { PluginConsentRequest, PluginConsentRow } from './pluginSdkProtocol.js'
+
+export const CONSENT_PROMPT_TIMEOUT_MS = 120_000
+export const CONSENT_PROMPT_COOLDOWN_MS = 10_000
+/** Modals — not capabilities — per plugin per mount (spec §9.5). */
+export const CONSENT_MAX_PROMPTS_PER_MOUNT = 3
+
+export type ConsentDecisionSource =
+ | 'existing_grant'
+ | 'prompt_allowed'
+ | 'prompt_denied'
+ | 'not_required'
+
+export type ConsentOutcome = {
+ granted: Record<string, boolean>
+ /** How each id was decided, for the audit line. */
+ source: Record<string, ConsentDecisionSource>
+}
+
+export type ConsentGateDeps = {
+ store: ConsentStore
+ /** Push the prompt to the trusted renderer. */
+ presentPrompt: (request: PluginConsentRequest) => void
+ /** Withdraw a prompt the user never answered (timeout, embed died). */
+ cancelPrompt: (promptId: string) => void
+ /** Hide/show the active plugin surface around the modal. */
+ setSurfaceVisible: (visible: boolean) => Promise<void>
+ /** True when a Desktop window is visible and focused. */
+ isWindowReady: () => boolean
+ now?: () => number
+ /**
+ * Injectable delay. Real code sleeps; tests assert the requested duration
+ * without spending it, so the cooldown stays a tested behaviour rather than a
+ * behaviour tests have to disable.
+ */
+ sleep?: (ms: number) => Promise<void>
+}
+
+type PendingPrompt = {
+ promptId: string
+ pluginId: string
+ capabilities: Set<string>
+ resolve: (allowed: Set<string>) => void
+ timer: ReturnType<typeof setTimeout> | null
+}
+
+type PluginSessionState = {
+ denials: Set<string>
+ promptCount: number
+ lastPromptAt: number
+}
+
+export class PluginConsentGate {
+ private readonly now: () => number
+ private readonly sleep: (ms: number) => Promise<void>
+ private readonly sessions = new Map<string, PluginSessionState>()
+ private pending: PendingPrompt | null = null
+ private queue: Promise<unknown> = Promise.resolve()
+
+ constructor(private readonly deps: ConsentGateDeps) {
+ this.now = deps.now ?? (() => Date.now())
+ this.sleep = deps.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms)))
+ }
+
+ private session(pluginId: string): PluginSessionState {
+ const existing = this.sessions.get(pluginId)
+ if (existing) return existing
+ const created: PluginSessionState = { denials: new Set(), promptCount: 0, lastPromptAt: 0 }
+ this.sessions.set(pluginId, created)
+ return created
+ }
+
+ /** Called on unmount: denials and the prompt budget are per-mount state. */
+ resetPlugin(pluginId: string): void {
+ this.sessions.delete(pluginId)
+ if (this.pending?.pluginId === pluginId) {
+ const pending = this.pending
+ this.pending = null
+ if (pending.timer) clearTimeout(pending.timer)
+ this.deps.cancelPrompt(pending.promptId)
+ pending.resolve(new Set())
+ }
+ }
+
+ resetAll(): void {
+ this.sessions.clear()
+ }
+
+ /**
+ * Is this capability already granted, at a descriptor version that still
+ * covers today's payload? A grant recorded before the payload widened does
+ * NOT carry over (spec §9.6) — silently widening an existing grant is the
+ * easiest way to turn consent into theatre.
+ */
+ async isGranted(key: {
+ envKey: string
+ userId: string
+ pluginId: string
+ capability: string
+ }): Promise<boolean> {
+ const descriptor = getCapability(key.capability)
+ if (!descriptor) return false
+ if (!descriptor.requiresConsent) return true
+ const grant = await this.deps.store.get(key)
+ if (!grant) return false
+ return grant.descriptorVersion >= descriptor.descriptorVersion
+ }
+
+ /**
+ * Resolve consent for a set of capabilities, prompting at most once for
+ * whatever is still undecided. This is the single entry point — a lone
+ * capability call is just a batch of one.
+ */
+ async ensure(input: {
+ envKey: string
+ userId: string
+ pluginId: string
+ pluginTitle: string
+ capabilities: string[]
+ }): Promise<ConsentOutcome> {
+ const granted: Record<string, boolean> = {}
+ const source: Record<string, ConsentDecisionSource> = {}
+ const session = this.session(input.pluginId)
+ const toPrompt: string[] = []
+
+ for (const capability of input.capabilities) {
+ const descriptor = getCapability(capability)
+ if (!descriptor) {
+ granted[capability] = false
+ source[capability] = 'prompt_denied'
+ continue
+ }
+ if (!descriptor.requiresConsent) {
+ granted[capability] = true
+ source[capability] = 'not_required'
+ continue
+ }
+ if (await this.isGranted({ ...input, capability })) {
+ granted[capability] = true
+ source[capability] = 'existing_grant'
+ continue
+ }
+ if (session.denials.has(capability)) {
+ // Session-sticky: one refusal buys silence for the rest of the mount.
+ granted[capability] = false
+ source[capability] = 'prompt_denied'
+ continue
+ }
+ toPrompt.push(capability)
+ }
+
+ if (toPrompt.length === 0) return { granted, source }
+
+ const allowed = await this.promptFor(input, toPrompt)
+ for (const capability of toPrompt) {
+ const isAllowed = allowed.has(capability)
+ granted[capability] = isAllowed
+ source[capability] = isAllowed ? 'prompt_allowed' : 'prompt_denied'
+ if (!isAllowed) session.denials.add(capability)
+ }
+ return { granted, source }
+ }
+
+ private async promptFor(
+ input: { envKey: string; userId: string; pluginId: string; pluginTitle: string },
+ capabilities: string[]
+ ): Promise<Set<string>> {
+ // Serialize: one modal at a time, globally. A second request whose rows are
+ // already in flight joins that prompt rather than opening another.
+ const run = this.queue.then(
+ () => this.runPrompt(input, capabilities),
+ () => this.runPrompt(input, capabilities)
+ )
+ this.queue = run.then(
+ () => undefined,
+ () => undefined
+ )
+ return run
+ }
+
+ private async runPrompt(
+ input: { envKey: string; userId: string; pluginId: string; pluginTitle: string },
+ capabilities: string[]
+ ): Promise<Set<string>> {
+ const session = this.session(input.pluginId)
+
+ // Re-check: a queued request may have been answered by the prompt ahead of
+ // it, or denied while it waited.
+ const stillNeeded: string[] = []
+ for (const capability of capabilities) {
+ if (session.denials.has(capability)) continue
+ if (await this.isGranted({ ...input, capability })) continue
+ stillNeeded.push(capability)
+ }
+ if (stillNeeded.length === 0) {
+ const resolved = new Set<string>()
+ for (const capability of capabilities) {
+ if (await this.isGranted({ ...input, capability })) resolved.add(capability)
+ }
+ return resolved
+ }
+
+ if (session.promptCount >= CONSENT_MAX_PROMPTS_PER_MOUNT) {
+ // Budget spent. Everything left is denied until the user reopens the
+ // plugin. Not recorded as a session denial: the user never saw this ask.
+ return new Set()
+ }
+
+ const cooldownRemaining = CONSENT_PROMPT_COOLDOWN_MS - (this.now() - session.lastPromptAt)
+ if (session.lastPromptAt > 0 && cooldownRemaining > 0) {
+ await this.sleep(cooldownRemaining)
+ }
+
+ const ready = await this.waitForWindow()
+ if (!ready) return new Set()
+
+ const rows: PluginConsentRow[] = sortCapabilitiesForPrompt(stillNeeded).flatMap(capability => {
+ const descriptor = getCapability(capability)
+ if (!descriptor) return []
+ return [
+ {
+ capability,
+ title: descriptor.consent.title,
+ dataDescription: descriptor.consent.dataDescription,
+ tier: descriptor.consent.tier,
+ },
+ ]
+ })
+ if (rows.length === 0) return new Set()
+
+ const promptId = randomUUID()
+ const request: PluginConsentRequest = {
+ promptId,
+ pluginId: input.pluginId,
+ pluginTitle: input.pluginTitle,
+ rows,
+ priorPromptCount: session.promptCount,
+ }
+
+ session.promptCount += 1
+ session.lastPromptAt = this.now()
+
+ let allowed = new Set<string>()
+ await this.deps.setSurfaceVisible(false)
+ try {
+ allowed = await new Promise<Set<string>>(resolve => {
+ const timer = setTimeout(() => {
+ if (this.pending?.promptId !== promptId) return
+ this.pending = null
+ this.deps.cancelPrompt(promptId)
+ // A prompt nobody answered counts as a denial (spec §9.3).
+ resolve(new Set())
+ }, CONSENT_PROMPT_TIMEOUT_MS)
+ this.pending = {
+ promptId,
+ pluginId: input.pluginId,
+ capabilities: new Set(stillNeeded),
+ resolve,
+ timer,
+ }
+ this.deps.presentPrompt(request)
+ })
+ } finally {
+ await this.deps.setSurfaceVisible(true).catch(() => undefined)
+ }
+
+ const grantedNow = new Set<string>()
+ for (const capability of stillNeeded) {
+ if (!allowed.has(capability)) continue
+ const descriptor = getCapability(capability)
+ if (!descriptor) continue
+ const grant: ConsentGrant = {
+ envKey: input.envKey,
+ userId: input.userId,
+ pluginId: input.pluginId,
+ capability,
+ grantedAt: new Date(this.now()).toISOString(),
+ lastUsedAt: null,
+ descriptorVersion: descriptor.descriptorVersion,
+ revision: 0,
+ }
+ await this.deps.store.put(grant)
+ grantedNow.add(capability)
+ }
+
+ // Capabilities the caller asked about that were already granted before this
+ // prompt still belong in the answer.
+ for (const capability of capabilities) {
+ if (grantedNow.has(capability)) continue
+ if (await this.isGranted({ ...input, capability })) grantedNow.add(capability)
+ }
+ return grantedNow
+ }
+
+ /**
+ * Park until a Desktop window is visible and focused, so a modal never races
+ * onto a screen the user is not looking at. Polls rather than subscribing to
+ * window events: the gate must stay Electron-free for tests, and the wait is
+ * bounded by the prompt timeout anyway.
+ */
+ private async waitForWindow(): Promise<boolean> {
+ if (this.deps.isWindowReady()) return true
+ const deadline = this.now() + CONSENT_PROMPT_TIMEOUT_MS
+ while (this.now() < deadline) {
+ await this.sleep(500)
+ if (this.deps.isWindowReady()) return true
+ }
+ return false
+ }
+
+ /**
+ * The trusted renderer's answer. A resolve for an unknown, stale, or
+ * already-answered promptId is dropped — the nonce is what stops an embed
+ * from answering its own prompt even if it could reach the channel.
+ */
+ resolvePrompt(promptId: string, allowed: string[]): boolean {
+ const pending = this.pending
+ if (!pending || pending.promptId !== promptId) return false
+ this.pending = null
+ if (pending.timer) clearTimeout(pending.timer)
+ const accepted = new Set(allowed.filter(capability => pending.capabilities.has(capability)))
+ pending.resolve(accepted)
+ return true
+ }
+
+ hasPendingPrompt(): boolean {
+ return this.pending !== null
+ }
+}
diff --git a/desktop-app/src/pluginConsentStore.ts b/desktop-app/src/pluginConsentStore.ts
new file mode 100644
index 000000000..6d53bef85
--- /dev/null
+++ b/desktop-app/src/pluginConsentStore.ts
@@ -0,0 +1,212 @@
+/**
+ * Consent grant persistence (spec §10).
+ *
+ * The interface is the v1 obligation; the local implementation is v1's answer.
+ * A server-backed store (spec §10.6) implements the same interface, which is
+ * the test of whether the layering is right: syncing grants across devices
+ * should touch this file and nothing the plugin can observe.
+ *
+ * Storage: one JSON file per environment under `<userData>/plugin-consent/`,
+ * mode 0600, written atomically. Scoped by `envKey` exactly like `tokenStore`
+ * and the sandbox-ui partitions, so cluster A's grants never leak into
+ * cluster B's. Keyed by `userId` inside the file, so a shared machine keeps two
+ * humans' decisions apart.
+ *
+ * NOT encrypted, deliberately: grants are not secrets ("plugin X may read Y"),
+ * and an attacker who can read this file can already read the audit log or
+ * patch the app bundle. safeStorage would add a platform-dependent failure mode
+ * for no real gain. 0600 is the protection.
+ */
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+
+const ENV_KEY_SHAPE = /^[a-z0-9_]+-[0-9a-f]{12}$/
+const SCHEMA_VERSION = 1
+
+export type ConsentGrant = {
+ envKey: string
+ userId: string
+ /** `<recipeNs>/<recipeName>` */
+ pluginId: string
+ capability: string
+ grantedAt: string
+ lastUsedAt: string | null
+ /** Bumped when a capability's payload widens; older grants stop covering it (§9.6). */
+ descriptorVersion: number
+ /** Monotonic per grant, for the v2 sync merge. */
+ revision: number
+}
+
+export type GrantKey = {
+ envKey: string
+ userId: string
+ pluginId: string
+ capability: string
+}
+
+export interface ConsentStore {
+ list(envKey: string, userId: string): Promise<ConsentGrant[]>
+ get(key: GrantKey): Promise<ConsentGrant | null>
+ put(grant: ConsentGrant): Promise<void>
+ touch(key: GrantKey): Promise<void>
+ revoke(key: GrantKey): Promise<void>
+ revokeAllForPlugin(envKey: string, userId: string, pluginId: string): Promise<void>
+ /** v2 hook; the local implementation does not define it. */
+ sync?(envKey: string, userId: string): Promise<void>
+}
+
+type ConsentFile = {
+ version: number
+ users: Record<string, ConsentGrant[]>
+}
+
+function emptyFile(): ConsentFile {
+ return { version: SCHEMA_VERSION, users: {} }
+}
+
+function sameGrant(grant: ConsentGrant, key: GrantKey): boolean {
+ return grant.pluginId === key.pluginId && grant.capability === key.capability
+}
+
+export class LocalConsentStore implements ConsentStore {
+ /** envKey → parsed file. Invalidated on every write. */
+ private cache = new Map<string, ConsentFile>()
+ /** Serializes read-modify-write so two concurrent puts cannot drop one. */
+ private chain: Promise<unknown> = Promise.resolve()
+
+ constructor(
+ private readonly baseDir: string,
+ private readonly now: () => number = () => Date.now()
+ ) {}
+
+ private fileFor(envKey: string): string {
+ if (!ENV_KEY_SHAPE.test(envKey)) throw new Error('Invalid envKey: unexpected shape')
+ return path.join(this.baseDir, `${envKey}.json`)
+ }
+
+ private async load(envKey: string): Promise<ConsentFile> {
+ const cached = this.cache.get(envKey)
+ if (cached) return cached
+ const file = this.fileFor(envKey)
+ let parsed: ConsentFile
+ try {
+ const raw = await fs.readFile(file, 'utf8')
+ const candidate = JSON.parse(raw) as ConsentFile
+ if (
+ !candidate ||
+ typeof candidate !== 'object' ||
+ candidate.version !== SCHEMA_VERSION ||
+ typeof candidate.users !== 'object'
+ ) {
+ throw new Error(`unsupported consent file version: ${candidate?.version}`)
+ }
+ parsed = candidate
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException)?.code
+ if (code && code !== 'ENOENT') {
+ // Fail CLOSED: an unreadable or future-version file means every
+ // capability re-prompts. Never partially parse a consent file — a
+ // half-understood grant list is worse than no grant list.
+ console.warn('[PluginSDK] consent file unreadable, starting empty:', err)
+ await fs.rename(file, `${file}.corrupt-${this.now()}`).catch(() => undefined)
+ } else if (!code) {
+ console.warn('[PluginSDK] consent file invalid, starting empty:', err)
+ await fs.rename(file, `${file}.corrupt-${this.now()}`).catch(() => undefined)
+ }
+ parsed = emptyFile()
+ }
+ this.cache.set(envKey, parsed)
+ return parsed
+ }
+
+ private async save(envKey: string, data: ConsentFile): Promise<void> {
+ const file = this.fileFor(envKey)
+ await fs.mkdir(this.baseDir, { recursive: true, mode: 0o700 })
+ // Atomic: a crash mid-write leaves the previous file intact rather than a
+ // truncated one that would fail closed and silently drop every grant.
+ const tmp = `${file}.tmp-${this.now()}`
+ await fs.writeFile(tmp, JSON.stringify(data, null, 2), { encoding: 'utf8', mode: 0o600 })
+ await fs.rename(tmp, file)
+ this.cache.set(envKey, data)
+ }
+
+ private mutate<T>(fn: () => Promise<T>): Promise<T> {
+ const run = this.chain.then(fn, fn)
+ this.chain = run.then(
+ () => undefined,
+ () => undefined
+ )
+ return run
+ }
+
+ async list(envKey: string, userId: string): Promise<ConsentGrant[]> {
+ const data = await this.load(envKey)
+ return [...(data.users[userId] ?? [])]
+ }
+
+ async get(key: GrantKey): Promise<ConsentGrant | null> {
+ const rows = await this.list(key.envKey, key.userId)
+ return rows.find(row => sameGrant(row, key)) ?? null
+ }
+
+ async put(grant: ConsentGrant): Promise<void> {
+ await this.mutate(async () => {
+ const data = await this.load(grant.envKey)
+ const rows = data.users[grant.userId] ?? []
+ const existing = rows.find(row => sameGrant(row, grant))
+ const next = rows.filter(row => !sameGrant(row, grant))
+ next.push({ ...grant, revision: (existing?.revision ?? 0) + 1 })
+ data.users[grant.userId] = next
+ await this.save(grant.envKey, data)
+ })
+ }
+
+ async touch(key: GrantKey): Promise<void> {
+ await this.mutate(async () => {
+ const data = await this.load(key.envKey)
+ const rows = data.users[key.userId] ?? []
+ const row = rows.find(entry => sameGrant(entry, key))
+ if (!row) return
+ row.lastUsedAt = new Date(this.now()).toISOString()
+ await this.save(key.envKey, data)
+ })
+ }
+
+ async revoke(key: GrantKey): Promise<void> {
+ await this.mutate(async () => {
+ const data = await this.load(key.envKey)
+ const rows = data.users[key.userId] ?? []
+ data.users[key.userId] = rows.filter(row => !sameGrant(row, key))
+ await this.save(key.envKey, data)
+ })
+ }
+
+ async revokeAllForPlugin(envKey: string, userId: string, pluginId: string): Promise<void> {
+ await this.mutate(async () => {
+ const data = await this.load(envKey)
+ const rows = data.users[userId] ?? []
+ data.users[userId] = rows.filter(row => row.pluginId !== pluginId)
+ await this.save(envKey, data)
+ })
+ }
+
+ /**
+ * Drop grants for plugins the user can no longer reach. Called from the
+ * launch-time partition GC pass, which already computes that set (§10.5).
+ */
+ async pruneToPlugins(envKey: string, userId: string, allowed: Set<string>): Promise<void> {
+ await this.mutate(async () => {
+ const data = await this.load(envKey)
+ const rows = data.users[userId] ?? []
+ const kept = rows.filter(row => allowed.has(row.pluginId))
+ if (kept.length === rows.length) return
+ data.users[userId] = kept
+ await this.save(envKey, data)
+ })
+ }
+
+ /** ONLY for tests. */
+ _invalidateCacheForTests(): void {
+ this.cache.clear()
+ }
+}
diff --git a/desktop-app/src/pluginRateLimiter.ts b/desktop-app/src/pluginRateLimiter.ts
new file mode 100644
index 000000000..202945d02
--- /dev/null
+++ b/desktop-app/src/pluginRateLimiter.ts
@@ -0,0 +1,97 @@
+/**
+ * Per-plugin token buckets (spec §6.9).
+ *
+ * Two layers, both required:
+ * - per (plugin, capability), so a chatty `gfs.list` cannot starve anything;
+ * - per plugin across all capabilities, so a plugin cannot round-robin its
+ * way past the per-capability budgets.
+ *
+ * Buckets refill continuously rather than resetting on a window boundary, so a
+ * plugin polling at the limit degrades smoothly instead of getting a burst
+ * every 60 s. `now` is injectable for tests.
+ */
+
+export type RateLimitDecision = { allowed: true } | { allowed: false; retryAfterMs: number }
+
+export type RateLimitSpec = { perMinute: number; perHour: number }
+
+type Bucket = { tokens: number; capacity: number; refillPerMs: number; updatedAt: number }
+
+/** Global ceiling across every capability of one plugin (spec §6.9). */
+export const PLUGIN_GLOBAL_LIMIT: RateLimitSpec = { perMinute: 120, perHour: 2400 }
+
+function makeBucket(capacity: number, perMs: number, now: number): Bucket {
+ return { tokens: capacity, capacity, refillPerMs: perMs, updatedAt: now }
+}
+
+function refill(bucket: Bucket, now: number): void {
+ const elapsed = Math.max(0, now - bucket.updatedAt)
+ bucket.tokens = Math.min(bucket.capacity, bucket.tokens + elapsed * bucket.refillPerMs)
+ bucket.updatedAt = now
+}
+
+function tryTake(bucket: Bucket, now: number): RateLimitDecision {
+ refill(bucket, now)
+ if (bucket.tokens >= 1) {
+ bucket.tokens -= 1
+ return { allowed: true }
+ }
+ // Time until one whole token exists again.
+ const deficit = 1 - bucket.tokens
+ return { allowed: false, retryAfterMs: Math.ceil(deficit / bucket.refillPerMs) }
+}
+
+export class PluginRateLimiter {
+ /** key → [minuteBucket, hourBucket] */
+ private readonly buckets = new Map<string, [Bucket, Bucket]>()
+
+ constructor(private readonly now: () => number = () => Date.now()) {}
+
+ private pair(key: string, spec: RateLimitSpec): [Bucket, Bucket] {
+ const existing = this.buckets.get(key)
+ if (existing) return existing
+ const t = this.now()
+ const created: [Bucket, Bucket] = [
+ makeBucket(spec.perMinute, spec.perMinute / 60_000, t),
+ makeBucket(spec.perHour, spec.perHour / 3_600_000, t),
+ ]
+ this.buckets.set(key, created)
+ return created
+ }
+
+ /**
+ * Consume one token from the capability bucket AND the plugin-global bucket.
+ * Both must have capacity; when the capability bucket allows but the global
+ * one does not, the capability token is refunded so a globally throttled
+ * plugin does not also burn its per-capability budget.
+ */
+ take(pluginId: string, capability: string, spec: RateLimitSpec): RateLimitDecision {
+ const now = this.now()
+ const capPair = this.pair(`${pluginId}::${capability}`, spec)
+ const globalPair = this.pair(`${pluginId}::*`, PLUGIN_GLOBAL_LIMIT)
+
+ for (const bucket of capPair) {
+ const decision = tryTake(bucket, now)
+ if (!decision.allowed) return decision
+ }
+ for (const bucket of globalPair) {
+ const decision = tryTake(bucket, now)
+ if (!decision.allowed) {
+ for (const b of capPair) b.tokens = Math.min(b.capacity, b.tokens + 1)
+ return decision
+ }
+ }
+ return { allowed: true }
+ }
+
+ /** Drop a plugin's budgets on unmount so a fresh session starts clean. */
+ reset(pluginId: string): void {
+ for (const key of [...this.buckets.keys()]) {
+ if (key.startsWith(`${pluginId}::`)) this.buckets.delete(key)
+ }
+ }
+
+ resetAll(): void {
+ this.buckets.clear()
+ }
+}
diff --git a/desktop-app/src/pluginSdkBroker.ts b/desktop-app/src/pluginSdkBroker.ts
new file mode 100644
index 000000000..a0279f812
--- /dev/null
+++ b/desktop-app/src/pluginSdkBroker.ts
@@ -0,0 +1,377 @@
+/**
+ * The plugin SDK chokepoint (spec §4).
+ *
+ * Every capability call, from every plugin surface, passes through here in one
+ * fixed order:
+ *
+ * resolve caller → look up descriptor → require session → rate budget →
+ * consent → provider → minimize → audit
+ *
+ * There is deliberately no second path. Adding a capability cannot skip the
+ * consent check or the audit write because there is nowhere else for a request
+ * to go.
+ */
+import type { AuditEntry, AuditOutcome, PluginAuditLog } from './pluginAuditLog.js'
+import { shapeOf } from './pluginAuditLog.js'
+import type { PluginConsentGate } from './pluginConsentGate.js'
+import type { ConsentStore } from './pluginConsentStore.js'
+import type { PluginRateLimiter } from './pluginRateLimiter.js'
+import {
+ CAPABILITY_IDS,
+ CapabilityInputError,
+ CapabilityNotFoundError,
+ CapabilityTooLargeError,
+ type PluginSdkDataSource,
+ getCapability,
+} from './pluginSdkCapabilities.js'
+import {
+ PLUGIN_SDK_MAX_BATCH,
+ PLUGIN_SDK_PROTOCOL,
+ PLUGIN_SDK_VERSION,
+ type PluginSdkCapabilitiesResult,
+ type PluginSdkPermissionStateResult,
+ type PluginSdkPermissionsResult,
+ type PluginSdkResponse,
+ sdkError,
+ sdkOk,
+} from './pluginSdkProtocol.js'
+import { type PinnedPluginSurface, resolvePluginSurface } from './pluginSurfaceRegistry.js'
+
+export type BrokerDeps = {
+ source: PluginSdkDataSource
+ store: ConsentStore
+ gate: PluginConsentGate
+ limiter: PluginRateLimiter
+ audit: PluginAuditLog
+ /** Active environment key — scopes grants and the audit file. */
+ getEnvKey: () => string
+ /** Current user id, or null when logged out. */
+ getUserId: () => string | null
+ now?: () => number
+}
+
+type CacheEntry = { value: unknown; expiresAt: number }
+
+export class PluginSdkBroker {
+ private readonly now: () => number
+ private readonly cache = new Map<string, CacheEntry>()
+
+ constructor(private readonly deps: BrokerDeps) {
+ this.now = deps.now ?? (() => Date.now())
+ }
+
+ private async writeAudit(
+ surface: PinnedPluginSurface | null,
+ capability: string,
+ outcome: AuditOutcome,
+ extra: Partial<AuditEntry> = {}
+ ): Promise<void> {
+ const userId = this.deps.getUserId() ?? 'anonymous'
+ const entry: AuditEntry = {
+ ts: new Date(this.now()).toISOString(),
+ userId,
+ pluginId: surface?.pluginId ?? 'unknown',
+ capability,
+ outcome,
+ ...(surface ? { surface: surface.surface } : {}),
+ ...extra,
+ }
+ await this.deps.audit.append(this.deps.getEnvKey(), entry)
+ }
+
+ /**
+ * Sender → plugin. An unpinned sender is a hard rejection: the embed loads
+ * from the rpc-proxy origin so `assertTrustedSender` cannot be the check
+ * here, and the pinning map is what stands in its place (spec §8.1).
+ */
+ private resolveCaller(senderId: number): PinnedPluginSurface | null {
+ const surface = resolvePluginSurface(senderId)
+ if (!surface) {
+ console.warn('[PluginSDK] request from unpinned sender', senderId)
+ return null
+ }
+ return surface
+ }
+
+ listCapabilities(senderId: number): PluginSdkResponse<PluginSdkCapabilitiesResult> {
+ if (!this.resolveCaller(senderId)) {
+ return sdkError('internal', 'this surface is not registered', false)
+ }
+ return sdkOk({ capabilities: [...CAPABILITY_IDS], version: PLUGIN_SDK_VERSION })
+ }
+
+ /** Grant state without prompting, so a returning user sees no modal at all. */
+ async permissionState(
+ senderId: number,
+ requested: unknown
+ ): Promise<PluginSdkResponse<PluginSdkPermissionStateResult>> {
+ const surface = this.resolveCaller(senderId)
+ if (!surface) return sdkError('internal', 'this surface is not registered', false)
+ const userId = this.deps.getUserId()
+ if (!userId) return sdkError('unauthenticated', 'no active session', true)
+
+ let ids: string[]
+ try {
+ ids = normalizeCapabilityList(requested, { allowEmpty: true })
+ } catch (err) {
+ return sdkError('invalid_request', (err as Error).message, false)
+ }
+ const list = ids.length > 0 ? ids : CAPABILITY_IDS
+ const granted: Record<string, boolean> = {}
+ for (const capability of list) {
+ granted[capability] = await this.deps.gate.isGranted({
+ envKey: this.deps.getEnvKey(),
+ userId,
+ pluginId: surface.pluginId,
+ capability,
+ })
+ }
+ return sdkOk({ granted })
+ }
+
+ /**
+ * Batched consent (spec §9.2). One call, one modal, one decision per row.
+ * Returns a MAP even when the user declines everything — a partial grant is a
+ * normal state the plugin renders, not an exception.
+ */
+ async requestPermissions(
+ senderId: number,
+ payload: unknown
+ ): Promise<PluginSdkResponse<PluginSdkPermissionsResult>> {
+ const surface = this.resolveCaller(senderId)
+ if (!surface) return sdkError('internal', 'this surface is not registered', false)
+
+ const version = (payload as { v?: unknown })?.v
+ if (version !== undefined && version !== PLUGIN_SDK_PROTOCOL) {
+ return sdkError(
+ 'unsupported_version',
+ `unsupported protocol version: ${String(version)}`,
+ false
+ )
+ }
+ const userId = this.deps.getUserId()
+ if (!userId) return sdkError('unauthenticated', 'no active session', true)
+
+ let ids: string[]
+ try {
+ ids = normalizeCapabilityList((payload as { capabilities?: unknown })?.capabilities, {
+ allowEmpty: false,
+ })
+ } catch (err) {
+ return sdkError('invalid_request', (err as Error).message, false)
+ }
+
+ const outcome = await this.deps.gate.ensure({
+ envKey: this.deps.getEnvKey(),
+ userId,
+ pluginId: surface.pluginId,
+ pluginTitle: surface.pluginTitle,
+ capabilities: ids,
+ })
+
+ // One audit line per row, so the Settings activity view shows the user's
+ // decision per capability rather than one opaque "prompt" entry.
+ for (const capability of ids) {
+ const allowed = outcome.granted[capability] === true
+ await this.writeAudit(surface, capability, allowed ? 'granted' : 'denied', {
+ consent: outcome.source[capability],
+ })
+ }
+
+ const granted: Record<string, boolean> = {}
+ for (const capability of ids) granted[capability] = outcome.granted[capability] === true
+ return sdkOk({ granted, all: ids.every(capability => granted[capability]) })
+ }
+
+ /** One capability call. */
+ async request(senderId: number, payload: unknown): Promise<PluginSdkResponse> {
+ const surface = this.resolveCaller(senderId)
+ if (!surface) return sdkError('internal', 'this surface is not registered', false)
+
+ const request = (payload ?? {}) as { v?: unknown; capability?: unknown; params?: unknown }
+ if (request.v !== undefined && request.v !== PLUGIN_SDK_PROTOCOL) {
+ return sdkError(
+ 'unsupported_version',
+ `unsupported protocol version: ${String(request.v)}`,
+ false
+ )
+ }
+
+ const capability = typeof request.capability === 'string' ? request.capability : ''
+ const descriptor = getCapability(capability)
+ if (!descriptor) {
+ await this.writeAudit(surface, capability || 'unknown', 'error', {
+ code: 'unsupported_capability',
+ })
+ return sdkError('unsupported_capability', `unknown capability: ${capability}`, false)
+ }
+
+ const userId = this.deps.getUserId()
+ if (!userId) {
+ await this.writeAudit(surface, capability, 'error', { code: 'unauthenticated' })
+ return sdkError('unauthenticated', 'no active session', true)
+ }
+
+ let params: Record<string, unknown>
+ try {
+ params = descriptor.validate(request.params)
+ } catch (err) {
+ await this.writeAudit(surface, capability, 'error', { code: 'invalid_request' })
+ return sdkError('invalid_request', (err as Error).message, false)
+ }
+
+ const budget = this.deps.limiter.take(surface.pluginId, capability, descriptor.limits)
+ if (!budget.allowed) {
+ await this.writeAudit(surface, capability, 'rate_limited')
+ return sdkError('rate_limited', `too many requests; retry in ${budget.retryAfterMs}ms`, true)
+ }
+
+ const grantKey = {
+ envKey: this.deps.getEnvKey(),
+ userId,
+ pluginId: surface.pluginId,
+ capability,
+ }
+ const outcome = await this.deps.gate.ensure({
+ ...grantKey,
+ pluginTitle: surface.pluginTitle,
+ capabilities: [capability],
+ })
+ if (outcome.granted[capability] !== true) {
+ await this.writeAudit(surface, capability, 'denied', { consent: outcome.source[capability] })
+ return sdkError('permission_denied', 'the user has not granted this permission', true)
+ }
+
+ const cacheKey = `${surface.pluginId}::${capability}::${JSON.stringify(params)}`
+ if (descriptor.cacheTtlMs > 0) {
+ const hit = this.cache.get(cacheKey)
+ if (hit && hit.expiresAt > this.now()) {
+ await this.finishAllowed(
+ surface,
+ capability,
+ grantKey,
+ hit.value,
+ outcome.source[capability]
+ )
+ return sdkOk(hit.value)
+ }
+ }
+
+ let value: unknown
+ try {
+ value = await descriptor.run(
+ {
+ source: this.deps.source,
+ pluginId: surface.pluginId,
+ pluginTitle: surface.pluginTitle,
+ userId,
+ },
+ params
+ )
+ } catch (err) {
+ return this.mapProviderError(surface, capability, err)
+ }
+
+ // Revocation can land while a provider call is in flight. Fail closed: the
+ // user said no between the check and the answer, so the answer is not theirs
+ // to receive.
+ if (!(await this.deps.gate.isGranted(grantKey))) {
+ await this.writeAudit(surface, capability, 'revoked_mid_flight')
+ return sdkError('permission_revoked', 'this permission was revoked', true)
+ }
+
+ const serialized = JSON.stringify(value ?? null)
+ if (Buffer.byteLength(serialized, 'utf8') > descriptor.limits.maxResponseBytes) {
+ await this.writeAudit(surface, capability, 'error', { code: 'payload_too_large' })
+ return sdkError('payload_too_large', 'the result is too large to return', false)
+ }
+
+ if (descriptor.cacheTtlMs > 0) {
+ this.cache.set(cacheKey, { value, expiresAt: this.now() + descriptor.cacheTtlMs })
+ }
+ await this.finishAllowed(surface, capability, grantKey, value, outcome.source[capability])
+ return sdkOk(value)
+ }
+
+ private async finishAllowed(
+ surface: PinnedPluginSurface,
+ capability: string,
+ grantKey: { envKey: string; userId: string; pluginId: string; capability: string },
+ value: unknown,
+ consent: AuditEntry['consent']
+ ): Promise<void> {
+ const descriptor = getCapability(capability)
+ if (descriptor?.requiresConsent) {
+ await this.deps.store.touch(grantKey).catch(() => undefined)
+ }
+ await this.writeAudit(surface, capability, 'allowed', {
+ consent,
+ shape: shapeOf(value),
+ })
+ }
+
+ private async mapProviderError(
+ surface: PinnedPluginSurface,
+ capability: string,
+ err: unknown
+ ): Promise<PluginSdkResponse> {
+ if (err instanceof CapabilityInputError) {
+ await this.writeAudit(surface, capability, 'error', { code: 'invalid_request' })
+ return sdkError('invalid_request', err.message, false)
+ }
+ if (err instanceof CapabilityTooLargeError) {
+ await this.writeAudit(surface, capability, 'error', { code: 'payload_too_large' })
+ return sdkError('payload_too_large', err.message, false)
+ }
+ if (err instanceof CapabilityNotFoundError) {
+ await this.writeAudit(surface, capability, 'error', { code: 'not_found' })
+ return sdkError('not_found', 'not found', false)
+ }
+ // Upstream failures are logged locally and reported generically. An
+ // upstream body forwarded verbatim is a data-leak path (spec §12, T8), and
+ // `not_found` deliberately conflates "absent" with "not yours" so the SDK
+ // is never an existence oracle.
+ console.warn(`[PluginSDK] ${capability} failed for ${surface.pluginId}:`, err)
+ const message = err instanceof Error ? err.message : String(err)
+ if (/\b404\b|not found/i.test(message)) {
+ await this.writeAudit(surface, capability, 'error', { code: 'not_found' })
+ return sdkError('not_found', 'not found', false)
+ }
+ await this.writeAudit(surface, capability, 'error', { code: 'unavailable' })
+ return sdkError('unavailable', 'the desktop app could not complete this request', true)
+ }
+
+ /** Drop cached provider results (logout, team switch, revocation). */
+ invalidateCache(pluginId?: string): void {
+ if (!pluginId) {
+ this.cache.clear()
+ return
+ }
+ for (const key of [...this.cache.keys()]) {
+ if (key.startsWith(`${pluginId}::`)) this.cache.delete(key)
+ }
+ }
+}
+
+function normalizeCapabilityList(raw: unknown, options: { allowEmpty: boolean }): string[] {
+ if (raw === undefined || raw === null) {
+ if (options.allowEmpty) return []
+ throw new Error('capabilities is required')
+ }
+ if (!Array.isArray(raw)) throw new Error('capabilities must be an array')
+ if (raw.length === 0) {
+ if (options.allowEmpty) return []
+ throw new Error('capabilities must not be empty')
+ }
+ if (raw.length > PLUGIN_SDK_MAX_BATCH) {
+ throw new Error(`at most ${PLUGIN_SDK_MAX_BATCH} capabilities per request`)
+ }
+ const seen = new Set<string>()
+ for (const entry of raw) {
+ if (typeof entry !== 'string') throw new Error('capabilities must be strings')
+ if (seen.has(entry)) throw new Error(`duplicate capability: ${entry}`)
+ if (!getCapability(entry)) throw new Error(`unknown capability: ${entry}`)
+ seen.add(entry)
+ }
+ return [...seen]
+}
diff --git a/desktop-app/src/pluginSdkCapabilities.ts b/desktop-app/src/pluginSdkCapabilities.ts
new file mode 100644
index 000000000..22cd1dc13
--- /dev/null
+++ b/desktop-app/src/pluginSdkCapabilities.ts
@@ -0,0 +1,474 @@
+/**
+ * The capability catalog (spec §6).
+ *
+ * One immutable descriptor per capability. `minimize` is MANDATORY, not an
+ * optional passthrough: adding a capability must force an explicit decision
+ * about what the plugin sees. A `minimize` that returns its input unchanged is
+ * a review finding, not a shortcut.
+ *
+ * Every provider reaches upstream through the user's OWN session (the narrow
+ * `PluginSdkDataSource` view of AppService), so control-api authorizes exactly
+ * as it does for the Desktop's own pages. Consent is an additional gate on top
+ * of the user's ACL, never a substitute for it.
+ */
+import type {
+ GfsAccessibleResourcesPage,
+ GfsChildrenPage,
+ ResolvedGfsResource,
+} from './gfs/uriHandler.js'
+import type { PluginCapabilityTier, PluginTheme } from './pluginSdkProtocol.js'
+import type {
+ AccessCatalog,
+ AgentWithMcpServers,
+ RpcAllowedServersResult,
+ SessionState,
+} from './types.js'
+
+/** Image bytes ceiling, matching the Desktop's own GFS preview limit. */
+export const PLUGIN_GFS_IMAGE_MAX_BYTES = 10 * 1024 * 1024
+export const PLUGIN_GFS_TEXT_MAX_BYTES = 2 * 1024 * 1024
+
+/**
+ * Renderable image types. `image/svg+xml` is deliberately ABSENT: an SVG in an
+ * `<img>` cannot execute script, but it can pull external resources and is a
+ * standing parser-bug surface. A plugin that wants vector art ships it in its
+ * own bundle.
+ */
+export const PLUGIN_GFS_IMAGE_MIME_TYPES = [
+ 'image/png',
+ 'image/jpeg',
+ 'image/gif',
+ 'image/webp',
+ 'image/avif',
+] as const
+
+/** Magic-byte prefixes, so a `.png` whose bytes are not a PNG is refused. */
+const IMAGE_MAGIC: Array<{ mime: string; test: (b: Buffer) => boolean }> = [
+ {
+ mime: 'image/png',
+ test: b =>
+ b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])),
+ },
+ { mime: 'image/jpeg', test: b => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff },
+ { mime: 'image/gif', test: b => b.subarray(0, 6).toString('ascii').startsWith('GIF8') },
+ {
+ mime: 'image/webp',
+ test: b =>
+ b.subarray(0, 4).toString('ascii') === 'RIFF' &&
+ b.subarray(8, 12).toString('ascii') === 'WEBP',
+ },
+ {
+ mime: 'image/avif',
+ test: b =>
+ b.subarray(4, 8).toString('ascii') === 'ftyp' &&
+ b.subarray(8, 12).toString('ascii').startsWith('avi'),
+ },
+]
+
+export function detectImageMime(bytes: Buffer): string | null {
+ for (const entry of IMAGE_MAGIC) {
+ try {
+ if (entry.test(bytes)) return entry.mime
+ } catch {
+ // A file shorter than a magic prefix simply is not that format.
+ }
+ }
+ return null
+}
+
+/** The narrow slice of AppService a provider may touch. Keeps tests Electron-free. */
+export interface PluginSdkDataSource {
+ getSessionState(): Promise<SessionState>
+ listMyAgents(): Promise<AgentWithMcpServers[]>
+ getAccessCatalog(): Promise<AccessCatalog>
+ listAccessibleMcpServers(): Promise<RpcAllowedServersResult>
+ listAccessibleGfsResources(drive?: string, cursor?: string): Promise<GfsAccessibleResourcesPage>
+ listGfsChildren(resourceId: string, drive?: string, cursor?: string): Promise<GfsChildrenPage>
+ downloadGfsUri(uri: string): Promise<{ resource: ResolvedGfsResource; bytes: ArrayBuffer }>
+ getPluginTheme(): PluginTheme
+ showPluginNotification(input: {
+ pluginId: string
+ pluginTitle: string
+ title: string
+ body?: string
+ ref?: string
+ }): Promise<{ delivered: boolean; reason?: 'suppressed' | 'unsupported' }>
+}
+
+export type ProviderContext = {
+ source: PluginSdkDataSource
+ pluginId: string
+ pluginTitle: string
+ userId: string
+}
+
+export type CapabilityDescriptor = {
+ id: string
+ /** Bump when the payload widens; older grants stop covering it (spec §9.6). */
+ descriptorVersion: number
+ requiresConsent: boolean
+ consent: {
+ title: string
+ dataDescription: string
+ tier: PluginCapabilityTier
+ }
+ limits: { perMinute: number; perHour: number; maxResponseBytes: number }
+ /** Milliseconds a result may be reused. 0 disables caching. */
+ cacheTtlMs: number
+ validate: (raw: unknown) => Record<string, unknown>
+ run: (ctx: ProviderContext, params: Record<string, unknown>) => Promise<unknown>
+}
+
+export class CapabilityInputError extends Error {}
+export class CapabilityNotFoundError extends Error {}
+export class CapabilityTooLargeError extends Error {}
+
+function noParams(raw: unknown): Record<string, unknown> {
+ if (raw === undefined || raw === null) return {}
+ if (typeof raw !== 'object' || Array.isArray(raw)) {
+ throw new CapabilityInputError('this capability takes no parameters')
+ }
+ const keys = Object.keys(raw as Record<string, unknown>)
+ if (keys.length > 0) {
+ throw new CapabilityInputError(`unexpected parameter: ${keys[0]}`)
+ }
+ return {}
+}
+
+function optionalString(value: unknown, field: string, maxLength: number): string | undefined {
+ if (value === undefined || value === null || value === '') return undefined
+ if (typeof value !== 'string') throw new CapabilityInputError(`${field} must be a string`)
+ if (value.length > maxLength) throw new CapabilityInputError(`${field} is too long`)
+ return value
+}
+
+function requiredString(value: unknown, field: string, maxLength: number): string {
+ const parsed = optionalString(value, field, maxLength)
+ if (!parsed) throw new CapabilityInputError(`${field} is required`)
+ return parsed
+}
+
+function allowKeys(raw: unknown, allowed: string[]): Record<string, unknown> {
+ if (raw === undefined || raw === null) return {}
+ if (typeof raw !== 'object' || Array.isArray(raw)) {
+ throw new CapabilityInputError('params must be an object')
+ }
+ const record = raw as Record<string, unknown>
+ for (const key of Object.keys(record)) {
+ if (!allowed.includes(key)) throw new CapabilityInputError(`unexpected parameter: ${key}`)
+ }
+ return record
+}
+
+/** Strip control characters from user-visible plugin-supplied text. */
+function plainText(value: string): string {
+ return value.replace(/[\u0000-\u001f\u007f]/g, ' ').trim()
+}
+
+export const CAPABILITIES: Record<string, CapabilityDescriptor> = {
+ 'identity.read': {
+ id: 'identity.read',
+ descriptorVersion: 1,
+ requiresConsent: true,
+ consent: {
+ title: 'See who you are',
+ dataDescription: 'Your name, email address, and user id.',
+ tier: 'personal',
+ },
+ limits: { perMinute: 10, perHour: 60, maxResponseBytes: 4 * 1024 },
+ cacheTtlMs: 60_000,
+ validate: noParams,
+ run: async ctx => {
+ const state = await ctx.source.getSessionState()
+ if (!state.authenticated || !state.me) throw new CapabilityNotFoundError('no session')
+ // `picture` is omitted on purpose: it is a remote URL and the embed CSP is
+ // `img-src 'self' data:`, so the plugin could not render it — shipping it
+ // would leak an identifier for zero benefit (spec §6.1).
+ return { userId: state.me.id, email: state.me.email, name: state.me.name }
+ },
+ },
+
+ 'org.read': {
+ id: 'org.read',
+ descriptorVersion: 1,
+ requiresConsent: true,
+ consent: {
+ title: 'See your current team',
+ dataDescription: 'Its name and your role in it.',
+ tier: 'workspace',
+ },
+ limits: { perMinute: 10, perHour: 60, maxResponseBytes: 4 * 1024 },
+ cacheTtlMs: 60_000,
+ validate: noParams,
+ run: async ctx => {
+ const state = await ctx.source.getSessionState()
+ if (!state.authenticated || !state.me) throw new CapabilityNotFoundError('no session')
+ return {
+ teamId: state.me.teamId,
+ teamName: state.me.teamName,
+ role: state.me.role,
+ }
+ },
+ },
+
+ 'agents.read': {
+ id: 'agents.read',
+ descriptorVersion: 1,
+ requiresConsent: true,
+ consent: {
+ title: 'See the agents you have access to',
+ dataDescription: 'Their names and which MCP servers they use.',
+ tier: 'workspace',
+ },
+ limits: { perMinute: 10, perHour: 120, maxResponseBytes: 256 * 1024 },
+ cacheTtlMs: 30_000,
+ validate: noParams,
+ run: async ctx => {
+ const agents = await ctx.source.listMyAgents()
+ return {
+ agents: agents.map(agent => ({
+ // `gfsSubject.id` is the stable grant-target id (`1st:<ns>/<name>`);
+ // older servers omit it, so `name` is the fallback identity.
+ id: agent.gfsSubject?.id ?? agent.name,
+ name: agent.name,
+ contextRef: agent.contextRef ?? null,
+ provider: agent.provider ?? null,
+ mcpServers: (agent.mcpServers ?? []).map(server => server.name),
+ })),
+ }
+ },
+ },
+
+ 'contexts.read': {
+ id: 'contexts.read',
+ descriptorVersion: 1,
+ requiresConsent: true,
+ consent: {
+ title: 'See the contexts you have access to',
+ dataDescription: 'The names of the contexts available to you.',
+ tier: 'workspace',
+ },
+ limits: { perMinute: 10, perHour: 120, maxResponseBytes: 64 * 1024 },
+ cacheTtlMs: 30_000,
+ validate: noParams,
+ run: async ctx => {
+ const catalog = await ctx.source.getAccessCatalog()
+ const userIds = new Set(catalog.userContextIds ?? [])
+ const seen = new Set<string>()
+ const contexts: Array<{ id: string; scope: 'user' | 'team' }> = []
+ for (const id of [...(catalog.userContextIds ?? []), ...(catalog.teamContextIds ?? [])]) {
+ if (seen.has(id)) continue
+ seen.add(id)
+ contexts.push({ id, scope: userIds.has(id) ? 'user' : 'team' })
+ }
+ return { contexts }
+ },
+ },
+
+ 'mcp.read': {
+ id: 'mcp.read',
+ descriptorVersion: 1,
+ requiresConsent: true,
+ consent: {
+ title: 'See the MCP servers you have access to',
+ dataDescription: 'Their names and which of your agents can call them.',
+ tier: 'workspace',
+ },
+ limits: { perMinute: 10, perHour: 120, maxResponseBytes: 128 * 1024 },
+ cacheTtlMs: 30_000,
+ validate: noParams,
+ run: async ctx => {
+ const [result, catalog] = await Promise.all([
+ ctx.source.listAccessibleMcpServers(),
+ ctx.source.getAccessCatalog().catch(() => null),
+ ])
+ const byServer = new Map<string, string[]>()
+ for (const [agent, servers] of Object.entries(catalog?.mcpServersByAgent ?? {})) {
+ for (const server of servers ?? []) {
+ byServer.set(server, [...(byServer.get(server) ?? []), agent])
+ }
+ }
+ // Every `url` is dropped. A cluster-internal URL is infrastructure detail
+ // the embed cannot even reach under `connect-src 'self'`, and shipping it
+ // would turn a read capability into a lateral-movement hint (spec §6.5).
+ return {
+ servers: (result.servers ?? []).map(server => ({
+ name: server.name,
+ agents: byServer.get(server.name) ?? [],
+ })),
+ }
+ },
+ },
+
+ 'gfs.list': {
+ id: 'gfs.list',
+ descriptorVersion: 1,
+ requiresConsent: true,
+ consent: {
+ title: 'See the shared files you have access to',
+ dataDescription: 'Their names, folders, and sizes. It will not be able to open them.',
+ tier: 'workspace',
+ },
+ limits: { perMinute: 30, perHour: 600, maxResponseBytes: 512 * 1024 },
+ cacheTtlMs: 0,
+ validate: raw => {
+ const record = allowKeys(raw, ['drive', 'resourceId', 'cursor'])
+ return {
+ drive: optionalString(record.drive, 'drive', 64),
+ resourceId: optionalString(record.resourceId, 'resourceId', 128),
+ cursor: optionalString(record.cursor, 'cursor', 512),
+ }
+ },
+ run: async (ctx, params) => {
+ const drive = params.drive as string | undefined
+ const resourceId = params.resourceId as string | undefined
+ const cursor = params.cursor as string | undefined
+ const page = resourceId
+ ? await ctx.source.listGfsChildren(resourceId, drive, cursor)
+ : await ctx.source.listAccessibleGfsResources(drive, cursor)
+ return {
+ items: (page.items ?? []).map(item => ({
+ resourceId: item.resourceId,
+ gfsUri: item.gfsUri,
+ name: item.name,
+ kind: item.kind,
+ bytes: typeof item.bytes === 'number' ? item.bytes : null,
+ version: item.version,
+ })),
+ nextCursor: page.nextCursor ?? null,
+ }
+ },
+ },
+
+ 'gfs.read': {
+ id: 'gfs.read',
+ descriptorVersion: 1,
+ requiresConsent: true,
+ consent: {
+ title: 'Open shared files you have access to',
+ dataDescription: 'It will be able to read the contents of any file you can read.',
+ tier: 'personal',
+ },
+ limits: { perMinute: 20, perHour: 300, maxResponseBytes: PLUGIN_GFS_IMAGE_MAX_BYTES * 2 },
+ cacheTtlMs: 0,
+ validate: raw => {
+ const record = allowKeys(raw, ['uri', 'as'])
+ const uri = requiredString(record.uri, 'uri', 2048)
+ if (!uri.startsWith('gfs://')) throw new CapabilityInputError('uri must be a gfs:// link')
+ const as = requiredString(record.as, 'as', 16)
+ if (as !== 'text' && as !== 'dataUrl') {
+ throw new CapabilityInputError("as must be 'text' or 'dataUrl'")
+ }
+ return { uri, as }
+ },
+ run: async (ctx, params) => {
+ const uri = params.uri as string
+ const as = params.as as 'text' | 'dataUrl'
+ const { resource, bytes } = await ctx.source.downloadGfsUri(uri)
+ const buffer = Buffer.from(bytes)
+ const base = {
+ gfsUri: resource.gfsUri,
+ name: resource.name,
+ bytes: buffer.byteLength,
+ }
+
+ if (as === 'dataUrl') {
+ if (buffer.byteLength > PLUGIN_GFS_IMAGE_MAX_BYTES) {
+ throw new CapabilityTooLargeError('image is larger than 10 MB')
+ }
+ // Trust the bytes, not the name. The declared MIME must be renderable
+ // AND the magic bytes must agree (spec §6.6, T12).
+ const detected = detectImageMime(buffer)
+ if (!detected || !PLUGIN_GFS_IMAGE_MIME_TYPES.includes(detected as never)) {
+ throw new CapabilityInputError(
+ 'file is not a renderable image (png, jpeg, gif, webp, avif)'
+ )
+ }
+ return {
+ ...base,
+ as,
+ mimeType: detected,
+ dataUrl: `data:${detected};base64,${buffer.toString('base64')}`,
+ }
+ }
+
+ if (buffer.byteLength > PLUGIN_GFS_TEXT_MAX_BYTES) {
+ throw new CapabilityTooLargeError('file is larger than 2 MB')
+ }
+ const text = buffer.toString('utf8')
+ // A lossy decode means the bytes were not UTF-8; returning replacement
+ // characters would silently corrupt whatever the plugin does next.
+ if (text.includes('\uFFFD')) {
+ throw new CapabilityInputError('file is not valid UTF-8 text')
+ }
+ return { ...base, as, mimeType: 'text/plain', text }
+ },
+ },
+
+ 'theme.read': {
+ id: 'theme.read',
+ descriptorVersion: 1,
+ // The ONE unscoped capability. Permitted only because the response says
+ // nothing about the user, their org, or their data — only about the
+ // Desktop's own presentation (spec §6.7). It is still audited, and still
+ // listed on the plugin's Settings row.
+ requiresConsent: false,
+ consent: {
+ title: 'See the app appearance',
+ dataDescription: 'Whether the desktop app is in light or dark mode.',
+ tier: 'ambient',
+ },
+ limits: { perMinute: 60, perHour: 600, maxResponseBytes: 1024 },
+ cacheTtlMs: 0,
+ validate: noParams,
+ run: async ctx => ({ theme: ctx.source.getPluginTheme() }),
+ },
+
+ 'notifications.notify': {
+ id: 'notifications.notify',
+ descriptorVersion: 1,
+ requiresConsent: true,
+ consent: {
+ title: 'Send you notifications',
+ dataDescription: 'It will be able to get your attention while you work elsewhere.',
+ tier: 'workspace',
+ },
+ limits: { perMinute: 2, perHour: 20, maxResponseBytes: 1024 },
+ cacheTtlMs: 0,
+ validate: raw => {
+ const record = allowKeys(raw, ['title', 'body', 'ref'])
+ const title = plainText(requiredString(record.title, 'title', 120))
+ if (!title) throw new CapabilityInputError('title is required')
+ const body = optionalString(record.body, 'body', 400)
+ const ref = optionalString(record.ref, 'ref', 256)
+ return { title, body: body ? plainText(body) : undefined, ref }
+ },
+ run: async (ctx, params) =>
+ ctx.source.showPluginNotification({
+ pluginId: ctx.pluginId,
+ pluginTitle: ctx.pluginTitle,
+ title: params.title as string,
+ body: params.body as string | undefined,
+ ref: params.ref as string | undefined,
+ }),
+ },
+}
+
+export const CAPABILITY_IDS = Object.keys(CAPABILITIES)
+
+export function getCapability(id: string): CapabilityDescriptor | null {
+ return Object.prototype.hasOwnProperty.call(CAPABILITIES, id) ? (CAPABILITIES[id] ?? null) : null
+}
+
+/** Prompt row ordering: most sensitive first, never buried at the bottom. */
+const TIER_ORDER: Record<PluginCapabilityTier, number> = { personal: 0, workspace: 1, ambient: 2 }
+
+export function sortCapabilitiesForPrompt(ids: string[]): string[] {
+ return [...ids].sort((a, b) => {
+ const left = getCapability(a)
+ const right = getCapability(b)
+ const delta =
+ TIER_ORDER[left?.consent.tier ?? 'workspace'] - TIER_ORDER[right?.consent.tier ?? 'workspace']
+ return delta !== 0 ? delta : a.localeCompare(b)
+ })
+}
diff --git a/desktop-app/src/pluginSdkProtocol.ts b/desktop-app/src/pluginSdkProtocol.ts
new file mode 100644
index 000000000..6a4fe1619
--- /dev/null
+++ b/desktop-app/src/pluginSdkProtocol.ts
@@ -0,0 +1,166 @@
+/**
+ * Plugin UI SDK wire contract (spec `docs/features/plugin-ui-sdk-1.md` §5).
+ *
+ * Shared by three worlds that never share a module graph at runtime: the
+ * embed preload (isolated world, no Node), the main process, and the trusted
+ * renderer. Keep this file free of Electron and Node imports so all three can
+ * type against it.
+ *
+ * One invoke channel carries every capability call and one carries batched
+ * consent, so the broker (`pluginSdkBroker.ts`) is the single place a request
+ * can be gated and audited. Adding a capability must never mean adding a
+ * channel.
+ */
+
+export const PLUGIN_SDK_VERSION = '1.0.0'
+export const PLUGIN_SDK_PROTOCOL = 1
+
+/** Embed → main: one capability call. */
+export const PLUGIN_SDK_REQUEST_CHANNEL = 'clerum:plugin-sdk:request'
+/** Embed → main: batched consent for 1..8 capabilities in one modal. */
+export const PLUGIN_SDK_PERMISSIONS_CHANNEL = 'clerum:plugin-sdk:request-permissions'
+/** Embed → main: read grant state without prompting. */
+export const PLUGIN_SDK_PERMISSION_STATE_CHANNEL = 'clerum:plugin-sdk:permissions'
+/** Embed → main: which capability ids this host build implements. */
+export const PLUGIN_SDK_CAPABILITIES_CHANNEL = 'clerum:plugin-sdk:capabilities'
+/** Main → embed: events (theme, permission changes, session, notification clicks). */
+export const PLUGIN_SDK_EVENT_CHANNEL = 'clerum:plugin-sdk:event'
+
+/** Main → trusted renderer: open the consent modal. */
+export const PLUGIN_SDK_CONSENT_REQUESTED_CHANNEL = 'pluginSdk:consentRequested'
+/** Main → trusted renderer: withdraw a pending prompt (embed died, timeout). */
+export const PLUGIN_SDK_CONSENT_CANCELLED_CHANNEL = 'pluginSdk:consentCancelled'
+/** Trusted renderer → main: the user's decision. */
+export const PLUGIN_SDK_CONSENT_RESOLVE_CHANNEL = 'pluginSdk:resolveConsent'
+
+/** Hard ceiling on rows in one prompt (spec §9.5). */
+export const PLUGIN_SDK_MAX_BATCH = 8
+
+export type PluginSdkErrorCode =
+ | 'unsupported_capability'
+ | 'unsupported_version'
+ | 'invalid_request'
+ | 'unauthenticated'
+ | 'permission_denied'
+ | 'permission_revoked'
+ | 'rate_limited'
+ | 'not_found'
+ | 'payload_too_large'
+ | 'unavailable'
+ | 'internal'
+
+export type PluginSdkError = {
+ code: PluginSdkErrorCode
+ /** Safe for the plugin to display. Never carries upstream internals. */
+ message: string
+ /** True when an identical later call may succeed without user action. */
+ retryable: boolean
+}
+
+export type PluginSdkResponse<T = unknown> =
+ | { ok: true; data: T }
+ | { ok: false; error: PluginSdkError }
+
+export type PluginSdkRequest = {
+ v: number
+ capability: string
+ params?: Record<string, unknown>
+}
+
+export type PluginSdkPermissionsRequest = {
+ v: number
+ capabilities: string[]
+}
+
+export type PluginSdkPermissionsResult = {
+ /** Every requested id is present. */
+ granted: Record<string, boolean>
+ /** True when the user allowed every requested capability. */
+ all: boolean
+}
+
+export type PluginSdkPermissionStateResult = {
+ granted: Record<string, boolean>
+}
+
+export type PluginSdkCapabilitiesResult = {
+ capabilities: string[]
+ version: string
+}
+
+export type PluginTheme = 'light' | 'dark'
+
+export type PluginSdkEvent =
+ | { type: 'theme.changed'; theme: PluginTheme }
+ | { type: 'permission.changed'; capability: string; granted: boolean }
+ | { type: 'session.changed'; authenticated: boolean }
+ | { type: 'notification.clicked'; ref: string | null }
+
+/** Sensitivity tier — drives prompt ordering and audit verbosity (spec §6). */
+export type PluginCapabilityTier = 'personal' | 'workspace' | 'ambient'
+
+/** One row of a consent prompt, as the trusted renderer receives it. */
+export type PluginConsentRow = {
+ capability: string
+ title: string
+ dataDescription: string
+ tier: PluginCapabilityTier
+}
+
+export type PluginConsentRequest = {
+ promptId: string
+ pluginId: string
+ pluginTitle: string
+ rows: PluginConsentRow[]
+ /** How many prompts this plugin has already shown this mount (spec §9.5). */
+ priorPromptCount: number
+}
+
+export type PluginConsentResolution = {
+ promptId: string
+ /** Capability ids the user left checked. Everything else counts as denied. */
+ allowed: string[]
+}
+
+/**
+ * Views the TRUSTED renderer consumes (Settings → Plugin permissions).
+ *
+ * They live here rather than beside their producers because `renderer.d.ts` —
+ * and therefore the UI's tsconfig — types against this module, and this module
+ * is the only one in the SDK with no Node or Electron imports. Pointing the UI
+ * at `pluginSdkRuntime.ts` would drag Electron's types into the Vite project.
+ */
+export type PluginGrantView = {
+ pluginId: string
+ pluginTitle: string
+ capability: string
+ title: string
+ dataDescription: string
+ tier: string
+ grantedAt: string
+ lastUsedAt: string | null
+}
+
+export type PluginAuditEntryView = {
+ ts: string
+ userId: string
+ pluginId: string
+ capability: string
+ outcome: string
+ consent?: string
+ surface?: string
+ shape?: { fields?: string[]; count?: number; bytes?: number }
+ code?: string
+}
+
+export function sdkError(
+ code: PluginSdkErrorCode,
+ message: string,
+ retryable = false
+): { ok: false; error: PluginSdkError } {
+ return { ok: false, error: { code, message, retryable } }
+}
+
+export function sdkOk<T>(data: T): { ok: true; data: T } {
+ return { ok: true, data }
+}
diff --git a/desktop-app/src/pluginSdkRuntime.ts b/desktop-app/src/pluginSdkRuntime.ts
new file mode 100644
index 000000000..915dd75e5
--- /dev/null
+++ b/desktop-app/src/pluginSdkRuntime.ts
@@ -0,0 +1,369 @@
+/**
+ * Electron wiring for the plugin SDK (spec §4).
+ *
+ * Everything Electron-shaped lives here so the broker, gate, store, and
+ * capability catalog stay testable without an Electron runtime. This module is
+ * the only one in the SDK that knows about BrowserWindow, Notification, or the
+ * sandbox-ui driver.
+ */
+import { BrowserWindow, Notification, app } from 'electron'
+import path from 'node:path'
+import type { AppService } from './appService.js'
+import { getActiveEnvKey } from './config.js'
+import { type AuditEntry, PluginAuditLog } from './pluginAuditLog.js'
+import { PluginConsentGate } from './pluginConsentGate.js'
+import { type ConsentGrant, LocalConsentStore } from './pluginConsentStore.js'
+import { PluginRateLimiter } from './pluginRateLimiter.js'
+import { PluginSdkBroker } from './pluginSdkBroker.js'
+import { CAPABILITIES, type PluginSdkDataSource, getCapability } from './pluginSdkCapabilities.js'
+import {
+ PLUGIN_SDK_CONSENT_CANCELLED_CHANNEL,
+ PLUGIN_SDK_CONSENT_REQUESTED_CHANNEL,
+ PLUGIN_SDK_EVENT_CHANNEL,
+ type PluginGrantView,
+ type PluginSdkEvent,
+ type PluginTheme,
+} from './pluginSdkProtocol.js'
+import {
+ type PinnedPluginSurface,
+ allPinnedSurfaces,
+ pinPluginSurface,
+ resolvePluginSurface,
+ surfacesForPlugin,
+ unpinPluginSurface,
+ unpinPluginSurfacesOfKind,
+} from './pluginSurfaceRegistry.js'
+import { PluginThemeStore } from './pluginThemeStore.js'
+
+type RuntimeDeps = {
+ service: AppService
+ getMainWindow: () => BrowserWindow | null
+ /** Overridable for tests. */
+ userDataDir?: string
+}
+
+let runtime: PluginSdkRuntime | null = null
+
+export class PluginSdkRuntime {
+ readonly store: LocalConsentStore
+ readonly audit: PluginAuditLog
+ readonly limiter: PluginRateLimiter
+ readonly gate: PluginConsentGate
+ readonly broker: PluginSdkBroker
+ readonly theme: PluginThemeStore
+
+ /** pluginId → human title, learned at mount, used for prompts + notifications. */
+ private readonly titles = new Map<string, string>()
+
+ constructor(private readonly deps: RuntimeDeps) {
+ const baseDir = deps.userDataDir ?? app.getPath('userData')
+ this.store = new LocalConsentStore(path.join(baseDir, 'plugin-consent'))
+ this.audit = new PluginAuditLog(path.join(baseDir, 'plugin-audit'))
+ this.limiter = new PluginRateLimiter()
+ this.theme = new PluginThemeStore(baseDir)
+
+ this.gate = new PluginConsentGate({
+ store: this.store,
+ presentPrompt: request => this.sendToRenderer(PLUGIN_SDK_CONSENT_REQUESTED_CHANNEL, request),
+ cancelPrompt: promptId =>
+ this.sendToRenderer(PLUGIN_SDK_CONSENT_CANCELLED_CHANNEL, { promptId }),
+ setSurfaceVisible: visible => this.deps.service.setSandboxUiVisible(visible),
+ isWindowReady: () => {
+ const win = this.deps.getMainWindow()
+ if (!win || win.isDestroyed()) return false
+ return win.isVisible() && !win.isMinimized() && win.isFocused()
+ },
+ })
+
+ this.broker = new PluginSdkBroker({
+ source: this.dataSource(),
+ store: this.store,
+ gate: this.gate,
+ limiter: this.limiter,
+ audit: this.audit,
+ getEnvKey: () => getActiveEnvKey(),
+ getUserId: () => this.currentUserId(),
+ })
+
+ this.theme.onChange(theme => {
+ this.broadcastEvent({ type: 'theme.changed', theme })
+ })
+ void this.theme.load()
+ }
+
+ private currentUserId(): string | null {
+ const metadata = this.deps.service.getTokenMetadata()
+ if (!metadata.hasSession) return null
+ return this.deps.service.getCachedUserId()
+ }
+
+ private sendToRenderer(channel: string, payload: unknown): void {
+ const win = this.deps.getMainWindow()
+ if (!win || win.isDestroyed()) return
+ win.webContents.send(channel, payload)
+ }
+
+ /** Deliver an event to every mounted surface of one plugin. */
+ private sendEventToPlugin(pluginId: string, event: PluginSdkEvent): void {
+ for (const surface of surfacesForPlugin(pluginId)) {
+ const contents = webContentsById(surface.webContentsId)
+ if (!contents) continue
+ contents.send(PLUGIN_SDK_EVENT_CHANNEL, event)
+ }
+ }
+
+ /** Deliver an event to every mounted plugin surface. */
+ private broadcastEvent(event: PluginSdkEvent): void {
+ for (const surface of allPinnedSurfaces()) {
+ const contents = webContentsById(surface.webContentsId)
+ if (!contents) continue
+ contents.send(PLUGIN_SDK_EVENT_CHANNEL, event)
+ }
+ }
+
+ // ── Surface lifecycle ──────────────────────────────────────────────
+
+ pinSandboxUiSurface(input: {
+ pluginId: string
+ pluginTitle: string
+ webContentsId: number
+ generation: number
+ }): void {
+ // The driver tears the previous embed down inside the next mount, so clear
+ // the kind first — a stale pin would otherwise outlive its webContents.
+ for (const dropped of unpinPluginSurfacesOfKind('sandbox-ui-embed')) {
+ this.releasePlugin(dropped.pluginId)
+ }
+ this.titles.set(input.pluginId, input.pluginTitle)
+ pinPluginSurface({ ...input, surface: 'sandbox-ui-embed' })
+ }
+
+ unpinSandboxUiSurface(webContentsId: number): void {
+ const surface = resolvePluginSurface(webContentsId)
+ unpinPluginSurface(webContentsId)
+ if (surface) this.releasePlugin(surface.pluginId)
+ }
+
+ unpinAllSandboxUiSurfaces(): void {
+ for (const dropped of unpinPluginSurfacesOfKind('sandbox-ui-embed')) {
+ this.releasePlugin(dropped.pluginId)
+ }
+ }
+
+ /** Per-mount state dies with the mount: denials, prompt budget, rate budget, cache. */
+ private releasePlugin(pluginId: string): void {
+ this.gate.resetPlugin(pluginId)
+ this.limiter.reset(pluginId)
+ this.broker.invalidateCache(pluginId)
+ }
+
+ // ── Session / theme signals ────────────────────────────────────────
+
+ notifySessionChanged(authenticated: boolean): void {
+ this.broker.invalidateCache()
+ this.broadcastEvent({ type: 'session.changed', authenticated })
+ }
+
+ setTheme(theme: unknown): void {
+ this.theme.set(theme)
+ }
+
+ // ── Settings surface (trusted renderer) ────────────────────────────
+
+ async listGrants(): Promise<PluginGrantView[]> {
+ const userId = this.currentUserId()
+ if (!userId) return []
+ const grants = await this.store.list(getActiveEnvKey(), userId)
+ return grants.flatMap(grant => {
+ const descriptor = getCapability(grant.capability)
+ if (!descriptor) return []
+ return [
+ {
+ pluginId: grant.pluginId,
+ pluginTitle:
+ this.titles.get(grant.pluginId) ?? grant.pluginId.split('/').pop() ?? grant.pluginId,
+ capability: grant.capability,
+ title: descriptor.consent.title,
+ dataDescription: descriptor.consent.dataDescription,
+ tier: descriptor.consent.tier,
+ grantedAt: grant.grantedAt,
+ lastUsedAt: grant.lastUsedAt,
+ },
+ ]
+ })
+ }
+
+ async revokeGrant(pluginId: string, capability: string): Promise<void> {
+ const userId = this.currentUserId()
+ if (!userId) throw new Error('no active session')
+ const envKey = getActiveEnvKey()
+ await this.store.revoke({ envKey, userId, pluginId, capability })
+ this.broker.invalidateCache(pluginId)
+ await this.audit.append(envKey, {
+ ts: new Date().toISOString(),
+ userId,
+ pluginId,
+ capability,
+ outcome: 'revoked',
+ consent: 'user_revoked',
+ })
+ // Immediate, so a running plugin drops back to its unauthenticated
+ // rendering instead of discovering the revocation on its next call.
+ this.sendEventToPlugin(pluginId, { type: 'permission.changed', capability, granted: false })
+ }
+
+ async revokeAllForPlugin(pluginId: string): Promise<void> {
+ const userId = this.currentUserId()
+ if (!userId) throw new Error('no active session')
+ const envKey = getActiveEnvKey()
+ const existing = (await this.store.list(envKey, userId)).filter(
+ grant => grant.pluginId === pluginId
+ )
+ await this.store.revokeAllForPlugin(envKey, userId, pluginId)
+ this.broker.invalidateCache(pluginId)
+ for (const grant of existing) {
+ await this.audit.append(envKey, {
+ ts: new Date().toISOString(),
+ userId,
+ pluginId,
+ capability: grant.capability,
+ outcome: 'revoked',
+ consent: 'user_revoked',
+ })
+ this.sendEventToPlugin(pluginId, {
+ type: 'permission.changed',
+ capability: grant.capability,
+ granted: false,
+ })
+ }
+ }
+
+ async readAudit(options?: { limit?: number; includeAmbient?: boolean }): Promise<AuditEntry[]> {
+ const userId = this.currentUserId()
+ if (!userId) return []
+ const entries = await this.audit.read(getActiveEnvKey(), {
+ limit: options?.limit ?? 200,
+ userId,
+ })
+ if (options?.includeAmbient) return entries
+ // `theme.read` fires constantly; including it by default would drown the
+ // entries a user actually opened this view to see (spec §10.3).
+ return entries.filter(entry => getCapability(entry.capability)?.consent.tier !== 'ambient')
+ }
+
+ async clearAudit(): Promise<void> {
+ await this.audit.clear(getActiveEnvKey())
+ }
+
+ resolveConsentPrompt(promptId: string, allowed: string[]): boolean {
+ return this.gate.resolvePrompt(promptId, allowed)
+ }
+
+ /** Prune grants for plugins the user can no longer reach (spec §10.5). */
+ async pruneGrantsToPlugins(pluginIds: Set<string>): Promise<void> {
+ const userId = this.currentUserId()
+ if (!userId) return
+ await this.store.pruneToPlugins(getActiveEnvKey(), userId, pluginIds)
+ }
+
+ // ── Data source ────────────────────────────────────────────────────
+
+ private dataSource(): PluginSdkDataSource {
+ const service = this.deps.service
+ return {
+ getSessionState: () => service.getSessionState(),
+ listMyAgents: () => service.listMyAgents(),
+ getAccessCatalog: () => service.getAccessCatalog(),
+ listAccessibleMcpServers: () => service.listAccessibleMcpServers(),
+ listAccessibleGfsResources: (drive, cursor) =>
+ service.listAccessibleGfsResources(drive, cursor),
+ listGfsChildren: (resourceId, drive, cursor) =>
+ service.listGfsChildren(resourceId, drive, cursor),
+ downloadGfsUri: uri => service.downloadGfsUri(uri),
+ getPluginTheme: () => this.theme.get(),
+ showPluginNotification: input => this.showNotification(input),
+ }
+ }
+
+ private async showNotification(input: {
+ pluginId: string
+ pluginTitle: string
+ title: string
+ body?: string
+ ref?: string
+ }): Promise<{ delivered: boolean; reason?: 'suppressed' | 'unsupported' }> {
+ // Suppressed when the user is already looking at this plugin: interrupting
+ // someone about the thing on their screen is noise, not attention.
+ if (this.isPluginInForeground(input.pluginId)) {
+ return { delivered: false, reason: 'suppressed' }
+ }
+ if (!Notification.isSupported()) return { delivered: false, reason: 'unsupported' }
+
+ // Mandatory attribution — a plugin must never be able to look like Evenfire
+ // itself or like another plugin (spec §6.8, T13).
+ const notification = new Notification({
+ title: `${input.pluginTitle} — ${input.title}`,
+ ...(input.body ? { body: input.body } : {}),
+ })
+ notification.on('click', () => {
+ const win = this.deps.getMainWindow()
+ if (win && !win.isDestroyed()) {
+ if (win.isMinimized()) win.restore()
+ win.show()
+ win.focus()
+ }
+ this.sendToRenderer('pluginSdk:notificationClicked', {
+ pluginId: input.pluginId,
+ ref: input.ref ?? null,
+ })
+ this.sendEventToPlugin(input.pluginId, {
+ type: 'notification.clicked',
+ ref: input.ref ?? null,
+ })
+ })
+ notification.show()
+ return { delivered: true }
+ }
+
+ private isPluginInForeground(pluginId: string): boolean {
+ const win = this.deps.getMainWindow()
+ if (!win || win.isDestroyed() || !win.isVisible() || win.isMinimized() || !win.isFocused()) {
+ return false
+ }
+ return surfacesForPlugin(pluginId).some(surface => surface.surface === 'sandbox-ui-embed')
+ }
+}
+
+function webContentsById(id: number): Electron.WebContents | null {
+ for (const win of BrowserWindow.getAllWindows()) {
+ for (const view of win.contentView?.children ?? []) {
+ const contents = (view as unknown as { webContents?: Electron.WebContents }).webContents
+ if (contents && !contents.isDestroyed() && contents.id === id) return contents
+ }
+ if (!win.isDestroyed() && win.webContents.id === id) return win.webContents
+ }
+ return null
+}
+
+export function initPluginSdkRuntime(deps: RuntimeDeps): PluginSdkRuntime {
+ runtime = new PluginSdkRuntime(deps)
+ return runtime
+}
+
+export function getPluginSdkRuntime(): PluginSdkRuntime {
+ if (!runtime) throw new Error('plugin SDK runtime not initialized')
+ return runtime
+}
+
+export function tryGetPluginSdkRuntime(): PluginSdkRuntime | null {
+ return runtime
+}
+
+/** ONLY for tests. */
+export function _resetPluginSdkRuntimeForTests(): void {
+ runtime = null
+}
+
+export type { AuditEntry, ConsentGrant }
+export { CAPABILITIES }
+export type { PinnedPluginSurface, PluginTheme }
diff --git a/desktop-app/src/pluginSurfaceRegistry.ts b/desktop-app/src/pluginSurfaceRegistry.ts
new file mode 100644
index 000000000..1a1ab67b5
--- /dev/null
+++ b/desktop-app/src/pluginSurfaceRegistry.ts
@@ -0,0 +1,89 @@
+/**
+ * Which plugin is on the other end of an SDK request (spec §8.1).
+ *
+ * The plugin never identifies itself. Main derives its identity from the
+ * sender's `webContents.id`, pinned when the surface mounts and unpinned when
+ * it tears down. This generalizes the pinning map already proven for the
+ * session-refresh IPC (`sandboxUiSessionRefresh.ts`) so more than one kind of
+ * plugin surface can use it — today the sandbox-ui embed, tomorrow the Side
+ * Window (spec §14).
+ *
+ * Why identity cannot be self-asserted: the embed loads from the rpc-proxy
+ * origin, so `assertTrustedSender` (which requires file:// or the dev URL)
+ * would reject every SDK call. The pinning map IS the trust check for these
+ * channels. A sender absent from the map is a bug or an attack; either way it
+ * gets nothing.
+ */
+
+export type PluginSurfaceKind = 'sandbox-ui-embed' | 'side-window'
+
+export type PinnedPluginSurface = {
+ /** `<recipeNs>/<recipeName>` — the consent + audit key. */
+ pluginId: string
+ /** Human title from the installed recipe, for prompt copy. Never plugin-supplied. */
+ pluginTitle: string
+ surface: PluginSurfaceKind
+ webContentsId: number
+ /**
+ * Mount generation. The driver bumps its own counter on every mount; a
+ * request tagged with a superseded generation is dropped so a slow call from
+ * the previous embed cannot land against the new one's grants.
+ */
+ generation: number
+}
+
+const byWebContentsId = new Map<number, PinnedPluginSurface>()
+
+export function pinPluginSurface(surface: PinnedPluginSurface): void {
+ byWebContentsId.set(surface.webContentsId, surface)
+}
+
+export function unpinPluginSurface(webContentsId: number): void {
+ byWebContentsId.delete(webContentsId)
+}
+
+/**
+ * Drop every pin of one kind and report what was dropped.
+ *
+ * The sandbox-ui embed is one-at-a-time and its driver tears the previous view
+ * down *inside* the next mount, so the outgoing surface never gets an unpin of
+ * its own. Clearing the kind before pinning the newcomer is what stops a dead
+ * webContents id from lingering in the map (and, after id reuse, from
+ * resolving to the wrong plugin).
+ */
+export function unpinPluginSurfacesOfKind(kind: PluginSurfaceKind): PinnedPluginSurface[] {
+ const dropped: PinnedPluginSurface[] = []
+ for (const [id, surface] of [...byWebContentsId.entries()]) {
+ if (surface.surface !== kind) continue
+ dropped.push(surface)
+ byWebContentsId.delete(id)
+ }
+ return dropped
+}
+
+/**
+ * Resolve a sender to its plugin. Returns null for an unpinned sender — the
+ * caller MUST treat that as a hard rejection, never as "unknown plugin".
+ */
+export function resolvePluginSurface(webContentsId: number): PinnedPluginSurface | null {
+ return byWebContentsId.get(webContentsId) ?? null
+}
+
+/** Every surface currently mounted for a plugin (Side Window + embed). */
+export function surfacesForPlugin(pluginId: string): PinnedPluginSurface[] {
+ return [...byWebContentsId.values()].filter(s => s.pluginId === pluginId)
+}
+
+/** Every pinned surface, for events that go to all plugins (theme, session). */
+export function allPinnedSurfaces(): PinnedPluginSurface[] {
+ return [...byWebContentsId.values()]
+}
+
+export function pinnedSurfaceCount(): number {
+ return byWebContentsId.size
+}
+
+/** ONLY for tests. */
+export function _resetPluginSurfacesForTests(): void {
+ byWebContentsId.clear()
+}
diff --git a/desktop-app/src/pluginThemeStore.ts b/desktop-app/src/pluginThemeStore.ts
new file mode 100644
index 000000000..bc32dee1e
--- /dev/null
+++ b/desktop-app/src/pluginThemeStore.ts
@@ -0,0 +1,81 @@
+/**
+ * Desktop theme, visible to the main process (spec §6.7).
+ *
+ * Theme has always lived in the renderer: `App.tsx` reads and writes
+ * `localStorage['evenfire.ui.theme']` and stamps `data-theme` on the document.
+ * Main had no idea what it was, which `theme.read` and the `theme.changed`
+ * event both need.
+ *
+ * Rather than move ownership wholesale (a migration that would have to reconcile
+ * localStorage with a new on-disk file and get the boot ordering right), the
+ * renderer stays the writer and main keeps a MIRROR: the renderer pushes the
+ * current value on boot and on every change, and main persists the last value
+ * so an embed that asks before the renderer has reported gets the right answer
+ * instead of a default flash.
+ *
+ * This is a deliberate narrowing of spec §6.7. The observable contract for
+ * plugins is identical; if theme ever needs to be authoritative in main (say a
+ * headless surface), this module is where that change lands.
+ */
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+import type { PluginTheme } from './pluginSdkProtocol.js'
+
+const FILE_NAME = 'plugin-sdk-theme.json'
+const DEFAULT_THEME: PluginTheme = 'dark'
+
+export class PluginThemeStore {
+ private theme: PluginTheme = DEFAULT_THEME
+ private loaded = false
+ private listeners = new Set<(theme: PluginTheme) => void>()
+
+ constructor(private readonly baseDir: string) {}
+
+ private get file(): string {
+ return path.join(this.baseDir, FILE_NAME)
+ }
+
+ /** Best-effort hydrate. A missing or unreadable file is simply the default. */
+ async load(): Promise<PluginTheme> {
+ if (this.loaded) return this.theme
+ this.loaded = true
+ try {
+ const raw = await fs.readFile(this.file, 'utf8')
+ const parsed = JSON.parse(raw) as { theme?: unknown }
+ if (parsed?.theme === 'light' || parsed?.theme === 'dark') this.theme = parsed.theme
+ } catch {
+ // Default stands.
+ }
+ return this.theme
+ }
+
+ get(): PluginTheme {
+ return this.theme
+ }
+
+ /** Renderer reported a value. Notifies listeners only on an actual change. */
+ set(next: unknown): void {
+ const theme: PluginTheme = next === 'light' ? 'light' : next === 'dark' ? 'dark' : DEFAULT_THEME
+ if (theme === this.theme && this.loaded) return
+ this.theme = theme
+ this.loaded = true
+ void fs
+ .mkdir(this.baseDir, { recursive: true })
+ .then(() => fs.writeFile(this.file, JSON.stringify({ theme }), 'utf8'))
+ .catch(err => console.warn('[PluginSDK] theme persist failed:', err))
+ for (const listener of this.listeners) {
+ try {
+ listener(theme)
+ } catch (err) {
+ console.warn('[PluginSDK] theme listener failed:', err)
+ }
+ }
+ }
+
+ onChange(listener: (theme: PluginTheme) => void): () => void {
+ this.listeners.add(listener)
+ return () => {
+ this.listeners.delete(listener)
+ }
+ }
+}
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 5a947e7bc..a90f5bf69 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -1,4 +1,5 @@
import { contextBridge, ipcRenderer } from 'electron'
+import type { PluginConsentRequest } from './pluginSdkProtocol.js'
import type {
HostMessageRequest,
ProfileSettingsOpenOptions,
@@ -423,6 +424,7 @@ const clerum = Object.freeze({
open: (args: {
recipeNs: string
recipeName: string
+ title?: string
defaultPath?: string
routePath?: string
bounds: { x: number; y: number; width: number; height: number; dpr?: number }
@@ -455,6 +457,38 @@ const clerum = Object.freeze({
return () => ipcRenderer.off('sandboxUi:refreshError', listener)
},
},
+ /**
+ * Plugin permissions, trusted-renderer half: the consent modal and the
+ * Settings revocation surface. The plugin-facing half lives in a different
+ * preload (`sandboxUiEmbedPreload.ts`) behind a different trust model.
+ */
+ pluginSdk: {
+ onConsentRequested: (callback: (request: PluginConsentRequest) => void) => {
+ const listener = (_event: unknown, request: PluginConsentRequest) => callback(request)
+ ipcRenderer.on('pluginSdk:consentRequested', listener)
+ return () => ipcRenderer.off('pluginSdk:consentRequested', listener)
+ },
+ onConsentCancelled: (callback: (args: { promptId: string }) => void) => {
+ const listener = (_event: unknown, args: { promptId: string }) => callback(args)
+ ipcRenderer.on('pluginSdk:consentCancelled', listener)
+ return () => ipcRenderer.off('pluginSdk:consentCancelled', listener)
+ },
+ onNotificationClicked: (callback: (args: { pluginId: string; ref: string | null }) => void) => {
+ const listener = (_event: unknown, args: { pluginId: string; ref: string | null }) =>
+ callback(args)
+ ipcRenderer.on('pluginSdk:notificationClicked', listener)
+ return () => ipcRenderer.off('pluginSdk:notificationClicked', listener)
+ },
+ resolveConsent: (promptId: string, allowed: string[]) =>
+ ipcRenderer.invoke('pluginSdk:resolveConsent', { promptId, allowed }),
+ listGrants: () => ipcRenderer.invoke('pluginSdk:listGrants'),
+ revoke: (pluginId: string, capability?: string) =>
+ ipcRenderer.invoke('pluginSdk:revoke', { pluginId, capability }),
+ activity: (limit?: number, includeAmbient?: boolean) =>
+ ipcRenderer.invoke('pluginSdk:activity', { limit, includeAmbient }),
+ clearActivity: () => ipcRenderer.invoke('pluginSdk:clearActivity'),
+ setTheme: (theme: string) => ipcRenderer.invoke('pluginSdk:setTheme', { theme }),
+ },
})
contextBridge.exposeInMainWorld('clerum', clerum)
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index 319e24fb2..0becb1c9d 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -1,3 +1,8 @@
+import type {
+ PluginAuditEntryView,
+ PluginConsentRequest,
+ PluginGrantView,
+} from './pluginSdkProtocol.js'
import {
AccessCatalog,
AgentWithMcpServers,
@@ -568,6 +573,19 @@ declare global {
callback: (args: { appRef: string; message: string }) => void
) => () => void
}
+ pluginSdk: {
+ onConsentRequested: (callback: (request: PluginConsentRequest) => void) => () => void
+ onConsentCancelled: (callback: (args: { promptId: string }) => void) => () => void
+ onNotificationClicked: (
+ callback: (args: { pluginId: string; ref: string | null }) => void
+ ) => () => void
+ resolveConsent: (promptId: string, allowed: string[]) => Promise<boolean>
+ listGrants: () => Promise<PluginGrantView[]>
+ revoke: (pluginId: string, capability?: string) => Promise<void>
+ activity: (limit?: number, includeAmbient?: boolean) => Promise<PluginAuditEntryView[]>
+ clearActivity: () => Promise<void>
+ setTheme: (theme: string) => Promise<void>
+ }
}
}
}
diff --git a/desktop-app/src/sandboxUiEmbedPreload.ts b/desktop-app/src/sandboxUiEmbedPreload.ts
index 3f845b9e1..cce68e64d 100644
--- a/desktop-app/src/sandboxUiEmbedPreload.ts
+++ b/desktop-app/src/sandboxUiEmbedPreload.ts
@@ -1,31 +1,63 @@
import { contextBridge, ipcRenderer } from 'electron'
+// TYPE-ONLY import: erased at compile time, so it never becomes a `require`.
+import type { PluginSdkEvent, PluginSdkResponse } from './pluginSdkProtocol.js'
/**
- * Preload script attached to every sandbox-ui `WebContentsView`. Exposes
- * a small surface to recipe JS:
+ * Channel names are duplicated here on purpose.
*
- * `clerum.requestSessionRefresh()` — recover from a stale session
- * cookie when an SSE/fetch hits 401 between scheduled refreshes.
- * The trusted main-process timer runs at ~270 s after each mint, so
- * most apps will never need this.
+ * This preload runs with `sandbox: true`, where Electron's `require` is a
+ * polyfill limited to `electron` and a couple of Node builtins — a relative
+ * `require('./pluginSdkProtocol.js')` throws at runtime. Until the preload gets
+ * its own bundling step, the values are inlined and
+ * `__tests__/sandboxUiEmbedPreload.contract.test.ts` asserts they still match
+ * `pluginSdkProtocol.ts` so the two cannot drift apart silently.
+ */
+const PLUGIN_SDK_VERSION = '1.0.0'
+const PLUGIN_SDK_PROTOCOL = 1
+const PLUGIN_SDK_REQUEST_CHANNEL = 'clerum:plugin-sdk:request'
+const PLUGIN_SDK_PERMISSIONS_CHANNEL = 'clerum:plugin-sdk:request-permissions'
+const PLUGIN_SDK_PERMISSION_STATE_CHANNEL = 'clerum:plugin-sdk:permissions'
+const PLUGIN_SDK_CAPABILITIES_CHANNEL = 'clerum:plugin-sdk:capabilities'
+const PLUGIN_SDK_EVENT_CHANNEL = 'clerum:plugin-sdk:event'
+
+/**
+ * Preload script attached to every sandbox-ui `WebContentsView`. Exposes the
+ * plugin-facing surface to recipe JS:
*
- * `clerum.onOauthCompleted(callback)` — subscribe to the OAuth
- * completion envelope. Fired after the user clicks an
- * `<a href="clerum://oauth?clientId=…">Connect</a>` button, the
- * provider redirects to control-api, the grant is stored, and the
- * success page bounces to `clerum://oauth-completed`. The recipe
- * uses this to flip its UI to the authenticated state.
+ * Legacy (unchanged, and deliberately so — every shipped recipe uses these):
+ * `clerum.requestSessionRefresh()` — recover from a stale session cookie
+ * when an SSE/fetch hits 401 between scheduled refreshes.
+ * `clerum.onOauthCompleted(cb)` — OAuth completion envelope, on its own
+ * legacy channel.
*
- * Both IPC handlers in main are sender-pinned by `webContents.id` and
- * rate-limited; the preload is exposed to *untrusted* recipe JS, so the
- * abuse surface is bounded by the main-side gating, not by anything on
- * this side of the contextBridge.
+ * Plugin UI SDK (spec `docs/features/plugin-ui-sdk-1.md` §7):
+ * `clerum.sdk.*` — version, capability list, batched consent,
+ * grant state, events.
+ * `clerum.identity/org/agents/contexts/mcp/gfs/theme/notifications`
+ * — one thin wrapper per capability.
+ *
+ * Everything here is a dumb pipe. No validation, no caching, no policy: this
+ * code runs in a world the plugin's own JS can reach, so anything enforced on
+ * this side is advisory. The real gating (caller pinning, consent, rate limits,
+ * response minimization) is entirely main-side in `pluginSdkBroker.ts`.
*/
type SandboxUiOauthCompletedPayload = {
oauthClientId: string
provider: string
}
+function invoke<T>(channel: string, payload?: unknown): Promise<PluginSdkResponse<T>> {
+ return ipcRenderer.invoke(channel, payload) as Promise<PluginSdkResponse<T>>
+}
+
+function capability<T>(id: string, params?: unknown): Promise<PluginSdkResponse<T>> {
+ return invoke<T>(PLUGIN_SDK_REQUEST_CHANNEL, {
+ v: PLUGIN_SDK_PROTOCOL,
+ capability: id,
+ ...(params === undefined ? {} : { params }),
+ })
+}
+
contextBridge.exposeInMainWorld(
'clerum',
Object.freeze({
@@ -45,5 +77,44 @@ contextBridge.exposeInMainWorld(
ipcRenderer.off('clerum:sandbox-ui:oauth-completed', listener)
}
},
+
+ sdk: Object.freeze({
+ version: PLUGIN_SDK_VERSION,
+ protocol: PLUGIN_SDK_PROTOCOL,
+ /** Capability ids this host build implements — lets a plugin degrade
+ * gracefully on an older Desktop instead of hard-failing. */
+ capabilities: () => invoke(PLUGIN_SDK_CAPABILITIES_CHANNEL),
+ /** Ask for several capabilities in ONE modal. The intended entry point. */
+ requestPermissions: (capabilities: string[]) =>
+ invoke(PLUGIN_SDK_PERMISSIONS_CHANNEL, { v: PLUGIN_SDK_PROTOCOL, capabilities }),
+ /** Grant state without prompting, so a returning user sees no modal. */
+ permissions: (capabilities?: string[]) =>
+ invoke(PLUGIN_SDK_PERMISSION_STATE_CHANNEL, capabilities ?? null),
+ on: (callback: (event: PluginSdkEvent) => void): (() => void) => {
+ const listener = (_event: Electron.IpcRendererEvent, payload: PluginSdkEvent): void => {
+ callback(payload)
+ }
+ ipcRenderer.on(PLUGIN_SDK_EVENT_CHANNEL, listener)
+ return () => {
+ ipcRenderer.off(PLUGIN_SDK_EVENT_CHANNEL, listener)
+ }
+ },
+ }),
+
+ identity: Object.freeze({ get: () => capability('identity.read') }),
+ org: Object.freeze({ get: () => capability('org.read') }),
+ agents: Object.freeze({ list: () => capability('agents.read') }),
+ contexts: Object.freeze({ list: () => capability('contexts.read') }),
+ mcp: Object.freeze({ list: () => capability('mcp.read') }),
+ gfs: Object.freeze({
+ list: (params?: { drive?: string; resourceId?: string; cursor?: string }) =>
+ capability('gfs.list', params ?? {}),
+ read: (params: { uri: string; as: 'text' | 'dataUrl' }) => capability('gfs.read', params),
+ }),
+ theme: Object.freeze({ get: () => capability('theme.read') }),
+ notifications: Object.freeze({
+ notify: (params: { title: string; body?: string; ref?: string }) =>
+ capability('notifications.notify', params),
+ }),
})
)
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 5b9c335ee..1b0e2bd33 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -13,6 +13,8 @@ import { AppHeader } from '@components/AppHeader'
import { BootSplash } from '@components/BootSplash'
import { Button, ToastStack } from '@components/Common'
import { ConfirmDialog } from '@components/ConfirmDialog'
+import { PluginConsentModal } from '@components/PluginConsentModal'
+import type { PluginConsentRequest } from '@components/PluginConsentModal/types'
import { SidebarNav } from '@components/SidebarNav'
import { DESKTOP_ROUTES, SIDEBAR_COLLAPSED_KEY } from '@constants/navigation'
import { THEME_STORAGE_KEY } from '@constants/theme'
@@ -211,6 +213,34 @@ export function App() {
])
activeConversationOriginRef.current = activeConversationOrigin
+ /**
+ * Plugin permission prompts (spec §9). Main hides the plugin's
+ * `WebContentsView` before pushing the request and restores it once the user
+ * answers, so this modal is the only thing on screen while it is up.
+ */
+ const [pluginConsentPrompt, setPluginConsentPrompt] = React.useState<PluginConsentRequest | null>(
+ null
+ )
+
+ React.useEffect(() => {
+ const offRequested = window.clerum.pluginSdk?.onConsentRequested?.(request => {
+ setPluginConsentPrompt(request)
+ })
+ const offCancelled = window.clerum.pluginSdk?.onConsentCancelled?.(({ promptId }) => {
+ // Main withdrew the prompt (timeout, or the plugin was closed under it).
+ setPluginConsentPrompt(current => (current?.promptId === promptId ? null : current))
+ })
+ return () => {
+ offRequested?.()
+ offCancelled?.()
+ }
+ }, [])
+
+ const resolvePluginConsent = React.useCallback((promptId: string, allowed: string[]) => {
+ setPluginConsentPrompt(current => (current?.promptId === promptId ? null : current))
+ void window.clerum.pluginSdk?.resolveConsent?.(promptId, allowed)?.catch?.(() => undefined)
+ }, [])
+
React.useEffect(() => {
document.documentElement.setAttribute('data-theme', themeMode)
try {
@@ -218,6 +248,11 @@ export function App() {
} catch {
// Ignore storage failures in restricted environments.
}
+ // Mirror into the main process so `theme.read` and the `theme.changed`
+ // event can answer for plugin embeds, which have no access to this
+ // renderer's localStorage. The renderer stays the writer; main only keeps
+ // the last value it was told.
+ void window.clerum.pluginSdk?.setTheme?.(themeMode)?.catch?.(() => undefined)
}, [themeMode])
React.useEffect(() => {
@@ -1242,6 +1277,12 @@ export function App() {
{environmentSetupConfirmationDialog}
{environmentSetupSuccessDialog}
{sandboxUiDeepLinkDialog}
+ {pluginConsentPrompt ? (
+ <PluginConsentModal
+ request={pluginConsentPrompt}
+ onResolve={resolvePluginConsent}
+ />
+ ) : null}
</DesktopStateProvider>
</McpRuntimeProvider>
</AgentChatProviders>
diff --git a/desktop-app/ui/src/components/PluginConsentModal/index.tsx b/desktop-app/ui/src/components/PluginConsentModal/index.tsx
new file mode 100644
index 000000000..6174af16b
--- /dev/null
+++ b/desktop-app/ui/src/components/PluginConsentModal/index.tsx
@@ -0,0 +1,116 @@
+import { useEffect, useId, useRef, useState } from 'react'
+import { createPortal } from 'react-dom'
+import { Button } from '@components/Common'
+import type { PluginConsentModalProps } from './types'
+
+/**
+ * The plugin permission prompt (spec §9.2, §9.4).
+ *
+ * Rendered by the TRUSTED renderer while the plugin's own `WebContentsView` is
+ * hidden by the main process — a WebContentsView paints above renderer DOM
+ * regardless of z-index, so hiding it is the only way to guarantee the plugin
+ * can neither fake this modal nor paint over it.
+ *
+ * Every string here except `pluginTitle` comes from the host's own capability
+ * catalog. The plugin cannot influence a single word of what the user reads,
+ * and it cannot mark a row "required": that pressure belongs in the plugin's
+ * own UI after a partial grant, where the user can see who is asking.
+ *
+ * Rows arrive pre-sorted most-sensitive-first and start checked; unchecking is
+ * how a user grants part of a request.
+ */
+export function PluginConsentModal({ request, onResolve }: PluginConsentModalProps) {
+ const titleId = useId()
+ const allowButtonRef = useRef<HTMLButtonElement | null>(null)
+ const [checked, setChecked] = useState<Set<string>>(
+ () => new Set(request.rows.map(row => row.capability))
+ )
+
+ useEffect(() => {
+ setChecked(new Set(request.rows.map(row => row.capability)))
+ }, [request.promptId, request.rows])
+
+ useEffect(() => {
+ allowButtonRef.current?.focus()
+ }, [request.promptId])
+
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ // Escape denies everything — a prompt nobody answered is not consent.
+ if (event.key === 'Escape') onResolve(request.promptId, [])
+ }
+ window.addEventListener('keydown', handleKeyDown)
+ return () => window.removeEventListener('keydown', handleKeyDown)
+ }, [onResolve, request.promptId])
+
+ const toggle = (capability: string) => {
+ setChecked(previous => {
+ const next = new Set(previous)
+ if (next.has(capability)) next.delete(capability)
+ else next.add(capability)
+ return next
+ })
+ }
+
+ return createPortal(
+ <div className="confirm-dialog-backdrop da-plugin-consent-backdrop" role="presentation">
+ <div
+ className="confirm-dialog da-plugin-consent"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={titleId}
+ >
+ <h3 id={titleId}>{request.pluginTitle} wants access to your information</h3>
+
+ {request.priorPromptCount > 0 ? (
+ <p className="muted da-plugin-consent__count">
+ This plugin has asked for permissions {request.priorPromptCount + 1} times this session.
+ </p>
+ ) : null}
+
+ <ul className="da-plugin-consent__rows">
+ {request.rows.map(row => (
+ <li key={row.capability} className="da-plugin-consent__row">
+ <label className="da-plugin-consent__label">
+ <input
+ type="checkbox"
+ checked={checked.has(row.capability)}
+ onChange={() => toggle(row.capability)}
+ />
+ <span>
+ <span className="da-plugin-consent__row-title">{row.title}</span>
+ <span className="da-plugin-consent__row-detail muted">{row.dataDescription}</span>
+ </span>
+ </label>
+ </li>
+ ))}
+ </ul>
+
+ <p className="muted da-plugin-consent__footer">
+ You can change this any time in Settings → Plugin permissions.
+ </p>
+
+ <div className="confirm-dialog-actions">
+ <Button
+ color="neutral"
+ onClick={() => onResolve(request.promptId, [])}
+ size="sm"
+ variant="ghost"
+ >
+ Deny
+ </Button>
+ <Button
+ ref={allowButtonRef}
+ color="primary"
+ disabled={checked.size === 0}
+ onClick={() => onResolve(request.promptId, [...checked])}
+ size="sm"
+ >
+ Allow
+ </Button>
+ </div>
+ </div>
+ </div>,
+ document.body
+ )
+}
diff --git a/desktop-app/ui/src/components/PluginConsentModal/types.ts b/desktop-app/ui/src/components/PluginConsentModal/types.ts
new file mode 100644
index 000000000..ad96a4b6f
--- /dev/null
+++ b/desktop-app/ui/src/components/PluginConsentModal/types.ts
@@ -0,0 +1,22 @@
+export type PluginConsentTier = 'personal' | 'workspace' | 'ambient'
+
+export type PluginConsentRow = {
+ capability: string
+ title: string
+ dataDescription: string
+ tier: PluginConsentTier
+}
+
+export type PluginConsentRequest = {
+ promptId: string
+ pluginId: string
+ pluginTitle: string
+ rows: PluginConsentRow[]
+ priorPromptCount: number
+}
+
+export type PluginConsentModalProps = {
+ request: PluginConsentRequest
+ /** Resolve with the capabilities the user left checked. */
+ onResolve: (promptId: string, allowed: string[]) => void
+}
diff --git a/desktop-app/ui/src/components/PluginPermissions/index.tsx b/desktop-app/ui/src/components/PluginPermissions/index.tsx
new file mode 100644
index 000000000..cfe02c0be
--- /dev/null
+++ b/desktop-app/ui/src/components/PluginPermissions/index.tsx
@@ -0,0 +1,213 @@
+import { useState } from 'react'
+import { Button, EmptyState, StatusBanner, TabButton } from '@components/Common'
+import { usePluginPermissionsController } from '@hooks/domain/usePluginPermissionsController'
+
+const GRANTS_GRID_COLS = 'minmax(10rem, 1.2fr) minmax(12rem, 1.6fr) minmax(8rem, 0.7fr) 6rem'
+const ACTIVITY_GRID_COLS =
+ 'minmax(9rem, 0.8fr) minmax(9rem, 0.9fr) minmax(9rem, 1fr) minmax(6rem, 0.5fr)'
+
+function formatTimestamp(value: string | null): string {
+ if (!value) return 'Never'
+ const parsed = new Date(value)
+ if (Number.isNaN(parsed.getTime())) return 'Unknown'
+ return parsed.toLocaleString()
+}
+
+function outcomeLabel(outcome: string): string {
+ switch (outcome) {
+ case 'allowed':
+ return 'Shared'
+ case 'granted':
+ return 'Granted'
+ case 'denied':
+ return 'Denied'
+ case 'revoked':
+ return 'Revoked'
+ case 'revoked_mid_flight':
+ return 'Revoked mid-request'
+ case 'rate_limited':
+ return 'Rate limited'
+ default:
+ return 'Error'
+ }
+}
+
+/**
+ * Settings → Plugin permissions (spec §11).
+ *
+ * Two views over the same trust decision: what a plugin currently holds, and
+ * what it has actually been doing. Denials and rate-limits are deliberately
+ * included in Activity — a plugin that keeps asking for things the user keeps
+ * refusing is a pattern worth being able to notice.
+ */
+export function PluginPermissions() {
+ const controller = usePluginPermissionsController()
+ const [view, setView] = useState<'grants' | 'activity'>('grants')
+ const [expanded, setExpanded] = useState<string | null>(null)
+
+ return (
+ <section className="page-card settings-card" aria-labelledby="settings-plugin-permissions">
+ <div className="page-card__header">
+ <div className="settings-card-title-row">
+ <div>
+ <h3 id="settings-plugin-permissions">Plugin permissions</h3>
+ <p className="muted">
+ Plugins can only see what you have explicitly allowed. Revoking takes effect
+ immediately, even while a plugin is open.
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div className="page-tabs" role="tablist" aria-label="Plugin permission views">
+ <TabButton
+ active={view === 'grants'}
+ className="page-tab"
+ role="tab"
+ onClick={() => setView('grants')}
+ >
+ Permissions
+ </TabButton>
+ <TabButton
+ active={view === 'activity'}
+ className="page-tab"
+ role="tab"
+ onClick={() => setView('activity')}
+ >
+ Activity
+ </TabButton>
+ </div>
+
+ {controller.error ? <StatusBanner tone="error">{controller.error}</StatusBanner> : null}
+
+ {view === 'grants' ? (
+ controller.loading ? (
+ <EmptyState
+ title="Loading permissions…"
+ body="Reading what each plugin is allowed to see."
+ />
+ ) : controller.groups.length === 0 ? (
+ <EmptyState
+ title="No plugin has been granted access to your information."
+ body="When a plugin asks for something, you will see a prompt naming exactly what it wants."
+ />
+ ) : (
+ <div className="da-grid" style={{ '--da-grid-cols': GRANTS_GRID_COLS }}>
+ <div className="da-grid__head">
+ <span className="da-grid__col-header">Plugin</span>
+ <span className="da-grid__col-header">Permissions</span>
+ <span className="da-grid__col-header">Last used</span>
+ <span className="da-grid__col-header da-grid__col-header--right">Actions</span>
+ </div>
+ <div className="da-grid__body">
+ {controller.groups.map(group => (
+ <div key={group.pluginId}>
+ <div className="da-grid__row da-grid__row--clickable">
+ <span className="da-grid__cell">
+ <Button
+ align="start"
+ block
+ onClick={() =>
+ setExpanded(current =>
+ current === group.pluginId ? null : group.pluginId
+ )
+ }
+ variant="text"
+ >
+ {group.pluginTitle}
+ </Button>
+ </span>
+ <span className="da-grid__cell">
+ {group.capabilities.map(grant => grant.title).join(' · ')}
+ </span>
+ <span className="da-grid__cell">{formatTimestamp(group.lastUsedAt)}</span>
+ <span className="da-grid__cell da-grid__cell--right">
+ <Button
+ color="danger"
+ disabled={controller.revoking}
+ onClick={() => void controller.revoke(group.pluginId)}
+ size="sm"
+ variant="ghost"
+ >
+ Revoke all
+ </Button>
+ </span>
+ </div>
+
+ {expanded === group.pluginId
+ ? group.capabilities.map(grant => (
+ <div
+ className="da-grid__row da-grid__row--compact"
+ key={`${grant.pluginId}:${grant.capability}`}
+ >
+ <span className="da-grid__cell muted">{grant.title}</span>
+ {/* The same sentence the consent prompt showed, verbatim —
+ the user re-reads what they agreed to, not a paraphrase. */}
+ <span className="da-grid__cell muted">{grant.dataDescription}</span>
+ <span className="da-grid__cell muted">
+ Granted {formatTimestamp(grant.grantedAt)}
+ </span>
+ <span className="da-grid__cell da-grid__cell--right">
+ <Button
+ color="danger"
+ disabled={controller.revoking}
+ onClick={() =>
+ void controller.revoke(grant.pluginId, grant.capability)
+ }
+ size="sm"
+ variant="ghost"
+ >
+ Revoke
+ </Button>
+ </span>
+ </div>
+ ))
+ : null}
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+ ) : controller.activity.length === 0 ? (
+ <EmptyState
+ title="No plugin activity recorded yet."
+ body="Requests a plugin makes will be listed here."
+ />
+ ) : (
+ <>
+ <div className="da-grid" style={{ '--da-grid-cols': ACTIVITY_GRID_COLS }}>
+ <div className="da-grid__head">
+ <span className="da-grid__col-header">When</span>
+ <span className="da-grid__col-header">Plugin</span>
+ <span className="da-grid__col-header">Requested</span>
+ <span className="da-grid__col-header">Result</span>
+ </div>
+ <div className="da-grid__body">
+ {controller.activity.map((entry, index) => (
+ <div
+ className="da-grid__row da-grid__row--compact"
+ key={`${entry.ts}-${entry.capability}-${index}`}
+ >
+ <span className="da-grid__cell">{formatTimestamp(entry.ts)}</span>
+ <span className="da-grid__cell">{entry.pluginId.split('/').pop()}</span>
+ <span className="da-grid__cell">{entry.capability}</span>
+ <span className="da-grid__cell">{outcomeLabel(entry.outcome)}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ <div className="settings-form">
+ <Button
+ color="neutral"
+ onClick={() => void controller.clearActivity()}
+ size="sm"
+ variant="ghost"
+ >
+ Clear activity log
+ </Button>
+ </div>
+ </>
+ )}
+ </section>
+ )
+}
diff --git a/desktop-app/ui/src/hooks/domain/queryKeys.ts b/desktop-app/ui/src/hooks/domain/queryKeys.ts
index 1b9604a84..88da02d27 100644
--- a/desktop-app/ui/src/hooks/domain/queryKeys.ts
+++ b/desktop-app/ui/src/hooks/domain/queryKeys.ts
@@ -22,4 +22,7 @@ export const desktopQueryKeys = {
['desktop-app', 'gfs', sessionScope, 'children', drive, resourceId] as const,
gfsAffordances: (sessionScope: string, resourceId: string, drive: string) =>
['desktop-app', 'gfs', sessionScope, 'affordances', drive, resourceId] as const,
+ pluginGrants: ['desktop-app', 'plugin-sdk', 'grants'] as const,
+ pluginActivity: (limit: number) =>
+ ['desktop-app', 'plugin-sdk', 'activity', String(limit)] as const,
}
diff --git a/desktop-app/ui/src/hooks/domain/usePluginPermissionsController.ts b/desktop-app/ui/src/hooks/domain/usePluginPermissionsController.ts
new file mode 100644
index 000000000..6f61cbbde
--- /dev/null
+++ b/desktop-app/ui/src/hooks/domain/usePluginPermissionsController.ts
@@ -0,0 +1,101 @@
+import { useCallback, useMemo } from 'react'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import type { PluginAuditEntryView, PluginGrantView } from '../../../../src/pluginSdkProtocol'
+import { desktopQueryKeys } from './queryKeys'
+
+const ACTIVITY_LIMIT = 200
+
+export type PluginPermissionGroup = {
+ pluginId: string
+ pluginTitle: string
+ capabilities: PluginGrantView[]
+ /** Most recent `lastUsedAt` across the plugin's grants, for the summary row. */
+ lastUsedAt: string | null
+}
+
+function toErrorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error)
+}
+
+/**
+ * Settings → Plugin permissions (spec §11).
+ *
+ * Grants and audit entries both come from the main process over IPC rather than
+ * from the network, but they are still server-state-shaped (owned elsewhere,
+ * refetched, invalidated after a mutation), so they follow the same TanStack
+ * Query pattern as every other data section in this app.
+ */
+export function usePluginPermissionsController() {
+ const queryClient = useQueryClient()
+
+ const grantsQuery = useQuery({
+ queryKey: desktopQueryKeys.pluginGrants,
+ queryFn: () => window.clerum.pluginSdk.listGrants(),
+ })
+
+ const activityQuery = useQuery({
+ queryKey: desktopQueryKeys.pluginActivity(ACTIVITY_LIMIT),
+ queryFn: () => window.clerum.pluginSdk.activity(ACTIVITY_LIMIT),
+ })
+
+ const invalidate = useCallback(() => {
+ void queryClient.invalidateQueries({ queryKey: desktopQueryKeys.pluginGrants })
+ void queryClient.invalidateQueries({
+ queryKey: desktopQueryKeys.pluginActivity(ACTIVITY_LIMIT),
+ })
+ }, [queryClient])
+
+ const revokeMutation = useMutation({
+ mutationFn: ({ pluginId, capability }: { pluginId: string; capability?: string }) =>
+ window.clerum.pluginSdk.revoke(pluginId, capability),
+ onSuccess: invalidate,
+ })
+
+ const clearActivityMutation = useMutation({
+ mutationFn: () => window.clerum.pluginSdk.clearActivity(),
+ onSuccess: invalidate,
+ })
+
+ /** One row per plugin; capabilities nested underneath. */
+ const groups = useMemo<PluginPermissionGroup[]>(() => {
+ const byPlugin = new Map<string, PluginPermissionGroup>()
+ for (const grant of grantsQuery.data ?? []) {
+ const existing = byPlugin.get(grant.pluginId)
+ if (existing) {
+ existing.capabilities.push(grant)
+ if (grant.lastUsedAt && (!existing.lastUsedAt || grant.lastUsedAt > existing.lastUsedAt)) {
+ existing.lastUsedAt = grant.lastUsedAt
+ }
+ continue
+ }
+ byPlugin.set(grant.pluginId, {
+ pluginId: grant.pluginId,
+ pluginTitle: grant.pluginTitle,
+ capabilities: [grant],
+ lastUsedAt: grant.lastUsedAt,
+ })
+ }
+ return [...byPlugin.values()].sort((a, b) => a.pluginTitle.localeCompare(b.pluginTitle))
+ }, [grantsQuery.data])
+
+ const activity = useMemo<PluginAuditEntryView[]>(
+ () => activityQuery.data ?? [],
+ [activityQuery.data]
+ )
+
+ return {
+ groups,
+ activity,
+ loading: grantsQuery.isPending || activityQuery.isPending,
+ error: grantsQuery.error
+ ? toErrorMessage(grantsQuery.error)
+ : activityQuery.error
+ ? toErrorMessage(activityQuery.error)
+ : null,
+ revoking: revokeMutation.isPending,
+ revoke: (pluginId: string, capability?: string) =>
+ revokeMutation.mutateAsync({ pluginId, ...(capability ? { capability } : {}) }),
+ clearActivity: () => clearActivityMutation.mutateAsync(),
+ refresh: invalidate,
+ }
+}
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsx
index 56e754e26..bd5b8945e 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx
+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx
@@ -259,6 +259,9 @@ export function SandboxUiPage({
await window.clerum.sandboxUi.open({
recipeNs,
recipeName,
+ // Title travels from the trusted app list into consent prompts and
+ // notification attribution. The plugin never gets to name itself.
+ ...(app.label ? { title: app.label } : {}),
defaultPath: app.defaultPath,
...(app.routePath ? { routePath: app.routePath } : {}),
bounds,
diff --git a/desktop-app/ui/src/pages/SettingsPage.tsx b/desktop-app/ui/src/pages/SettingsPage.tsx
index f844f2166..fa8269a57 100644
--- a/desktop-app/ui/src/pages/SettingsPage.tsx
+++ b/desktop-app/ui/src/pages/SettingsPage.tsx
@@ -1,6 +1,7 @@
import { type FormEvent, useEffect, useMemo, useState } from 'react'
import { useAuthContext } from '@contexts/AuthContext'
import { Button, Field, IconButton, SelectInput, TabButton, TextInput } from '@components/Common'
+import { PluginPermissions } from '@components/PluginPermissions'
import {
IconBell,
IconConnectors,
@@ -33,7 +34,7 @@ import type {
import type { SettingsPageProps } from './SettingsPage.types'
type NotificationPreferenceSection = 'inApp' | 'desktop'
-type SettingsTab = 'account' | 'appearance' | 'notifications' | 'social' | 'information'
+type SettingsTab = 'account' | 'appearance' | 'notifications' | 'plugins' | 'social' | 'information'
type EndpointDiagnostics = {
appInfo: DesktopAppInfo | null
@@ -527,6 +528,16 @@ export function SettingsPage({
>
Notifications
</TabButton>
+ <TabButton
+ active={activeSettingsTab === 'plugins'}
+ className="page-tab"
+ id="settings-tab-plugins"
+ role="tab"
+ aria-controls="settings-panel-plugins"
+ onClick={() => setActiveSettingsTab('plugins')}
+ >
+ Plugin permissions
+ </TabButton>
{hasSocialChannelsAccess ? (
<TabButton
active={activeSettingsTab === 'social'}
@@ -633,6 +644,17 @@ export function SettingsPage({
</section>
) : null}
+ {activeSettingsTab === 'plugins' ? (
+ <section
+ className="settings-tab-panel"
+ id="settings-panel-plugins"
+ role="tabpanel"
+ aria-labelledby="settings-tab-plugins"
+ >
+ <PluginPermissions />
+ </section>
+ ) : null}
+
{activeSettingsTab === 'notifications' ? (
<section
className="settings-tab-panel"
diff --git a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
index c0ff013d6..61196c00a 100644
--- a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
@@ -150,6 +150,7 @@ describe('SandboxUiPage', () => {
expect(sandboxUi.open).toHaveBeenCalledWith({
recipeNs: 'sandbox-recipes',
recipeName: 'sales-crm',
+ title: "Andy's Sales CRM",
defaultPath: '/',
bounds: {
x: 16,
@@ -188,6 +189,9 @@ describe('SandboxUiPage', () => {
expect(sandboxUi.open).toHaveBeenCalledWith({
recipeNs: 'sandbox-recipes',
recipeName: 'task-board',
+ // Host-owned title: consent prompts and notification attribution read
+ // this, so it must come from the app list, never from the plugin.
+ title: 'Agentic Task Board',
defaultPath: '/',
routePath: '/tasks/task-42',
bounds: {
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index 586dc9269..9275931cb 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -14613,3 +14613,56 @@ pre {
grid-template-columns: minmax(0, 1fr);
}
}
+
+/* ── Plugin consent prompt (spec §9.4) ─────────────────────────────────
+ Reuses the confirm-dialog shell; only the permission rows are new. Wider
+ than a confirm dialog because each row carries a full scope sentence, and
+ a batched prompt can list up to eight of them. */
+.da-plugin-consent {
+ width: min(480px, 100%);
+}
+
+.da-plugin-consent__count {
+ margin: 0 0 var(--space-2);
+ font-size: var(--font-size-sm);
+}
+
+.da-plugin-consent__rows {
+ list-style: none;
+ margin: 0 0 var(--space-2);
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+}
+
+.da-plugin-consent__row {
+ border: 1px solid rgba(var(--edge-rgb), 0.32);
+ border-radius: var(--radius-sm);
+ padding: var(--space-2);
+}
+
+.da-plugin-consent__label {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr);
+ gap: var(--space-2);
+ align-items: start;
+ cursor: pointer;
+}
+
+.da-plugin-consent__row-title {
+ display: block;
+ font-size: var(--font-size-sm);
+ font-weight: var(--font-weight-medium);
+}
+
+.da-plugin-consent__row-detail {
+ display: block;
+ font-size: var(--font-size-sm);
+ line-height: var(--line-height-normal);
+}
+
+.da-plugin-consent__footer {
+ margin: 0 0 var(--space-2);
+ font-size: var(--font-size-sm);
+}
diff --git a/docs/features/plugin-ui-sdk-1.md b/docs/features/plugin-ui-sdk-1.md
new file mode 100644
index 000000000..28ae626fd
--- /dev/null
+++ b/docs/features/plugin-ui-sdk-1.md
@@ -0,0 +1,1343 @@
+# Plugin UI SDK — typed, consented context bridge for sandbox-UI plugins
+
+Status: **Draft spec, not implemented.** Target surface: `desktop-app`.
+Sibling story: Side Window (out of scope here, but the broker is designed so it
+can host that surface without a contract change — §14).
+
+---
+
+## 1. Problem
+
+A plugin (a `WorkflowRecipe` with `spec.ui`, see
+[`WORKFLOW_RECIPE_GUIDE`](../agents/CLERUM_WORKFLOW_RECIPE_GUIDE.md) §6) renders
+inside a hardened Electron `WebContentsView`: `nodeIntegration:false`,
+`contextIsolation:true`, `sandbox:true`, a per-recipe partition, a strict CSP
+from rpc-proxy (`rpc-proxy/src/routes/sandboxUi.ts:94`), and a navigation policy
+pinning it to its own `view/*` prefix (`desktop-app/src/sandboxUiPartitionPolicies.ts`).
+
+That isolation is correct and it is also the problem: the plugin knows nothing
+about the human using it. Today the only ways a plugin learns anything about its
+user are:
+
+- `X-Clerum-User`, injected by rpc-proxy into requests reaching the plugin's own
+ backend — an opaque id, server-side only, invisible to the embed's JS.
+- Whatever the plugin asks the user to re-type into its own forms.
+- Whatever a recipe author smuggles through `inputContract` defaults at install
+ time.
+
+So every plugin that wants "hello, Andres" or "which of your agents should I
+target?" reinvents context passing, and reinvents it insecurely: prompting for
+an email it cannot verify, or asking the operator to bake identity into a Secret.
+
+Meanwhile the Desktop App already holds all of it — session identity, the access
+catalog of agents/contexts/MCP servers, GFS resources, the notification channel,
+the theme. There is no sanctioned, auditable way to hand any of it across the
+embed boundary.
+
+**This spec defines that way: a typed IPC SDK, deny-by-default, with per-plugin ×
+per-capability consent, user-visible revocation, and an audit log.**
+
+For the user-visible arc all of this machinery is in service of — first open to
+revocation, including where it goes wrong — read **§17 (Appendix A)** first. The
+sections in between specify how that arc is made true.
+
+## 2. Goals / non-goals
+
+### Goals
+
+1. A **typed request/response + event API** between the plugin UI process and
+ the Desktop master process, versioned, with a single audited chokepoint.
+2. **Context providers** for identity, org, agents, contexts, MCP servers, GFS
+ files, plus a notification sink and theme — extensible by adding a capability
+ descriptor, not by adding an IPC channel.
+3. A **consent layer**: any capability the user has not already approved for
+ *this plugin* surfaces a permission prompt naming the plugin and the exact
+ scope. Approvals persist per (user, environment, plugin, capability).
+4. **Revocation** from Desktop settings, taking effect immediately on the
+ running embed.
+5. An **audit log** of what each plugin requested and what it received.
+
+### Non-goals
+
+- **No new credential path.** The SDK never hands a plugin a session token, RPC
+ token, OAuth grant, or any bearer material. It returns *data*, brokered by
+ main, fetched with the user's own session. A plugin that wants to act as the
+ user still goes through the existing OAuth (§7 of the recipe guide) or
+ `backgroundAccess` broker paths.
+- **No writes in v1.** Every capability is a read, except `notifications.notify`
+ (which writes only to the user's own notification surface). No "create an
+ agent", no "write this GFS file", no "trigger that workflow". Those are v2
+ candidates and each needs its own consent copy and threat review.
+- **No CRD change.** Capabilities are requested at runtime, not declared in
+ `spec.ui` (decision D2, §3.3). The recipe YAML is untouched by this feature.
+- **No server-side consent store in v1** — but the store is behind an interface
+ so v2 can sync it (decision D1, §10.6).
+- **No bypass of existing platform boundaries.** If control-api would deny the
+ user the data, the SDK denies it too; consent is an *additional* gate, never a
+ substitute for the user's own ACL.
+
+## 3. Decisions
+
+| # | Decision | Rationale |
+|---|---|---|
+| D1 | Consent grants + audit persist **locally now, behind a `ConsentStore` interface designed for server sync later**. | Ships without a DB migration; the IPC contract does not change when sync lands (§10.6). |
+| D2 | Capabilities are **runtime-requested, not declared in the CRD**. Undeclared ≠ denied because there is nothing to declare; the *prompt* is the gate. | Zero platform work; feature lives entirely in `desktop-app`. Cost: no pre-install disclosure and a prompt-spam surface, mitigated in §9.5 / §12. |
+| D3 | The permission prompt is an **in-app React modal in the trusted renderer**, not `dialog.showMessageBox`. | Room for real scope copy ("your name and email address"), the plugin's title and icon, and a link into the revocation page. Spoof-resistance comes from hiding the `WebContentsView` while the modal is up (§9.4). |
+| D4 | A grant is **always-until-revoked**. No "allow once", no "allow for this session". | One state per (plugin, capability): granted or not. A *denial* is session-sticky only (§9.3) so a user who mis-clicks Deny is not permanently stuck. |
+
+## 4. Architecture
+
+```
+┌──────────────────────────────────────────────────────────────────────────┐
+│ Plugin UI (UNTRUSTED) │
+│ origin: rpc-proxy /api/v1/sandbox-ui/<ns>/<name>/view/ │
+│ WebContentsView · sandbox:true · contextIsolation:true · per-recipe │
+│ partition · CSP: script-src 'self'; connect-src 'self'; img-src │
+│ 'self' data: │
+│ │
+│ window.clerum.identity.get() ──────────────┐ │
+└───────────────────────────────────────────────┼──────────────────────────┘
+ │ contextBridge
+┌───────────────────────────────────────────────▼──────────────────────────┐
+│ sandboxUiEmbedPreload.ts (isolated world, no Node) │
+│ one invoke channel: clerum:plugin-sdk:request │
+│ one event channel: clerum:plugin-sdk:event │
+└───────────────────────────────────────────────┬──────────────────────────┘
+ │ ipcRenderer.invoke
+┌───────────────────────────────────────────────▼──────────────────────────┐
+│ MAIN PROCESS (TRUSTED) │
+│ │
+│ pluginSdkBroker.ts ← THE chokepoint. Every request passes here. │
+│ 1. resolveCaller(senderId) → pluginId, or reject (§8.1) │
+│ 2. capabilityRegistry.lookup() → descriptor or unsupported_capability│
+│ 3. requireSession() → unauthenticated │
+│ 4. rateLimiter.take() → rate_limited │
+│ 5. consentGate.check/prompt() → permission_denied │
+│ 6. descriptor.provider(ctx) → data │
+│ 7. descriptor.minimize(data) → wire payload │
+│ 8. auditLog.append(...) → always, allow or deny │
+│ │
+│ pluginSurfaceRegistry.ts webContents.id → { pluginId, surface } │
+│ pluginConsentStore.ts grants, local impl behind an interface │
+│ pluginAuditLog.ts append-only JSONL per environment │
+│ pluginSdkCapabilities.ts the capability catalog (§6) │
+│ │ │
+│ AppService ────────────────────────┘ (existing: getSessionState, │
+│ listMyAgents, getAccessCatalog, listAccessibleMcpServers, │
+│ listAccessibleGfsResources, downloadGfsUri, listTeams, …) │
+└───────────────────────────────────────────────┬──────────────────────────┘
+ │ ipcMain → trusted renderer
+┌───────────────────────────────────────────────▼──────────────────────────┐
+│ Desktop renderer (TRUSTED, file:// or dev URL) │
+│ PluginConsentModal — the prompt (§9) │
+│ SettingsPage → Plugin permissions — revocation + audit (§11) │
+└──────────────────────────────────────────────────────────────────────────┘
+```
+
+### 4.1 Message flow across the processes
+
+The boxes above are the topology; this is the traffic. One diagram covers the
+three cases that matter — a first call that must prompt, a later call against an
+existing grant, and a revocation pushed back down into a running plugin.
+
+```mermaid
+%%{init: {'theme':'base', 'themeVariables': {'fontSize':'12px'}}}%%
+sequenceDiagram
+ autonumber
+ actor U as User
+ participant P as Plugin UI<br/>(WebContentsView, untrusted)
+ participant PL as Embed preload<br/>(isolated world)
+ participant B as pluginSdkBroker<br/>(main)
+ participant ST as Consent store<br/>+ audit log (main)
+ participant R as Desktop renderer<br/>(trusted)
+ participant AS as AppService<br/>(main)
+ participant API as control-api /<br/>external-rest-api
+
+ Note over P,API: A — first open: batched consent, one modal
+ U->>P: Opens the plugin
+ P->>PL: sdk.requestPermissions([identity, org, agents, gfs.list])
+ PL->>B: invoke 'clerum:plugin-sdk:request-permissions'
+ activate B
+ B->>B: resolveCaller(event.sender.id) → pluginId (§8.1)
+ B->>ST: grants for (env, user, plugin)?
+ ST-->>B: none
+ B->>R: setSandboxUiVisible(false)
+ B->>R: 'pluginSdk:consentRequested' {promptId, rows[]}
+ deactivate B
+ R->>U: PluginConsentModal (embed hidden, §9.4)
+ U-->>R: Allow 3 of 4 rows
+ R->>B: 'pluginSdk:resolveConsent' {promptId, allowed[]}
+ activate B
+ Note over R,B: assertTrustedSender — the embed cannot answer its own prompt
+ B->>ST: put × 3 grants · sessionDeny × 1 · audit × 4
+ B->>R: setSandboxUiVisible(true)
+ B-->>PL: {ok, granted:{…}, all:false}
+ deactivate B
+ PL-->>P: result map
+
+ Note over P,API: B — a granted capability: no prompt, no token crosses the bridge
+ P->>PL: identity.get()
+ PL->>B: invoke 'clerum:plugin-sdk:request'
+ activate B
+ B->>ST: grant + rate budget
+ ST-->>B: granted
+ B->>AS: getSessionState()
+ AS->>API: GET /me (user's session token — main only)
+ API-->>AS: SessionMe
+ AS-->>B: SessionMe
+ B->>B: minimize() → {userId, email, name}
+ B->>ST: audit {outcome: allowed, fields:[…]}
+ B-->>PL: {ok:true, data}
+ deactivate B
+ PL-->>P: identity
+
+ Note over P,API: C — revocation reaches a running plugin
+ U->>R: Settings → revoke "Shared files"
+ R->>B: 'pluginSdk:revoke' {pluginId, capability}
+ activate B
+ B->>ST: revoke + audit
+ B->>PL: 'clerum:plugin-sdk:event' {permission.changed, granted:false}
+ deactivate B
+ PL-->>P: onEvent callback
+ P->>U: Re-renders without the file panel (no reload)
+```
+
+Read the diagram for what is *absent* as much as what is present: no arrow ever
+runs from **P** to **API**, and no credential ever travels leftward past **B**.
+The plugin's only edge is to its own preload; every hop beyond that is main
+acting on the user's behalf.
+
+Three further properties fall out of this shape and are worth stating explicitly:
+
+- **The plugin never talks to control-api on the user's behalf.** It talks to
+ main; main talks to control-api with the user's own session token; only the
+ minimized result crosses back. The user's ACL is enforced upstream exactly as
+ it is for the Desktop's own pages.
+- **One chokepoint.** Adding a capability cannot accidentally skip the consent
+ check or the audit write, because there is no second code path.
+- **Identity of the caller is not self-asserted.** The plugin does not send its
+ own id; main derives it from the sender's `webContents.id` (§8.1).
+
+## 5. Wire protocol
+
+### 5.1 Envelope
+
+One invoke channel carries every capability call:
+
+```ts
+// desktop-app/src/pluginSdkProtocol.ts (shared main ⇄ preload types)
+
+export const PLUGIN_SDK_REQUEST_CHANNEL = 'clerum:plugin-sdk:request'
+export const PLUGIN_SDK_PERMISSIONS_CHANNEL = 'clerum:plugin-sdk:request-permissions'
+export const PLUGIN_SDK_EVENT_CHANNEL = 'clerum:plugin-sdk:event'
+export const PLUGIN_SDK_VERSION = '1.0.0'
+
+export type PluginSdkRequest = {
+ /** Protocol version the embed was built against. Major mismatch → error. */
+ v: 1
+ /** Capability id, e.g. 'identity.read'. See §6. */
+ capability: string
+ /** Capability-specific params. Validated per descriptor; unknown keys rejected. */
+ params?: Record<string, unknown>
+}
+
+export type PluginSdkResponse<T = unknown> =
+ | { ok: true; data: T }
+ | { ok: false; error: PluginSdkError }
+
+export type PluginSdkError = {
+ code: PluginSdkErrorCode
+ /** Safe for the plugin to display. Never contains upstream internals. */
+ message: string
+ /** True when a later identical call may succeed without user action. */
+ retryable: boolean
+}
+
+/**
+ * Batched consent. One call, one modal, one decision per capability.
+ * This is the intended way a plugin acquires permissions (§9.2).
+ */
+export type PluginSdkPermissionsRequest = {
+ v: 1
+ /** 1–8 capability ids. Duplicates and unknown ids are rejected up front. */
+ capabilities: string[]
+}
+
+export type PluginSdkPermissionsResult = {
+ /** capability id → granted. Every requested id is present. */
+ granted: Record<string, boolean>
+ /** True when the user allowed every requested capability. */
+ all: boolean
+}
+```
+
+The bridge **resolves** with the envelope and never rejects. Electron serializes
+a thrown `Error` down to its message string, which loses the error code; an
+explicit envelope keeps `code` machine-readable. The optional npm wrapper (§7.3)
+re-throws typed errors for authors who prefer `try/catch`.
+
+`requestPermissions` returns a **map, not an error**, even when the user declines
+everything — "the user said no to two of these" is a normal outcome the plugin
+must render, not an exceptional one. Individual capability calls still return
+`permission_denied` per §5.2.
+
+### 5.2 Error codes
+
+| Code | Meaning | `retryable` |
+|---|---|---|
+| `unsupported_capability` | Unknown id, or a capability this host build does not implement. | false |
+| `unsupported_version` | `v` is not a version this host speaks. | false |
+| `invalid_request` | Params failed the descriptor's validator (unknown key, wrong type, over a length cap). | false |
+| `unauthenticated` | No Desktop session (user logged out, or logged out mid-call). | true |
+| `permission_denied` | The user denied this capability, or the prompt timed out (§9.3). | true |
+| `permission_revoked` | A grant existed and was revoked; distinct from `permission_denied` so a plugin can show "access was removed" rather than re-prompting. | true |
+| `rate_limited` | Per-plugin or per-capability budget exhausted. Carries a `retryAfterMs` hint in `message`. | true |
+| `not_found` | The referenced resource (e.g. a `gfs://` URI) does not exist or the user cannot see it. Deliberately conflated — see §12. | false |
+| `payload_too_large` | The result exceeds the capability's response cap (§6.8). | false |
+| `unavailable` | Upstream (control-api / external-rest-api / gfsc) failed. | true |
+| `internal` | Anything else. Details go to the desktop log, not to the plugin. | true |
+
+### 5.3 Events
+
+Events are pushed on `clerum:plugin-sdk:event`, only ever to a pinned sender:
+
+```ts
+export type PluginSdkEvent =
+ | { type: 'theme.changed'; theme: PluginTheme }
+ | { type: 'permission.changed'; capability: string; granted: boolean }
+ | { type: 'session.changed'; authenticated: boolean }
+ // Pre-existing, kept on its own legacy channel for compatibility (§7.2):
+ // clerum:sandbox-ui:oauth-completed
+```
+
+`permission.changed` is what makes revocation feel immediate: the Settings page
+revokes, main invalidates its in-memory grant cache and emits the event, and a
+well-written plugin drops back to its unauthenticated rendering without the user
+having to reload it.
+
+Events are **not** a capability — subscribing is free. But an event only fires
+for a capability whose data the plugin could already have obtained:
+`theme.changed` always fires (theme is unscoped, §6.7), `permission.changed`
+fires only about that plugin's own grants, `session.changed` carries a boolean
+and nothing else.
+
+## 6. Capability catalog
+
+Every capability is one immutable descriptor:
+
+```ts
+export type CapabilityDescriptor<P, R> = {
+ id: string
+ /** Copy shown in the consent prompt. */
+ consent: {
+ /** "See who you are" */
+ title: string
+ /** "Your name, email address, and user id." */
+ dataDescription: string
+ /** Sensitivity drives prompt styling and audit verbosity. */
+ tier: 'personal' | 'workspace' | 'ambient'
+ }
+ /** 'ambient' capabilities skip the prompt entirely (§6.7). */
+ requiresConsent: boolean
+ validate: (raw: unknown) => P
+ provider: (ctx: ProviderContext, params: P) => Promise<R>
+ /** Strip everything the plugin does not need before it crosses the bridge. */
+ minimize: (raw: R) => unknown
+ limits: { perMinute: number; perHour: number; maxResponseBytes: number }
+}
+```
+
+### 6.1 `identity.read` — who the user is
+
+> **Prompt:** "**{Plugin}** wants to see who you are — your name, email address,
+> and user id." Tier: `personal`.
+
+```ts
+type IdentityReadResult = {
+ userId: string // SessionMe.id
+ email: string // SessionMe.email
+ name: string | null // SessionMe.name
+}
+```
+
+Source: `AppService.getSessionState()` → `SessionMe`
+(`desktop-app/src/types.ts:31`).
+
+`picture` is **omitted**. It is a remote URL, and the embed's CSP is
+`img-src 'self' data:` — the plugin could not render it anyway, so shipping it
+would leak an identifier for zero benefit. If avatars are ever wanted, they come
+back as a `data:` URI through a separate capability, not as a URL here.
+
+### 6.2 `org.read` — the current workspace
+
+> **Prompt:** "**{Plugin}** wants to see your current team — its name and your
+> role in it." Tier: `workspace`.
+
+```ts
+type OrgReadResult = {
+ teamId: string | null
+ teamName: string | null
+ role: 'owner' | 'admin' | 'member' | string | null
+}
+```
+
+Source: `SessionMe.teamId / teamName / role`, with `AppService.listTeams()` as
+the fallback when the session payload is stale.
+
+**Team switching:** grants are keyed by `userId`, not by team (§10.2). After
+`AppService.switchTeam()`, an already-granted `org.read` returns the *new* team
+without re-prompting. That is intentional — the consent was "see which workspace
+I am in", and the answer changed. A `session.changed` event fires so the plugin
+can refetch.
+
+### 6.3 `agents.read` — agents the user can reach
+
+> **Prompt:** "**{Plugin}** wants to see the agents you have access to — their
+> names and which MCP servers they use." Tier: `workspace`.
+
+```ts
+type AgentsReadResult = {
+ agents: Array<{
+ /** Stable grant-target id when the server supplied one, else `name`. */
+ id: string
+ name: string
+ contextRef: string | null
+ provider: string | null
+ mcpServers: string[] // names only
+ }>
+}
+```
+
+Source: `AppService.listMyAgents()` → `AgentWithMcpServers[]`
+(`desktop-app/src/types.ts:375`), served fresh from `GET /me/agents`.
+`id` is `gfsSubject.id` (`1st:<ns>/<name>`) when present, else `name` — which
+also satisfies the "agent id and name" requirement without a second capability.
+
+`minimize` flattens `mcpServers: Array<{name}>` to `string[]` and drops
+`gfsSubject.type`.
+
+### 6.4 `contexts.read` — contexts the user can reach
+
+> **Prompt:** "**{Plugin}** wants to see the contexts you have access to."
+> Tier: `workspace`.
+
+```ts
+type ContextsReadResult = {
+ contexts: Array<{ id: string; scope: 'user' | 'team' }>
+}
+```
+
+Source: `AppService.getAccessCatalog()` → `AccessCatalog.userContextIds` /
+`teamContextIds` (`desktop-app/src/types.ts:413`). `scope` is derived from which
+list the id came from; ids present in both report `'user'`.
+
+### 6.5 `mcp.read` — MCP servers the user can invoke
+
+> **Prompt:** "**{Plugin}** wants to see the MCP servers you have access to."
+> Tier: `workspace`.
+
+```ts
+type McpReadResult = {
+ servers: Array<{ name: string; agents: string[] }>
+}
+```
+
+Source: `AppService.listAccessibleMcpServers()` → `RpcAllowedServersResult`
+(`desktop-app/src/types.ts:457`), joined with `AccessCatalog.mcpServersByAgent`
+to fill `agents`.
+
+`minimize` **drops every `url`**. A server's cluster-internal URL is
+infrastructure detail the embed has no use for (CSP `connect-src 'self'` means it
+cannot call it) and is exactly the kind of thing that turns a read capability
+into a lateral-movement hint.
+
+### 6.6 `gfs.list` and `gfs.read` — Global File System
+
+Two capabilities, because listing what exists and reading bytes are different
+risks and deserve different prompts.
+
+> **`gfs.list` prompt:** "**{Plugin}** wants to see the shared files you have
+> access to — their names, folders, and sizes. It will not be able to open
+> them." Tier: `workspace`.
+
+```ts
+type GfsListParams = { drive?: string; resourceId?: string; cursor?: string }
+type GfsListResult = {
+ items: Array<{
+ resourceId: string
+ gfsUri: string
+ name: string
+ kind: 'file' | 'directory'
+ bytes: number | null
+ version: number
+ }>
+ nextCursor: string | null
+}
+```
+
+Source: `AppService.listAccessibleGfsResources()` (no `resourceId`) or
+`AppService.listGfsChildren()` (with one).
+
+> **`gfs.read` prompt:** "**{Plugin}** wants to open shared files you have access
+> to. It will be able to read the contents of any file you can read." Tier:
+> `personal` — content is materially more sensitive than a file listing.
+
+```ts
+type GfsReadParams = {
+ uri: string // gfs://<drive>/<resource>
+ as: 'text' | 'dataUrl'
+}
+type GfsReadResult = {
+ gfsUri: string
+ name: string
+ mimeType: string
+ bytes: number
+} & ({ as: 'text'; text: string } | { as: 'dataUrl'; dataUrl: string })
+```
+
+Source: `AppService.downloadGfsUri()` → `{ resource, bytes }`, which resolves the
+URI through the API on every call (no local mirror) so a revoked GFS grant denies
+immediately at the server, independent of SDK consent.
+
+**Image rendering (the "render an image from GFS" requirement) is `gfs.read` with
+`as: 'dataUrl'`.** The embed's CSP is `img-src 'self' data:` — `blob:` is *not*
+in the list, so an object URL would be blocked. The contract is therefore a
+`data:` URI the plugin drops straight into `<img src>`:
+
+```js
+const res = await window.clerum.gfs.read({ uri: 'gfs://main/reports/chart.png', as: 'dataUrl' })
+if (res.ok) document.querySelector('#chart').src = res.data.dataUrl
+```
+
+Rules for `as: 'dataUrl'`:
+
+- MIME allowlist: `image/png`, `image/jpeg`, `image/gif`, `image/webp`,
+ `image/avif`. **`image/svg+xml` is refused** (`invalid_request`) — an SVG in
+ `<img>` cannot execute script, but it can reference external resources and it
+ is a persistent parser-bug surface; a plugin that wants vector art can ship it
+ in its own bundle.
+- Size cap: reuse the existing preview ceiling (`ui/src/lib/gfsImagePreview.ts`,
+ `assertGfsImagePreviewSize`) so the SDK and the Desktop's own previewer agree.
+ Over the cap → `payload_too_large`.
+- The MIME type is taken from the resolved resource and re-checked against the
+ actual magic bytes before encoding. A file named `.png` whose bytes are not a
+ PNG is refused.
+
+`as: 'text'` has its own cap (§6.8) and refuses non-UTF-8 bytes.
+
+### 6.7 `theme.read` — Desktop appearance (unscoped)
+
+> No prompt. Tier: `ambient`, `requiresConsent: false`.
+
+```ts
+type ThemeReadResult = { theme: 'light' | 'dark' }
+```
+
+This is the one capability that does not prompt, and the exception needs a stated
+principle rather than a shrug: **`requiresConsent: false` is permitted only when
+the response contains no information about the user, their org, or their data —
+only about the Desktop's own presentation.** Theme qualifies. It is still logged
+in the audit trail at `debug` verbosity, and it is still listed on the plugin's
+Settings row as "Appearance (no permission needed)" so the user is never
+surprised to learn a plugin knows their theme.
+
+**Implementation note — theme currently lives in the wrong process.** The
+renderer owns it: `App.tsx` reads/writes `localStorage['evenfire.ui.theme']`
+(`ui/src/constants/theme.ts`) and sets `data-theme` on `documentElement`. Main
+has no idea what the theme is. This capability therefore requires lifting theme
+into main as the source of truth (`themeStore.ts`, persisted alongside other
+desktop preferences), with the renderer reading it over IPC on boot and pushing
+changes back. The `theme.changed` event (§5.3) then fans out to any mounted
+embed. This is real work, not a lookup, and it is on the critical path for
+milestone M3 (§15).
+
+### 6.8 `notifications.notify` — get the user's attention
+
+> **Prompt:** "**{Plugin}** wants to send you notifications." Tier: `workspace`.
+
+```ts
+type NotifyParams = {
+ title: string // ≤ 120 chars, plain text
+ body?: string // ≤ 400 chars, plain text
+ /** Opaque to the host; echoed back on click so the plugin can route. */
+ ref?: string // ≤ 256 chars
+}
+type NotifyResult = { delivered: boolean; reason?: 'suppressed' | 'unsupported' }
+```
+
+Behaviour:
+
+- Routes to the **existing** native notification path (`notifications:show` in
+ `desktop-app/src/ipc.ts`), plus an in-app badge on the plugin's entry in the
+ app rail so an attention request is not lost when OS notifications are off.
+- The notification is **always attributed**: the title is rendered as
+ `{Plugin title} — {title}`, so a plugin cannot impersonate Evenfire itself or
+ another plugin.
+- Plain text only. Title and body are stripped of control characters and never
+ interpreted as markup.
+- **Suppressed when the plugin's own embed is mounted, visible, and its window
+ focused** — the user is already looking at it. Returns
+ `{ delivered: false, reason: 'suppressed' }` rather than an error.
+- Clicking focuses the Desktop window, navigates to that plugin, and delivers a
+ `{ type: 'notification.clicked', ref }` event to the embed if it is mounted.
+- Rate limits are deliberately the tightest in the catalog (§6.9). This is the
+ only capability that can produce OS-level noise.
+
+### 6.9 Limits
+
+| Capability | per min | per hour | max response |
+|---|---|---|---|
+| `identity.read` | 10 | 60 | 4 KB |
+| `org.read` | 10 | 60 | 4 KB |
+| `agents.read` | 10 | 120 | 256 KB |
+| `contexts.read` | 10 | 120 | 64 KB |
+| `mcp.read` | 10 | 120 | 128 KB |
+| `gfs.list` | 30 | 600 | 512 KB |
+| `gfs.read` | 20 | 300 | image cap (§6.6) / 2 MB text |
+| `theme.read` | 60 | 600 | 1 KB |
+| `notifications.notify` | 2 | 20 | — |
+
+Plus a **global per-plugin ceiling** of 120 requests/minute across all
+capabilities, so a plugin cannot round-robin its way past the per-capability
+budgets. Budgets are token buckets keyed by `(pluginId, capability)`, reset on
+unmount.
+
+Results are cached in main for a short TTL (identity/org/theme: 60 s; agents,
+contexts, mcp: 30 s; gfs: none) so a chatty plugin polling `identity.read` does
+not turn into upstream load. A cache hit is still rate-limited and still audited.
+
+## 7. The plugin-facing API
+
+### 7.1 Injected global
+
+The embed preload keeps exposing `window.clerum` and gains namespaces. Every
+method returns `Promise<PluginSdkResponse<T>>`:
+
+```ts
+window.clerum = {
+ // ── existing, unchanged (§7.2) ────────────────────────────────
+ requestSessionRefresh(): Promise<void>
+ onOauthCompleted(cb: (p: { oauthClientId: string; provider: string }) => void): () => void
+
+ // ── SDK ───────────────────────────────────────────────────────
+ sdk: {
+ version: '1.0.0'
+ /** Capability ids this host build implements. No consent, no user data. */
+ capabilities(): Promise<PluginSdkResponse<{ capabilities: string[] }>>
+ /** Ask for several capabilities in ONE prompt. The intended entry point (§9.2). */
+ requestPermissions(
+ capabilities: string[]
+ ): Promise<PluginSdkResponse<PluginSdkPermissionsResult>>
+ /** Which of these are already granted? No prompt, no user data. */
+ permissions(
+ capabilities?: string[]
+ ): Promise<PluginSdkResponse<{ granted: Record<string, boolean> }>>
+ on(cb: (e: PluginSdkEvent) => void): () => void
+ }
+ identity: { get(): Promise<PluginSdkResponse<IdentityReadResult>> }
+ org: { get(): Promise<PluginSdkResponse<OrgReadResult>> }
+ agents: { list(): Promise<PluginSdkResponse<AgentsReadResult>> }
+ contexts: { list(): Promise<PluginSdkResponse<ContextsReadResult>> }
+ mcp: { list(): Promise<PluginSdkResponse<McpReadResult>> }
+ gfs: {
+ list(p?: GfsListParams): Promise<PluginSdkResponse<GfsListResult>>
+ read(p: GfsReadParams): Promise<PluginSdkResponse<GfsReadResult>>
+ }
+ theme: { get(): Promise<PluginSdkResponse<ThemeReadResult>> }
+ notifications: { notify(p: NotifyParams): Promise<PluginSdkResponse<NotifyResult>> }
+}
+```
+
+`sdk.capabilities()` exists so a plugin can degrade gracefully on an older
+Desktop build instead of hard-failing on `unsupported_capability`.
+`sdk.permissions()` lets a plugin check state on every boot without prompting —
+after the first run, a returning user should see the plugin's full UI with no
+modal at all.
+
+The intended startup shape, for the common plugin that needs several
+capabilities to be useful at all:
+
+```js
+const need = ['identity.read', 'org.read', 'agents.read', 'gfs.list']
+
+const have = await window.clerum.sdk.permissions(need)
+const missing = need.filter(c => !have.data.granted[c])
+
+if (missing.length) {
+ const res = await window.clerum.sdk.requestPermissions(missing) // ONE modal
+ if (!res.ok || !res.data.all) return renderSetupNeeded(res.data?.granted)
+}
+renderDashboard()
+```
+
+Everything is `Object.freeze`d at the contextBridge boundary, as today.
+
+### 7.2 Backward compatibility
+
+`requestSessionRefresh` and `onOauthCompleted` keep their current names,
+signatures, and IPC channels (`clerum:sandbox-ui:request-refresh`,
+`clerum:sandbox-ui:oauth-completed`). Existing plugins keep working with no
+change. The OAuth completion event is **not** folded into the new event channel
+in v1 — moving it would break every shipped recipe that listens for it.
+
+### 7.3 Optional npm wrapper
+
+`@evenfire/plugin-ui-sdk` — a dependency-free typed wrapper the author bundles
+(CSP forbids CDN scripts, so it must be bundled, never `<script src>`-ed):
+
+```ts
+import { createClient, PluginPermissionError } from '@evenfire/plugin-ui-sdk'
+
+const evenfire = createClient() // throws if not running inside Evenfire
+
+// One modal for everything this plugin needs, only for what is still missing.
+const { all, granted } = await evenfire.ensurePermissions([
+ 'identity.read', 'org.read', 'agents.read', 'gfs.list',
+])
+if (!all) return renderSetupNeeded(granted)
+
+try {
+ const me = await evenfire.identity.get() // unwrapped; throws typed errors
+ greet(me.name ?? me.email)
+} catch (err) {
+ if (err instanceof PluginPermissionError) showConnectPrompt()
+}
+```
+
+`ensurePermissions()` is the wrapper's one piece of real logic: it calls
+`sdk.permissions()` first and only opens a prompt for the ids still missing, so a
+returning user never sees a modal. Everything else is convenience — the `.d.ts`,
+envelope unwrapping, typed errors, `isAvailable()`. The injected global remains
+the actual contract, so a plugin with no build step can use the SDK directly.
+
+## 8. Caller identity and trust
+
+### 8.1 How main knows which plugin is calling
+
+The plugin does **not** identify itself. Main derives it:
+
+```
+mountSandboxUiView() → pluginSurfaceRegistry.pin(webContents.id, {
+ pluginId: `${recipeNs}/${recipeName}`,
+ surface: 'sandbox-ui-embed',
+ title, generation })
+teardownActive() → pluginSurfaceRegistry.unpin(webContents.id)
+```
+
+On every request, `resolveCaller(event.sender.id)` looks up the pinning map. An
+unpinned sender is rejected with `internal` and logged loudly — it means either a
+bug or a sender that should not be reaching this channel at all.
+
+This is the same pattern already proven for the refresh IPC
+(`desktop-app/src/sandboxUiSessionRefresh.ts`: `senderToRefreshContext`,
+`handleEmbedRefreshRequest`), generalized so it can hold more than one surface
+(§14). Note the deliberate asymmetry with the rest of the IPC surface: these
+handlers must **not** call `assertTrustedSender` (the embed loads from the
+rpc-proxy origin, not `file://`), which is exactly why the pinning map is the
+trust check. `desktop-app/src/ipc.ts:1414-1423` documents this today; the new
+handler carries the same comment.
+
+Properties:
+
+- A plugin cannot claim to be another plugin: the id comes from the mount, not
+ the message.
+- A torn-down embed is unpinned before its renderer finishes dying, so late
+ in-flight IPC from a closed plugin is rejected.
+- The `generation` counter guards the mount race the driver already handles
+ (`mountGeneration` in `sandboxUiDriver.ts`): a request from generation N is
+ dropped once generation N+1 has mounted.
+
+### 8.2 What never crosses the bridge
+
+Session tokens, RPC tokens, OAuth access/refresh tokens, the broker token,
+cookie values, MCP server URLs, cluster-internal FQDNs, other users' data, other
+plugins' grants, raw upstream error bodies.
+
+A `minimize()` function is **mandatory** on every descriptor — not optional with
+a passthrough default — so adding a capability forces an explicit decision about
+what the plugin sees. Reviewers should treat a `minimize` that returns its input
+unchanged as a finding.
+
+## 9. Consent
+
+### 9.1 State
+
+One row per `(envKey, userId, pluginId, capability)`:
+
+```ts
+type ConsentGrant = {
+ envKey: string // partitionFor()'s env scoping, from config.getActiveEnvKey()
+ userId: string
+ pluginId: string // '<recipeNs>/<recipeName>'
+ capability: string
+ grantedAt: string // ISO 8601
+ lastUsedAt: string | null
+ /** Bumped when the descriptor's data shape widens (§9.6). */
+ descriptorVersion: number
+ revision: number // monotonic, for the v2 sync merge (§10.6)
+}
+```
+
+Absence of a row = not granted. There is no `denied` row — see §9.3.
+
+### 9.2 Flow — batched consent is the primary path
+
+Most plugins need several capabilities before they can render anything useful; a
+CRM dashboard with no identity, no agents, and no files is a blank page. Asking
+for those one modal at a time is both worse UX and, under the §9.5 budget,
+self-defeating. **The unit of consent is therefore the prompt, not the
+capability**: one call, one modal, one decision per row.
+
+```
+embed → clerum.sdk.requestPermissions(
+ ['identity.read', 'org.read', 'agents.read', 'gfs.list'])
+ broker: pinned? → yes, pluginId = sandbox-recipes/leadforge
+ broker: every id known + ≤8 + no duplicates else invalid_request
+ broker: session present else unauthenticated
+ broker: drop ids already granted / already session-denied
+ broker: prompt budget ok (§9.5)
+ broker: consentGate.promptBatch(...)
+ → main: sandboxUi.setVisible(false) [embed hidden]
+ → main → renderer: 'pluginSdk:consentRequested'
+ { promptId, pluginId, pluginTitle, pluginIcon,
+ rows: [{ capability, title, dataDescription, tier }, …] }
+ → renderer renders PluginConsentModal — every row checked by default,
+ each independently uncheckable, one Allow button
+ → user unchecks 'gfs.list', clicks Allow
+ → renderer → main: 'pluginSdk:resolveConsent' [assertTrustedSender]
+ { promptId, allowed: ['identity.read','org.read','agents.read'] }
+ → main: consentStore.put() × 3
+ sessionDenials.add('gfs.list')
+ auditLog.append() × 4 [one line per row]
+ → main: sandboxUi.setVisible(true) [embed restored]
+embed ← { ok: true, data: { granted: { 'identity.read': true, 'org.read': true,
+ 'agents.read': true, 'gfs.list': false }, all: false } }
+
+… later …
+embed → clerum.identity.get()
+ broker: consentStore.get(...) → hit, no prompt
+ broker: provider() → SessionMe ; minimize() → { userId, email, name }
+ broker: auditLog.append('allowed', { fields: ['userId','email','name'] })
+embed ← { ok: true, data: { … } }
+```
+
+**Rows are individually declinable, and the plugin cannot mark any of them
+required.** A plugin that genuinely needs all four is free to say so in its own
+UI after the fact ("LeadForge needs access to your files to show the pipeline") —
+what it must not do is borrow the *host's* chrome to apply that pressure. A
+"Required" badge rendered by Evenfire in Evenfire's modal reads as the platform
+vouching for the demand, and once one plugin gets it every plugin marks
+everything required. The all-or-nothing conversation belongs in the plugin's own
+pixels, where the user can tell who is asking.
+
+Modal anatomy:
+
+```
+┌──────────────────────────────────────────────────────────────┐
+│ [icon] LeadForge wants access to your information │
+│ │
+│ ☑ See who you are │
+│ Your name, email address, and user id. │
+│ ☑ See your current team │
+│ Its name and your role in it. │
+│ ☑ See the agents you have access to │
+│ Their names and which MCP servers they use. │
+│ ☐ See the shared files you have access to │
+│ Their names, folders, and sizes. It will not be able │
+│ to open them. │
+│ │
+│ You can change this any time in Settings → Plugin │
+│ permissions. │
+│ [ Deny ] [ Allow ] │
+└──────────────────────────────────────────────────────────────┘
+```
+
+`dataDescription` is rendered verbatim from the descriptor, so the sentence the
+user reads here is byte-identical to the one the Settings page shows them later.
+Rows are ordered `personal` first, then `workspace`, then `ambient` — the most
+sensitive ask should not be the one buried at the bottom of a long modal.
+**Deny** clears every row and closes.
+
+A single capability call on an ungranted capability still prompts, for one row.
+That path exists for the capability a plugin discovers it needs mid-session
+(a `gfs.read` when the user clicks a file), not as the normal way to acquire the
+startup set.
+
+### 9.3 Denial semantics
+
+D4 makes *grants* permanent-until-revoked. Denials are deliberately weaker:
+
+- **Deny** records no row — including a row left unchecked in a batch prompt. It
+ adds `(pluginId, capability)` to an in-memory `sessionDenials` set, cleared
+ when the embed unmounts or the app quits.
+- While denied, the capability returns `permission_denied` **immediately**, with
+ no prompt. This is the anti-prompt-spam mechanism (§12, T4): one denial buys
+ silence for the rest of the session.
+- Reopening the plugin gives it one more chance to ask. That is the escape hatch
+ for a mis-click, and the reason no "never ask again" checkbox is needed in v1:
+ the user can simply not press Allow.
+- A prompt that times out (120 s) or is dismissed with Escape counts as a
+ denial.
+
+### 9.4 Spoof resistance
+
+The prompt renders in the trusted renderer, but a `WebContentsView` always paints
+above renderer DOM regardless of z-index — a plugin could otherwise paint a fake
+modal, or paint over the real one. Mitigations, all required:
+
+1. **Hide the embed for the duration of the prompt** via the existing
+ `setSandboxUiVisible(false)` path (`ui/src/pages/SandboxUiPage.tsx:387` already
+ does this for overlays). The plugin cannot render anything while the modal is
+ up.
+2. **Main owns the prompt text.** The renderer receives a `capability` id and
+ renders copy from its own catalog; no plugin-supplied string reaches the
+ modal except the plugin's own title and icon, both from the recipe's
+ installed metadata (never from an SDK call), both truncated and rendered as
+ text.
+3. **`promptId` is a main-generated nonce.** A resolve for an unknown, stale, or
+ already-resolved `promptId` is dropped.
+4. **The resolve channel is `assertTrustedSender`-guarded**, so the embed cannot
+ answer its own prompt even if it could reach the channel.
+5. **One prompt at a time, globally.** Concurrent requests queue. A capability
+ already represented as a row in the in-flight prompt joins that prompt rather
+ than opening a second one, so a plugin that fires `requestPermissions([…])`
+ and an eager `identity.get()` in the same tick gets one modal, not two.
+6. **The prompt requires a focused, visible Desktop window.** If the window is
+ hidden or unfocused, the request parks (up to the 120 s timeout) rather than
+ racing a modal onto a screen the user is not looking at.
+
+### 9.5 Prompt budget
+
+D2 (no CRD declaration) means a hostile plugin can ask for anything. Beyond
+session-sticky denial, the gate enforces:
+
+- At most **3 consent prompts (modals) per plugin per mount**, and at most **8
+ capability rows** in any one of them. The budget counts *modals*, not
+ capabilities — a plugin asking for its whole startup set in one batch spends
+ one of three, which is why §9.2's batched path is the sanctioned one and a
+ per-capability drip is not. Beyond the budget, ungranted capabilities return
+ `permission_denied` until the user reopens the plugin.
+- A **10 s cooldown** between modals, so a plugin cannot chain them fast enough
+ to train the user into reflexive clicking.
+- The modal shows a persistent "This plugin has asked for permissions N times
+ this session" line from the second prompt onward.
+
+Batching moves the pressure from *volume* to *breadth*: instead of four modals a
+hostile plugin now writes one modal with eight rows. That is the better failure
+mode — a single screen listing everything a plugin wants is exactly the artifact
+a user can evaluate, and an eight-row modal from a note-taking plugin looks
+wrong in a way that four modals spread over thirty seconds does not.
+
+### 9.6 Descriptor versioning
+
+If a capability's payload later widens (say `identity.read` starts returning a
+phone number), the descriptor's `descriptorVersion` increments. Grants at a
+lower version **do not** cover the wider payload: the gate re-prompts with copy
+that names the new field. Silently widening what an existing grant covers is the
+single easiest way to turn a consent system into theatre, so the version check
+is a hard requirement, not a nicety.
+
+## 10. Storage
+
+### 10.1 Interface
+
+```ts
+export interface ConsentStore {
+ list(envKey: string, userId: string): Promise<ConsentGrant[]>
+ get(k: GrantKey): Promise<ConsentGrant | null>
+ put(g: ConsentGrant): Promise<void>
+ revoke(k: GrantKey): Promise<void>
+ revokeAllForPlugin(envKey: string, userId: string, pluginId: string): Promise<void>
+ /** v2 hook, unused by the local impl. */
+ sync?(envKey: string, userId: string): Promise<void>
+}
+```
+
+### 10.2 Local implementation (v1)
+
+- File: `<userData>/plugin-consent/<envKey>.json`, mode `0600`, written
+ atomically (temp file + rename), one file per environment — mirroring how
+ `tokenStore.ts` scopes secrets and `partitionFor()` scopes partitions by
+ `envKey`. Cluster A's grants never leak into cluster B's.
+- Keyed by `userId` inside the file, so a shared machine with two accounts keeps
+ grants separate.
+- `envKey` is validated with the same `ENV_KEY_SHAPE` guard `tokenStore.ts` uses
+ before it is interpolated into a path.
+- **Not encrypted.** Grants are not secrets — they are a list of "plugin X may
+ read Y". Encrypting them with `safeStorage` would buy nothing against an
+ attacker with local file access (who could just edit the plaintext audit log
+ or the app bundle) while adding a failure mode on platforms where `safeStorage`
+ is unavailable. The file being world-unreadable is the protection.
+- Schema carries `{ version: 1, users: { [userId]: ConsentGrant[] } }`. An
+ unreadable or version-newer file is treated as **empty** (fail closed: every
+ capability re-prompts) and moved aside, never partially parsed.
+- In-memory cache in front, invalidated on write and on revocation, so the hot
+ path is not a file read.
+
+### 10.3 Audit log
+
+- File: `<userData>/plugin-audit/<envKey>.jsonl`, append-only, mode `0600`.
+- One line per decision:
+
+```json
+{"ts":"2026-08-06T10:14:02.113Z","userId":"u_123","pluginId":"sandbox-recipes/leadforge",
+ "capability":"identity.read","outcome":"allowed","consent":"existing_grant",
+ "shape":{"fields":["userId","email","name"]},"bytes":142,"surface":"sandbox-ui-embed"}
+```
+
+- **Records shape, never content.** `fields` for objects, `count` for lists,
+ `bytes` for blobs. The audit log must never become a second copy of the user's
+ email, their file contents, or their agent names — a log that reproduces the
+ data it is auditing is a liability, not a control.
+- `outcome ∈ allowed | denied | revoked_mid_flight | rate_limited | error`.
+ `consent ∈ existing_grant | prompt_allowed | prompt_denied | not_required`.
+- Rotation at 5 MB or 90 days, whichever first; one `.1` generation kept.
+- `ambient` capabilities are recorded at `debug` verbosity and excluded from the
+ Settings view by default (a `theme.read` every second would drown the log the
+ user actually cares about), but they are still on disk.
+
+### 10.4 What is *not* stored
+
+Prompt decisions of `deny` (in-memory only, §9.3), request params, response
+payloads, and any bearer material.
+
+### 10.5 Logout, uninstall, environment switch
+
+- **Logout:** grants are retained, keyed by `userId`. Logging back in as the same
+ user restores them; a different user starts clean. In-flight SDK calls fail
+ `unauthenticated` and a `session.changed` event fires.
+- **Plugin uninstalled / access revoked (Members tab):** the next launch's
+ partition GC pass (`sandboxUiPartitionGc.ts`) already walks partitions the user
+ no longer has ACL for. The consent store hooks the same pass and drops grants
+ for plugins the user can no longer see. Until then a stale grant is harmless —
+ the plugin cannot be mounted.
+- **Environment switch:** different `envKey`, different file, no crossover.
+
+### 10.6 Path to server-side sync (v2)
+
+The interface above is the whole v1 obligation; this is the sketch it must not
+foreclose.
+
+- control-api gains `GET/PUT/DELETE /api/v1/me/plugin-consent`, rows scoped to
+ `(userId, pluginId, capability)` with a monotonic `revision`.
+- `RemoteConsentStore` implements the same interface; `SyncingConsentStore`
+ composes local + remote with local-first reads (so the SDK works offline) and
+ last-writer-wins by `revision`, except that **a revocation always wins over a
+ concurrent grant** — the safe direction for a security-relevant merge.
+- The audit log gains an optional shipper to the same endpoint so operators can
+ see org-wide plugin behaviour.
+- **No change to the IPC contract, the descriptors, or the prompt.** That is the
+ test of whether this spec's layering is right: v2 should touch
+ `pluginConsentStore.ts` and nothing the plugin can observe.
+
+## 11. Revocation UI
+
+New Settings section: **Settings → Plugin permissions**
+(`ui/src/pages/SettingsPage.tsx`, following the `.page-card` conventions in
+`desktop-app/ui/AGENTS.md` — `da-grid` for the listing, `Common` controls, no new
+CSS files).
+
+**Plugin list** — one row per plugin holding ≥1 grant:
+
+| Plugin | Permissions | Last used | |
+|---|---|---|---|
+| LeadForge | Identity · Agents · Shared files | 2 minutes ago | ⋯ |
+| Sales CRM | Identity · Notifications | yesterday | ⋯ |
+
+Row expands to per-capability detail: the human title, the same
+`dataDescription` string the prompt showed (so the user is re-reading exactly
+what they agreed to, not a paraphrase), `grantedAt`, `lastUsedAt`, and a
+**Revoke** button. Row menu offers **Revoke all for this plugin**.
+
+Empty state: "No plugin has been granted access to your information."
+
+**Activity** — a tab over the audit log, newest first, filterable by plugin and
+by outcome, showing timestamp / plugin / capability / outcome / shape summary.
+Denials and rate-limits are included: a plugin that repeatedly asks for things
+the user refuses is exactly what a user should be able to notice. "Reveal log
+file" opens the containing folder.
+
+Revocation is immediate:
+
+1. `consentStore.revoke(key)`, cache invalidated.
+2. `permission.changed { capability, granted: false }` to the plugin if mounted.
+3. Any in-flight request for that capability resolves `permission_revoked`.
+4. Audit line with `outcome: 'revoked'`.
+
+The plugin is **not** reloaded or unmounted. A plugin should handle losing a
+permission the way it handles never having had it; forcing a reload would be a
+worse experience for the many well-behaved plugins to marginally inconvenience
+the rare misbehaving one.
+
+## 12. Threat model
+
+| # | Threat | Mitigation |
+|---|---|---|
+| T1 | Plugin claims to be a different plugin to reuse its grants. | Caller identity from the pinning map, never from the message (§8.1). |
+| T2 | Plugin reads context without consent. | Deny by default; the broker is the only path and consent precedes the provider call (§4). |
+| T3 | Plugin paints a fake permission dialog to phish an approval. | Embed hidden during prompts; main owns prompt copy; nonce'd `promptId`; trusted-sender resolve (§9.4). |
+| T4 | Prompt fatigue — plugin spams modals until the user clicks Allow. | 3 prompts/mount, 10 s cooldown, session-sticky denial, prompt-count line in the modal (§9.5). |
+| T5 | Plugin exfiltrates context to a third party. | Not preventable at this layer and the spec should say so plainly: once a plugin legitimately holds the user's email, it can POST it to its own backend (its own origin is allowed by `connect-src 'self'`). The mitigations are *disclosure* (the prompt states what is shared), *attribution* (the audit log records who got what), and *revocation*. Users grant to a plugin they chose to install; the SDK makes that grant visible and reversible, it does not make it enforceable after the fact. |
+| T6 | Escalation via SDK past the user's own ACL. | Every provider calls an `AppService` method with the user's session; upstream authorizes exactly as it does for the Desktop's own pages. The SDK can only ever return a subset. |
+| T7 | Resource exhaustion (polling, huge GFS reads). | Per-capability + global token buckets, response caps, short-TTL caching (§6.9). |
+| T8 | Data leak through error messages. | Fixed error-code taxonomy; upstream bodies never forwarded; `not_found` deliberately conflates "does not exist" with "you cannot see it" so the SDK is not an existence oracle for GFS resources (§5.2). |
+| T9 | Grant tampering on disk. | `0600`, atomic writes, fail-closed on unparseable input. An attacker with write access to `userData` already owns the app; this is hygiene, not a boundary. |
+| T10 | Stale grant after ACL removal. | Partition-GC-time cleanup plus the fact that an unreachable plugin cannot mount (§10.5). |
+| T11 | Late IPC from a torn-down or superseded embed. | Unpin on teardown; generation check (§8.1). |
+| T12 | Malicious image bytes via `gfs.read`. | MIME allowlist, SVG refused, magic-byte re-check, size cap, `data:` only — and the renderer is Chromium's own image decoder in a sandboxed process (§6.6). |
+| T13 | Notification spoofing ("Evenfire: enter your password"). | Mandatory plugin-title prefix, plain text only, tight rate limit (§6.8). |
+
+## 13. Testing
+
+**Unit (vitest, `desktop-app/src/__tests__/`)** — the broker's decision table is
+the highest-value target:
+
+- `pluginSdkBroker`: unpinned sender rejected; stale generation rejected; unknown
+ capability; version mismatch; unauthenticated; rate-limit exhaustion and
+ refill; grant hit skips prompt; grant miss prompts; denial is session-sticky;
+ prompt budget exhaustion; descriptor-version bump forces re-prompt; revocation
+ mid-flight yields `permission_revoked`; every outcome writes exactly one audit
+ line.
+- `requestPermissions` batching: unknown/duplicate/over-8 id lists rejected
+ before any modal renders; already-granted and already-denied ids are dropped
+ from the prompt but still present in the returned map; a partial allow returns
+ the right per-row map with `all: false`; each row writes its own audit line;
+ declined rows land in `sessionDenials`; a batch spends exactly one prompt from
+ the budget; a concurrent single-capability call for a row already in flight
+ joins that modal instead of queueing a second.
+- `pluginConsentStore`: round-trip; per-env and per-user isolation; corrupt file
+ → empty + moved aside; atomic write leaves no partial file; concurrent
+ put/revoke ordering.
+- `pluginAuditLog`: shape-only redaction (a test that asserts a known email
+ string never appears in the file is worth having explicitly); rotation.
+- Each descriptor's `minimize`: given a full upstream payload, assert the wire
+ payload has exactly the documented keys — this is the regression net against
+ a future field silently widening a capability.
+- `gfs.read`: MIME allowlist, SVG refusal, magic-byte mismatch, size cap.
+
+**Renderer (`ui/src/**/__tests__`)** — modal renders host-owned copy for a given
+capability id; Allow/Deny/Escape/timeout resolve correctly; embed visibility
+toggles around the modal; Settings list renders grants, revoke calls through and
+updates optimistically; audit tab filters.
+
+**Integration** — mount a fixture recipe whose UI exercises each capability;
+assert: first call prompts, second does not, revoke → `permission_revoked`, and
+that a second concurrently-pinned surface cannot read the first's grants.
+
+**Manual / security review checklist** — verify the embed cannot reach
+`pluginSdk:resolveConsent`; verify the modal is not clickable-through to the
+`WebContentsView`; verify no token appears in any audit line or SDK response.
+
+## 14. Side Window compatibility
+
+The Side Window will host plugin UIs in a different Electron surface with the
+same need for context. Nothing in this spec is embed-specific except the pinning
+call sites:
+
+- `pluginSurfaceRegistry` already carries `surface: 'sandbox-ui-embed' |
+ 'side-window'`; the Side Window's mount path pins and unpins the same way.
+- Grants are keyed by `pluginId`, **not** by surface — a user who granted
+ LeadForge their identity in the embed should not be re-prompted when the same
+ plugin appears in the Side Window. Same plugin, same user, same decision.
+- The audit line records `surface` so the two are distinguishable after the fact.
+- The consent modal must render above whichever surface is active; if the Side
+ Window is a separate `BrowserWindow`, the prompt targets that window and the
+ §9.4 hide-the-embed step becomes hide-the-active-plugin-surface.
+
+The only thing the Side Window must not do is introduce a second broker.
+
+## 15. Implementation plan
+
+New files (all `desktop-app/src/` unless noted):
+
+| File | Purpose |
+|---|---|
+| `pluginSdkProtocol.ts` | Shared request/response/event/error types, channel names, version. |
+| `pluginSdkCapabilities.ts` | The descriptor catalog (§6). |
+| `pluginSdkBroker.ts` | The chokepoint (§4). |
+| `pluginSurfaceRegistry.ts` | `webContents.id → { pluginId, surface, generation }`. |
+| `pluginConsentStore.ts` | Interface + local implementation (§10). |
+| `pluginConsentGate.ts` | Prompt queue, budget, session denials, timeout. |
+| `pluginAuditLog.ts` | Append-only JSONL + rotation. |
+| `pluginRateLimiter.ts` | Token buckets. |
+| `themeStore.ts` | Theme as main-process state (§6.7). |
+| `ui/src/components/PluginConsentModal/` | The prompt. |
+| `ui/src/pages/SettingsPage` + `PluginPermissions*` | Revocation + activity (§11). |
+| `packages/plugin-ui-sdk/` | Optional npm wrapper + `.d.ts` (§7.3). |
+
+Modified: `sandboxUiEmbedPreload.ts` (new namespaces), `sandboxUiDriver.ts`
+(pin/unpin on mount/teardown), `ipc.ts` (broker handler + trusted resolve
+handler), `appService.ts` (thin accessors the providers call), `preload.ts` +
+`renderer.d.ts` (settings/modal IPC), `ui/src/App.tsx` (theme moves to main).
+
+Milestones:
+
+- **M1 — Transport.** Protocol types, registry, broker skeleton, audit log,
+ rate limiter, `sdk.capabilities()` + `identity.read` with consent hardcoded to
+ deny. Proves the pinning and audit path end to end.
+- **M2 — Consent.** Store, gate, multi-row modal, `sdk.requestPermissions` /
+ `sdk.permissions`, prompt budget, `identity.read` live. First capability a
+ plugin can actually use. The modal is multi-row from the start — retrofitting
+ batching onto a single-capability prompt would mean rewriting the gate, the
+ audit fan-out, and the budget accounting.
+- **M3 — Catalog.** `org.read`, `agents.read`, `contexts.read`, `mcp.read`,
+ `theme.read` (+ theme lift to main), events.
+- **M4 — Files + attention.** `gfs.list`, `gfs.read` incl. `dataUrl` images,
+ `notifications.notify`.
+- **M5 — Revocation UI.** Settings page, activity tab, revocation events,
+ partition-GC grant cleanup.
+- **M6 — Author experience.** npm wrapper, a sample recipe under
+ `workflow-recipes/samples/` exercising every capability, and a section in the
+ recipe authoring guide.
+
+M1+M2 are the security-critical pair and should land together behind a flag;
+M3–M4 are additive descriptors; M5 must ship before the flag flips on, because
+a grant the user cannot revoke is not consent.
+
+## 16. Open questions
+
+1. **Should `gfs.read` be granted per-resource rather than per-capability?**
+ Today "open shared files" is one grant covering everything the user can read.
+ A per-folder scope is a much better privacy story and a much worse UX (a
+ prompt per file). A middle path — grant per top-level drive folder — is
+ worth prototyping before M4 freezes the descriptor.
+2. **Does `identity.read` need splitting?** Some plugins want a display name and
+ nothing else. `identity.read` (name only) + `identity.email` as separate
+ capabilities would be more honest, at the cost of two prompts for the common
+ case. Cheap to add later, breaking to remove.
+3. **Should the SDK expose the plugin's own recipe metadata** (name, version,
+ install time)? No user data, arguably `ambient`, plausibly useful for a plugin
+ showing its own version. Deferred.
+4. **Audit retention default.** 90 days / 5 MB is a guess. Should the user be
+ able to clear it, and does clearing it deserve its own audit line?
+5. **First-run disclosure.** With no CRD declaration (D2), the user learns what a
+ plugin wants only when it asks. Should the Settings row show "has never
+ requested any permission" so a dormant plugin is distinguishable from a
+ well-behaved one?
+6. **Recovering from a declined row inside a session.** Session-sticky denial
+ (§9.3) means a plugin's own "Enable file access" button is inert until the
+ user closes and reopens the plugin — which no user will guess. The clean fix
+ is to let a *user gesture inside the plugin* re-open the prompt for a declined
+ capability once per session, but the SDK cannot distinguish a real click from
+ a synthetic one, so "user gesture" would be plugin-asserted and therefore
+ worthless as a gate. The alternative is a "Request again" affordance on the
+ Settings row, which is trustworthy but hidden. Unresolved; M5 should not ship
+ without picking one.
+
+---
+
+## 17. Appendix A — End-user walkthrough
+
+The sections above specify mechanism. This one is the arc a single user actually
+lives through, and it is the thing to check any future change against: if an
+amendment makes Scene 2 stop being true, the amendment is wrong.
+
+Cast: **Andres**, a member of the Acme team. **LeadForge**, a sandbox-UI plugin
+that wants identity, org, agents, and shared files.
+
+### Scene 0 — the plugin arrives
+
+An operator installs LeadForge from the registry and grants Andres access on the
+recipe's **Members** tab. Nothing SDK-related has happened. LeadForge appears in
+the Desktop app rail like any other plugin.
+
+### Scene 1 — first open: exactly one modal
+
+Andres clicks LeadForge. The embed mounts and loads. Its JS calls
+`sdk.permissions([...])`, gets four `false`s, and calls `sdk.requestPermissions()`
+with all four (§7.1). Its own UI is still a skeleton — no data yet.
+
+The embed then **visibly blanks**, and a modal appears over it:
+
+> **LeadForge wants access to your information**
+> ☑ See who you are — *Your name, email address, and user id.*
+> ☑ See your current team — *Its name and your role in it.*
+> ☑ See the agents you have access to — *Their names and which MCP servers they use.*
+> ☑ See the shared files you have access to — *Their names, folders, and sizes. It will not be able to open them.*
+> *You can change this any time in Settings → Plugin permissions.*
+> ⟨Deny⟩ ⟨Allow⟩
+
+**The blanking is deliberate and users should read it as "the app is asking, not
+the plugin."** A `WebContentsView` paints above renderer DOM regardless of
+z-index, so hiding the embed is the only way to guarantee the plugin can neither
+draw a convincing fake modal nor paint over the real one (§9.4).
+
+Andres unchecks files, clicks Allow. The modal closes, LeadForge reappears and
+paints a real dashboard: his name in the header, his agents in a dropdown, and —
+because it asked for four things and got three — an inline "Connect your shared
+files to see pipeline documents" card where the file list would have been. That
+card is LeadForge's own pixels. The host never renders a plugin's case for why it
+needs something (§9.2).
+
+Total cost of first run: **one modal**, covering the plugin's entire startup set.
+
+### Scene 2 — every subsequent open: no modal
+
+Tomorrow, next week, next month: `sdk.permissions()` returns three `true`s, the
+plugin skips `requestPermissions` entirely, and the dashboard paints immediately.
+This is where users spend virtually all their time, and it is why a no-prompt
+state check is part of the contract rather than a convenience.
+
+### Scene 3 — a permission that appears later
+
+A month in, Andres clicks the "Connect your shared files" card. The embed blanks,
+a **one-row** modal appears carrying the same file sentence he read the first
+time — verbatim, from the same `dataDescription` string (§6). He allows; the card
+becomes his file list. Grants accrete as the plugin gets used, one honest ask at
+a time, never a re-litigation of the whole set.
+
+### Scene 4 — the plugin wants attention
+
+Andres is mid-conversation with an agent. LeadForge, in the background, calls
+`notifications.notify`. He sees an OS notification titled **"LeadForge — 3 new
+inbound leads"** — mandatorily prefixed with the plugin's title so nothing can
+pose as Evenfire itself or as another plugin (§6.8, T13). Clicking it focuses the
+window and lands him in LeadForge.
+
+Had he been *looking* at LeadForge, nothing would have fired: the plugin gets
+`{ delivered: false, reason: 'suppressed' }`, because interrupting someone about
+the thing they are currently staring at is noise, not attention.
+
+### Scene 5 — checking up on it
+
+**Settings → Plugin permissions** (§11):
+
+| Plugin | Permissions | Last used | |
+|---|---|---|---|
+| LeadForge | Identity · Team · Agents · Shared files | 2 minutes ago | ⋯ |
+| Sales CRM | Identity · Notifications | yesterday | ⋯ |
+
+Expanding LeadForge shows each capability with the same sentence from the prompt,
+`grantedAt`, `lastUsedAt`, and **Revoke**. The **Activity** tab shows what
+actually happened — including denials and rate-limits, so a plugin that keeps
+asking for things Andres keeps refusing becomes visible as a pattern rather than
+a series of separately-forgotten annoyances.
+
+### Scene 6 — revocation
+
+Andres revokes "Shared files." Immediately: the grant is gone, and if LeadForge
+is open it receives `permission.changed` and drops back to the "Connect your
+shared files" card **without a reload** (§11). A request already in flight returns
+`permission_revoked` — a different code from `permission_denied` precisely so the
+plugin can say "your file access was removed" rather than re-prompting him.
+
+### The unhappy paths
+
+| Situation | What Andres experiences | Spec |
+|---|---|---|
+| He clicks **Deny**. | LeadForge gets four `false`s and renders its own "this plugin needs access to work" state. Nothing is recorded as a permanent no; the refusal lasts until he closes and reopens the plugin. | §9.3 |
+| He then clicks LeadForge's own "Grant access" button **in the same session** — and nothing happens. | The known gap. Session-sticky denial is what stops a prompt loop, but it also makes the plugin's retry button inert until reopen, which no user will guess. | §16 #6 |
+| The plugin asks for a 4th, 5th, 6th thing in one session. | After three modals it stops being able to ask until he reopens the plugin. A well-built plugin never notices this ceiling exists. | §9.5 |
+| He switches teams. | Granted `org.read` starts returning the new team, no re-prompt. He consented to "see which workspace I'm in"; the answer changed. | §6.2 |
+| He logs out and back in. | Grants survive, keyed to his user id. A different user on the same machine starts clean. | §10.5 |
+| He opens Evenfire on his laptop instead of his desktop. | He gets the first-run modal again — grants do not travel in v1. | §10.2, §10.6 |
+| LeadForge updates and now wants a phone number inside `identity.read`. | He is re-prompted, with copy naming the new field. Silently widening an existing grant would turn all of the above into theatre. | §9.6 |
+
+### What he never sees
+
+The theme handoff (no prompt — it says nothing about him, §6.7), the rate
+limiting, the response minimization, and the audit log doing its work.
+
+The target shape of the whole experience: **one modal when he installs, one more
+the day he uses a new corner of the plugin, and a settings page he visits only
+when he gets suspicious.**