Skip to content

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

TypeScript

feat(desktop): recursive folder download as a single zip in the Files view (BUG-175)

M8a1641ce16e7
diff --git a/desktop-app/ui/src/components/GfsResourceMenu/GfsResourceMenu.test.tsx b/desktop-app/ui/src/components/GfsResourceMenu/GfsResourceMenu.test.tsx
index 5a7d8be1d..d36af17f5 100644
--- a/desktop-app/ui/src/components/GfsResourceMenu/GfsResourceMenu.test.tsx
+++ b/desktop-app/ui/src/components/GfsResourceMenu/GfsResourceMenu.test.tsx
@@ -83,6 +83,24 @@ describe('GfsResourceMenu', () => {
expect(screen.queryByRole('menu', { name: 'Actions for report.txt' })).toBeNull()
})
+ it('offers Download as zip for folders when the caller provides the action', () => {
+ const onDownloadZip = vi.fn()
+ render(
+ <GfsResourceMenu resourceName="Assets" onDownload={undefined} onDownloadZip={onDownloadZip} />
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'Options for Assets' }))
+ const menu = screen.getByRole('menu', { name: 'Actions for Assets' })
+ const zipItem = within(menu).getByRole('menuitem', { name: 'Download as zip' })
+ expect(zipItem.getAttribute('data-gfs-action')).toBe('download-zip')
+ // The plain single-file Download entry stays independent of the zip entry.
+ expect(within(menu).queryByRole('menuitem', { name: 'Download' })).toBeNull()
+
+ fireEvent.click(zipItem)
+ expect(onDownloadZip).toHaveBeenCalledOnce()
+ expect(screen.queryByRole('menu', { name: 'Actions for Assets' })).toBeNull()
+ })
+
it.each(['Shared with me', 'Marketing'])(
'keeps the %s breadcrumb menu inside the Files surface as the sidebar resizes',
resourceName => {
diff --git a/desktop-app/ui/src/components/GfsResourceMenu/index.tsx b/desktop-app/ui/src/components/GfsResourceMenu/index.tsx
index 4753b4b8d..726980434 100644
--- a/desktop-app/ui/src/components/GfsResourceMenu/index.tsx
+++ b/desktop-app/ui/src/components/GfsResourceMenu/index.tsx
@@ -72,6 +72,7 @@ export function GfsResourceMenu({
onOpenChange,
onPreview,
onDownload,
+ onDownloadZip,
onRename,
onMove,
onReplace,
@@ -308,6 +309,7 @@ export function GfsResourceMenu({
].filter(isMenuAction),
[
menuAction('download', 'Download', <IconDownload />, onDownload),
+ menuAction('download-zip', 'Download as zip', <IconDownload />, onDownloadZip),
menuAction(
'replace',
'Replace file',
diff --git a/desktop-app/ui/src/components/GfsResourceMenu/types.ts b/desktop-app/ui/src/components/GfsResourceMenu/types.ts
index 332fcf9d9..2c54468d5 100644
--- a/desktop-app/ui/src/components/GfsResourceMenu/types.ts
+++ b/desktop-app/ui/src/components/GfsResourceMenu/types.ts
@@ -13,6 +13,8 @@ export type GfsResourceMenuProps = {
onOpenChange?: (open: boolean) => void
onPreview?: () => void
onDownload?: () => void
+ /** Recursive folder export as a single zip archive (BUG-175). */
+ onDownloadZip?: () => void
onRename?: () => void
onReplace?: (file: File) => void
/** Open the move-to-folder flow. Move authority is parent-relative and
diff --git a/desktop-app/ui/src/lib/__tests__/gfsFolderZip.test.ts b/desktop-app/ui/src/lib/__tests__/gfsFolderZip.test.ts
new file mode 100644
index 000000000..23c827011
--- /dev/null
+++ b/desktop-app/ui/src/lib/__tests__/gfsFolderZip.test.ts
@@ -0,0 +1,358 @@
+// @vitest-environment jsdom
+import { describe, expect, it, vi } from 'vitest'
+import {
+ GFS_ZIP_MAX_ENTRIES,
+ type GfsFolderZipDeps,
+ GfsFolderZipLimitError,
+ type GfsFolderZipProgress,
+ type GfsZipChildItem,
+ createGfsFolderZip,
+ createGfsReadThrottle,
+} from '../gfsFolderZip'
+
+interface ManualClock {
+ now: () => number
+ sleep: (ms: number) => Promise<void>
+ /** Resolves one pending sleep and advances the clock by its delay. */
+ advanceOne: () => boolean
+ pending: () => number
+}
+
+function manualClock(): ManualClock {
+ let current = 1_000_000
+ const wakeups: Array<{ delayMs: number; wake: () => void }> = []
+ return {
+ now: () => current,
+ sleep: ms =>
+ new Promise<void>(resolve => {
+ wakeups.push({ delayMs: ms, wake: () => resolve() })
+ }),
+ advanceOne: () => {
+ const next = wakeups.shift()
+ if (!next) return false
+ current += next.delayMs
+ next.wake()
+ return true
+ },
+ pending: () => wakeups.length,
+ }
+}
+
+function folder(
+ overrides: Partial<GfsZipChildItem> & { resourceId: string; name: string }
+): GfsZipChildItem {
+ return {
+ gfsUri: `gfs://main/${overrides.resourceId}`,
+ kind: 'file',
+ bytes: 4,
+ drive: 'main',
+ ...overrides,
+ }
+}
+
+function depsFor(
+ pages: Record<string, Array<{ items: GfsZipChildItem[]; nextCursor: string | null }>>,
+ downloads: Record<string, () => Promise<{ bytes: ArrayBuffer }>> = {}
+): GfsFolderZipDeps {
+ return {
+ listChildren: vi.fn(async (resourceId: string, _drive: string, cursor?: string) => {
+ const pageList = pages[resourceId]
+ if (!pageList) throw new Error(`unexpected listChildren for ${resourceId}`)
+ const index = cursor ? Number(cursor) : 0
+ const page = pageList[index]
+ if (!page) throw new Error(`no page ${index} for ${resourceId}`)
+ return { items: page.items, nextCursor: page.nextCursor }
+ }),
+ download: vi.fn(async (uri: string) => {
+ const produce = downloads[uri]
+ if (produce) return produce()
+ return { bytes: bytesOf(uri) }
+ }),
+ // Spacing itself has a dedicated manual-clock test below the walk; here it
+ // is a no-op so the orchestration tests run instantly.
+ throttle: { acquire: async () => undefined },
+ sleep: async () => undefined,
+ }
+}
+
+function bytesOf(text: string): ArrayBuffer {
+ return new TextEncoder().encode(text).buffer as ArrayBuffer
+}
+
+describe('createGfsReadThrottle', () => {
+ it('spaces requests to the 120/min budget with the injected clock', async () => {
+ const clock = manualClock()
+ const throttle = createGfsReadThrottle({ now: clock.now, sleep: clock.sleep })
+ const timings: number[] = []
+
+ const job = (async () => {
+ for (let index = 0; index < 4; index += 1) {
+ await throttle.acquire()
+ timings.push(clock.now())
+ }
+ })()
+
+ // Drive the clock until the job is done: resolve a pending sleep when one
+ // exists, otherwise let microtasks run so the job can arm the next one.
+ while (timings.length < 4) {
+ if (!clock.advanceOne()) await Promise.resolve()
+ }
+ await job
+
+ expect(timings).toEqual([1_000_000, 1_000_500, 1_001_000, 1_001_500])
+ })
+})
+
+describe('createGfsFolderZip', () => {
+ it('walks nested folders with pagination and archives every readable file', async () => {
+ const deps = depsFor({
+ 'folder-root': [
+ { items: [folder({ resourceId: 'a', name: 'a.txt' })], nextCursor: '1' },
+ {
+ items: [
+ folder({ resourceId: 'sub', name: 'sub', kind: 'directory' }),
+ folder({ resourceId: 'b', name: 'b.png' }),
+ ],
+ nextCursor: null,
+ },
+ ],
+ sub: [{ items: [folder({ resourceId: 'c', name: 'c.md' })], nextCursor: null }],
+ })
+ const progress: GfsFolderZipProgress[] = []
+ const result = await createGfsFolderZip(
+ { resourceId: 'folder-root', drive: 'main', name: 'Docs' },
+ {
+ deps,
+ onProgress: value => progress.push(value),
+ }
+ )
+
+ 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)
+
+ const names = zipEntryNames(result.bytes)
+ expect(names.sort()).toEqual(['Docs/a.txt', 'Docs/b.png', 'Docs/sub/c.md'].sort())
+ expect(progress.map(value => value.phase)).toContain('downloading')
+ expect(progress.at(-1)?.phase).toBe('assembling')
+ })
+
+ it('skips unreadable rows and 403 downloads with visible reasons', async () => {
+ const deps = depsFor(
+ {
+ root: [
+ {
+ items: [
+ folder({
+ resourceId: 'hidden-dir',
+ name: 'hidden-dir',
+ kind: 'directory',
+ readable: false,
+ }),
+ folder({ resourceId: 'hidden', name: 'hidden.txt', readable: false }),
+ folder({ resourceId: 'denied', name: 'denied.txt' }),
+ folder({ resourceId: 'ok', name: 'ok.txt' }),
+ ],
+ nextCursor: null,
+ },
+ ],
+ },
+ {
+ 'gfs://main/ok': async () => ({ bytes: bytesOf('fine') }),
+ 'gfs://main/denied': async () => {
+ throw new Error('gfs download failed: 403 httpStatus=403 forbidden')
+ },
+ }
+ )
+
+ const result = await createGfsFolderZip(
+ { resourceId: 'root', drive: 'main', name: 'Mixed' },
+ { deps }
+ )
+
+ expect(result.fileCount).toBe(1)
+ expect(result.skipped).toEqual([
+ { path: 'Mixed/hidden-dir', reason: 'No access' },
+ { path: 'Mixed/hidden.txt', reason: 'No access' },
+ { path: 'Mixed/denied.txt', reason: 'Permission denied' },
+ ])
+ expect(zipEntryNames(result.bytes)).toEqual(['Mixed/ok.txt'])
+ })
+
+ it('skips a subfolder whose listing itself is denied and continues the walk', async () => {
+ const deps: GfsFolderZipDeps = {
+ listChildren: vi.fn(async (resourceId: string) => {
+ if (resourceId === 'root')
+ return {
+ items: [folder({ resourceId: 'locked', name: 'locked', kind: 'directory' })],
+ nextCursor: null,
+ }
+ throw new Error("Error invoking remote method 'gfs:listChildren': Error: httpStatus=403")
+ }),
+ download: async () => ({ bytes: bytesOf('x') }),
+ throttle: { acquire: async () => undefined },
+ sleep: async () => undefined,
+ }
+
+ const result = await createGfsFolderZip(
+ { resourceId: 'root', drive: 'main', name: 'Root' },
+ { deps }
+ )
+
+ expect(result.fileCount).toBe(0)
+ expect(result.skipped).toEqual([{ path: 'Root/locked', reason: 'Permission denied' }])
+ })
+
+ it('refuses over the declared byte ceiling with a clear message', async () => {
+ const deps = depsFor({
+ root: [
+ {
+ items: [
+ folder({ resourceId: 'big', name: 'big.bin', bytes: 600 }),
+ folder({ resourceId: 'big2', name: 'big2.bin', bytes: 600 }),
+ ],
+ nextCursor: null,
+ },
+ ],
+ })
+
+ await expect(
+ createGfsFolderZip(
+ { resourceId: 'root', drive: 'main', name: 'Huge' },
+ { deps, limits: { maxTotalBytes: 1024 } }
+ )
+ ).rejects.toBeInstanceOf(GfsFolderZipLimitError)
+ await expect(
+ createGfsFolderZip(
+ { resourceId: 'root', drive: 'main', name: 'Huge' },
+ { deps, limits: { maxTotalBytes: 1024 } }
+ )
+ ).rejects.toThrow(/exceeds the 1 KiB folder-zip limit/)
+ })
+
+ it('refuses over the declared entry ceiling', async () => {
+ expect(GFS_ZIP_MAX_ENTRIES).toBeGreaterThan(0)
+ const deps = depsFor({
+ root: [
+ {
+ items: [
+ folder({ resourceId: 'one', name: 'one.txt' }),
+ folder({ resourceId: 'two', name: 'two.txt' }),
+ folder({ resourceId: 'three', name: 'three.txt' }),
+ ],
+ nextCursor: null,
+ },
+ ],
+ })
+
+ await expect(
+ createGfsFolderZip(
+ { resourceId: 'root', drive: 'main', name: 'Many' },
+ { deps, limits: { maxEntries: 2 } }
+ )
+ ).rejects.toThrow(/more than 2 files/)
+ })
+
+ it('refuses when the actual downloaded bytes exceed the ceiling', async () => {
+ const deps = depsFor(
+ {
+ root: [
+ {
+ items: [folder({ resourceId: 'lied', name: 'lied.bin', bytes: 1 })],
+ nextCursor: null,
+ },
+ ],
+ },
+ { 'gfs://main/lied': async () => ({ bytes: new ArrayBuffer(2048) }) }
+ )
+
+ await expect(
+ createGfsFolderZip(
+ { resourceId: 'root', drive: 'main', name: 'Sneaky' },
+ { deps, limits: { maxTotalBytes: 1024 } }
+ )
+ ).rejects.toThrow(/exceeded the 1 KiB folder-zip limit while downloading/)
+ })
+
+ it('backs off once on a 429 using the server-provided retry hint', async () => {
+ let attempts = 0
+ const deps: GfsFolderZipDeps = {
+ listChildren: vi.fn(async () => {
+ attempts += 1
+ if (attempts === 1)
+ throw new Error('gfs children failed: 429 httpStatus=429 retryAfterSeconds=2')
+ return { items: [], nextCursor: null }
+ }),
+ download: async () => ({ bytes: new ArrayBuffer(0) }),
+ throttle: { acquire: async () => undefined },
+ sleep: async () => undefined,
+ }
+
+ const result = await createGfsFolderZip(
+ { resourceId: 'root', drive: 'main', name: 'Throttled' },
+ { deps }
+ )
+ expect(attempts).toBe(2)
+ expect(result.fileCount).toBe(0)
+ })
+
+ it('aborts on a non-permission download failure instead of a holey archive', async () => {
+ const deps: GfsFolderZipDeps = {
+ listChildren: vi.fn(async () => ({
+ items: [folder({ resourceId: 'flaky', name: 'flaky.txt' })],
+ nextCursor: null,
+ })),
+ download: async () => {
+ throw new Error('gfs download failed: 500 httpStatus=500')
+ },
+ throttle: { acquire: async () => undefined },
+ sleep: async () => undefined,
+ }
+
+ await expect(
+ createGfsFolderZip({ resourceId: 'root', drive: 'main', name: 'Broken' }, { deps })
+ ).rejects.toThrow(/500/)
+ })
+
+ it('sanitizes hostile names into safe in-archive paths', async () => {
+ const deps = depsFor({
+ root: [
+ {
+ items: [
+ folder({ resourceId: 'n1', name: '../escape.txt' }),
+ folder({ resourceId: 'n2', name: 'a/b.txt' }),
+ folder({ resourceId: 'n3', name: '' }),
+ ],
+ nextCursor: null,
+ },
+ ],
+ })
+ const result = await createGfsFolderZip(
+ { resourceId: 'root', drive: 'main', name: 'Weird/Name' },
+ { deps }
+ )
+ expect(zipEntryNames(result.bytes).sort()).toEqual(
+ ['Weird_Name/_escape.txt', 'Weird_Name/a_b.txt', 'Weird_Name/unnamed'].sort()
+ )
+ })
+})
+
+/** Minimal central-directory name reader for assertions. */
+function zipEntryNames(archive: Uint8Array): string[] {
+ const view = new DataView(archive.buffer, archive.byteOffset, archive.byteLength)
+ const decoder = new TextDecoder()
+ const eocdOffset = archive.length - 22
+ const entryCount = view.getUint16(eocdOffset + 10, true)
+ const centralDirectoryOffset = view.getUint32(eocdOffset + 16, true)
+ const names: string[] = []
+ let cursor = centralDirectoryOffset
+ for (let index = 0; index < entryCount; index += 1) {
+ const nameLength = view.getUint16(cursor + 28, true)
+ names.push(decoder.decode(archive.subarray(cursor + 46, cursor + 46 + nameLength)))
+ cursor += 46 + nameLength
+ }
+ return names
+}
diff --git a/desktop-app/ui/src/lib/__tests__/zipWriter.test.ts b/desktop-app/ui/src/lib/__tests__/zipWriter.test.ts
new file mode 100644
index 000000000..81ff6044f
--- /dev/null
+++ b/desktop-app/ui/src/lib/__tests__/zipWriter.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, it } from 'vitest'
+import { crc32, createZipWriter } from '../zipWriter'
+
+/** Reads a STORED zip back through its end-of-central-directory record. */
+function readStoredZip(archive: Uint8Array): Array<{ name: string; bytes: Uint8Array }> {
+ const view = new DataView(archive.buffer, archive.byteOffset, archive.byteLength)
+ const decoder = new TextDecoder()
+
+ // EOCD is the last structure; comment length is 0, so it is the final 22 bytes.
+ const eocdOffset = archive.length - 22
+ expect(view.getUint32(eocdOffset, true)).toBe(0x06054b50)
+ const entryCount = view.getUint16(eocdOffset + 10, true)
+ const centralDirectoryOffset = view.getUint32(eocdOffset + 16, true)
+
+ const entries: Array<{ name: string; bytes: Uint8Array }> = []
+ let cursor = centralDirectoryOffset
+ for (let index = 0; index < entryCount; index += 1) {
+ expect(view.getUint32(cursor, true)).toBe(0x02014b50)
+ const crc = view.getUint32(cursor + 16, true)
+ const size = view.getUint32(cursor + 20, true)
+ const nameLength = view.getUint16(cursor + 28, true)
+ const localHeaderOffset = view.getUint32(cursor + 42, true)
+ const name = decoder.decode(archive.subarray(cursor + 46, cursor + 46 + nameLength))
+
+ expect(view.getUint32(localHeaderOffset, true)).toBe(0x04034b50)
+ expect(view.getUint16(localHeaderOffset + 8, true)).toBe(0) // STORED
+ const localNameLength = view.getUint16(localHeaderOffset + 26, true)
+ const dataOffset = localHeaderOffset + 30 + localNameLength
+ const bytes = archive.subarray(dataOffset, dataOffset + size)
+ expect(bytes.length).toBe(size)
+ expect(crc32(bytes)).toBe(crc)
+
+ entries.push({ name, bytes })
+ cursor += 46 + nameLength
+ }
+ return entries
+}
+
+function textBytes(text: string): Uint8Array {
+ return new TextEncoder().encode(text)
+}
+
+describe('crc32', () => {
+ it('matches the known CRC-32 check vector', () => {
+ expect(crc32(textBytes('123456789'))).toBe(0xcbf43926)
+ })
+
+ it('is empty-input stable', () => {
+ expect(crc32(new Uint8Array(0))).toBe(0)
+ })
+})
+
+describe('createZipWriter', () => {
+ it('writes a single stored entry that reads back byte-identical', () => {
+ const writer = createZipWriter()
+ writer.addFile('folder/hello.txt', textBytes('hello evenfire'))
+ const archive = writer.build()
+
+ expect(readStoredZip(archive)).toEqual([
+ { name: 'folder/hello.txt', bytes: textBytes('hello evenfire') },
+ ])
+ })
+
+ it('writes multiple nested entries in add order', () => {
+ const writer = createZipWriter()
+ const payloadA = textBytes('aaa')
+ const payloadB = new Uint8Array([0, 1, 2, 250, 251, 255])
+ const payloadC = new Uint8Array(0)
+ writer.addFile('root/b.bin', payloadB)
+ writer.addFile('root/sub/deep/a.txt', payloadA)
+ writer.addFile('root/empty.dat', payloadC)
+
+ expect(writer.entryCount()).toBe(3)
+ expect(readStoredZip(writer.build())).toEqual([
+ { name: 'root/b.bin', bytes: payloadB },
+ { name: 'root/sub/deep/a.txt', bytes: payloadA },
+ { name: 'root/empty.dat', bytes: payloadC },
+ ])
+ })
+
+ it('de-duplicates repeated entry names instead of colliding', () => {
+ const writer = createZipWriter()
+ writer.addFile('docs/plan.md', textBytes('first'))
+ writer.addFile('docs/plan.md', textBytes('second'))
+
+ const names = readStoredZip(writer.build()).map(entry => entry.name)
+ expect(names).toEqual(['docs/plan.md', 'docs/plan (2).md'])
+ expect(writer.has('docs/plan.md')).toBe(true)
+ expect(writer.has('docs/plan (2).md')).toBe(true)
+ })
+
+ it('marks names as UTF-8 in both header sets', () => {
+ const writer = createZipWriter()
+ writer.addFile('报告/tafel-übe.png', textBytes('x'))
+ const archive = writer.build()
+ const view = new DataView(archive.buffer, archive.byteOffset, archive.byteLength)
+
+ const eocdOffset = archive.length - 22
+ const centralDirectoryOffset = view.getUint32(eocdOffset + 16, true)
+ expect(view.getUint32(centralDirectoryOffset, true)).toBe(0x02014b50)
+ expect(view.getUint16(centralDirectoryOffset + 8, true) & 0x0800).toBe(0x0800)
+
+ const localHeaderOffset = view.getUint32(centralDirectoryOffset + 42, true)
+ expect(view.getUint32(localHeaderOffset, true)).toBe(0x04034b50)
+ expect(view.getUint16(localHeaderOffset + 6, true) & 0x0800).toBe(0x0800)
+ })
+
+ it('produces an empty but valid archive with no entries', () => {
+ const writer = createZipWriter()
+ const archive = writer.build()
+ expect(archive.length).toBe(22)
+ expect(readStoredZip(archive)).toEqual([])
+ })
+})
diff --git a/desktop-app/ui/src/lib/gfsDownload.ts b/desktop-app/ui/src/lib/gfsDownload.ts
index aa13a36aa..f56cd5735 100644
--- a/desktop-app/ui/src/lib/gfsDownload.ts
+++ b/desktop-app/ui/src/lib/gfsDownload.ts
@@ -1,13 +1,19 @@
/**
- * Save a GFS resource to disk: download its bytes and trigger a browser save.
- * The single place that performs the save-to-disk, shared by the Files page and
- * the sidebar file explorer (spec 18 §3.A.4) so the "download a non-previewable
- * file" path is not duplicated — the preview-vs-download DECISION stays in
- * `gfsPreview`. Throws on a download failure so each caller keeps its own
- * fail-closed (authority) and toast handling.
+ * Save GFS content to disk through the renderer's anchor-download path — the
+ * single place that performs the save-to-disk, shared by the Files page, the
+ * sidebar file explorer (spec 18 §3.A.4) and the folder-zip export (BUG-175),
+ * so the "download a non-previewable file" path is not duplicated. The
+ * preview-vs-download DECISION stays in `gfsPreview`. Throws on a download
+ * failure so each caller keeps its own fail-closed (authority) and toast
+ * handling.
*/
export async function saveGfsFileToDisk(uri: string, name: string): Promise<void> {
const { bytes } = await window.clerum.gfs.download(uri)
+ saveBytesToDisk(bytes, name)
+}
+
+/** Anchor-save already downloaded bytes (used by the in-memory zip assembly). */
+export function saveBytesToDisk(bytes: BlobPart, name: string): void {
const url = URL.createObjectURL(new Blob([bytes]))
const anchor = document.createElement('a')
anchor.href = url
diff --git a/desktop-app/ui/src/lib/gfsFolderZip.ts b/desktop-app/ui/src/lib/gfsFolderZip.ts
new file mode 100644
index 000000000..db6a24df7
--- /dev/null
+++ b/desktop-app/ui/src/lib/gfsFolderZip.ts
@@ -0,0 +1,292 @@
+/**
+ * BUG-175 — recursive "Download as zip" for a GFS folder, assembled fully in
+ * the renderer from the existing `window.clerum.gfs` read plane.
+ *
+ * Budget contract: the server meters GFS reads per actor (~120 requests/min
+ * shared with the browsing surface), so every listing and download below goes
+ * through `createGfsReadThrottle`, which spaces requests to that budget, and a
+ * 429 answer backs off once by the server-provided `retryAfterSeconds` before
+ * failing. Byte and entry ceilings bound the walk before anything large is
+ * buffered, and entries the caller cannot read (a listing row marked
+ * unreadable, or a 403 on the download itself) are skipped and reported back
+ * so the result can show a visible skip notice instead of a silently holey
+ * archive.
+ */
+import { isRateLimited, parseHttpStatus, parseRetryAfterSeconds } from '@lib/gfsGrantErrors'
+import { createZipWriter } from '@lib/zipWriter'
+
+/** Server-side GFS read budget the walk must respect (requests per minute). */
+export const GFS_ZIP_READS_PER_MINUTE = 120
+/** Refuse before buffering: total uncompressed bytes across the folder. */
+export const GFS_ZIP_MAX_TOTAL_BYTES = 1024 * 1024 * 1024
+/** Refuse before buffering: total file entries across the folder. */
+export const GFS_ZIP_MAX_ENTRIES = 2000
+
+export interface GfsZipSkippedEntry {
+ path: string
+ reason: string
+}
+
+export type GfsFolderZipPhase = 'listing' | 'downloading' | 'assembling'
+
+export interface GfsFolderZipProgress {
+ phase: GfsFolderZipPhase
+ filesFound: number
+ filesAdded: number
+ currentPath: string | null
+}
+
+export interface GfsFolderZipResult {
+ bytes: Uint8Array<ArrayBuffer>
+ fileName: string
+ fileCount: number
+ skipped: GfsZipSkippedEntry[]
+}
+
+/** The walk exceeded a configured ceiling — a refusal, not a failure. */
+export class GfsFolderZipLimitError extends Error {}
+
+export interface GfsReadThrottle {
+ acquire(): Promise<void>
+}
+
+export interface CreateGfsReadThrottleOptions {
+ requestsPerMinute?: number
+ now?: () => number
+ sleep?: (ms: number) => Promise<void>
+}
+
+/**
+ * Sequential read spacing for the server's per-actor GFS budget: one acquired
+ * slot per request, `60_000 / requestsPerMinute` apart. Injectable clock and
+ * sleep keep the spacing testable without real time.
+ */
+export function createGfsReadThrottle(options: CreateGfsReadThrottleOptions = {}): GfsReadThrottle {
+ const requestsPerMinute = options.requestsPerMinute ?? GFS_ZIP_READS_PER_MINUTE
+ const now = options.now ?? (() => Date.now())
+ const sleep = options.sleep ?? (ms => new Promise<void>(resolve => setTimeout(resolve, ms)))
+ const intervalMs = 60_000 / requestsPerMinute
+ let nextAllowedAt = 0
+ return {
+ async acquire() {
+ const current = now()
+ if (current < nextAllowedAt) {
+ await sleep(nextAllowedAt - current)
+ }
+ nextAllowedAt = Math.max(nextAllowedAt, now()) + intervalMs
+ },
+ }
+}
+
+export interface GfsZipChildItem {
+ resourceId: string
+ gfsUri: string
+ name: string
+ kind: 'file' | 'directory'
+ bytes: number
+ drive?: string
+ readable?: boolean
+}
+
+export interface GfsZipChildrenPage {
+ items: GfsZipChildItem[]
+ nextCursor: string | null
+}
+
+export interface GfsFolderZipDeps {
+ listChildren(resourceId: string, drive: string, cursor?: string): Promise<GfsZipChildrenPage>
+ download(uri: string): Promise<{ bytes: ArrayBuffer }>
+ throttle: GfsReadThrottle
+ sleep: (ms: number) => Promise<void>
+}
+
+export interface CreateGfsFolderZipOptions {
+ onProgress?: (progress: GfsFolderZipProgress) => void
+ limits?: { maxTotalBytes?: number; maxEntries?: number }
+ deps?: Partial<GfsFolderZipDeps>
+}
+
+export interface GfsZipFolderSource {
+ resourceId: string
+ drive: string
+ name: string
+}
+
+function toMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error)
+}
+
+/** A per-resource denial for THIS entry (403/forbidden), not a session failure. */
+function isAccessDenied(message: string): boolean {
+ return parseHttpStatus(message) === 403 || message.toLowerCase().includes('forbidden')
+}
+
+/** Zip-safe path segment: no separators, no NUL, no traversal prefix. */
+function sanitizeZipSegment(name: string): string {
+ const cleaned = name
+ .replace(/[/\\\u0000]/g, '_')
+ .replace(/^\.+/, '')
+ .trim()
+ return cleaned || 'unnamed'
+}
+
+function sanitizeFileName(name: string): string {
+ return name.replace(/[/\\\u0000]/g, '_').trim() || 'folder'
+}
+
+export async function createGfsFolderZip(
+ folder: GfsZipFolderSource,
+ options: CreateGfsFolderZipOptions = {}
+): Promise<GfsFolderZipResult> {
+ const maxTotalBytes = options.limits?.maxTotalBytes ?? GFS_ZIP_MAX_TOTAL_BYTES
+ const maxEntries = options.limits?.maxEntries ?? GFS_ZIP_MAX_ENTRIES
+ const listChildren: GfsFolderZipDeps['listChildren'] =
+ options.deps?.listChildren ??
+ ((resourceId, drive, cursor) => window.clerum.gfs.listChildren(resourceId, drive, cursor))
+ const download: GfsFolderZipDeps['download'] =
+ options.deps?.download ?? (uri => window.clerum.gfs.download(uri))
+ const sleep =
+ options.deps?.sleep ?? ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)))
+ const throttle = options.deps?.throttle ?? createGfsReadThrottle()
+
+ const report = (progress: GfsFolderZipProgress) => options.onProgress?.(progress)
+
+ /** One 429 backs off by the server-provided hint and retries exactly once. */
+ const withRateLimitRetry = async <T>(operation: () => Promise<T>): Promise<T> => {
+ try {
+ return await operation()
+ } catch (error) {
+ const message = toMessage(error)
+ if (!isRateLimited(message)) throw error
+ await sleep(Math.min((parseRetryAfterSeconds(message) ?? 15) * 1000, 120_000))
+ return operation()
+ }
+ }
+
+ const writer = createZipWriter()
+ const skipped: GfsZipSkippedEntry[] = []
+ const files: Array<{ uri: string; path: string }> = []
+ const rootName = sanitizeZipSegment(folder.name)
+ const queue: Array<{ resourceId: string; prefix: string }> = [
+ { resourceId: folder.resourceId, prefix: rootName },
+ ]
+ const visitedFolders = new Set<string>()
+ let plannedBytes = 0
+
+ // ── Phase 1: recursive listing (breadth-first, cursor-paginated). ──
+ report({ phase: 'listing', filesFound: 0, filesAdded: 0, currentPath: rootName })
+ while (queue.length) {
+ const next = queue.shift()!
+ if (visitedFolders.has(next.resourceId)) continue
+ visitedFolders.add(next.resourceId)
+ let cursor: string | undefined
+ do {
+ await throttle.acquire()
+ let page: GfsZipChildrenPage
+ try {
+ page = await withRateLimitRetry(() => listChildren(next.resourceId, folder.drive, cursor))
+ } catch (error) {
+ const message = toMessage(error)
+ if (isAccessDenied(message)) {
+ skipped.push({ path: next.prefix, reason: 'Permission denied' })
+ break
+ }
+ throw error
+ }
+ for (const child of page.items) {
+ const path = `${next.prefix}/${sanitizeZipSegment(child.name)}`
+ if (child.kind === 'directory') {
+ if (child.readable === false) {
+ skipped.push({ path, reason: 'No access' })
+ continue
+ }
+ queue.push({ resourceId: child.resourceId, prefix: path })
+ continue
+ }
+ if (child.readable === false) {
+ skipped.push({ path, reason: 'No access' })
+ continue
+ }
+ if (files.length + 1 > maxEntries) {
+ throw new GfsFolderZipLimitError(
+ `"${folder.name}" holds more than ${maxEntries} files, which exceeds the folder-zip limit. Download smaller subfolders individually.`
+ )
+ }
+ plannedBytes += child.bytes
+ if (plannedBytes > maxTotalBytes) {
+ throw new GfsFolderZipLimitError(
+ `"${folder.name}" exceeds the ${formatZipBytes(maxTotalBytes)} folder-zip limit. Download smaller subfolders individually.`
+ )
+ }
+ files.push({ uri: child.gfsUri, path })
+ report({
+ phase: 'listing',
+ filesFound: files.length,
+ filesAdded: 0,
+ currentPath: path,
+ })
+ }
+ cursor = page.nextCursor ?? undefined
+ } while (cursor)
+ }
+
+ // ── Phase 2: throttled downloads, skipping per-resource denials. ──
+ let addedBytes = 0
+ for (const [index, file] of files.entries()) {
+ report({
+ phase: 'downloading',
+ filesFound: files.length,
+ filesAdded: index,
+ currentPath: file.path,
+ })
+ await throttle.acquire()
+ let bytes: ArrayBuffer
+ try {
+ bytes = (await withRateLimitRetry(() => download(file.uri))).bytes
+ } catch (error) {
+ const message = toMessage(error)
+ if (isAccessDenied(message)) {
+ skipped.push({ path: file.path, reason: 'Permission denied' })
+ continue
+ }
+ throw error
+ }
+ const data = new Uint8Array(bytes)
+ addedBytes += data.length
+ if (addedBytes > maxTotalBytes) {
+ throw new GfsFolderZipLimitError(
+ `"${folder.name}" exceeded the ${formatZipBytes(maxTotalBytes)} folder-zip limit while downloading. Download smaller subfolders individually.`
+ )
+ }
+ writer.addFile(file.path, data)
+ }
+
+ // ── Phase 3: assemble the archive. ──
+ report({
+ phase: 'assembling',
+ filesFound: files.length,
+ filesAdded: writer.entryCount(),
+ currentPath: null,
+ })
+ const archive = writer.build()
+ return {
+ bytes: archive,
+ fileName: `${sanitizeFileName(folder.name)}.zip`,
+ fileCount: writer.entryCount(),
+ skipped,
+ }
+}
+
+function formatZipBytes(bytes: number): string {
+ if (bytes >= 1024 * 1024 * 1024) return `${Math.round(bytes / (1024 * 1024 * 1024))} GiB`
+ if (bytes >= 1024 * 1024) return `${Math.round(bytes / (1024 * 1024))} MiB`
+ return `${Math.round(bytes / 1024)} KiB`
+}
+
+/** Visible skip notice for the result toast: names the first few skips. */
+export function describeZipSkips(skipped: GfsZipSkippedEntry[]): string {
+ const visible = skipped.slice(0, 3).map(entry => `${entry.path} (${entry.reason})`)
+ const more = skipped.length - visible.length
+ const names = more > 0 ? `${visible.join(', ')} and ${more} more` : visible.join(', ')
+ return `Skipped ${skipped.length} ${skipped.length === 1 ? 'entry' : 'entries'}: ${names}`
+}
diff --git a/desktop-app/ui/src/lib/zipWriter.ts b/desktop-app/ui/src/lib/zipWriter.ts
new file mode 100644
index 000000000..6b4f480dd
--- /dev/null
+++ b/desktop-app/ui/src/lib/zipWriter.ts
@@ -0,0 +1,192 @@
+/**
+ * Minimal ZIP writer used by the client-side folder export (BUG-175).
+ *
+ * Entries are written with the STORED method (no compression): the archived
+ * GFS payloads are already-encoded documents and media, an in-memory writer in
+ * the renderer must stay small and deterministic, and a stored archive remains
+ * a fully valid ZIP for every standard extractor. No compression also means
+ * the total size guard can reason about byte budgets exactly.
+ *
+ * Format reference: APPNOTE.TXT (PKWARE) — local file header (4.3.7), central
+ * directory (4.3.12), end-of-central-directory (4.3.19). Names are UTF-8 with
+ * the general-purpose flag bit 11 set. DOS timestamps are zero (deterministic
+ * output; the source of truth for content dates is the GFS listing).
+ */
+
+const LOCAL_FILE_HEADER_SIGNATURE = 0x04034b50
+const CENTRAL_DIRECTORY_SIGNATURE = 0x02014b50
+const END_OF_CENTRAL_DIRECTORY_SIGNATURE = 0x06054b50
+const VERSION_NEEDED = 20
+const UTF8_FLAG = 0x0800
+const STORED_METHOD = 0
+
+const CRC32_POLYNOMIAL = 0xedb88320
+
+let crc32Table: Uint32Array | null = null
+
+function crc32TableFor(): Uint32Array {
+ if (crc32Table) return crc32Table
+ const table = new Uint32Array(256)
+ for (let index = 0; index < 256; index += 1) {
+ let value = index
+ for (let bit = 0; bit < 8; bit += 1) {
+ value = value & 1 ? (value >>> 1) ^ CRC32_POLYNOMIAL : value >>> 1
+ }
+ table[index] = value >>> 0
+ }
+ crc32Table = table
+ return table
+}
+
+/** Standard CRC-32 (IEEE 802.3, reflected), as stored in ZIP headers. */
+export function crc32(bytes: Uint8Array): number {
+ const table = crc32TableFor()
+ let crc = 0xffffffff
+ for (let index = 0; index < bytes.length; index += 1) {
+ crc = (crc >>> 8) ^ table[(crc ^ bytes[index]!) & 0xff]!
+ }
+ return (crc ^ 0xffffffff) >>> 0
+}
+
+interface StoredEntry {
+ nameBytes: Uint8Array
+ crc: number
+ size: number
+ localHeaderOffset: number
+ bytes: Uint8Array
+}
+
+export interface ZipWriter {
+ /** Adds one entry; returns the path actually written (see `addFile`). */
+ addFile(path: string, bytes: Uint8Array): string
+ /** True once any entry with this exact path was added. */
+ has(path: string): boolean
+ entryCount(): number
+ /** Assembles the final archive bytes (local records + central directory). */
+ build(): Uint8Array<ArrayBuffer>
+}
+
+function encodeName(path: string): Uint8Array {
+ return new TextEncoder().encode(path)
+}
+
+export function createZipWriter(): ZipWriter {
+ const entries: StoredEntry[] = []
+ const usedNames = new Set<string>()
+
+ return {
+ addFile(path, bytes) {
+ const writtenPath = ensureUniqueName(path, usedNames)
+ usedNames.add(writtenPath)
+ const nameBytes = encodeName(writtenPath)
+ entries.push({
+ nameBytes,
+ crc: crc32(bytes),
+ size: bytes.length,
+ localHeaderOffset: 0,
+ bytes,
+ })
+ return writtenPath
+ },
+
+ has(path) {
+ return usedNames.has(path)
+ },
+
+ entryCount() {
+ return entries.length
+ },
+
+ build() {
+ const parts: Uint8Array[] = []
+ let offset = 0
+ const localHeaderSize = (entry: StoredEntry) => 30 + entry.nameBytes.length
+
+ for (const entry of entries) {
+ entry.localHeaderOffset = offset
+ const header = new Uint8Array(localHeaderSize(entry))
+ const view = new DataView(header.buffer)
+ view.setUint32(0, LOCAL_FILE_HEADER_SIGNATURE, true)
+ view.setUint16(4, VERSION_NEEDED, true)
+ view.setUint16(6, UTF8_FLAG, true)
+ view.setUint16(8, STORED_METHOD, true)
+ view.setUint16(10, 0, true) // mod time
+ view.setUint16(12, 0, true) // mod date
+ view.setUint32(14, entry.crc, true)
+ view.setUint32(18, entry.size, true) // compressed size (stored)
+ view.setUint32(22, entry.size, true) // uncompressed size
+ view.setUint16(26, entry.nameBytes.length, true)
+ view.setUint16(28, 0, true) // extra length
+ header.set(entry.nameBytes, 30)
+ parts.push(header, entry.bytes)
+ offset += header.length + entry.bytes.length
+ }
+
+ const centralDirectoryOffset = offset
+ for (const entry of entries) {
+ const record = new Uint8Array(46 + entry.nameBytes.length)
+ const view = new DataView(record.buffer)
+ view.setUint32(0, CENTRAL_DIRECTORY_SIGNATURE, true)
+ view.setUint16(4, VERSION_NEEDED, true) // made by
+ view.setUint16(6, VERSION_NEEDED, true) // needed
+ view.setUint16(8, UTF8_FLAG, true)
+ view.setUint16(10, STORED_METHOD, true)
+ view.setUint16(12, 0, true) // mod time
+ view.setUint16(14, 0, true) // mod date
+ view.setUint32(16, entry.crc, true)
+ view.setUint32(20, entry.size, true)
+ view.setUint32(24, entry.size, true)
+ view.setUint16(28, entry.nameBytes.length, true)
+ view.setUint16(30, 0, true) // extra length
+ view.setUint16(32, 0, true) // comment length
+ view.setUint16(34, 0, true) // disk start
+ view.setUint16(36, 0, true) // internal attributes
+ view.setUint32(38, 0, true) // external attributes
+ view.setUint32(42, entry.localHeaderOffset, true)
+ record.set(entry.nameBytes, 46)
+ parts.push(record)
+ offset += record.length
+ }
+ const centralDirectorySize = offset - centralDirectoryOffset
+
+ const eocd = new Uint8Array(22)
+ const view = new DataView(eocd.buffer)
+ view.setUint32(0, END_OF_CENTRAL_DIRECTORY_SIGNATURE, true)
+ view.setUint16(4, 0, true) // this disk
+ view.setUint16(6, 0, true) // central directory disk
+ view.setUint16(8, entries.length, true)
+ view.setUint16(10, entries.length, true)
+ view.setUint32(12, centralDirectorySize, true)
+ view.setUint32(16, centralDirectoryOffset, true)
+ view.setUint16(20, 0, true) // comment length
+ parts.push(eocd)
+
+ const total = parts.reduce((sum, part) => sum + part.length, 0)
+ const out = new Uint8Array(total)
+ let cursor = 0
+ for (const part of parts) {
+ out.set(part, cursor)
+ cursor += part.length
+ }
+ return out
+ },
+ }
+}
+
+/** `a/b.txt` → `a/b (2).txt` style de-duplication for repeated zip names. */
+function ensureUniqueName(path: string, usedNames: Set<string>): string {
+ if (!usedNames.has(path)) return path
+ const slash = path.lastIndexOf('/')
+ const directory = slash >= 0 ? path.slice(0, slash + 1) : ''
+ const base = slash >= 0 ? path.slice(slash + 1) : path
+ const dot = base.lastIndexOf('.')
+ const stem = dot > 0 ? base.slice(0, dot) : base
+ const extension = dot > 0 ? base.slice(dot) : ''
+ let counter = 2
+ let candidate = `${directory}${stem} (${counter})${extension}`
+ while (usedNames.has(candidate)) {
+ counter += 1
+ candidate = `${directory}${stem} (${counter})${extension}`
+ }
+ return candidate
+}
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index 67291218c..e0e1b62b7 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -40,8 +40,14 @@ import {
useGfsBrowserController,
} from '@hooks/domain/useGfsBrowserController'
import { isEventFromNestedInteractive } from '@lib/clickableRowProps'
-import { saveGfsFileToDisk } from '@lib/gfsDownload'
+import { saveBytesToDisk, saveGfsFileToDisk } from '@lib/gfsDownload'
import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'
+import {
+ GfsFolderZipLimitError,
+ type GfsFolderZipProgress,
+ createGfsFolderZip,
+ describeZipSkips,
+} from '@lib/gfsFolderZip'
import {
describeGfsGrantError,
describeGfsReadError,
@@ -274,6 +280,13 @@ export function FilesPage({
>(null)
const [dragActive, setDragActive] = useState(false)
const [droppedUploadCount, setDroppedUploadCount] = useState(0)
+ // BUG-175 — live folder-zip job for the progress strip; null when idle. One
+ // job at a time: the walk holds the shared GFS read budget.
+ const [zipJob, setZipJob] = useState<{
+ folderName: string
+ progress: GfsFolderZipProgress
+ } | null>(null)
+ const zipJobRef = useRef(false)
const [draggingResourceId, setDraggingResourceId] = useState<string | null>(null)
const [dragOverFolderId, setDragOverFolderId] = useState<string | null>(null)
const [movingResourceId, setMovingResourceId] = useState<string | null>(null)
@@ -795,6 +808,52 @@ export function FilesPage({
}
}
+ /**
+ * BUG-175 — recursive folder export as one zip archive, assembled in the
+ * renderer. The walk is throttled to the shared GFS read budget, refuses
+ * over the size/entry ceilings with a clear message, and reports entries it
+ * had to skip (no access / permission denied) in a visible notice after the
+ * save so the archive's holes are never silent.
+ */
+ const handleFolderZipDownload = async (folder: GfsDriveResource) => {
+ if (zipJobRef.current) return
+ zipJobRef.current = true
+ const initialProgress: GfsFolderZipProgress = {
+ phase: 'listing',
+ filesFound: 0,
+ filesAdded: 0,
+ currentPath: null,
+ }
+ setZipJob({ folderName: folder.name, progress: initialProgress })
+ try {
+ const result = await createGfsFolderZip(
+ { resourceId: folder.resourceId, drive: folder.drive || GFS_DRIVE_MAIN, name: folder.name },
+ {
+ onProgress: progress => setZipJob({ folderName: folder.name, progress }),
+ }
+ )
+ saveBytesToDisk(result.bytes, result.fileName)
+ pushToast?.(
+ `Downloaded ${result.fileName} (${result.fileCount} ${result.fileCount === 1 ? 'file' : 'files'})`,
+ 'success'
+ )
+ if (result.skipped.length) {
+ pushToast?.(describeZipSkips(result.skipped), 'warn', { durationMs: 10_000 })
+ }
+ } catch (zipError) {
+ if (!failClosedOnAuthorizationError(zipError)) {
+ const message =
+ zipError instanceof GfsFolderZipLimitError
+ ? zipError.message
+ : describeGfsReadError(zipError).message
+ pushToast?.(message, 'error')
+ }
+ } finally {
+ zipJobRef.current = false
+ setZipJob(null)
+ }
+ }
+
const handleCopyLink = async (uri: string) => {
try {
await navigator.clipboard.writeText(uri)
@@ -1298,6 +1357,12 @@ export function FilesPage({
onRename: gates.canRename ? () => openRenameTarget(folder) : undefined,
onMove: () => setMoveTarget(folder),
onDelete: gates.canDelete ? () => setDeleteTarget(folder) : undefined,
+ onDownloadZip:
+ folder.readable === false
+ ? undefined
+ : () => {
+ void handleFolderZipDownload(folder)
+ },
})
const visibleResources = useMemo<GfsDriveResource[]>(() => {
@@ -1546,6 +1611,18 @@ export function FilesPage({
</div>
) : null}
+ {zipJob ? (
+ <div className="da-gfs-zip-progress" role="status" data-testid="gfs-zip-progress">
+ <span className="da-gfs-zip-progress__label">
+ {zipJob.progress.phase === 'listing'
+ ? `Preparing ${zipJob.folderName}.zip — reading folder contents…`
+ : zipJob.progress.phase === 'downloading'
+ ? `Preparing ${zipJob.folderName}.zip — downloading ${zipJob.progress.filesAdded} of ${zipJob.progress.filesFound} ${zipJob.progress.filesFound === 1 ? 'file' : 'files'}…`
+ : `Preparing ${zipJob.folderName}.zip — assembling archive…`}
+ </span>
+ </div>
+ ) : null}
+
{accessibleNotice ? <StatusBanner tone="info" text={accessibleNotice} /> : null}
{visibleError && !accessRevoked && !blockingFailure ? (
// Presented, not raw. The banner is the non-blocking half of the
diff --git a/desktop-app/ui/src/pages/FilesPage.types.ts b/desktop-app/ui/src/pages/FilesPage.types.ts
index 810997f80..1f7b4b89a 100644
--- a/desktop-app/ui/src/pages/FilesPage.types.ts
+++ b/desktop-app/ui/src/pages/FilesPage.types.ts
@@ -10,7 +10,7 @@ export type GfsDriveResource = GfsBrowserChild & {
export interface FilesPageProps {
/** App-level toast dispatcher for success feedback (desktop-app/ui rule). */
- pushToast?: (message: string, tone: Tone) => void
+ pushToast?: (message: string, tone: Tone, options?: { durationMs?: number }) => void
/**
* A `gfs://` link handed over from elsewhere in the app — today, a plugin
* asking to open a resource this page can show better than an overlay can
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index a9599643c..2341347fc 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -3279,6 +3279,204 @@ describe('FilesPage', () => {
expect(pushToast).toHaveBeenCalledWith('Too many file requests — try again in 7s.', 'error')
})
+ it('downloads a folder recursively as one zip with progress and a skip notice (BUG-175)', async () => {
+ vi.useFakeTimers()
+ const listChildren = vi.fn(async () => ({
+ items: [
+ {
+ resourceId: 'doc-1',
+ rid: 'doc-1',
+ gfsUri: 'gfs://main/doc-1',
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: 'plan.md',
+ kind: 'file' as const,
+ path: '/Assets/plan.md',
+ version: 0,
+ bytes: 4,
+ },
+ {
+ resourceId: 'hidden-1',
+ rid: 'hidden-1',
+ gfsUri: 'gfs://main/hidden-1',
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: 'secret.txt',
+ kind: 'file' as const,
+ path: '/Assets/secret.txt',
+ version: 0,
+ bytes: 4,
+ readable: false,
+ },
+ ],
+ nextCursor: null,
+ }))
+ const download = vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3, 4]).buffer }))
+ const pushToast = vi.fn()
+ const createObjectURL = vi.fn(() => 'blob:folder-zip')
+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+ Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: createObjectURL })
+ Object.defineProperty(URL, 'revokeObjectURL', {
+ configurable: true,
+ value: vi.fn(),
+ })
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { listChildren, download } },
+ })
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ accessibleResources: [
+ {
+ resourceId: 'folder-1',
+ rid: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ drive: 'main',
+ parentResourceId: null,
+ name: 'Assets',
+ kind: 'directory',
+ path: '/Assets',
+ version: 0,
+ bytes: 0,
+ sources: ['grant'],
+ permissions: ['read'],
+ coversDescendants: false,
+ },
+ ],
+ })
+
+ renderFilesPage(pushToast)
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Options for Assets' }))
+ })
+ await act(async () => {
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Download as zip' }))
+ })
+
+ // The job is in flight with a visible status strip before anything saved.
+ expect(screen.getByTestId('gfs-zip-progress').getAttribute('role')).toBe('status')
+ // Walk the throttled listing + download (500 ms of spacing per request).
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5_000)
+ })
+ await act(async () => {
+ await Promise.resolve()
+ })
+ expect(screen.queryByTestId('gfs-zip-progress')).toBeNull()
+
+ expect(listChildren).toHaveBeenCalledWith('folder-1', 'main', undefined)
+ expect(download).toHaveBeenCalledWith('gfs://main/doc-1')
+ expect(createObjectURL).toHaveBeenCalledWith(expect.any(Blob))
+ expect(click).toHaveBeenCalled()
+ const savedName = (click.mock.instances[0] as HTMLAnchorElement | undefined)?.download
+ expect(savedName).toBe('Assets.zip')
+ expect(pushToast).toHaveBeenCalledWith('Downloaded Assets.zip (1 file)', 'success')
+ expect(pushToast).toHaveBeenCalledWith(
+ 'Skipped 1 entry: Assets/secret.txt (No access)',
+ 'warn',
+ expect.anything()
+ )
+ })
+
+ it('refuses a folder zip over the size limit with a clear message and saves nothing', async () => {
+ vi.useFakeTimers()
+ const listChildren = vi.fn(async () => ({
+ items: [
+ {
+ resourceId: 'huge-1',
+ rid: 'huge-1',
+ gfsUri: 'gfs://main/huge-1',
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: 'huge.bin',
+ kind: 'file' as const,
+ path: '/Assets/huge.bin',
+ version: 0,
+ bytes: 1024 * 1024 * 1024 + 1,
+ },
+ ],
+ nextCursor: null,
+ }))
+ const download = vi.fn(async () => ({ bytes: new ArrayBuffer(0) }))
+ const pushToast = vi.fn()
+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { listChildren, download } },
+ })
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ accessibleResources: [
+ {
+ resourceId: 'folder-1',
+ rid: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ drive: 'main',
+ parentResourceId: null,
+ name: 'Assets',
+ kind: 'directory',
+ path: '/Assets',
+ version: 0,
+ bytes: 0,
+ sources: ['grant'],
+ permissions: ['read'],
+ coversDescendants: false,
+ },
+ ],
+ })
+
+ renderFilesPage(pushToast)
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Options for Assets' }))
+ })
+ await act(async () => {
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Download as zip' }))
+ await vi.advanceTimersByTimeAsync(5_000)
+ })
+ await act(async () => {
+ await Promise.resolve()
+ })
+ expect(screen.queryByTestId('gfs-zip-progress')).toBeNull()
+
+ expect(download).not.toHaveBeenCalled()
+ expect(click).not.toHaveBeenCalled()
+ expect(pushToast).toHaveBeenCalledWith(
+ expect.stringContaining('exceeds the 1 GiB folder-zip limit'),
+ 'error'
+ )
+ })
+
+ it('omits Download as zip for a folder the session cannot read', async () => {
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ accessibleResources: [
+ {
+ resourceId: 'folder-9',
+ rid: 'folder-9',
+ gfsUri: 'gfs://main/folder-9',
+ drive: 'main',
+ parentResourceId: null,
+ name: 'Locked',
+ kind: 'directory',
+ path: '/Locked',
+ version: 0,
+ bytes: 0,
+ readable: false,
+ sources: ['grant'],
+ permissions: [],
+ coversDescendants: false,
+ },
+ ],
+ })
+
+ renderFilesPage()
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Options for Locked' }))
+ })
+
+ expect(screen.queryByRole('menuitem', { name: 'Download as zip' })).toBeNull()
+ })
+
it('shows the document icon for txt, md, pdf, doc and docx files instead of the clip', () => {
hookMock.useGfsBrowserController.mockReturnValue({
...baseController(),
@@ -4137,6 +4335,7 @@ describe('FilesPage', () => {
'Open EvenDrive link',
'Rename',
'Move to…',
+ 'Download as zip',
'Delete',
]
// The active folder is already open, so its menu is the row menu minus the
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index 4f76b41ce..793519dfd 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -15269,6 +15269,39 @@ pre {
font-size: var(--font-size-sm);
}
+/* BUG-175 — folder-zip assembly progress strip. */
+.da-gfs-zip-progress {
+ display: flex;
+ align-items: center;
+ gap: var(--space-1-5);
+ border: 1px solid rgba(var(--accent-rgb), 0.35);
+ border-radius: var(--radius-control);
+ background: rgba(var(--panel-rgb), 0.72);
+ color: var(--text);
+ padding: var(--space-1-5) var(--space-2);
+ font-size: var(--font-size-sm);
+ line-height: 1.35;
+}
+
+.da-gfs-zip-progress__label {
+ min-width: 0;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.da-gfs-zip-progress__label::before {
+ content: '';
+ flex: 0 0 auto;
+ width: var(--space-1);
+ height: var(--space-1);
+ border-radius: 999px;
+ background: var(--accent);
+ margin-right: var(--space-1-5);
+ display: inline-block;
+ animation: da-gfs-loading-dot 1.2s ease-in-out infinite;
+}
+
.da-gfs-loading__dots {
display: inline-flex;
align-items: center;