Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-app): address PR #292 review — plugin UI SDK medium findings
Andy Pavia45dd9c98db8b
diff --git a/desktop-app/src/__tests__/pluginConsentGate.test.ts b/desktop-app/src/__tests__/pluginConsentGate.test.tsindex 82b1f1f3a..be86abe61 100644--- a/desktop-app/src/__tests__/pluginConsentGate.test.ts+++ b/desktop-app/src/__tests__/pluginConsentGate.test.ts@@ -25,6 +25,14 @@ let clock: numbertype GateOptions = {decide?: (request: PluginConsentRequest) => string[] | nullwindowReady?: () => boolean+ setSurfaceVisible?: (visible: boolean) => Promise<void>+}++/** Spin the macrotask queue until `pred` holds — deterministic, no fixed sleep. */+async function flushUntil(pred: () => boolean, maxTicks = 1000): Promise<void> {+ for (let i = 0; i < maxTicks && !pred(); i++) {+ await new Promise(resolve => setTimeout(resolve, 0))+ }}function makeGate(options: GateOptions = {}): PluginConsentGate {@@ -41,9 +49,11 @@ function makeGate(options: GateOptions = {}): PluginConsentGate {}},cancelPrompt: promptId => cancelled.push(promptId),- setSurfaceVisible: async visible => {- visibility.push(visible)- },+ setSurfaceVisible:+ options.setSurfaceVisible ??+ (async visible => {+ visibility.push(visible)+ }),isWindowReady: options.windowReady ?? (() => true),now: () => clock,sleep: async ms => {@@ -163,13 +173,40 @@ describe('PluginConsentGate', () => {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))+ // Wait until the prompt is actually presented (deterministic) rather than a+ // single arbitrary tick, which raced the async setup under I/O load.+ await flushUntil(() => prompts.length === 1)gate.resetPlugin(BASE.pluginId)const outcome = await pendingexpect(cancelled).toHaveLength(1)expect(outcome.granted['identity.read']).toBe(false)})+ it('cancels a prompt whose plugin unmounts during the surface-hide flip', async () => {+ // Regression for the ordering window: the pending prompt is registered before+ // the `setSurfaceVisible(false)` await, so an unmount mid-flip is cancelled as+ // a denial instead of hanging until the 120 s timeout — and is never shown.+ let releaseHide!: () => void+ const hideBlocked = new Promise<void>(resolve => {+ releaseHide = resolve+ })+ const gate = makeGate({+ decide: () => null,+ setSurfaceVisible: async visible => {+ visibility.push(visible)+ if (visible === false) await hideBlocked+ },+ })+ const pending = gate.ensure({ ...BASE, capabilities: ['identity.read'] })+ await flushUntil(() => visibility.includes(false))+ gate.resetPlugin(BASE.pluginId)+ releaseHide()+ const outcome = await pending+ expect(cancelled).toHaveLength(1)+ expect(outcome.granted['identity.read']).toBe(false)+ expect(prompts).toHaveLength(0)+ })+it('does not prompt for an ambient capability', async () => {const gate = makeGate()const outcome = await gate.ensure({ ...BASE, capabilities: ['theme.read'] })diff --git a/desktop-app/src/__tests__/pluginRateLimiter.test.ts b/desktop-app/src/__tests__/pluginRateLimiter.test.tsnew file mode 100644index 000000000..32f812a32--- /dev/null+++ b/desktop-app/src/__tests__/pluginRateLimiter.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it } from 'vitest'+import { PLUGIN_GLOBAL_LIMIT, PluginRateLimiter } from '../pluginRateLimiter.js'++const PLUGIN = 'ns/plugin'+const CAP = 'gfs.read'++/** A limiter whose clock is a mutable number we advance by hand. */+function makeLimiter(startAt = 0): { limiter: PluginRateLimiter; advance: (ms: number) => void } {+ let clock = startAt+ const limiter = new PluginRateLimiter(() => clock)+ return { limiter, advance: (ms: number) => (clock += ms) }+}++describe('PluginRateLimiter', () => {+ it('allows up to the per-minute budget, then denies on the minute window', () => {+ const { limiter } = makeLimiter()+ const spec = { perMinute: 3, perHour: 100 }+ for (let i = 0; i < 3; i++) {+ expect(limiter.take(PLUGIN, CAP, spec).allowed).toBe(true)+ }+ const denied = limiter.take(PLUGIN, CAP, spec)+ expect(denied.allowed).toBe(false)+ if (!denied.allowed) {+ // One per-minute token refills after 60_000 / 3 = 20_000 ms.+ expect(denied.retryAfterMs).toBe(20_000)+ }+ })++ it('does not spend a minute token when the hour window denies (intra-pair refund)', () => {+ // Reviewer repro (R1-M1/R1-M6): perMinute:5, perHour:2. After two allowed+ // calls the hour bucket is empty; every further call must be denied by the+ // HOUR window, never over-charge the minute window. Pre-fix, the third call+ // spent a minute token and a later call got denied by *minute* (retryAfter+ // 12_000) after only two successes.+ const { limiter } = makeLimiter()+ const spec = { perMinute: 5, perHour: 2 }++ expect(limiter.take(PLUGIN, CAP, spec).allowed).toBe(true)+ expect(limiter.take(PLUGIN, CAP, spec).allowed).toBe(true)++ // ms for one per-hour token to refill (computed as the limiter does it).+ const hourRetry = Math.ceil(1 / (spec.perHour / 3_600_000))+ const minuteRetry = Math.ceil(1 / (spec.perMinute / 60_000)) // 12_000+ for (let i = 0; i < 4; i++) {+ const denied = limiter.take(PLUGIN, CAP, spec)+ expect(denied.allowed).toBe(false)+ if (!denied.allowed) {+ // Always the hour window — the minute window is never the limiter here,+ // proving no minute token was silently consumed on a denied call.+ expect(denied.retryAfterMs).toBe(hourRetry)+ expect(denied.retryAfterMs).not.toBe(minuteRetry)+ }+ }+ })++ it('refunds the capability tokens when the global window denies', () => {+ // Drive the plugin-global minute ceiling to empty using a cheap capability,+ // then a DIFFERENT capability (with its own fresh budget) must still be+ // denied by the global window — and get its capability tokens back, so once+ // the global window refills it is immediately usable again.+ const { limiter, advance } = makeLimiter()+ const cheap = { perMinute: PLUGIN_GLOBAL_LIMIT.perMinute + 10, perHour: 100_000 }+ for (let i = 0; i < PLUGIN_GLOBAL_LIMIT.perMinute; i++) {+ expect(limiter.take(PLUGIN, 'gfs.list', cheap).allowed).toBe(true)+ }++ const other = { perMinute: 5, perHour: 50 }+ const deniedByGlobal = limiter.take(PLUGIN, 'gfs.read', other)+ expect(deniedByGlobal.allowed).toBe(false)++ // Refill exactly one global-minute token; the capability pair was refunded,+ // so 'gfs.read' still has its full budget and the call now succeeds.+ advance(Math.ceil(60_000 / PLUGIN_GLOBAL_LIMIT.perMinute))+ expect(limiter.take(PLUGIN, 'gfs.read', other).allowed).toBe(true)+ })++ it('refills continuously over time', () => {+ const { limiter, advance } = makeLimiter()+ const spec = { perMinute: 2, perHour: 100 }+ expect(limiter.take(PLUGIN, CAP, spec).allowed).toBe(true)+ expect(limiter.take(PLUGIN, CAP, spec).allowed).toBe(true)+ expect(limiter.take(PLUGIN, CAP, spec).allowed).toBe(false)++ advance(30_000) // one per-minute token (60_000 / 2)+ expect(limiter.take(PLUGIN, CAP, spec).allowed).toBe(true)+ expect(limiter.take(PLUGIN, CAP, spec).allowed).toBe(false)+ })++ it('keeps separate budgets per plugin and clears them on reset', () => {+ const { limiter } = makeLimiter()+ const spec = { perMinute: 1, perHour: 100 }+ expect(limiter.take('ns/a', CAP, spec).allowed).toBe(true)+ expect(limiter.take('ns/a', CAP, spec).allowed).toBe(false)+ // A different plugin is unaffected.+ expect(limiter.take('ns/b', CAP, spec).allowed).toBe(true)+ // Reset restores plugin a's budget.+ limiter.reset('ns/a')+ expect(limiter.take('ns/a', CAP, spec).allowed).toBe(true)+ })+})diff --git a/desktop-app/src/__tests__/pluginSdkCapabilities.test.ts b/desktop-app/src/__tests__/pluginSdkCapabilities.test.tsindex cbd6ad250..2c1c475f8 100644--- a/desktop-app/src/__tests__/pluginSdkCapabilities.test.ts+++ b/desktop-app/src/__tests__/pluginSdkCapabilities.test.ts@@ -298,6 +298,19 @@ describe('gfs.open', () => {expect(result).toEqual({ opened: true })})+ it('drops the internal reason on failure so it is not an accessibility oracle', async () => {+ // The producer distinguishes not_found / unavailable internally; the plugin+ // must only ever see `{ opened: false }` — otherwise it can tell an absent or+ // unauthorized resource apart from a transient failure without consent.+ const result = await run(+ 'gfs.open',+ { uri: 'gfs://main/secret.png' },+ { openGfsResource: async () => ({ opened: false, reason: 'not_found' }) }+ )+ expect(result).toEqual({ opened: false })+ expect(result).not.toHaveProperty('reason')+ })+it('rejects a non-gfs uri and unexpected params', () => {const descriptor = getCapability('gfs.open')expect(() => descriptor?.validate({ uri: 'https://evil.example/x' })).toThrow()diff --git a/desktop-app/src/pluginConsentGate.ts b/desktop-app/src/pluginConsentGate.tsindex b30245a8b..c59d119a7 100644--- a/desktop-app/src/pluginConsentGate.ts+++ b/desktop-app/src/pluginConsentGate.ts@@ -261,26 +261,39 @@ export class PluginConsentGate {session.promptCount += 1session.lastPromptAt = this.now()+ // Register the pending prompt BEFORE the surface-visibility await. If the+ // plugin unmounts during that await (unpin → releasePlugin → resetPlugin),+ // resetPlugin must be able to find and cancel this prompt; otherwise it sees+ // `pending === null`, cancels nothing, and the await below hangs until the+ // 120 s timeout.+ let resolvePrompt!: (allowed: Set<string>) => void+ const promptResult = new Promise<Set<string>>(resolve => {+ resolvePrompt = 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).+ resolvePrompt(new Set())+ }, CONSENT_PROMPT_TIMEOUT_MS)+ this.pending = {+ promptId,+ pluginId: input.pluginId,+ capabilities: new Set(stillNeeded),+ resolve: resolvePrompt,+ timer,+ }+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,- }+ await this.deps.setSurfaceVisible(false)+ // If the plugin unmounted during the await, resetPlugin already cleared+ // `this.pending` and resolved the prompt as a denial — never present it.+ if (this.pending?.promptId === promptId) {this.deps.presentPrompt(request)- })+ }+ allowed = await promptResult} finally {await this.deps.setSurfaceVisible(true).catch(() => undefined)}diff --git a/desktop-app/src/pluginRateLimiter.ts b/desktop-app/src/pluginRateLimiter.tsindex 202945d02..b003fb275 100644--- a/desktop-app/src/pluginRateLimiter.ts+++ b/desktop-app/src/pluginRateLimiter.ts@@ -30,15 +30,23 @@ function refill(bucket: Bucket, now: number): void {bucket.updatedAt = now}-function tryTake(bucket: Bucket, now: number): RateLimitDecision {- refill(bucket, now)- if (bucket.tokens >= 1) {- bucket.tokens -= 1- return { allowed: true }+/**+ * Refill both buckets of a pair, then take a token from each only if BOTH have+ * capacity. Checking before committing means a request denied by one window+ * never spends a token in the other — so the limiter stays exactly as strict as+ * the spec and no token is silently lost between the minute/hour windows.+ */+function tryTakePair(pair: [Bucket, Bucket], now: number): RateLimitDecision {+ for (const bucket of pair) refill(bucket, now)+ for (const bucket of pair) {+ if (bucket.tokens < 1) {+ // Time until one whole token exists again in the starved window.+ const deficit = 1 - bucket.tokens+ return { allowed: false, retryAfterMs: Math.ceil(deficit / bucket.refillPerMs) }+ }}- // Time until one whole token exists again.- const deficit = 1 - bucket.tokens- return { allowed: false, retryAfterMs: Math.ceil(deficit / bucket.refillPerMs) }+ for (const bucket of pair) bucket.tokens -= 1+ return { allowed: true }}export class PluginRateLimiter {@@ -61,25 +69,23 @@ export class PluginRateLimiter {/*** 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.+ * Both pairs must have capacity in both their windows; a denial anywhere spends+ * nothing. If the capability pair allows but the global pair denies, the+ * capability tokens are 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- }+ const capDecision = tryTakePair(capPair, now)+ if (!capDecision.allowed) return capDecision++ const globalDecision = tryTakePair(globalPair, now)+ if (!globalDecision.allowed) {+ for (const b of capPair) b.tokens = Math.min(b.capacity, b.tokens + 1)+ return globalDecision}return { allowed: true }}diff --git a/desktop-app/src/pluginSdkCapabilities.ts b/desktop-app/src/pluginSdkCapabilities.tsindex 603c94b43..ac083ff27 100644--- a/desktop-app/src/pluginSdkCapabilities.ts+++ b/desktop-app/src/pluginSdkCapabilities.ts@@ -412,11 +412,13 @@ export const CAPABILITIES: Record<string, CapabilityDescriptor> = {// Unscoped, and the second capability to qualify. The rule from §6.7 is that// `requiresConsent: false` needs the response to carry nothing about the// user; this one adds the other half: the ACTION must be unmissable. The- // plugin gets back `{ opened }` and nothing else — it never learns the file's- // name, size, or contents. What happens is that the Desktop's own viewer- // opens, over the plugin, showing the user a file they already have access- // to, resolved with their session. Prompting "may this plugin show you your- // own file?" would be noise in front of an action the user can see.+ // plugin gets back a bare `{ opened }` and nothing else — not the file's+ // name, size, contents, nor WHY a failure happened (the `run` below drops the+ // internal `reason`, so absent/unauthorized/transient all collapse to+ // `opened: false`). What happens is that the Desktop's own viewer opens, over+ // the plugin, showing the user a file they already have access to, resolved+ // with their session. Prompting "may this plugin show you your own file?"+ // would be noise in front of an action the user can see.requiresConsent: false,consent: {title: 'Open a shared file in the Evenfire viewer',@@ -434,7 +436,12 @@ export const CAPABILITIES: Record<string, CapabilityDescriptor> = {if (!uri.startsWith('gfs://')) throw new CapabilityInputError('uri must be a gfs:// link')return { uri }},- run: async (ctx, params) => ctx.source.openGfsResource({ uri: params.uri as string }),+ run: async (ctx, params) => {+ // Never forward the internal `reason` to the plugin: it would turn a+ // failed open into an accessibility oracle (not_found vs unavailable).+ const result = await ctx.source.openGfsResource({ uri: params.uri as string })+ return { opened: result.opened }+ },},'theme.read': {diff --git a/desktop-app/src/pluginSdkRuntime.ts b/desktop-app/src/pluginSdkRuntime.tsindex 6c2a8587c..7fb39bd3d 100644--- a/desktop-app/src/pluginSdkRuntime.ts+++ b/desktop-app/src/pluginSdkRuntime.ts@@ -288,9 +288,14 @@ export class PluginSdkRuntime {/*** Resolve a `gfs://` link with the USER's session and hand it to the trusted- * renderer to display. The plugin gets back only whether it opened: it never- * sees the name, size, or bytes, and an unauthorized or missing resource is- * the same "could not open" either way, so this is not an existence oracle.+ * renderer to display. The plugin gets back only whether it opened — never the+ * name, size, or bytes. The internal `reason` returned here is for the audit+ * line and the navigation path; the `gfs.open` capability drops it before the+ * plugin sees it, so absent and unauthorized both read as `opened: false`.+ * A resolvable link IS still distinguishable from a non-resolvable one, so this+ * is a narrow accessibility signal — bounded by the 6/min budget, unguessable+ * resource ids, a live user session, and a viewer that paints over the plugin+ * on every hit. Reads over that bound: mark the capability `requiresConsent`.** Reached two ways, both landing here so they share the rate budget and the* audit line: `clerum.gfs.open(uri)` through the broker, and a plaindiff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsxindex ad51348e5..d21c6414e 100644--- a/desktop-app/ui/src/App.tsx+++ b/desktop-app/ui/src/App.tsx@@ -218,7 +218,9 @@ export function App() {/*** 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.+ * answers, so the plugin can neither fake the prompt nor paint over it. The+ * prompt is centered over — and its backdrop scoped to — the plugin's embed+ * rect, not the whole window; the rest of the trusted app chrome stays visible.*/const [pluginConsentPrompt, setPluginConsentPrompt] = React.useState<PluginConsentRequest | null>(nulldiff --git a/desktop-app/ui/src/components/PluginConsentModal/index.tsx b/desktop-app/ui/src/components/PluginConsentModal/index.tsxindex 265506e26..4a0f99cd3 100644--- a/desktop-app/ui/src/components/PluginConsentModal/index.tsx+++ b/desktop-app/ui/src/components/PluginConsentModal/index.tsx@@ -106,12 +106,13 @@ export function PluginConsentModal({ request, onResolve }: PluginConsentModalProrole="presentation"style={backdropStyle}>- <div- className="confirm-dialog da-plugin-consent"- role="dialog"- aria-modal="true"- aria-labelledby={titleId}- >+ {/* Deliberately NOT aria-modal: the backdrop is scoped to the plugin's+ embed rectangle (see backdropStyle above), so the surrounding trusted+ app chrome stays visible and interactive by design. Claiming full-window+ modality here would misdescribe the DOM to assistive tech. The plugin+ cannot exploit the un-dimmed chrome — main hides the plugin's own+ WebContentsView while this prompt is up. */}+ <div className="confirm-dialog da-plugin-consent" role="dialog" aria-labelledby={titleId}><h3 id={titleId}>{request.pluginTitle} wants access to your information</h3>{request.priorPromptCount > 0 ? (diff --git a/desktop-app/ui/src/components/PluginPermissions/index.tsx b/desktop-app/ui/src/components/PluginPermissions/index.tsxindex cfe02c0be..a6258c652 100644--- a/desktop-app/ui/src/components/PluginPermissions/index.tsx+++ b/desktop-app/ui/src/components/PluginPermissions/index.tsx@@ -125,7 +125,7 @@ export function PluginPermissions() {<Buttoncolor="danger"disabled={controller.revoking}- onClick={() => void controller.revoke(group.pluginId)}+ onClick={() => controller.revoke(group.pluginId).catch(() => undefined)}size="sm"variant="ghost">@@ -152,7 +152,9 @@ export function PluginPermissions() {color="danger"disabled={controller.revoking}onClick={() =>- void controller.revoke(grant.pluginId, grant.capability)+ controller+ .revoke(grant.pluginId, grant.capability)+ .catch(() => undefined)}size="sm"variant="ghost"@@ -199,7 +201,7 @@ export function PluginPermissions() {<div className="settings-form"><Buttoncolor="neutral"- onClick={() => void controller.clearActivity()}+ onClick={() => controller.clearActivity().catch(() => undefined)}size="sm"variant="ghost">diff --git a/desktop-app/ui/src/hooks/domain/usePluginPermissionsController.ts b/desktop-app/ui/src/hooks/domain/usePluginPermissionsController.tsindex 6f61cbbde..ca954da15 100644--- a/desktop-app/ui/src/hooks/domain/usePluginPermissionsController.ts+++ b/desktop-app/ui/src/hooks/domain/usePluginPermissionsController.ts@@ -87,11 +87,19 @@ export function usePluginPermissionsController() {groups,activity,loading: grantsQuery.isPending || activityQuery.isPending,+ // Surface query AND mutation failures. Without the mutation errors a failed+ // revoke/clear silently left the UI unchanged, so the user believed a+ // permission was revoked when it was not. React Query clears each mutation's+ // error on its next run, so a stale message does not linger.error: grantsQuery.error? toErrorMessage(grantsQuery.error): activityQuery.error? toErrorMessage(activityQuery.error)- : null,+ : revokeMutation.error+ ? toErrorMessage(revokeMutation.error)+ : clearActivityMutation.error+ ? toErrorMessage(clearActivityMutation.error)+ : null,revoking: revokeMutation.isPending,revoke: (pluginId: string, capability?: string) =>revokeMutation.mutateAsync({ pluginId, ...(capability ? { capability } : {}) }),