Skip to content

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

TypeScript

fix(desktop): propagate the zip walk stop to producer-side fetches (R1-M1)

Me47b8e6e5a99
diff --git a/desktop-app/src/__tests__/ipc.gfsAbort.test.ts b/desktop-app/src/__tests__/ipc.gfsAbort.test.ts
new file mode 100644
index 000000000..c7ea8d2ed
--- /dev/null
+++ b/desktop-app/src/__tests__/ipc.gfsAbort.test.ts
@@ -0,0 +1,122 @@
+/**
+ * R1-M1 — producer-side cancellation. A cancellable GFS read ('gfs:listChildren'
+ * or 'gfs:download') carries a requestId; 'gfs:abort' must abort the in-flight
+ * request's AbortController so the producer fetch ends instead of burning the
+ * per-actor read budget after the user pressed Stop.
+ */
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+import type { AppService } from '../appService.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() },
+ 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.
+vi.mock('../appService.js', () => ({ AppService: class {} }))
+
+/** A service read that settles ONLY when its signal aborts, like a real fetch. */
+function hangingRead() {
+ return vi.fn(
+ (_resourceId: string, _drive?: string, _cursor?: string, signal?: AbortSignal) =>
+ new Promise((_resolve, reject) => {
+ signal?.addEventListener('abort', () => reject(new Error('producer aborted')), {
+ once: true,
+ })
+ })
+ )
+}
+
+const trusted = { senderFrame: { url: 'file:///app/index.html' } }
+
+function handler(channel: string): Handler {
+ const registered = electron.handlers.get(channel)
+ if (!registered) throw new Error(`no handler registered for ${channel}`)
+ return registered
+}
+
+function abortListener(): Listener {
+ const registered = electron.listeners.get('gfs:abort')
+ if (!registered) throw new Error('no gfs:abort listener registered')
+ return registered
+}
+
+async function flushMicrotasks() {
+ for (let index = 0; index < 25; index += 1) await Promise.resolve()
+}
+
+describe('gfs producer-side abort (R1-M1)', () => {
+ const service = {
+ listGfsChildren: hangingRead(),
+ downloadGfsUri: vi.fn(async () => new ArrayBuffer(0)),
+ }
+
+ beforeAll(async () => {
+ const { registerIpcHandlers } = await import('../ipc.js')
+ registerIpcHandlers(service as unknown as AppService)
+ })
+
+ afterEach(() => {
+ service.listGfsChildren.mockClear()
+ })
+
+ it('aborts the in-flight producer listing when the renderer stops the walk', async () => {
+ const pending = handler('gfs:listChildren')(trusted, {
+ resourceId: 'folder-1',
+ requestId: 'req-1',
+ })
+ const rejection = expect(pending).rejects.toThrow('producer aborted')
+ await flushMicrotasks()
+ const signal = service.listGfsChildren.mock.calls[0]?.[3] as AbortSignal | undefined
+ expect(signal).toBeInstanceOf(AbortSignal)
+ expect(signal?.aborted).toBe(false)
+
+ abortListener()(trusted, { requestId: 'req-1' })
+ await rejection
+ expect(signal?.aborted).toBe(true)
+ })
+
+ it('leaves unrelated in-flight requests alone', async () => {
+ const pending = handler('gfs:listChildren')(trusted, {
+ resourceId: 'folder-1',
+ requestId: 'req-a',
+ })
+ await flushMicrotasks()
+ const signal = service.listGfsChildren.mock.calls[0]?.[3] as AbortSignal | undefined
+
+ abortListener()(trusted, { requestId: 'req-other' })
+ await flushMicrotasks()
+ expect(signal?.aborted).toBe(false)
+ expect(pending).toEqual(expect.any(Promise)) // still pending, not rejected
+
+ abortListener()(trusted, { requestId: 'req-a' })
+ await expect(pending).rejects.toThrow('producer aborted')
+ })
+
+ it('runs uncancellable reads without a signal when no requestId is sent', async () => {
+ const immediate = vi.fn(async () => ({ items: [], nextCursor: null }))
+ service.listGfsChildren.mockImplementationOnce(immediate)
+ await handler('gfs:listChildren')(trusted, { resourceId: 'folder-1' })
+ expect(immediate).toHaveBeenCalledWith('folder-1', undefined, undefined, undefined)
+ })
+})
diff --git a/desktop-app/src/__tests__/ipc.gfsDownloadLimit.test.ts b/desktop-app/src/__tests__/ipc.gfsDownloadLimit.test.ts
index ceaee48d3..65e116000 100644
--- a/desktop-app/src/__tests__/ipc.gfsDownloadLimit.test.ts
+++ b/desktop-app/src/__tests__/ipc.gfsDownloadLimit.test.ts
@@ -56,12 +56,12 @@ describe('gfs:download maxBytes boundary (R1-H2)', () => {
it('passes a within-ceiling bound through to the service', async () => {
await handler('gfs:download')(trusted, { uri, maxBytes: 1024 })
- expect(service.downloadGfsUri).toHaveBeenCalledWith(uri, 1024)
+ expect(service.downloadGfsUri).toHaveBeenCalledWith(uri, 1024, undefined)
})
it('stays uncapped when no bound is requested', async () => {
await handler('gfs:download')(trusted, { uri })
- expect(service.downloadGfsUri).toHaveBeenCalledWith(uri, undefined)
+ expect(service.downloadGfsUri).toHaveBeenCalledWith(uri, undefined, undefined)
})
it('rejects a bound above the ceiling before reaching the service', async () => {
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index 7fc59f65c..b5161ff41 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -2100,17 +2100,21 @@ export class AppService {
* oversized payload materializes); omitting it (save-to-disk, plugin SDK)
* reads the full body.
*/
- async downloadGfsUri(uri: string, maxBytes?: number) {
+ async downloadGfsUri(uri: string, maxBytes?: number, signal?: AbortSignal) {
return this.gfsClient.download(
uri,
this.requireSessionToken(),
- maxBytes !== undefined ? { maxBytes } : undefined
+ maxBytes !== undefined || signal !== undefined ? { maxBytes, signal } : undefined
)
}
/** List a gfs directory's children (deny-by-default: only what the user is granted). */
- async listGfsChildren(resourceId: string, drive?: string, cursor?: string) {
- return this.gfsClient.listChildren(resourceId, this.requireSessionToken(), { drive, cursor })
+ async listGfsChildren(resourceId: string, drive?: string, cursor?: string, signal?: AbortSignal) {
+ return this.gfsClient.listChildren(resourceId, this.requireSessionToken(), {
+ drive,
+ cursor,
+ signal,
+ })
}
/** List explicit gfs resources the current user can read through grants or shares. */
diff --git a/desktop-app/src/gfs/boundedDownload.ts b/desktop-app/src/gfs/boundedDownload.ts
index ba3a09144..a9806525f 100644
--- a/desktop-app/src/gfs/boundedDownload.ts
+++ b/desktop-app/src/gfs/boundedDownload.ts
@@ -25,11 +25,17 @@ export interface BoundedDownloadDeps {
export async function fetchBoundedBytes(
url: string,
token: string,
- opts?: { maxBytes?: number },
+ opts?: { maxBytes?: number; signal?: AbortSignal },
deps: BoundedDownloadDeps = { fetch }
): Promise<ArrayBuffer> {
const maxBytes = opts?.maxBytes
const controller = new AbortController()
+ // An external signal (producer-side cancellation, R1-M1) funnels into the
+ // same controller that bounds the body: aborting it ends the fetch.
+ if (opts?.signal) {
+ if (opts.signal.aborted) controller.abort()
+ else opts.signal.addEventListener('abort', () => controller.abort(), { once: true })
+ }
const res = await deps.fetch(url, {
headers: { authorization: `Bearer ${token}` },
signal: controller.signal,
diff --git a/desktop-app/src/gfs/uriHandler.ts b/desktop-app/src/gfs/uriHandler.ts
index 84d1d606b..5e650fe9d 100644
--- a/desktop-app/src/gfs/uriHandler.ts
+++ b/desktop-app/src/gfs/uriHandler.ts
@@ -93,8 +93,13 @@ export interface GfsTransport {
* Binary fetch for downloads (resolves to the raw bytes). `opts.maxBytes`
* bounds the download so an oversized payload is rejected before it fully
* materializes; omitting it reads the whole body (the save-to-disk path).
+ * `opts.signal` cancels the producer-side fetch (folder-zip Stop).
*/
- fetchBytes(url: string, token: string, opts?: { maxBytes?: number }): Promise<ArrayBuffer>
+ fetchBytes(
+ url: string,
+ token: string,
+ opts?: { maxBytes?: number; signal?: AbortSignal }
+ ): Promise<ArrayBuffer>
}
/**
@@ -419,13 +424,13 @@ export class GfsClient {
constructor(private readonly transport: GfsTransport) {}
/** Resolve a gfs:// URI to its current resource (validates the URI locally first). */
- async resolveUri(uri: string, token: string): Promise<ResolvedGfsResource> {
+ async resolveUri(uri: string, token: string, signal?: AbortSignal): Promise<ResolvedGfsResource> {
parseGfsUri(uri) // fail fast on a malformed URI before a round-trip
try {
const payload = await this.transport.requestJson<GfsEnvelope<ResolvedGfsResource>>(
'GET',
joinUrl(this.transport.baseUrl, `/api/v1/me/gfs/resolve?uri=${encodeURIComponent(uri)}`),
- { token }
+ { token, signal }
)
return unwrap(payload)
} catch (error) {
@@ -442,20 +447,20 @@ export class GfsClient {
async download(
uri: string,
token: string,
- opts?: { maxBytes?: number }
+ opts?: { maxBytes?: number; signal?: AbortSignal }
): Promise<{ resource: ResolvedGfsResource; bytes: ArrayBuffer }> {
// resolveUri runs first and already surfaces its own verdict, so a 429 on the
// resolve leg reaches the renderer with the resolve message, not this one.
- const resource = await this.resolveUri(uri, token)
+ const resource = await this.resolveUri(uri, token, opts?.signal)
const proxyUrl = joinUrl(
this.transport.baseUrl,
`/api/v1/me/gfs/proxy/${resource.resourceId}?drive=${encodeURIComponent(resource.drive)}`
)
try {
- const bytes =
- opts?.maxBytes !== undefined
- ? await this.transport.fetchBytes(proxyUrl, token, { maxBytes: opts.maxBytes })
- : await this.transport.fetchBytes(proxyUrl, token)
+ const bytes = await this.transport.fetchBytes(proxyUrl, token, {
+ maxBytes: opts?.maxBytes,
+ signal: opts?.signal,
+ })
return { resource, bytes }
} catch (error) {
throw surfaceGfsGrantError(error)
@@ -470,7 +475,7 @@ export class GfsClient {
async listChildren(
resourceId: string,
token: string,
- opts?: { drive?: string; cursor?: string }
+ opts?: { drive?: string; cursor?: string; signal?: AbortSignal }
): Promise<GfsChildrenPage> {
const q = new URLSearchParams()
q.set('drive', opts?.drive ?? DEFAULT_DRIVE)
@@ -482,7 +487,7 @@ export class GfsClient {
this.transport.baseUrl,
`/api/v1/me/gfs/resources/${encodeURIComponent(resourceId)}/children?${q.toString()}`
),
- { token }
+ { token, signal: opts?.signal }
)
return unwrap(payload)
} catch (error) {
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index fd631e7a6..b4a7f8b3d 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -291,6 +291,32 @@ export function registerIpcHandlers(service: AppService): void {
const entityChangeOwnerCleanupRegistered = new Set<number>()
const activeDesktopNotifications = new Map<string, Notification>()
+ // Producer-side cancellation for cancellable GFS reads (folder-zip walk,
+ // R1-M1): the renderer attaches a requestId to an invoke and fires
+ // 'gfs:abort' on Stop; the in-flight request's AbortController ends the
+ // producer fetch instead of leaving it to burn the read budget.
+ const gfsRequestAborters = new Map<string, AbortController>()
+ ipcMain.on('gfs:abort', (event, payload: { requestId?: string }) => {
+ try {
+ assertTrustedSender(event)
+ } catch {
+ return
+ }
+ const requestId = payload?.requestId ? sanitizeString(payload.requestId) : ''
+ if (requestId) gfsRequestAborters.get(requestId)?.abort()
+ })
+ function runWithGfsAbortSignal<T>(
+ requestId: string | undefined,
+ run: (signal?: AbortSignal) => Promise<T>
+ ): Promise<T> {
+ if (!requestId) return run(undefined)
+ const controller = new AbortController()
+ gfsRequestAborters.set(requestId, controller)
+ return run(controller.signal).finally(() => {
+ gfsRequestAborters.delete(requestId)
+ })
+ }
+
ipcMain.handle('auth:getSessionState', async event => {
assertTrustedSender(event)
return service.getSessionState()
@@ -480,18 +506,24 @@ export function registerIpcHandlers(service: AppService): void {
assertTrustedSender(event)
return service.resolveGfsUri(sanitizeString(payload?.uri))
})
- ipcMain.handle('gfs:download', async (event, payload: { uri: string; maxBytes?: number }) => {
- assertTrustedSender(event)
- // Optional producer-side bound (folder-zip walk): when present it is
- // validated here in main so an over-large body is rejected before it
- // materializes in either process. Absent keeps the single-file
- // save-to-disk path uncapped.
- const maxBytes = sanitizeOptionalPositiveInteger(payload?.maxBytes, 'maxBytes')
- if (maxBytes !== undefined && maxBytes > GFS_DOWNLOAD_MAX_BYTES_CEILING) {
- throw new Error('download limit exceeds the allowed maximum')
+ ipcMain.handle(
+ 'gfs:download',
+ async (event, payload: { uri: string; maxBytes?: number; requestId?: string }) => {
+ assertTrustedSender(event)
+ // Optional producer-side bound (folder-zip walk): when present it is
+ // validated here in main so an over-large body is rejected before it
+ // materializes in either process. Absent keeps the single-file
+ // save-to-disk path uncapped.
+ const maxBytes = sanitizeOptionalPositiveInteger(payload?.maxBytes, 'maxBytes')
+ if (maxBytes !== undefined && maxBytes > GFS_DOWNLOAD_MAX_BYTES_CEILING) {
+ throw new Error('download limit exceeds the allowed maximum')
+ }
+ const requestId = payload?.requestId ? sanitizeString(payload.requestId) : undefined
+ return runWithGfsAbortSignal(requestId, signal =>
+ service.downloadGfsUri(sanitizeString(payload?.uri), maxBytes, signal)
+ )
}
- return service.downloadGfsUri(sanitizeString(payload?.uri), maxBytes)
- })
+ )
ipcMain.handle(
'gfs:downloadPreview',
async (event, payload: { uri: string; maxBytes: number }) => {
@@ -524,11 +556,17 @@ export function registerIpcHandlers(service: AppService): void {
)
ipcMain.handle(
'gfs:listChildren',
- async (event, payload: { resourceId: string; drive?: string; cursor?: string }) => {
+ async (
+ event,
+ payload: { resourceId: string; drive?: string; cursor?: string; requestId?: string }
+ ) => {
assertTrustedSender(event)
const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
const cursor = payload?.cursor ? sanitizeString(payload.cursor) : undefined
- return service.listGfsChildren(sanitizeString(payload?.resourceId), drive, cursor)
+ const requestId = payload?.requestId ? sanitizeString(payload.requestId) : undefined
+ return runWithGfsAbortSignal(requestId, signal =>
+ service.listGfsChildren(sanitizeString(payload?.resourceId), drive, cursor, signal)
+ )
}
)
ipcMain.handle(
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 2e4290488..09bbf8651 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -45,6 +45,26 @@ const DESKTOP_COMMAND_IDS = new Set<DesktopCommandId>([
'app.backToApps',
])
+/**
+ * Producer-side cancellation wiring (folder-zip Stop, R1-M1): a cancellable
+ * invoke carries a requestId; if the caller's signal aborts, tell main to abort
+ * the in-flight request. The cleanup detaches the listener once the invoke
+ * settles either way.
+ */
+function attachRequestAbort(signal?: AbortSignal): {
+ requestId?: string
+ cleanup: () => void
+} {
+ if (!signal) return { cleanup: () => undefined }
+ const requestId = crypto.randomUUID()
+ const onAbort = () => ipcRenderer.send('gfs:abort', { requestId })
+ signal.addEventListener('abort', onAbort, { once: true })
+ return {
+ requestId,
+ cleanup: () => signal.removeEventListener('abort', onAbort),
+ }
+}
+
function isDesktopCommandId(value: unknown): value is DesktopCommandId {
return typeof value === 'string' && DESKTOP_COMMAND_IDS.has(value as DesktopCommandId)
}
@@ -143,14 +163,31 @@ const clerum = Object.freeze({
},
gfs: {
resolve: (uri: string) => ipcRenderer.invoke('gfs:resolve', { uri }),
- download: (uri: string, options?: { maxBytes?: number }) =>
- ipcRenderer.invoke('gfs:download', { uri, maxBytes: options?.maxBytes }),
+ download: (uri: string, options?: { maxBytes?: number; signal?: AbortSignal }) => {
+ const abort = attachRequestAbort(options?.signal)
+ return ipcRenderer
+ .invoke('gfs:download', {
+ uri,
+ maxBytes: options?.maxBytes,
+ requestId: abort.requestId,
+ })
+ .finally(abort.cleanup)
+ },
downloadPreview: (uri: string, maxBytes: number) =>
ipcRenderer.invoke('gfs:downloadPreview', { uri, maxBytes }),
listAccessible: (drive?: string, cursor?: string) =>
ipcRenderer.invoke('gfs:listAccessible', { drive, cursor }),
- listChildren: (resourceId: string, drive?: string, cursor?: string) =>
- ipcRenderer.invoke('gfs:listChildren', { resourceId, drive, cursor }),
+ listChildren: (
+ resourceId: string,
+ drive?: string,
+ cursor?: string,
+ options?: { signal?: AbortSignal }
+ ) => {
+ const abort = attachRequestAbort(options?.signal)
+ return ipcRenderer
+ .invoke('gfs:listChildren', { resourceId, drive, cursor, requestId: abort.requestId })
+ .finally(abort.cleanup)
+ },
affordances: (resourceId: string, drive?: string) =>
ipcRenderer.invoke('gfs:affordances', { resourceId, drive }),
createFolder: (parentResourceId: string, name: string, drive?: string) =>
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index 3a3b7edd0..5d71ccae3 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -133,7 +133,7 @@ declare global {
}>
download: (
uri: string,
- options?: { maxBytes?: number }
+ options?: { maxBytes?: number; signal?: AbortSignal }
) => Promise<{
resource: {
drive: string
@@ -198,7 +198,8 @@ declare global {
listChildren: (
resourceId: string,
drive?: string,
- cursor?: string
+ cursor?: string,
+ options?: { signal?: AbortSignal }
) => Promise<{
items: Array<{
resourceId: string
diff --git a/desktop-app/test/gfsUriHandler.test.ts b/desktop-app/test/gfsUriHandler.test.ts
index 0591f0233..1c2172faa 100644
--- a/desktop-app/test/gfsUriHandler.test.ts
+++ b/desktop-app/test/gfsUriHandler.test.ts
@@ -109,7 +109,8 @@ describe('GfsClient.download', () => {
expect(new TextDecoder().decode(bytes)).toBe('hello')
expect(t.fetchBytes).toHaveBeenCalledWith(
`https://api.example/api/v1/me/gfs/proxy/${RID}?drive=main`,
- 'tok'
+ 'tok',
+ { maxBytes: undefined, signal: undefined }
)
})
})
diff --git a/desktop-app/ui/src/lib/__tests__/gfsFolderZip.test.ts b/desktop-app/ui/src/lib/__tests__/gfsFolderZip.test.ts
index 87520d9ff..83a4aded0 100644
--- a/desktop-app/ui/src/lib/__tests__/gfsFolderZip.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/gfsFolderZip.test.ts
@@ -135,9 +135,13 @@ describe('createGfsFolderZip', () => {
expect(result.fileName).toBe('Docs.zip')
expect(result.fileCount).toBe(3)
expect(result.skipped).toEqual([])
- expect(deps.listChildren).toHaveBeenCalledWith('folder-root', 'main', undefined)
- expect(deps.listChildren).toHaveBeenCalledWith('folder-root', 'main', '1')
- expect(deps.listChildren).toHaveBeenCalledWith('sub', 'main', undefined)
+ expect(deps.listChildren).toHaveBeenCalledWith('folder-root', 'main', undefined, {
+ signal: undefined,
+ })
+ expect(deps.listChildren).toHaveBeenCalledWith('folder-root', 'main', '1', {
+ signal: undefined,
+ })
+ expect(deps.listChildren).toHaveBeenCalledWith('sub', 'main', undefined, { signal: undefined })
const names = zipEntryNames(result.bytes)
expect(names.sort()).toEqual(['Docs/a.txt', 'Docs/b.png', 'Docs/sub/c.md'].sort())
@@ -293,6 +297,34 @@ describe('createGfsFolderZip', () => {
expect(deps.download).not.toHaveBeenCalled()
})
+ it('forwards the stop signal to the producer bridge on both call kinds (R1-M1)', async () => {
+ const controller = new AbortController()
+ const listChildren = vi.fn(() => new Promise(() => undefined))
+ const download = vi.fn(async () => ({ bytes: new ArrayBuffer(4) }))
+ const previousClerum = (window as { clerum?: unknown }).clerum
+ ;(window as { clerum?: unknown }).clerum = { gfs: { listChildren, download } }
+
+ try {
+ const walk = createGfsFolderZip(
+ { resourceId: 'root', drive: 'main', name: 'Bridge' },
+ { signal: controller.signal }
+ )
+ const rejection = expect(walk).rejects.toMatchObject({ name: 'AbortError' })
+ for (let index = 0; index < 200 && listChildren.mock.calls.length === 0; index += 1)
+ await Promise.resolve()
+ const bridgeOptions = listChildren.mock.calls[0]?.[3] as { signal?: AbortSignal } | undefined
+ // The default wiring hands the walk's signal to the bridge, so the
+ // producer fetch dies with the walk instead of outliving the Stop.
+ expect(bridgeOptions?.signal).toBeInstanceOf(AbortSignal)
+ expect(bridgeOptions?.signal?.aborted).toBe(false)
+ controller.abort()
+ await rejection
+ expect(bridgeOptions?.signal?.aborted).toBe(true)
+ } finally {
+ ;(window as { clerum?: unknown }).clerum = previousClerum
+ }
+ })
+
it('skips entries whose complete path would overflow the 16-bit ZIP name field (R1-M2)', async () => {
// A 110-deep chain of 700-byte segment names crosses 65535 assembled
// bytes around depth ~93: the overlong child is skipped (visible notice,
diff --git a/desktop-app/ui/src/lib/gfsFolderZip.ts b/desktop-app/ui/src/lib/gfsFolderZip.ts
index 4d5b3dd40..3ffea63f6 100644
--- a/desktop-app/ui/src/lib/gfsFolderZip.ts
+++ b/desktop-app/ui/src/lib/gfsFolderZip.ts
@@ -120,13 +120,25 @@ export interface GfsZipChildrenPage {
}
export interface GfsFolderZipDeps {
- listChildren(resourceId: string, drive: string, cursor?: string): Promise<GfsZipChildrenPage>
+ /**
+ * Lists one folder page. `options.signal` propagates the walk's stop to the
+ * producer-side fetch when the default bridge is used (R1-M1).
+ */
+ listChildren(
+ resourceId: string,
+ drive: string,
+ cursor?: string,
+ options?: { signal?: AbortSignal }
+ ): Promise<GfsZipChildrenPage>
/**
* Downloads one file. `options.maxBytes` is the producer-side bound for the
* transfer (R1-H2): the bounded fetch rejects before an over-budget body
- * materializes in either process.
+ * materializes in either process. `options.signal` as above.
*/
- download(uri: string, options?: { maxBytes?: number }): Promise<{ bytes: ArrayBuffer }>
+ download(
+ uri: string,
+ options?: { maxBytes?: number; signal?: AbortSignal }
+ ): Promise<{ bytes: ArrayBuffer }>
throttle: GfsReadThrottle
sleep: (ms: number) => Promise<void>
}
@@ -244,12 +256,22 @@ export async function createGfsFolderZip(
): Promise<GfsFolderZipResult> {
const maxTotalBytes = options.limits?.maxTotalBytes ?? GFS_ZIP_MAX_TOTAL_BYTES
const maxEntries = options.limits?.maxEntries ?? GFS_ZIP_MAX_ENTRIES
+ // Defaults read the real bridge; the walk's AbortSignal rides along on both
+ // call kinds so a Stop cancels the producer-side fetch, not just the
+ // renderer's patience (R1-M1).
const listChildren: GfsFolderZipDeps['listChildren'] =
options.deps?.listChildren ??
- ((resourceId, drive, cursor) => window.clerum.gfs.listChildren(resourceId, drive, cursor))
+ ((resourceId, drive, cursor, requestOptions) =>
+ window.clerum.gfs.listChildren(resourceId, drive, cursor, {
+ signal: requestOptions?.signal ?? options.signal,
+ }))
const download: GfsFolderZipDeps['download'] =
options.deps?.download ??
- ((uri, requestOptions) => window.clerum.gfs.download(uri, requestOptions))
+ ((uri, requestOptions) =>
+ window.clerum.gfs.download(uri, {
+ maxBytes: requestOptions?.maxBytes,
+ signal: requestOptions?.signal ?? options.signal,
+ }))
const sleep =
options.deps?.sleep ?? ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)))
const throttle = options.deps?.throttle ?? createGfsReadThrottle()
@@ -324,7 +346,9 @@ export async function createGfsFolderZip(
await withAbort(throttle.acquire())
let page: GfsZipChildrenPage
try {
- page = await withRateLimitRetry(() => listChildren(next.resourceId, folder.drive, cursor))
+ page = await withRateLimitRetry(() =>
+ listChildren(next.resourceId, folder.drive, cursor, { signal })
+ )
} catch (error) {
const message = toMessage(error)
if (isAccessDenied(message)) {
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index 3db634dc7..43e3c6505 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -3582,6 +3582,17 @@ describe('FilesPage', () => {
expect(pushToast).toHaveBeenCalledWith('Stopped preparing Assets.zip.', 'info')
expect(pushToast).not.toHaveBeenCalledWith(expect.stringContaining('Downloaded'), 'success')
expect(click).not.toHaveBeenCalled()
+
+ // A replacement walk starts cleanly once the stopped one has settled —
+ // one job at a time, no overlap (R1-M1).
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Options for Assets' }))
+ })
+ await act(async () => {
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Download as zip' }))
+ })
+ expect(screen.getByTestId('gfs-zip-progress')).toBeTruthy()
+ expect(listChildren).toHaveBeenCalledTimes(2)
})
it('aborts a running zip walk when the page unmounts, so a remount cannot double-walk (M2)', async () => {