Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test(desktop): valid-state properties and producer-boundary proofs (R1-M6)
M7776023f84d1
diff --git a/desktop-app/src/__tests__/gfsCancellableInvoke.test.ts b/desktop-app/src/__tests__/gfsCancellableInvoke.test.tsindex 159417eed..e4b0fd9aa 100644--- a/desktop-app/src/__tests__/gfsCancellableInvoke.test.ts+++ b/desktop-app/src/__tests__/gfsCancellableInvoke.test.ts@@ -1,65 +1,109 @@/**- * R2-L3 — an already-aborted signal must start NO producer work: the invoke is- * never sent and no gfs:abort event fires. Also pins the mid-flight contract:- * requestId on the invoke, exactly one gfs:abort on abort, listener cleanup on- * settle.+ * R2-L3/R1-M6 — the REAL preload's cancellable GFS bridge, exercised through+ * a mocked Electron boundary. The preload is the sandboxed security surface,+ * so its behavior is tested directly (no extracted helper): an already-aborted+ * signal starts no producer work; a mid-flight abort fires gfs:abort exactly+ * once with the invoke's requestId; a signal-less call is a plain invoke.*/-import { describe, expect, it, vi } from 'vitest'-import { cancellableInvoke } from '../gfs/cancellableInvoke.js'+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'-function bridge() {+const electron = vi.hoisted(() => {+ const exposed = new Map<string, unknown>()return {- invoke: vi.fn(() => new Promise(() => undefined)),- send: vi.fn(),+ exposed,+ ipcRenderer: {+ invoke: vi.fn(() => new Promise(() => undefined)),+ send: vi.fn(),+ on: vi.fn(),+ removeAllListeners: vi.fn(),+ },+ }+})++vi.mock('electron', () => ({+ contextBridge: {+ exposeInMainWorld: vi.fn((name: string, value: unknown) => {+ electron.exposed.set(name, value)+ }),+ },+ ipcRenderer: electron.ipcRenderer,+ webUtils: { getPathForFile: vi.fn() },+}))++type ClerumBridge = {+ gfs: {+ listChildren: (+ resourceId: string,+ drive?: string,+ cursor?: string,+ options?: { signal?: AbortSignal }+ ) => Promise<unknown>+ download: (+ uri: string,+ options?: { maxBytes?: number; signal?: AbortSignal }+ ) => Promise<unknown>}}-describe('cancellableInvoke (R2-L3)', () => {+let bridge: ClerumBridge++beforeAll(async () => {+ await import('../preload.js')+ bridge = electron.exposed.get('clerum') as ClerumBridge+})++afterEach(() => {+ vi.clearAllMocks()+})++describe('preload cancellable GFS bridge (R2-L3)', () => {it('starts no IPC or producer work for an already-aborted signal', async () => {- const mockBridge = bridge()const controller = new AbortController()controller.abort()await expect(- cancellableInvoke(mockBridge, 'gfs:listChildren', { resourceId: 'r' }, controller.signal)+ bridge.gfs.listChildren('folder-1', 'main', undefined, { signal: controller.signal })+ ).rejects.toMatchObject({ name: 'AbortError' })+ await expect(+ bridge.gfs.download('gfs://main/x', { signal: controller.signal })).rejects.toMatchObject({ name: 'AbortError' })- expect(mockBridge.invoke).not.toHaveBeenCalled()- expect(mockBridge.send).not.toHaveBeenCalled()+ expect(electron.ipcRenderer.invoke).not.toHaveBeenCalled()+ expect(electron.ipcRenderer.send).not.toHaveBeenCalled()})- it('sends the requestId, fires gfs:abort exactly once on mid-flight abort, and detaches on settle', async () => {- const mockBridge = bridge()+ it('carries a requestId, fires gfs:abort once on abort, and detaches on settle', async () => {const controller = new AbortController()+ const pending = bridge.gfs.listChildren('folder-1', 'main', undefined, {+ signal: controller.signal,+ })+ pending.catch(() => undefined)- const pending = cancellableInvoke(- mockBridge,- 'gfs:download',- { uri: 'gfs://main/x', maxBytes: 10 },- controller.signal- )- expect(mockBridge.invoke).toHaveBeenCalledTimes(1)- const payload = mockBridge.invoke.mock.calls[0]?.[1] as { requestId?: string }+ expect(electron.ipcRenderer.invoke).toHaveBeenCalledTimes(1)+ const [channel, payload] = electron.ipcRenderer.invoke.mock.calls[0] as [+ string,+ { requestId?: string },+ ]+ expect(channel).toBe('gfs:listChildren')expect(typeof payload.requestId).toBe('string')controller.abort()- expect(mockBridge.send).toHaveBeenCalledTimes(1)- expect(mockBridge.send).toHaveBeenCalledWith('gfs:abort', { requestId: payload.requestId })- // A second abort event (late listener) must not re-send after cleanup.+ expect(electron.ipcRenderer.send).toHaveBeenCalledTimes(1)+ expect(electron.ipcRenderer.send).toHaveBeenCalledWith('gfs:abort', {+ requestId: payload.requestId,+ })+ // A late synthetic abort event must not re-send after cleanup.controller.signal.dispatchEvent(new Event('abort'))- pending.catch(() => undefined)- await Promise.resolve()- expect(mockBridge.send).toHaveBeenCalledTimes(1)+ expect(electron.ipcRenderer.send).toHaveBeenCalledTimes(1)})- it('invokes without a signal exactly as a plain pass-through', async () => {- const mockBridge = bridge()- mockBridge.invoke.mockReturnValue(Promise.resolve({ ok: true }))- const result = await cancellableInvoke<{ ok: boolean }>(mockBridge, 'gfs:resolve', {+ it('forwards the download bound and passes a signal-less call through untouched', async () => {+ electron.ipcRenderer.invoke.mockReturnValueOnce(Promise.resolve({ ok: true }))+ bridge.gfs.download('gfs://main/x', { maxBytes: 512 })+ expect(electron.ipcRenderer.invoke).toHaveBeenCalledWith('gfs:download', {uri: 'gfs://main/x',+ maxBytes: 512,+ requestId: undefined,})- expect(result).toEqual({ ok: true })- expect(mockBridge.invoke).toHaveBeenCalledWith('gfs:resolve', { uri: 'gfs://main/x' })- expect(mockBridge.send).not.toHaveBeenCalled()})})diff --git a/desktop-app/src/__tests__/gfsProducerAbort.test.ts b/desktop-app/src/__tests__/gfsProducerAbort.test.tsnew file mode 100644index 000000000..d1f2fb2d3--- /dev/null+++ b/desktop-app/src/__tests__/gfsProducerAbort.test.ts@@ -0,0 +1,134 @@+/**+ * R1-M6 (round 2) — cancellation proven through the REAL producer boundary.+ * The abort path is exercised end to end: the ipc handler's AbortController →+ * the real `GfsClient.listChildren` → the real transport `requestJson`+ * (signal-honoring stub that hangs until aborted), and separately the real+ * `fetchBoundedBytes` (its OWN controller funnels the external signal into the+ * fetch it starts). No service mock is abort-aware: the only fake is the+ * network leg, which OBSERVES the signal exactly like a real fetch.+ */+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'+import type { AppService } from '../appService.js'+import { fetchBoundedBytes } from '../gfs/boundedDownload.js'+import { GfsClient } from '../gfs/uriHandler.js'++type Handler = (event: unknown, payload: unknown) => Promise<unknown>+type Listener = (event: unknown, payload: unknown) => void++const electron = vi.hoisted(() => ({+ handlers: new Map<string, Handler>(),+ listeners: new Map<string, Listener>(),+}))++vi.mock('electron', () => ({+ BrowserWindow: { fromWebContents: vi.fn(), getAllWindows: vi.fn(() => []) },+ Notification: vi.fn(),+ app: { on: vi.fn(), getPath: vi.fn(), getVersion: vi.fn(), isReady: vi.fn(() => false) },+ clipboard: { writeText: vi.fn() },+ dialog: { showSaveDialog: vi.fn() },+ ipcMain: {+ handle: vi.fn((channel: string, handler: Handler) => {+ electron.handlers.set(channel, handler)+ }),+ on: vi.fn((channel: string, listener: Listener) => {+ electron.listeners.set(channel, listener)+ }),+ removeHandler: vi.fn(),+ },+}))+// ipc.ts only uses AppService as a type at registration; the real module would+// pull in the whole main-process graph. The service below is a thin adapter to+// the REAL GfsClient — nothing in the cancellation path is faked.+vi.mock('../appService.js', () => ({ AppService: class {} }))++const trusted = { senderFrame: { url: 'file:///app/index.html' } }++/** Network leg that hangs until its signal aborts — like a real fetch. */+function signalHangingRequestJson() {+ return vi.fn(+ (_method: unknown, _url: unknown, options?: { signal?: AbortSignal }) =>+ new Promise((_resolve, reject) => {+ if (options?.signal?.aborted) {+ reject(new DOMException('The operation was aborted.', 'AbortError'))+ return+ }+ options?.signal?.addEventListener(+ 'abort',+ () => reject(new DOMException('The operation was aborted.', 'AbortError')),+ { once: true }+ )+ })+ )+}++describe('producer-side abort through the real GfsClient (R1-M6)', () => {+ const requestJson = signalHangingRequestJson()+ const client = new GfsClient({+ baseUrl: 'https://api.example',+ requestJson: requestJson as unknown as never,+ fetchBytes: (url, token, opts) => fetchBoundedBytes(url, token, opts),+ })+ const service = {+ listGfsChildren: (resourceId: string, drive?: string, cursor?: string, signal?: AbortSignal) =>+ client.listChildren(resourceId, 'session-token', { drive, cursor, signal }),+ }++ beforeAll(async () => {+ const { registerIpcHandlers } = await import('../ipc.js')+ registerIpcHandlers(service as unknown as AppService)+ })++ afterEach(() => {+ requestJson.mockClear()+ })++ it('gfs:abort ends the real client listing through its transport signal', async () => {+ const pending = electron.handlers.get('gfs:listChildren')!(trusted, {+ resourceId: 'folder-1',+ requestId: 'req-real-1',+ })+ const rejection = expect(pending).rejects.toMatchObject({ name: 'AbortError' })+ for (let index = 0; index < 25 && requestJson.mock.calls.length === 0; index += 1) {+ await Promise.resolve()+ }+ // The REAL client reached the transport leg carrying the handler's signal.+ const transportOptions = requestJson.mock.calls[0]?.[2] as { signal?: AbortSignal }+ expect(transportOptions?.signal).toBeInstanceOf(AbortSignal)+ expect(transportOptions?.signal?.aborted).toBe(false)++ electron.listeners.get('gfs:abort')!(trusted, { requestId: 'req-real-1' })+ await rejection+ // The producer leg observed the abort — the fetch died, not just the IPC.+ expect(transportOptions?.signal?.aborted).toBe(true)+ })++ it('the real bounded fetch funnels an external signal into the fetch it starts', async () => {+ const controller = new AbortController()+ const seenSignals: Array<AbortSignal | undefined> = []+ const hangingFetch = (_url: unknown, init?: { signal?: AbortSignal }) =>+ new Promise<Response>((_resolve, reject) => {+ seenSignals.push(init?.signal)+ init?.signal?.addEventListener(+ 'abort',+ () => reject(new DOMException('The operation was aborted.', 'AbortError')),+ { once: true }+ )+ })+ const pending = fetchBoundedBytes(+ 'https://api.example/file',+ 'session-token',+ { signal: controller.signal },+ { fetch: hangingFetch as unknown as typeof fetch }+ )+ const rejection = expect(pending).rejects.toMatchObject({ name: 'AbortError' })+ for (let index = 0; index < 25 && seenSignals.length === 0; index += 1) {+ await Promise.resolve()+ }+ // The fetch the bounded downloader started received a REAL signal.+ expect(seenSignals[0]).toBeInstanceOf(AbortSignal)+ expect(seenSignals[0]!.aborted).toBe(false)+ controller.abort()+ await rejection+ expect(seenSignals[0]!.aborted).toBe(true)+ })+})diff --git a/desktop-app/src/gfs/cancellableInvoke.ts b/desktop-app/src/gfs/cancellableInvoke.tsdeleted file mode 100644index dc7db438c..000000000--- a/desktop-app/src/gfs/cancellableInvoke.ts+++ /dev/null@@ -1,33 +0,0 @@-/**- * Preload-side wiring for cancellable invokes (folder-zip Stop, R1-M1/R2-L3).- * Pure with an injected ipcRenderer-shaped bridge so the abort ordering is- * unit-testable without Electron:- *- * - an ALREADY-ABORTED signal starts NO producer work: the invoke is never- * sent and no abort event is fired (R2-L3) — the caller gets an AbortError- * immediately;- * - a signal that aborts mid-flight fires `gfs:abort` with the invoke's- * requestId exactly once, and the listener detaches when the invoke settles.- */-export interface CancellableIpcBridge {- invoke(channel: string, payload: unknown): Promise<unknown>- send(channel: string, payload: unknown): void-}--export function cancellableInvoke<T>(- bridge: CancellableIpcBridge,- channel: string,- payload: Record<string, unknown>,- signal?: AbortSignal-): Promise<T> {- if (!signal) return bridge.invoke(channel, payload) as Promise<T>- if (signal.aborted) {- return Promise.reject(new DOMException('Request was stopped before it started.', 'AbortError'))- }- const requestId = crypto.randomUUID()- const onAbort = () => bridge.send('gfs:abort', { requestId })- signal.addEventListener('abort', onAbort, { once: true })- return bridge- .invoke(channel, { ...payload, requestId })- .finally(() => signal.removeEventListener('abort', onAbort)) as Promise<T>-}diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.tsindex 41c6bcfde..f7f976b07 100644--- a/desktop-app/src/preload.ts+++ b/desktop-app/src/preload.ts@@ -1,6 +1,5 @@import { contextBridge, ipcRenderer, webUtils } from 'electron'import type { DesktopCommandId, DesktopCommandSource } from './desktopCommands.js'-import { cancellableInvoke } from './gfs/cancellableInvoke.js'import type { PluginConsentRequest } from './pluginSdkProtocol.js'import type {EntityChangeStreamEvent,@@ -47,22 +46,27 @@ const DESKTOP_COMMAND_IDS = new Set<DesktopCommandId>([])/**- * Producer-side cancellation wiring (folder-zip Stop, R1-M1): see- * gfs/cancellableInvoke.ts — a cancellable invoke carries a requestId; if the- * caller's signal aborts, main aborts the in-flight request. An already-- * aborted signal never starts producer work at all (R2-L3).+ * Producer-side cancellation wiring (folder-zip Stop, R1-M1): a cancellable+ * invoke carries a requestId; if the caller's signal aborts, main aborts the+ * in-flight request. An already-aborted signal never starts producer work —+ * no invoke, no gfs:abort event (R2-L3). Kept INLINE: the sandboxed preload+ * must stay free of relative value imports (self-containment contract).*/function cancellableGfsInvoke<T>(channel: string,payload: Record<string, unknown>,signal?: AbortSignal): Promise<T> {- return cancellableInvoke<T>(- { invoke: (c, p) => ipcRenderer.invoke(c, p), send: (c, p) => ipcRenderer.send(c, p) },- channel,- payload,- signal- )+ if (!signal) return ipcRenderer.invoke(channel, payload) as Promise<T>+ if (signal.aborted) {+ return Promise.reject(new DOMException('Request was stopped before it started.', 'AbortError'))+ }+ const requestId = crypto.randomUUID()+ const onAbort = () => ipcRenderer.send('gfs:abort', { requestId })+ signal.addEventListener('abort', onAbort, { once: true })+ return ipcRenderer+ .invoke(channel, { ...payload, requestId })+ .finally(() => signal.removeEventListener('abort', onAbort)) as Promise<T>}function isDesktopCommandId(value: unknown): value is DesktopCommandId {diff --git a/desktop-app/ui/src/hooks/domain/__tests__/composerMergeZipProperties.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/composerMergeZipProperties.test.tsxindex 6ca31d094..ff546cb87 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/composerMergeZipProperties.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/composerMergeZipProperties.test.tsx@@ -42,6 +42,26 @@ const referenceArbitrary = fcname: record.id,}))+// R1-M6 (round 2): starting states must be VALID composer states. A generator+// that can produce `existing` above the cap tests states production can never+// hold, so every invariant below was provable against garbage. The existing+// arrays are constrained to at-most-cap; incoming stays arbitrary.+const heldImagesArbitrary = fc+ .uniqueArray(imageArbitrary, {+ minLength: 0,+ maxLength: COMPOSER_MAX_IMAGE_ATTACHMENTS,+ selector: item => `${item.mimeType}:${item.sizeBytes}:${item.dataBase64}`,+ })+ .map(items => items as ComposerImageAttachment[])++const heldReferencesArbitrary = fc+ .uniqueArray(referenceArbitrary, {+ minLength: 0,+ maxLength: FILE_REFERENCE_MAX_COUNT,+ selector: item => item.id,+ })+ .map(items => items as ComposerReferenceAttachment[])+describe('composer merge invariants (R1-M6)', () => {it('counts a cap-time duplicate as a duplicate, not a drop (R2-L1)', () => {// Composer already at the cap; the restore payload is byte-identical to@@ -68,11 +88,14 @@ describe('composer merge invariants (R1-M6)', () => {it('image merge: cap, count conservation, and existing-set stability', () => {fc.assert(fc.property(- fc.array(imageArbitrary, { maxLength: 30 }),+ heldImagesArbitrary,fc.array(imageArbitrary, { maxLength: 30 }),(existing, incoming) => {+ // Valid starting state (R1-M6 round 2): a real composer is never+ // above the cap, and never holds byte-duplicates.+ expect(existing.length).toBeLessThanOrEqual(COMPOSER_MAX_IMAGE_ATTACHMENTS)const outcome = mergeComposerImageAttachments(- existing as ComposerImageAttachment[],+ existing,incoming as ComposerImageAttachment[])expect(outcome.next.length).toBeLessThanOrEqual(COMPOSER_MAX_IMAGE_ATTACHMENTS)@@ -81,6 +104,80 @@ describe('composer merge invariants (R1-M6)', () => {expect(outcome.next.slice(0, existing.length)).toEqual(existing)// Duplicates never consume slots: keeping room is consistent with counts.expect(outcome.kept).toBe(outcome.next.length - existing.length)+ // Decision path (R2-L1): drops can only be NOT-held incoming items.+ const heldKeys = new Set(+ existing.map(item => `${item.mimeType}:${item.sizeBytes}:${item.dataBase64}`)+ )+ const notHeldIncoming = incoming.filter(+ item => !heldKeys.has(`${item.mimeType}:${item.sizeBytes}:${item.dataBase64}`)+ )+ expect(outcome.dropped).toBeLessThanOrEqual(notHeldIncoming.length)+ }+ ),+ { numRuns: 80 }+ )+ })++ it('image merge at cap: incoming duplicates never count as drops (decision path)', () => {+ fc.assert(+ fc.property(+ fc.integer({ min: 0, max: COMPOSER_MAX_IMAGE_ATTACHMENTS }),+ fc.array(imageArbitrary, { maxLength: 10 }),+ (heldCount, extra) => {+ // A composer at the cap whose restore payload includes held images:+ // every held image reports as a duplicate and dropped is exactly the+ // not-held overflow.+ const held = Array.from({ length: heldCount }, (_, index) => ({+ ...({} as ComposerImageAttachment),+ id: `h-${index}`,+ name: `h-${index}.png`,+ mimeType: 'image/png' as const,+ dataBase64: `aGQt${index}`,+ sizeBytes: index,+ previewDataUrl: `data:image/png;base64,aGQt${index}`,+ }))+ const payload = [+ ...held.slice(0, Math.min(3, heldCount)),+ ...(extra as ComposerImageAttachment[]),+ ]+ const outcome = mergeComposerImageAttachments(held, payload)+ expect(outcome.next).toEqual(+ held.length ? expect.arrayContaining(held) : expect.anything()+ )+ expect(outcome.next.length).toBe(Math.max(heldCount, 0) + outcome.kept)+ const notHeld = payload.filter(+ item =>+ !held.some(h => h.dataBase64 === item.dataBase64 && h.sizeBytes === item.sizeBytes)+ )+ expect(outcome.dropped).toBe(+ Math.max(0, notHeld.length - Math.max(0, COMPOSER_MAX_IMAGE_ATTACHMENTS - heldCount))+ )+ }+ ),+ { numRuns: 60 }+ )+ })++ it('image merge idempotence: a second identical restore changes nothing', () => {+ fc.assert(+ fc.property(+ heldImagesArbitrary,+ fc.array(imageArbitrary, { maxLength: 15 }),+ (existing, incoming) => {+ const first = mergeComposerImageAttachments(+ existing,+ incoming as ComposerImageAttachment[]+ )+ const second = mergeComposerImageAttachments(+ first.next,+ incoming as ComposerImageAttachment[]+ )+ // State stability: nothing new is kept, the composer is unchanged, and+ // the payload still accounts entirely to duplicates + (persistent,+ // cap-driven) drops — never to new losses.+ expect(second.kept).toBe(0)+ expect(second.next).toEqual(first.next)+ expect(second.duplicates + second.dropped).toBe(incoming.length)}),{ numRuns: 60 }@@ -90,17 +187,43 @@ describe('composer merge invariants (R1-M6)', () => {it('reference merge: file cap, count conservation, and id uniqueness', () => {fc.assert(fc.property(- fc.array(referenceArbitrary, { maxLength: 25 }),+ heldReferencesArbitrary,fc.array(referenceArbitrary, { maxLength: 25 }),(existing, incoming) => {const outcome = mergeComposerReferenceAttachments(- existing as ComposerReferenceAttachment[],+ existing,incoming as ComposerReferenceAttachment[])+ expect(existing.length).toBeLessThanOrEqual(FILE_REFERENCE_MAX_COUNT)expect(outcome.next.length).toBeLessThanOrEqual(FILE_REFERENCE_MAX_COUNT)expect(outcome.kept + outcome.duplicates + outcome.dropped).toBe(incoming.length)const ids = new Set(outcome.next.map(item => item.id))expect(ids.size).toBe(outcome.next.length)+ // Held references are never dropped (dedupe runs first).+ expect(outcome.next.slice(0, existing.length)).toEqual(existing)+ }+ ),+ { numRuns: 80 }+ )+ })++ it('reference merge idempotence: a second identical restore changes nothing', () => {+ fc.assert(+ fc.property(+ heldReferencesArbitrary,+ fc.array(referenceArbitrary, { maxLength: 10 }),+ (existing, incoming) => {+ const first = mergeComposerReferenceAttachments(+ existing,+ incoming as ComposerReferenceAttachment[]+ )+ const second = mergeComposerReferenceAttachments(+ first.next,+ incoming as ComposerReferenceAttachment[]+ )+ expect(second.kept).toBe(0)+ expect(second.next).toEqual(first.next)+ expect(second.duplicates + second.dropped).toBe(incoming.length)}),{ numRuns: 60 }