Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-app): bound the sandbox-ui session mint and authorize-url calls
Diego Zacariasd430115097e9
diff --git a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.tsindex c779ce66e..80f775609 100644--- a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts+++ b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts@@ -5,6 +5,7 @@ import path from 'node:path'import { AppService } from '../appService.js'import { _resetPluginSdkRuntimeForTests, initPluginSdkRuntime } from '../pluginSdkRuntime.js'import { _resetPluginSurfacesForTests, resolvePluginSurface } from '../pluginSurfaceRegistry.js'+import { SANDBOX_UI_MINT_TIMEOUT_MS } from '../rpcProxyClient.js'import { getActiveSandboxUi, unmountSandboxUiView } from '../sandboxUiDriver.js'import {SANDBOX_UI_REFRESH_INTERVAL_MS,@@ -216,15 +217,36 @@ function mintFails(status: number, body: string): Response {return new Response(body, { status })}-const mintResponders = new Map<string, () => Response>()-const fetchMock = vi.fn(async (input: string | URL | Request): Promise<Response> => {- const url = String(input instanceof Request ? input.url : input)- const match = /\/api\/v1\/sandbox-ui\/sandbox-recipes\/([^/]+)\/session$/.exec(url)- if (!match) throw new Error(`unexpected fetch ${url}`)- const recipeName = decodeURIComponent(match[1]!)- const respond = mintResponders.get(recipeName)- return respond ? respond() : mintOk(recipeName)-})+// rpc-proxy accepted the mint and never answers: it settles only if the client+// aborts it.+function mintHangs(init?: RequestInit): Promise<Response> {+ return new Promise<Response>((_resolve, reject) => {+ const signal = init?.signal+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true })+ })+}++// `AbortSignal.timeout` runs on the runtime's own timers, which fake timers do+// not drive. The mint bound is shrunk to a few ms instead, keyed on its exact+// value so the app-wide 60 s default is left untouched.+function shrinkMintBound(toMs = 25) {+ const realTimeout = AbortSignal.timeout.bind(AbortSignal)+ vi.spyOn(AbortSignal, 'timeout').mockImplementation(ms =>+ realTimeout(ms === SANDBOX_UI_MINT_TIMEOUT_MS ? toMs : ms)+ )+}++const mintResponders = new Map<string, (init?: RequestInit) => Response | Promise<Response>>()+const fetchMock = vi.fn(+ async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {+ const url = String(input instanceof Request ? input.url : input)+ const match = /\/api\/v1\/sandbox-ui\/sandbox-recipes\/([^/]+)\/session$/.exec(url)+ if (!match) throw new Error(`unexpected fetch ${url}`)+ const recipeName = decodeURIComponent(match[1]!)+ const respond = mintResponders.get(recipeName)+ return respond ? respond(init) : mintOk(recipeName)+ }+)function mintCallsFor(recipeName: string): number {return fetchMock.mock.calls.filter(([input]) =>@@ -269,6 +291,7 @@ beforeEach(async () => {})afterEach(async () => {+ vi.restoreAllMocks()await unmountSandboxUiView()_resetSandboxUiRefreshForTests()_resetPluginSurfacesForTests()@@ -414,3 +437,43 @@ describe('AppService sandbox-ui embed whose renderer dies', () => {expect(mintCallsFor('first-app')).toBe(mintsBefore)})})++describe('AppService sandbox-ui mint against a hung rpc-proxy', () => {+ it('a close queued behind an open whose mint hangs still runs', async () => {+ const { service, parentWindow } = await setupWithLiveFirstApp()+ shrinkMintBound()+ mintResponders.set('second-app', mintHangs)++ const open = service.openSandboxUi(openArgs('second-app', parentWindow))+ const openOutcome = open.then(+ () => 'opened',+ (error: unknown) => error+ )+ let closed = false+ void service.closeSandboxUi().then(() => {+ closed = true+ })++ await vi.waitFor(() => expect(closed).toBe(true), { timeout: 1_000 })+ await expect(openOutcome).resolves.toMatchObject({ name: 'TimeoutError' })+ expect(getActiveSandboxUi()).toBeNull()+ })++ it('a refresh whose mint hangs stops and reports the error', async () => {+ const onRefreshError = vi.fn()+ const service = makeService()+ initPluginSdkRuntime({ service, getMainWindow: () => null, userDataDir })+ const parentWindow = new FakeParentWindow()+ await service.openSandboxUi({ ...openArgs('first-app', parentWindow), onRefreshError })+ shrinkMintBound()+ mintResponders.set('first-app', mintHangs)++ await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)++ await vi.waitFor(() => expect(onRefreshError).toHaveBeenCalledOnce(), { timeout: 1_000 })+ // Stopped: a further interval issues no mint.+ const mintsBefore = mintCallsFor('first-app')+ await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)+ expect(mintCallsFor('first-app')).toBe(mintsBefore)+ })+})diff --git a/desktop-app/src/__tests__/rpcProxyClient.test.ts b/desktop-app/src/__tests__/rpcProxyClient.test.tsindex e4170c873..b8483b021 100644--- a/desktop-app/src/__tests__/rpcProxyClient.test.ts+++ b/desktop-app/src/__tests__/rpcProxyClient.test.ts@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest'-import { RpcProxyClient } from '../rpcProxyClient.js'+import { RpcProxyClient, SANDBOX_UI_MINT_TIMEOUT_MS } from '../rpcProxyClient.js'// Mock the config module so the module-level url() helper uses a fixed base URLvi.mock('../config.js', () => ({@@ -837,6 +837,76 @@ describe('RpcProxyClient.requestSandboxUiOauthAuthorizeUrl', () => {})})+// `AbortSignal.timeout` runs on the runtime's own timers, which fake timers do+// not drive. The sandbox-ui bound is shrunk to a few ms instead, keyed on its+// exact value so the app-wide 60 s default is left untouched: a call still+// using that default stays pending and the test fails on its assertion.+function shrinkSandboxUiBound(toMs = 25) {+ const realTimeout = AbortSignal.timeout.bind(AbortSignal)+ return vi+ .spyOn(AbortSignal, 'timeout')+ .mockImplementation(ms => realTimeout(ms === SANDBOX_UI_MINT_TIMEOUT_MS ? toMs : ms))+}++// An rpc-proxy that accepts the request and never answers: the call can only+// settle if the client aborts it.+function fetchThatOnlySettlesOnAbort() {+ return vi.fn(+ (_input: string | URL | Request, init?: RequestInit) =>+ new Promise<Response>((_resolve, reject) => {+ const signal = init?.signal+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true })+ })+ )+}++async function outcomeWithin(promise: Promise<unknown>, ms: number): Promise<unknown> {+ const pending = Symbol('pending')+ const outcome = await Promise.race([+ promise.then(+ () => 'resolved',+ (error: unknown) => error+ ),+ new Promise(resolve => setTimeout(() => resolve(pending), ms)),+ ])+ return outcome === pending ? 'still pending' : outcome+}++describe('RpcProxyClient sandbox-ui calls against a hung rpc-proxy', () => {+ beforeEach(() => {+ vi.restoreAllMocks()+ })++ it('bounds the sandbox-ui calls well under the app-wide request timeout', () => {+ expect(SANDBOX_UI_MINT_TIMEOUT_MS).toBeGreaterThanOrEqual(15_000)+ expect(SANDBOX_UI_MINT_TIMEOUT_MS).toBeLessThanOrEqual(20_000)+ })++ it('rejects a session mint once its bound elapses', async () => {+ shrinkSandboxUiBound()+ vi.stubGlobal('fetch', fetchThatOnlySettlesOnAbort())++ const outcome = await outcomeWithin(+ new RpcProxyClient().mintSandboxUiSession('t', 'sandbox-recipes', 'crm'),+ 1_000+ )++ expect(outcome).toMatchObject({ name: 'TimeoutError' })+ })++ it('rejects an authorize-url request once its bound elapses', async () => {+ shrinkSandboxUiBound()+ vi.stubGlobal('fetch', fetchThatOnlySettlesOnAbort())++ const outcome = await outcomeWithin(+ new RpcProxyClient().requestSandboxUiOauthAuthorizeUrl('t', 'sandbox-recipes', 'crm', 'cid'),+ 1_000+ )++ expect(outcome).toMatchObject({ name: 'TimeoutError' })+ })+})+describe('RpcProxyClient.listSandboxUiApps', () => {let client: RpcProxyClientdiff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.tsindex 45c60dba0..d118284c8 100644--- a/desktop-app/src/rpcProxyClient.ts+++ b/desktop-app/src/rpcProxyClient.ts@@ -429,6 +429,14 @@ async function parseApprovalDecisionResponse(response: Response): Promise<Approv}}+// A sandbox-ui open/close runs on a single lifecycle queue, so a hung mint+// blocks every queued close behind it; and the refresh re-mints only 30 s+// before the cookie expires. The app-wide default (60 s) would be too loose+// for both.+// The embed's OAuth authorize-url call shares it: a hung one would leave the+// embed's click without any answer for a minute.+export const SANDBOX_UI_MINT_TIMEOUT_MS = 15_000+function url(path: string): string {return `${config.rpcProxyBaseUrl.replace(/\/+$/, '')}${path}`}@@ -675,6 +683,7 @@ export class RpcProxyClient {{method: 'POST',headers: { authorization: `Bearer ${rpcAccessToken}` },+ signal: withTimeout(undefined, SANDBOX_UI_MINT_TIMEOUT_MS),})if (response.status !== 204) {@@ -715,6 +724,7 @@ export class RpcProxyClient {'content-type': 'application/json',},body: JSON.stringify({ oauthClientId, background }),+ signal: withTimeout(undefined, SANDBOX_UI_MINT_TIMEOUT_MS),})if (!response.ok) {