Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-app): address PR #292 round-2 review — plugin UI SDK
Andy Paviaa3318bd24592
diff --git a/desktop-app/src/__tests__/pluginConsentGate.test.ts b/desktop-app/src/__tests__/pluginConsentGate.test.tsindex be86abe61..2760727c6 100644--- a/desktop-app/src/__tests__/pluginConsentGate.test.ts+++ b/desktop-app/src/__tests__/pluginConsentGate.test.ts@@ -33,6 +33,9 @@ async function flushUntil(pred: () => boolean, maxTicks = 1000): Promise<void> {for (let i = 0; i < maxTicks && !pred(); i++) {await new Promise(resolve => setTimeout(resolve, 0))}+ // Fail loudly rather than returning silently — a swallowed timeout lets a test+ // go green even when the awaited condition never became true.+ if (!pred()) throw new Error('flushUntil: predicate did not hold within maxTicks')}function makeGate(options: GateOptions = {}): PluginConsentGate {@@ -207,6 +210,24 @@ describe('PluginConsentGate', () => {expect(prompts).toHaveLength(0)})+ it('does not leak a pending prompt when the surface-hide flip rejects', async () => {+ // Regression (R2-L1): the pending entry + 120s timer are registered before+ // the hide await. If that await throws (WebContentsView destroyed mid-flip),+ // runPrompt must tear them down rather than leak them until the timeout.+ const gate = makeGate({+ decide: () => null,+ setSurfaceVisible: async visible => {+ visibility.push(visible)+ if (visible === false) throw new Error('view destroyed mid-flip')+ },+ })+ await expect(gate.ensure({ ...BASE, capabilities: ['identity.read'] })).rejects.toThrow(+ 'view destroyed mid-flip'+ )+ expect(gate.hasPendingPrompt()).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__/sandboxUiPartitionPolicies.test.ts b/desktop-app/src/__tests__/sandboxUiPartitionPolicies.test.tsindex 67461da60..acb506ff6 100644--- a/desktop-app/src/__tests__/sandboxUiPartitionPolicies.test.ts+++ b/desktop-app/src/__tests__/sandboxUiPartitionPolicies.test.ts@@ -1,10 +1,15 @@-import { describe, expect, it } from 'vitest'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type { WebContents } from 'electron'import {+ applySandboxUiNavigationPolicies,classifyEmbedNavigation,parseClerumOauthAuthorize,shouldAllowEmbedPermission,} from '../sandboxUiPartitionPolicies.js'+const { openExternal } = vi.hoisted(() => ({ openExternal: vi.fn() }))+vi.mock('electron', () => ({ shell: { openExternal } }))+describe('shouldAllowEmbedPermission', () => {it('allows fullscreen', () => {expect(shouldAllowEmbedPermission('fullscreen')).toBe(true)@@ -208,3 +213,101 @@ describe('parseClerumOauthAuthorize', () => {expect(parseClerumOauthAuthorize('clerum:not a url')).toBeNull()})})++describe('applySandboxUiNavigationPolicies (dispatch wiring)', () => {+ const allowed = 'https://rpc-proxy.example/api/v1/sandbox-ui/sandbox-recipes/r1/view/'++ beforeEach(() => {+ openExternal.mockClear()+ })++ /** A fake WebContents that captures the will-navigate + window-open handlers. */+ function makeWebContents() {+ let willNavigate: ((event: { preventDefault: () => void }, url: string) => void) | undefined+ let windowOpen: ((details: { url: string }) => { action: string }) | undefined+ const wc = {+ on: vi.fn((ev: string, cb: (event: { preventDefault: () => void }, url: string) => void) => {+ if (ev === 'will-navigate') willNavigate = cb+ }),+ setWindowOpenHandler: vi.fn((fn: (details: { url: string }) => { action: string }) => {+ windowOpen = fn+ }),+ } as unknown as WebContents+ return {+ wc,+ navigate(url: string) {+ const event = { preventDefault: vi.fn() }+ willNavigate?.(event, url)+ return event+ },+ openWindow: (url: string) => windowOpen?.({ url }),+ }+ }++ it('fires onOauthAuthorize (with background) and prevents default for a clerum oauth link', () => {+ const onOauthAuthorize = vi.fn()+ const onGfsOpen = vi.fn()+ const fake = makeWebContents()+ applySandboxUiNavigationPolicies(fake.wc, allowed, { onOauthAuthorize, onGfsOpen })++ const event = fake.navigate('clerum://oauth?clientId=salesforce-prod&background=1')+ expect(event.preventDefault).toHaveBeenCalledOnce()+ expect(onOauthAuthorize).toHaveBeenCalledWith('salesforce-prod', true)+ expect(onGfsOpen).not.toHaveBeenCalled()+ })++ it('fires onGfsOpen and prevents default for a gfs:// link', () => {+ const onGfsOpen = vi.fn()+ const fake = makeWebContents()+ applySandboxUiNavigationPolicies(fake.wc, allowed, { onGfsOpen })++ const event = fake.navigate('gfs://main/report.pdf')+ expect(event.preventDefault).toHaveBeenCalledOnce()+ expect(onGfsOpen).toHaveBeenCalledWith('gfs://main/report.pdf')+ })++ it('opens external https navigations in the OS browser', () => {+ const fake = makeWebContents()+ applySandboxUiNavigationPolicies(fake.wc, allowed, {})+ const event = fake.navigate('https://example.com/x')+ expect(event.preventDefault).toHaveBeenCalledOnce()+ expect(openExternal).toHaveBeenCalledWith('https://example.com/x')+ })++ it('lets an in-prefix view navigation through — no preventDefault, no dispatch', () => {+ const onGfsOpen = vi.fn()+ const onOauthAuthorize = vi.fn()+ const fake = makeWebContents()+ applySandboxUiNavigationPolicies(fake.wc, allowed, { onGfsOpen, onOauthAuthorize })+ const event = fake.navigate(`${allowed}index.html`)+ expect(event.preventDefault).not.toHaveBeenCalled()+ expect(onGfsOpen).not.toHaveBeenCalled()+ expect(onOauthAuthorize).not.toHaveBeenCalled()+ expect(openExternal).not.toHaveBeenCalled()+ })++ it('still supports the legacy positional oauth callback', () => {+ const legacyOauth = vi.fn()+ const fake = makeWebContents()+ applySandboxUiNavigationPolicies(fake.wc, allowed, legacyOauth)+ fake.navigate('clerum://oauth?clientId=google-gmail')+ expect(legacyOauth).toHaveBeenCalledWith('google-gmail', false)+ })++ it('dispatches window.open(gfs://…) and denies the popup', () => {+ const onGfsOpen = vi.fn()+ const fake = makeWebContents()+ applySandboxUiNavigationPolicies(fake.wc, allowed, { onGfsOpen })+ const result = fake.openWindow('gfs://main/a.png')+ expect(onGfsOpen).toHaveBeenCalledWith('gfs://main/a.png')+ expect(result).toEqual({ action: 'deny' })+ })++ it('routes window.open(https://…) to the OS browser and denies the popup', () => {+ const fake = makeWebContents()+ applySandboxUiNavigationPolicies(fake.wc, allowed, {})+ const result = fake.openWindow('https://example.com/')+ expect(openExternal).toHaveBeenCalledWith('https://example.com/')+ expect(result).toEqual({ action: 'deny' })+ })+})diff --git a/desktop-app/src/pluginConsentGate.ts b/desktop-app/src/pluginConsentGate.tsindex c59d119a7..6a27474aa 100644--- a/desktop-app/src/pluginConsentGate.ts+++ b/desktop-app/src/pluginConsentGate.ts@@ -294,6 +294,19 @@ export class PluginConsentGate {this.deps.presentPrompt(request)}allowed = await promptResult+ } catch (err) {+ // The hide flip (or presentPrompt) threw — e.g. the WebContentsView was+ // destroyed mid-flip, the exact race the pre-await registration targets.+ // Tear down this prompt's pending entry + timer so a thrown runPrompt does+ // not leak them for up to the 120 s timeout, and withdraw the prompt in+ // case presentPrompt threw after partially registering it (symmetry with+ // resetPlugin / the timeout path).+ if (this.pending?.promptId === promptId) {+ clearTimeout(timer)+ this.pending = null+ this.deps.cancelPrompt(promptId)+ }+ throw err} finally {await this.deps.setSurfaceVisible(true).catch(() => undefined)}diff --git a/desktop-app/ui/src/components/PluginPermissions/index.tsx b/desktop-app/ui/src/components/PluginPermissions/index.tsxindex a6258c652..4853bb075 100644--- a/desktop-app/ui/src/components/PluginPermissions/index.tsx+++ b/desktop-app/ui/src/components/PluginPermissions/index.tsx@@ -201,6 +201,7 @@ export function PluginPermissions() {<div className="settings-form"><Buttoncolor="neutral"+ disabled={controller.clearingActivity || controller.revoking}onClick={() => controller.clearActivity().catch(() => undefined)}size="sm"variant="ghost"diff --git a/desktop-app/ui/src/hooks/domain/__tests__/usePluginPermissionsController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/usePluginPermissionsController.test.tsxnew file mode 100644index 000000000..dd5c73037--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/__tests__/usePluginPermissionsController.test.tsx@@ -0,0 +1,84 @@+// @vitest-environment jsdom+import type { ReactNode } from 'react'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'+import { usePluginPermissionsController } from '../usePluginPermissionsController'++type PluginSdkMock = {+ listGrants: ReturnType<typeof vi.fn>+ activity: ReturnType<typeof vi.fn>+ revoke: ReturnType<typeof vi.fn>+ clearActivity: ReturnType<typeof vi.fn>+}++function installPluginSdk(overrides: Partial<PluginSdkMock> = {}): PluginSdkMock {+ const sdk: PluginSdkMock = {+ listGrants: vi.fn(async () => []),+ activity: vi.fn(async () => []),+ revoke: vi.fn(async () => undefined),+ clearActivity: vi.fn(async () => undefined),+ ...overrides,+ }+ Object.defineProperty(window, 'clerum', { configurable: true, value: { pluginSdk: sdk } })+ return sdk+}++function makeWrapper() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ })+ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ )+}++describe('usePluginPermissionsController', () => {+ afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+ delete (window as { clerum?: unknown }).clerum+ })++ it('surfaces a failed revoke in the error banner (R1-M4)', async () => {+ installPluginSdk({+ revoke: vi.fn(async () => {+ throw new Error('revoke failed')+ }),+ })+ const { result } = renderHook(() => usePluginPermissionsController(), {+ wrapper: makeWrapper(),+ })+ await waitFor(() => expect(result.current.loading).toBe(false))++ await act(async () => {+ await result.current.revoke('ns/plugin').catch(() => undefined)+ })+ // The security action used to fail silently; the banner must now show it.+ await waitFor(() => expect(result.current.error).toBe('revoke failed'))+ })++ it('clears a stale clear-activity error after a later successful revoke (R2-M1)', async () => {+ installPluginSdk({+ clearActivity: vi.fn(async () => {+ throw new Error('clear failed')+ }),+ })+ const { result } = renderHook(() => usePluginPermissionsController(), {+ wrapper: makeWrapper(),+ })+ await waitFor(() => expect(result.current.loading).toBe(false))++ await act(async () => {+ await result.current.clearActivity().catch(() => undefined)+ })+ await waitFor(() => expect(result.current.error).toBe('clear failed'))++ // A subsequent SUCCESSFUL revoke must not leave the stale clear-activity+ // error in the banner (reads as "your revoke failed" when it didn't).+ await act(async () => {+ await result.current.revoke('ns/plugin')+ })+ await waitFor(() => expect(result.current.error).toBeNull())+ })+})diff --git a/desktop-app/ui/src/hooks/domain/usePluginPermissionsController.ts b/desktop-app/ui/src/hooks/domain/usePluginPermissionsController.tsindex ca954da15..f8ac3a60b 100644--- a/desktop-app/ui/src/hooks/domain/usePluginPermissionsController.ts+++ b/desktop-app/ui/src/hooks/domain/usePluginPermissionsController.ts@@ -83,24 +83,32 @@ export function usePluginPermissionsController() {[activityQuery.data])+ // Show the error of the most-recently-submitted action, so a newer success+ // supersedes an older failure and no stale error lingers. Derived from+ // submittedAt rather than .reset()-ing the sibling — resetting an in-flight+ // mutation would drop a real failure and desync isPending. submittedAt is 0+ // for a mutation that has never run.+ const latestAction =+ clearActivityMutation.submittedAt > revokeMutation.submittedAt+ ? clearActivityMutation+ : revokeMutation+ const actionError = latestAction.error ? toErrorMessage(latestAction.error) : null+return {groups,activity,loading: grantsQuery.isPending || activityQuery.isPending,- // Surface query AND mutation failures. Without the mutation errors a failed+ // Query errors take precedence; otherwise the most-recent action's error+ // (null when it succeeded). Without surfacing mutation failures 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.+ // permission was revoked when it was not.error: grantsQuery.error? toErrorMessage(grantsQuery.error): activityQuery.error? toErrorMessage(activityQuery.error)- : revokeMutation.error- ? toErrorMessage(revokeMutation.error)- : clearActivityMutation.error- ? toErrorMessage(clearActivityMutation.error)- : null,+ : actionError,revoking: revokeMutation.isPending,+ clearingActivity: clearActivityMutation.isPending,revoke: (pluginId: string, capability?: string) =>revokeMutation.mutateAsync({ pluginId, ...(capability ? { capability } : {}) }),clearActivity: () => clearActivityMutation.mutateAsync(),