Skip to content

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

TypeScript

chore: sync evendrive improvements with dev

M9211704b6b2f
diff --cc desktop-app/ui/src/components/SidebarNav/index.tsx
index 091144c9d,3df859e8a..575bf40cb
--- a/desktop-app/ui/src/components/SidebarNav/index.tsx
+++ b/desktop-app/ui/src/components/SidebarNav/index.tsx
@@@ -11,8 -11,10 +11,9 @@@ import { DESKTOP_ROUTES, SIDEBAR_SESSIO
import { useClickOutside } from '@hooks/useClickOutside'
import { formatDesktopAppVersionTooltip, useDesktopAppInfo } from '@hooks/useDesktopAppInfo'
import type { NavItem } from '@/uiTypes'
+ import { FileExplorerTree } from './FileExplorerTree'
import {
IconAgents,
- IconAttachFile,
IconChat,
IconChevronRight,
IconConnectors,
@@@ -553,18 -573,41 +573,41 @@@ export function SidebarNav(
<NavItemControl
data-testid="nav-files"
className="nav-link-main"
- onClick={() => handleSelect(DESKTOP_ROUTES.files)}
- aria-label="EvenDrive"
+ onClick={handleFilesNavSelect}
+ aria-label="Files"
- leadingIcon={<IconAttachFile />}
+ leadingIcon={<IconHardDrive />}
trailingIcon={
<span className="nav-tooltip" role="tooltip">
- Files
+ EvenDrive
</span>
}
>
- Files
+ EvenDrive
</NavItemControl>
+ <IconButton
+ className="nav-link-session-toggle"
+ label={filesExplorerOpen ? 'Collapse file explorer' : 'Expand file explorer'}
+ aria-expanded={filesExplorerOpen}
+ data-testid="nav-files-explorer-toggle"
+ onClick={event => {
+ event.stopPropagation()
+ setFilesExplorerOpen(open => !open)
+ }}
+ variant="ghost"
+ >
+ <IconChevronRight className={filesExplorerOpen ? 'expanded' : ''} />
+ </IconButton>
</div>
+
+ {!collapsed && filesExplorerOpen && (
+ <div className="nav-file-explorer">
+ <FileExplorerTree
+ onOpenFolder={onOpenFilesSection}
+ onOpenPreview={onOpenPreviewSection}
+ pushToast={pushToast}
+ />
+ </div>
+ )}
</nav>
<div className="sidebar-footer">
diff --cc desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
index effc7f898,8cbd3dfa9..39f782143
--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
@@@ -8,8 -8,13 +8,14 @@@ import
useQueryClient,
} from '@tanstack/react-query'
import { GFS_BREADCRUMB_MAX_DEPTH } from '@constants/gfsBrowser'
+ import {
+ describeGfsReadError,
+ isRateLimited,
+ parseHttpStatus,
+ parseRetryAfterSeconds,
+ } from '@lib/gfsGrantErrors'
import type { GfsGrantListItem, GfsShareListItem } from '@/gfs/delegation.types'
+import { deriveGfsInheritedAccess } from '@/gfs/inheritedAccess'
import { desktopQueryKeys } from './queryKeys'
/**
@@@ -633,16 -782,77 +812,81 @@@ export function useGfsBrowserController
() => (authorityPending ? [] : (sharesQuery.data ?? [])),
[authorityPending, sharesQuery.data]
)
+ const inheritedAccess = useMemo(
+ () => (authorityPending || accessState === 'revoked' ? [] : (inheritedAccessQuery.data ?? [])),
+ [accessState, authorityPending, inheritedAccessQuery.data]
+ )
const accessibleErrorMessage = accessibleQuery.error ? toMessage(accessibleQuery.error) : null
+ // The timestamp is a dependency in its own right, not decoration. It is the
+ // only thing that distinguishes two consecutive failures carrying the same
+ // message, and without it the memo below never recomputes for the second one.
+ const accessibleErrorUpdatedAt = accessibleQuery.error ? accessibleQuery.errorUpdatedAt : 0
+ const childrenErrorMessage = childrenQuery.error ? toMessage(childrenQuery.error) : null
+ const childrenErrorUpdatedAt = childrenQuery.error ? childrenQuery.errorUpdatedAt : 0
+ const discoveryFailure = useMemo<GfsDiscoveryFailure | null>(() => {
+ if (!accessibleErrorMessage) return null
+ const kind = classifyDiscoveryFailure(accessibleErrorMessage)
+ const retryAfterSeconds = parseRetryAfterSeconds(accessibleErrorMessage)
+ return {
+ kind,
+ message: accessibleErrorMessage,
+ retryAvailableAt:
+ kind === 'rate-limited' && retryAfterSeconds !== null
+ ? accessibleErrorUpdatedAt + retryAfterSeconds * 1000
+ : null,
+ }
+ }, [accessibleErrorMessage, accessibleErrorUpdatedAt])
+ // The folder plane's own rate-limit deadline. `listAccessible` and
+ // `listChildren` are refused by ONE server budget, so a 429 on either means
+ // the next focus-driven refetch of either spends a request the server just
+ // turned down. Derived here rather than inside the effect below because the
+ // timestamp is what separates two consecutive refusals carrying the same
+ // message — without it the second one never recomputes.
+ const childrenRateLimitedUntil = useMemo<number | null>(() => {
+ if (!childrenErrorMessage || !isRateLimited(childrenErrorMessage)) return null
+ const retryAfterSeconds = parseRetryAfterSeconds(childrenErrorMessage)
+ return retryAfterSeconds !== null
+ ? childrenErrorUpdatedAt + retryAfterSeconds * 1000
+ : Date.now() + UNKNOWN_RATE_LIMIT_PAUSE_MS
+ }, [childrenErrorMessage, childrenErrorUpdatedAt])
+ useEffect(() => {
+ // A rate limit with no parseable window is still a rate limit. Leaving the
+ // pause open here would let every window focus spend another request
+ // against a server that just refused one.
+ const discoveryUntil =
+ discoveryFailure?.kind === 'rate-limited'
+ ? (discoveryFailure.retryAvailableAt ?? Date.now() + UNKNOWN_RATE_LIMIT_PAUSE_MS)
+ : 0
+ // The later of the two deadlines, never whichever one settled last. A
+ // discovery refetch that succeeds does not buy back the budget a refused
+ // folder listing is still waiting on, and arming from discovery alone left
+ // a folder 429 free to be re-spent on the very next window focus.
+ pausedUntilRef.current = Math.max(discoveryUntil, childrenRateLimitedUntil ?? 0)
+ }, [childrenRateLimitedUntil, discoveryFailure])
+ // The page must not reach into the query object to retry. Clearing the pause
+ // here is deliberate: an explicit retry is the user's decision, and the
+ // countdown in the UI is what keeps them from spending the request early.
+ // It drops back to the folder plane's deadline rather than to zero — the
+ // user asked for discovery, not for the next window focus to re-spend a
+ // folder listing the same budget is still refusing.
+ const retryDiscovery = useCallback(async () => {
+ pausedUntilRef.current = childrenRateLimitedUntil ?? 0
+ await accessibleQuery.refetch()
+ }, [accessibleQuery, childrenRateLimitedUntil])
+ // The same contract for the children query. Nothing to clear here: `refetch`
+ // is not gated by the focus predicate, and the pause is shared with
+ // discovery — clearing it on a folder retry would hand the next window focus
+ // a discovery request the server is still refusing. A folder listing is NOT
+ // fetched only on request, though: `refetchOnMount: 'always'` and the window
+ // focus bridge both reach it, which is why the pause above now covers it.
+ const retryChildren = useCallback(async () => {
+ await childrenQuery.refetch()
+ }, [childrenQuery])
const accessibleNotice =
sessionScope && !canListAccessibleResources
- ? 'Automatic EvenDrive discovery is not available in this desktop runtime. You can still open any EvenDrive link you have.'
- : accessibleErrorMessage && isResourceDiscoveryUnavailable(accessibleErrorMessage)
- ? 'Automatic EvenDrive discovery is not available from this server yet. You can still open any EvenDrive link you have.'
+ ? 'Automatic GFS discovery is not available in this desktop runtime. You can still open any GFS link you have.'
+ : discoveryFailure?.kind === 'unsupported'
+ ? 'Automatic GFS discovery is not available from this server yet. You can still open any GFS link you have.'
: null
const openUri = useCallback(
diff --cc desktop-app/ui/src/pages/FilesPage.tsx
index d464cc243,d33d66002..ba71ec004
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@@ -34,15 -32,22 +32,23 @@@ import
IconShare,
IconUpload,
} from '@components/SidebarNav/icons'
+import { GFS_DRIVE_MAIN } from '@constants/gfsBrowser'
import { desktopQueryKeys } from '@hooks/domain/queryKeys'
- import { type GfsCrumb, useGfsBrowserController } from '@hooks/domain/useGfsBrowserController'
+ import {
+ type GfsCrumb,
+ type GfsDiscoveryFailure,
+ useGfsBrowserController,
+ } from '@hooks/domain/useGfsBrowserController'
import { isEventFromNestedInteractive } from '@lib/clickableRowProps'
+ import { saveGfsFileToDisk } from '@lib/gfsDownload'
import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'
- import { describeGfsGrantError } from '@lib/gfsGrantErrors'
- import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'
- import { isGfsMarkdownPreviewFile } from '@lib/gfsMarkdownPreview'
- import { gfsVideoPreviewMimeType } from '@lib/gfsVideoPreview'
+ import {
+ describeGfsGrantError,
+ describeGfsReadError,
+ isRateLimited,
+ parseRetryAfterSeconds,
+ } from '@lib/gfsGrantErrors'
+ import { isGfsPreviewFile, resolveGfsPreview } from '@lib/gfsPreview'
import { formatSharedFileSize } from '@lib/sharedFiles'
import { GfsGrantList } from '@/gfs/GfsGrantList'
import type { GfsAccessRole } from '@/gfs/GfsGrantList'
@@@ -55,17 -57,10 +61,12 @@@ import
type GfsDelegationSubjectOption,
type GfsGrantListItem,
} from '@/gfs/delegation'
+import type { GfsInheritedAccessSource } from '@/gfs/delegation.types'
import { GfsFilePicker } from '@/gfs/filePicker'
+import { planInheritedRoleChange } from '@/gfs/inheritedAccess'
import { GfsMoveDialog } from '@/gfs/moveDialog'
import type { TeamDirectoryResult } from '../../../src/types'
- import type {
- FilesPageProps,
- GfsDriveResource,
- GfsPreviewResource,
- MyAgentEntry,
- } from './FilesPage.types'
+ import type { FilesPageProps, GfsDriveResource, MyAgentEntry } from './FilesPage.types'
function hasBit(affordances: { held?: string[] } | null, bit: string): boolean {
return Boolean(affordances?.held?.includes(bit))
@@@ -249,22 -231,6 +257,21 @@@ export function FilesPage(
const [manageOpen, setManageOpen] = useState(false)
const [shareDetailsOpen, setShareDetailsOpen] = useState(false)
const [updatingAccessRole, setUpdatingAccessRole] = useState(false)
+ // Pending parent-folder confirmation (role change or removal) for a member
+ // whose file access is inherited from ancestor folders. change-role carries
+ // the R1-H1 plan's affected folders, each with the bits the pre-flight
+ // validated on that folder itself.
+ const [parentUpdate, setParentUpdate] = useState<
+ | {
+ row: GfsMergedAccessRow
+ label: string
+ mode: 'change-role'
+ nextRole: GfsAccessRole
+ updates: Array<{ source: GfsInheritedAccessSource; bits: string[] }>
+ }
+ | { row: GfsMergedAccessRow; label: string; mode: 'remove' }
+ | null
+ >(null)
- const [filePreview, setFilePreview] = useState<GfsPreviewResource | null>(null)
const [dragActive, setDragActive] = useState(false)
const [droppedUploadCount, setDroppedUploadCount] = useState(0)
const [draggingResourceId, setDraggingResourceId] = useState<string | null>(null)
@@@ -597,195 -558,9 +604,189 @@@
}
}
+ // A merged row whose access comes from parent folders: any edit (upgrade,
+ // downgrade, or removal — no exceptions) is confirmed against the affected
+ // folders before anything is sent. Cancel reverts the dropdown untouched.
+ const handleInheritedRoleChange = async (
+ row: GfsMergedAccessRow,
+ label: string,
+ role: GfsAccessRole
+ ) => {
+ const inherited = row.inherited
+ if (!inherited) return
+ const subject = inherited.subject
+ // N1: the dropdown displays the MERGED effective role (direct ⊔
+ // inherited). Re-selecting the already-displayed role is a no-op —
+ // comparing it against the inherited-only floor instead would open the
+ // parent-update modal and escalate the parent folder for a non-change.
+ if (role === roleForAccessPermissions(row.permissions)) return
+ // R1-H1 plan: downgrade lowers every folder above the target; upgrade
+ // raises the single strongest folder; same-role selection touches none.
+ const affected = planInheritedRoleChange(inherited, role === 'editor')
+ if (affected.length === 0 && !row.grant && row.shares.length === 0) return
+ // Pre-flight: every affected folder's grant is judged by THAT folder's
+ // own grantable bits, never by the open file's affordances (which may be
+ // missing or narrower). A role a folder cannot grant fails loudly here —
+ // the confirmation never opens with a promise it cannot keep.
+ const updates: Array<{ source: GfsInheritedAccessSource; bits: string[] }> = []
+ for (const source of affected) {
+ let folderAffordances: { canDelegate: boolean; grantableBits: string[] }
+ try {
+ folderAffordances = await window.clerum.gfs.affordances(source.resourceId, GFS_DRIVE_MAIN)
+ } catch (affordancesError) {
+ if (failClosedOnAuthorizationError(affordancesError)) return
+ pushToast?.(describeGfsGrantError(affordancesError).message, 'error')
+ return
+ }
+ const bits = rolePermissionRequest(subject.type, role).filter(bit =>
+ folderAffordances.grantableBits.includes(bit)
+ )
+ const expressesRole =
+ role === 'editor' ? bits.includes('read') && bits.includes('write') : bits.includes('read')
+ if (!folderAffordances.canDelegate || !expressesRole) {
+ pushToast?.(
+ `Your access on ${source.name} does not allow making ${label} ${role === 'editor' ? 'an Editor' : 'Read-only'}.`,
+ 'error'
+ )
+ return
+ }
+ updates.push({ source, bits })
+ }
+ setParentUpdate({ row, label, mode: 'change-role', nextRole: role, updates })
+ }
+
+ const handleInheritedRemove = (row: GfsMergedAccessRow, label: string) => {
+ setParentUpdate({ row, label, mode: 'remove' })
+ }
+
+ const confirmParentUpdate = async () => {
+ const request = parentUpdate
+ const inherited = request?.row.inherited
+ if (!request || !inherited) {
+ setParentUpdate(null)
+ return
+ }
+ const sources = inherited.sources
+ const subject = inherited.subject
+ const subjectKey = subject.id ? `${subject.type}:${subject.id}` : subject.type
+ const label = request.label
+ setParentUpdate(null)
+ setUpdatingAccessRole(true)
+ // Partial-failure honesty (R1-H1): the confirm issues several sequential
+ // calls; the first failure stops the run, refreshes both lists so the
+ // dialog shows the TRUE partial state, and the toast says exactly how far
+ // the change got. Full success is never claimed on partial completion.
+ const failPartially = async (updateError: unknown, summary: string) => {
+ if (failClosedOnAuthorizationError(updateError)) return
+ pushToast?.(`${summary} (${describeGfsGrantError(updateError).message})`, 'error')
+ await Promise.all([ctrl.refreshGrants(), ctrl.refreshInheritedAccess(), ctrl.refreshShares()])
+ }
+ try {
+ if (request.mode === 'remove') {
+ let removed = 0
+ for (const source of sources) {
+ try {
+ if (source.grantId) await ctrl.revokeGrant(source.grantId)
+ for (const shareId of source.shareIds) await ctrl.revokeShare(shareId)
+ removed += 1
+ } catch (updateError) {
+ await failPartially(
+ updateError,
+ `Removed from ${removed} of ${sources.length} folders — ${source.name} still grants access`
+ )
+ return
+ }
+ }
+ // The file's own direct rows are aligned with the removal.
+ if (request.row.grant || request.row.shares.length > 0) {
+ try {
+ if (request.row.grant) await ctrl.revokeGrant(request.row.grant.id)
+ for (const share of request.row.shares) await ctrl.revokeShare(share.id)
+ } catch (updateError) {
+ await failPartially(
+ updateError,
+ `Removed from ${sources.length} of ${sources.length} folders — direct access on ${current?.name ?? 'this file'} could not be removed`
+ )
+ return
+ }
+ }
+ pushToast?.(
+ sources.length === 1
+ ? `Access removed on ${sources[0].name} and everything inside it`
+ : `Access removed on ${sources.length} folders and everything inside them`,
+ 'success'
+ )
+ await Promise.all([
+ ctrl.refreshGrants(),
+ ctrl.refreshInheritedAccess(),
+ ctrl.refreshShares(),
+ ])
+ return
+ }
+ const updates = request.updates
+ const affectedNames = updates.map(update => update.source.name)
+ let updated = 0
+ for (const { source, bits } of updates) {
+ try {
+ // Each affected folder's grant is updated with the bits the
+ // pre-flight validated on that folder, and keeps cascading to
+ // everything inside; its superseded share rows are consolidated.
+ await window.clerum.gfs.grant(source.resourceId, [subjectKey], bits, GFS_DRIVE_MAIN, true)
+ for (const shareId of source.shareIds) await ctrl.revokeShare(shareId)
+ updated += 1
+ } catch (updateError) {
+ await failPartially(
+ updateError,
+ `Updated ${updated} of ${updates.length} folders — ${source.name} still grants access`
+ )
+ return
+ }
+ }
+ // The file's own direct rows are aligned so they cannot mask the
+ // confirmed role: the grant upsert expresses the new role and every
+ // direct file share for the member is revoked after it — a stale
+ // editor share would otherwise keep the member an Editor.
+ if (request.row.grant || request.row.shares.length > 0) {
+ try {
+ const fileBits = rolePermissionRequest(subject.type, request.nextRole).filter(bit =>
+ affordances?.grantableBits.includes(bit)
+ )
+ // N2: an empty bit set means the file's affordances are
+ // unavailable (or grant nothing). Do not send an empty grant after
+ // the parent update; revoke the old direct grant instead so it
+ // cannot keep masking the confirmed parent role.
+ if (fileBits.length > 0) {
+ await ctrl.grant([subjectKey], fileBits, request.row.grant?.inherit ?? false)
+ } else if (request.row.grant) {
+ // An empty affordance result cannot express the requested direct
+ // role. Remove the old grant so it cannot keep masking the
+ // parent-folder downgrade while the UI reports success.
+ await ctrl.revokeGrant(request.row.grant.id)
+ }
+ for (const share of request.row.shares) await ctrl.revokeShare(share.id)
+ } catch (updateError) {
+ await failPartially(
+ updateError,
+ `Updated ${updates.length} of ${updates.length} folders — direct access on ${current?.name ?? 'this file'} still shows the old role`
+ )
+ return
+ }
+ }
+ pushToast?.(
+ affectedNames.length > 0
+ ? `${label} is now ${request.nextRole === 'editor' ? 'an Editor' : 'Read-only'} on ${joinFolderNames(affectedNames)} and everything inside ${affectedNames.length > 1 ? 'them' : 'it'}`
+ : `${label} is now ${request.nextRole === 'editor' ? 'an Editor' : 'Read-only'} on ${current?.name ?? 'this file'}`,
+ 'success'
+ )
+ await Promise.all([ctrl.refreshGrants(), ctrl.refreshInheritedAccess(), ctrl.refreshShares()])
+ } finally {
+ setUpdatingAccessRole(false)
+ }
+ }
+
const handleDownload = async (uri: string, name: string) => {
try {
- const { bytes } = await window.clerum.gfs.download(uri)
- const url = URL.createObjectURL(new Blob([bytes]))
- const anchor = document.createElement('a')
- anchor.href = url
- anchor.download = name
- anchor.click()
- setTimeout(() => URL.revokeObjectURL(url), 10_000)
+ await saveGfsFileToDisk(uri, name)
pushToast?.(`Downloaded ${name}`, 'success')
} catch (downloadError) {
if (failClosedOnAuthorizationError(downloadError)) return
@@@ -1332,8 -1166,8 +1430,8 @@@
<div className="page-layout da-gfs-layout">
<section
className="page-card da-gfs-drive"
- aria-label="Global File System browser"
+ aria-label="EvenDrive browser"
- aria-busy={visibleLoading || droppedUploadCount > 0}
+ aria-busy={driveBusy}
onDragEnter={handleGfsDragEnter}
onDragLeave={handleGfsDragLeave}
onDragOver={handleGfsDragOver}
@@@ -1689,53 -1562,34 +1815,53 @@@
<IconEdit width={16} height={16} />
</IconButton>
) : null}
- <GfsResourceMenu
- resourceName={resource.name}
- onManage={rowCanManage(resource) ? () => openManage(resource) : undefined}
- onCopyLink={() => void handleCopyLink(resource.gfsUri)}
- onDelete={
- rowCanDelete(resource) ? () => setDeleteTarget(resource) : undefined
- }
- onOpen={
- resource.kind === 'directory' ? () => openResource(resource) : undefined
- }
- onOpenChange={open =>
- ctrl.setRowAffordancesResourceId(open ? resource.resourceId : null)
- }
- onRename={
- rowCanRename(resource) ? () => openRenameTarget(resource) : undefined
- }
- onMove={() => setMoveTarget(resource)}
- onPreview={
- resource.readable !== false && isGfsPreviewFile(resource.name)
- ? () => void openFilePreview(resource)
- : undefined
- }
- onDownload={
- resource.readable !== false && resource.kind === 'file'
- ? () => void handleDownload(resource.gfsUri, resource.name)
- : undefined
- }
- />
+ {resource.kind === 'directory' ? (
+ <GfsResourceMenu
+ {...folderMenuPropsFor(
+ resource,
+ {
+ canManage: rowCanManage(resource),
+ canRename: rowCanRename(resource),
+ canDelete: rowCanDelete(resource),
+ },
+ {
+ onOpen: () => openResource(resource),
+ onOpenChange: open =>
+ ctrl.setRowAffordancesResourceId(
+ open ? resource.resourceId : null
+ ),
+ }
+ )}
+ />
+ ) : (
+ <GfsResourceMenu
+ resourceName={resource.name}
+ onManage={
+ rowCanManage(resource) ? () => openManage(resource) : undefined
+ }
+ onCopyLink={() => void handleCopyLink(resource.gfsUri)}
+ onDelete={
+ rowCanDelete(resource) ? () => setDeleteTarget(resource) : undefined
+ }
+ onOpenChange={open =>
+ ctrl.setRowAffordancesResourceId(open ? resource.resourceId : null)
+ }
+ onRename={
+ rowCanRename(resource) ? () => openRenameTarget(resource) : undefined
+ }
+ onMove={() => setMoveTarget(resource)}
+ onPreview={
- isGfsPreviewFile(resource.name)
++ resource.readable !== false && isGfsPreviewFile(resource.name)
+ ? () => void openFilePreview(resource)
+ : undefined
+ }
+ onDownload={
- resource.kind === 'file'
++ resource.readable !== false && resource.kind === 'file'
+ ? () => void handleDownload(resource.gfsUri, resource.name)
+ : undefined
+ }
+ />
+ )}
</span>
</div>
)
diff --cc desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index 3e99d99cc,005832755..b16b7a156
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@@ -3598,325 -2897,115 +3757,134 @@@ describe('FilesPage', () =>
expect(pushToast).toHaveBeenCalledWith('Deleted shared-report.txt', 'success')
})
- it('previews an image file in a closable modal without downloading it to disk', async () => {
- const download = vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer }))
- const createObjectURL = vi.fn(() => 'blob:gfs-image-preview')
- const revokeObjectURL = vi.fn()
- const anchorClick = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
- Object.defineProperty(URL, 'createObjectURL', {
- configurable: true,
- value: createObjectURL,
- })
- Object.defineProperty(URL, 'revokeObjectURL', {
- configurable: true,
- value: revokeObjectURL,
- })
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: { gfs: { download } },
- })
+ // Preview no longer opens a modal inside FilesPage (spec 18 §3.B.4): the page
+ // resolves the file kind and hands a descriptor up through onOpenPreview so the
+ // tab store opens/focuses a FilePreviewPage. These assert the observable
+ // handoff (T4), not the byte fetch — the fetch now lives in Gfs*PreviewBody.
+ const previewRow = (
+ name: string,
+ resourceId: string,
+ bytes: number
+ ): Record<string, unknown> => ({
+ resourceId,
+ rid: resourceId,
+ gfsUri: `gfs://main/${resourceId}`,
+ drive: 'main',
+ parentResourceId: null,
+ name,
+ kind: 'file',
+ path: `/${name}`,
+ version: 1,
+ bytes,
+ sources: ['grant'],
+ permissions: ['read'],
+ coversDescendants: false,
+ })
+
+ it('opens a preview tab for an image file instead of rendering a modal', () => {
+ const download = vi.fn()
+ Object.defineProperty(window, 'clerum', { configurable: true, value: { gfs: { download } } })
+ const onOpenPreview = vi.fn()
hookMock.useGfsBrowserController.mockReturnValue({
...baseController(),
- accessibleResources: [
- {
- resourceId: 'image-1',
- rid: 'image-1',
- gfsUri: 'gfs://main/image-1',
- drive: 'main',
- parentResourceId: null,
- name: 'diagram.PNG',
- kind: 'file',
- path: '/diagram.PNG',
- version: 1,
- bytes: 3,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- ],
+ accessibleResources: [previewRow('diagram.PNG', 'image-1', 3)],
})
- renderFilesPage()
- expect(download).not.toHaveBeenCalled()
+ renderFilesPage(undefined, onOpenPreview)
fireEvent.click(screen.getByRole('button', { name: 'diagram.PNG' }))
- const dialog = await screen.findByRole('dialog', { name: 'diagram.PNG' })
- await waitFor(() => expect(within(dialog).getByAltText('Preview of diagram.PNG')).toBeTruthy())
- const copyButton = within(dialog).getByRole('button', { name: /Copy image to clipboard/i })
- expect(copyButton.querySelector('svg')?.getAttribute('viewBox')).toBe('0 0 24 24')
- expect(copyButton.querySelector('path')?.getAttribute('d')).toBe('M0 0h24v24H0z')
- expect(download).toHaveBeenCalledWith('gfs://main/image-1')
- expect(download).toHaveBeenCalledTimes(1)
- expect(anchorClick).not.toHaveBeenCalled()
-
- fireEvent.click(within(dialog).getByRole('button', { name: 'Close image preview' }))
- await waitFor(() => expect(screen.queryByRole('dialog', { name: 'diagram.PNG' })).toBeNull())
- expect(revokeObjectURL).toHaveBeenCalledWith('blob:gfs-image-preview')
+ expect(onOpenPreview).toHaveBeenCalledWith({
+ gfsUri: 'gfs://main/image-1',
+ kind: 'image',
+ mimeType: 'image/png',
+ name: 'diagram.PNG',
+ bytes: 3,
+ })
+ // No modal, and FilesPage itself never fetches the bytes.
+ expect(screen.queryByRole('dialog', { name: 'diagram.PNG' })).toBeNull()
+ expect(download).not.toHaveBeenCalled()
})
- it('copies markdown source to the clipboard via the preview header button', async () => {
- const writeText = vi.fn(async () => undefined)
- Object.defineProperty(navigator, 'clipboard', {
- configurable: true,
- value: { ...(navigator.clipboard ?? {}), writeText },
- })
++ it('opens a GFS URI from the modal and closes after a successful resolve', async () => {
++ const openUri = vi.fn(async () => true)
++ hookMock.useGfsBrowserController.mockReturnValue({ ...baseController(), openUri })
++ renderFilesPage()
+
- const markdown = '# Hello\n\nGreetings.'
- const download = vi.fn(async () => ({
- bytes: new TextEncoder().encode(markdown).buffer,
- }))
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: { gfs: { download } },
++ expect(screen.queryByRole('button', { name: 'Open EvenDrive link' })).toBeNull()
++ fireEvent.click(screen.getByRole('button', { name: 'Options for Shared with me' }))
++ fireEvent.click(screen.getByRole('menuitem', { name: 'Open EvenDrive link' }))
++ const dialog = await screen.findByRole('dialog', { name: 'Open EvenDrive link' })
++ fireEvent.change(within(dialog).getByLabelText('EvenDrive link'), {
++ target: { value: 'gfs://main/resource-1' },
+ })
++ fireEvent.click(within(dialog).getByRole('button', { name: 'Open' }))
++
++ await waitFor(() => expect(openUri).toHaveBeenCalledWith('gfs://main/resource-1'))
++ await waitFor(() =>
++ expect(screen.queryByRole('dialog', { name: 'Open EvenDrive link' })).toBeNull()
++ )
++ })
++
+ it('opens a preview tab for a markdown file (no mimeType in the descriptor)', () => {
+ const onOpenPreview = vi.fn()
hookMock.useGfsBrowserController.mockReturnValue({
...baseController(),
- accessibleResources: [
- {
- resourceId: 'markdown-2',
- rid: 'markdown-2',
- gfsUri: 'gfs://main/markdown-2',
- drive: 'main',
- parentResourceId: null,
- name: 'README.md',
- kind: 'file',
- path: '/README.md',
- version: 1,
- bytes: markdown.length,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- ],
+ accessibleResources: [previewRow('README.md', 'markdown-1', 12)],
})
--
- renderFilesPage()
+ renderFilesPage(undefined, onOpenPreview)
fireEvent.click(screen.getByRole('button', { name: 'README.md' }))
- const dialog = await screen.findByRole('dialog', { name: 'README.md' })
- const copyButton = within(dialog).getByRole('button', {
- name: /Copy preview contents to clipboard/i,
+ expect(onOpenPreview).toHaveBeenCalledWith({
+ gfsUri: 'gfs://main/markdown-1',
+ kind: 'markdown',
+ name: 'README.md',
+ bytes: 12,
})
- expect(copyButton.querySelector('svg')?.getAttribute('viewBox')).toBe('0 0 24 24')
- expect(copyButton.querySelector('path')?.getAttribute('d')).toBe('M0 0h24v24H0z')
- fireEvent.click(copyButton)
-
- await waitFor(() => expect(writeText).toHaveBeenCalledWith(markdown))
})
- it('renders a .txt file as plain text inside the preview dialog', async () => {
- const download = vi.fn(async () => ({
- bytes: new TextEncoder().encode('line one\nline two\twith tab').buffer,
- }))
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: { gfs: { download } },
- })
+ it('opens a preview tab for a video file with its detected mimeType', () => {
+ const onOpenPreview = vi.fn()
hookMock.useGfsBrowserController.mockReturnValue({
...baseController(),
- accessibleResources: [
- {
- resourceId: 'text-1',
- rid: 'text-1',
- gfsUri: 'gfs://main/text-1',
- drive: 'main',
- parentResourceId: null,
- name: 'notes.txt',
- kind: 'file',
- path: '/notes.txt',
- version: 1,
- bytes: 26,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- ],
+ accessibleResources: [previewRow('demo.mp4', 'video-1', 3)],
})
- renderFilesPage()
- fireEvent.click(screen.getByRole('button', { name: 'notes.txt' }))
- const dialog = await screen.findByRole('dialog', { name: 'notes.txt' })
- const pre = await within(dialog).findByText(/line one/)
- expect(pre.tagName).toBe('PRE')
- expect(pre.textContent).toContain('line two\twith tab')
- })
-
- it('previews a video file in a closable HTML5 video dialog', async () => {
- const download = vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer }))
- const createObjectURL = vi.fn(() => 'blob:gfs-video-preview')
- const revokeObjectURL = vi.fn()
- Object.defineProperty(URL, 'createObjectURL', {
- configurable: true,
- value: createObjectURL,
- })
- Object.defineProperty(URL, 'revokeObjectURL', {
- configurable: true,
- value: revokeObjectURL,
- })
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: { gfs: { download } },
- })
- hookMock.useGfsBrowserController.mockReturnValue({
- ...baseController(),
- accessibleResources: [
- {
- resourceId: 'video-1',
- rid: 'video-1',
- gfsUri: 'gfs://main/video-1',
- drive: 'main',
- parentResourceId: null,
- name: 'demo.mp4',
- kind: 'file',
- path: '/demo.mp4',
- version: 1,
- bytes: 3,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- ],
- })
-
- renderFilesPage()
+ renderFilesPage(undefined, onOpenPreview)
fireEvent.click(screen.getByRole('button', { name: 'demo.mp4' }))
- const dialog = await screen.findByRole('dialog', { name: 'demo.mp4' })
- const video = await within(dialog).findByLabelText('Video preview of demo.mp4')
- expect(video.tagName).toBe('VIDEO')
- expect(video.getAttribute('controls')).not.toBeNull()
- expect(video.getAttribute('src')).toBe('blob:gfs-video-preview')
- expect(createObjectURL).toHaveBeenCalledWith(expect.objectContaining({ type: 'video/mp4' }))
-
- fireEvent.click(within(dialog).getByRole('button', { name: 'Close video preview' }))
- await waitFor(() => expect(screen.queryByRole('dialog', { name: 'demo.mp4' })).toBeNull())
- expect(revokeObjectURL).toHaveBeenCalledWith('blob:gfs-video-preview')
- })
-
- it('previews Markdown files with safe vanilla rendering', async () => {
- const markdown =
- '# Project guide\n\nUse **safe rendering**.\n\n1. First\n2. Second\n\n[Unsafe](javascript:alert)\n\n<script>alert("no")</script>'
- const download = vi.fn(async () => ({ bytes: new TextEncoder().encode(markdown).buffer }))
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: { gfs: { download } },
+ expect(onOpenPreview).toHaveBeenCalledWith({
+ gfsUri: 'gfs://main/video-1',
+ kind: 'video',
+ mimeType: 'video/mp4',
+ name: 'demo.mp4',
+ bytes: 3,
})
- hookMock.useGfsBrowserController.mockReturnValue({
- ...baseController(),
- accessibleResources: [
- {
- resourceId: 'markdown-1',
- rid: 'markdown-1',
- gfsUri: 'gfs://main/markdown-1',
- drive: 'main',
- parentResourceId: null,
- name: 'README.md',
- kind: 'file',
- path: '/README.md',
- version: 1,
- bytes: markdown.length,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- ],
- })
-
- renderFilesPage()
- fireEvent.click(screen.getByRole('button', { name: 'README.md' }))
-
- const dialog = await screen.findByRole('dialog', { name: 'README.md' })
- expect(
- await within(dialog).findByRole('heading', { name: 'Project guide', level: 1 })
- ).toBeTruthy()
- expect(within(dialog).getByText('safe rendering').tagName).toBe('STRONG')
- expect(within(dialog).getAllByRole('listitem')).toHaveLength(2)
- expect(within(dialog).getByText('Unsafe').closest('a')).toBeNull()
- expect(dialog.querySelector('script')).toBeNull()
- expect(download).toHaveBeenCalledWith('gfs://main/markdown-1')
-
- fireEvent.click(within(dialog).getByRole('button', { name: 'Close preview' }))
- await waitFor(() => expect(screen.queryByRole('dialog', { name: 'README.md' })).toBeNull())
})
- it('rejects oversized previews from metadata before downloading them', async () => {
- const download = vi.fn()
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: { gfs: { download } },
- })
+ it('downloads a previewable file when no preview surface is wired (fail-open to download)', async () => {
+ const download = vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer }))
+ const createObjectURL = vi.fn(() => 'blob:gfs-download')
+ const revokeObjectURL = vi.fn()
+ const anchorClick = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+ Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: createObjectURL })
+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: revokeObjectURL })
+ Object.defineProperty(window, 'clerum', { configurable: true, value: { gfs: { download } } })
hookMock.useGfsBrowserController.mockReturnValue({
...baseController(),
- accessibleResources: [
- {
- resourceId: 'large-image',
- rid: 'large-image',
- gfsUri: 'gfs://main/large-image',
- drive: 'main',
- parentResourceId: null,
- name: 'oversized.png',
- kind: 'file',
- path: '/oversized.png',
- version: 1,
- bytes: GFS_IMAGE_PREVIEW_MAX_BYTES + 1,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- {
- resourceId: 'large-markdown',
- rid: 'large-markdown',
- gfsUri: 'gfs://main/large-markdown',
- drive: 'main',
- parentResourceId: null,
- name: 'oversized.md',
- kind: 'file',
- path: '/oversized.md',
- version: 1,
- bytes: GFS_MARKDOWN_PREVIEW_MAX_BYTES + 1,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- ],
+ accessibleResources: [previewRow('diagram.PNG', 'image-1', 3)],
})
+ // No onOpenPreview: openFilePreview reports "not previewable" so the click
+ // falls through to the download path instead of silently doing nothing.
renderFilesPage()
- fireEvent.click(screen.getByRole('button', { name: 'oversized.png' }))
- let dialog = await screen.findByRole('dialog', { name: 'oversized.png' })
- expect(await within(dialog).findByText(/Image previews are limited to 10 MB/)).toBeTruthy()
- fireEvent.click(within(dialog).getByRole('button', { name: 'Close image preview' }))
-
- fireEvent.click(screen.getByRole('button', { name: 'oversized.md' }))
- dialog = await screen.findByRole('dialog', { name: 'oversized.md' })
- expect(await within(dialog).findByText(/Markdown previews are limited to 2 MB/)).toBeTruthy()
- expect(download).not.toHaveBeenCalled()
- })
-
- it('opens a GFS URI from the modal and closes after a successful resolve', async () => {
- const openUri = vi.fn(async () => true)
- hookMock.useGfsBrowserController.mockReturnValue({ ...baseController(), openUri })
- renderFilesPage()
-
- expect(screen.queryByRole('button', { name: 'Open EvenDrive link' })).toBeNull()
- fireEvent.click(screen.getByRole('button', { name: 'Options for Shared with me' }))
- fireEvent.click(screen.getByRole('menuitem', { name: 'Open EvenDrive link' }))
- const dialog = await screen.findByRole('dialog', { name: 'Open EvenDrive link' })
- fireEvent.change(within(dialog).getByLabelText('EvenDrive link'), {
- target: { value: 'gfs://main/resource-1' },
- })
- fireEvent.click(within(dialog).getByRole('button', { name: 'Open' }))
+ fireEvent.click(screen.getByRole('button', { name: 'diagram.PNG' }))
- await waitFor(() => expect(openUri).toHaveBeenCalledWith('gfs://main/resource-1'))
- await waitFor(() =>
- expect(screen.queryByRole('dialog', { name: 'Open EvenDrive link' })).toBeNull()
- )
+ await waitFor(() => expect(download).toHaveBeenCalledWith('gfs://main/image-1'))
+ expect(anchorClick).toHaveBeenCalled()
})
- it('opens an SVG GFS link in preview without leaving the browser on a file-only route', async () => {
- const download = vi.fn(async () => ({ bytes: new Uint8Array([60, 115, 118, 103]).buffer }))
- const createObjectURL = vi.fn(() => 'blob:gfs-svg-preview')
- const revokeObjectURL = vi.fn()
+ it('opens a preview tab from a resolved GFS link and closes the link dialog', async () => {
+ const onOpenPreview = vi.fn()
const resolvedFile: GfsCrumb = {
resourceId: 'svg-1',
gfsUri: 'gfs://main/svg-1',
@@@ -3955,25 -3036,25 +3915,27 @@@
}
hookMock.useGfsBrowserController.mockImplementation(useResolvedFileController)
- renderFilesPage()
+ renderFilesPage(undefined, onOpenPreview)
fireEvent.click(screen.getByRole('button', { name: 'Options for Shared with me' }))
- fireEvent.click(screen.getByRole('menuitem', { name: 'Open GFS link' }))
- const linkDialog = await screen.findByRole('dialog', { name: 'Open GFS link' })
- fireEvent.change(within(linkDialog).getByLabelText('gfs URI'), {
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Open EvenDrive link' }))
+ const linkDialog = await screen.findByRole('dialog', { name: 'Open EvenDrive link' })
+ fireEvent.change(within(linkDialog).getByLabelText('EvenDrive link'), {
target: { value: 'gfs://main/svg-1' },
})
fireEvent.click(within(linkDialog).getByRole('button', { name: 'Open' }))
- const preview = await screen.findByRole('dialog', { name: 'architecture.svg' })
await waitFor(() =>
- expect(within(preview).getByAltText('Preview of architecture.svg')).toBeTruthy()
+ expect(onOpenPreview).toHaveBeenCalledWith({
+ gfsUri: 'gfs://main/svg-1',
+ kind: 'image',
+ mimeType: 'image/svg+xml',
+ name: 'architecture.svg',
+ bytes: 4,
+ })
+ )
- await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Open GFS link' })).toBeNull())
++ await waitFor(() =>
++ expect(screen.queryByRole('dialog', { name: 'Open EvenDrive link' })).toBeNull()
+ )
- expect(download).toHaveBeenCalledWith('gfs://main/svg-1')
- expect(createObjectURL).toHaveBeenCalledWith(expect.objectContaining({ type: 'image/svg+xml' }))
- expect(screen.queryByRole('dialog', { name: 'Open EvenDrive link' })).toBeNull()
-
- fireEvent.click(within(preview).getByRole('button', { name: 'Close image preview' }))
- expect(screen.queryByRole('heading', { name: 'architecture.svg' })).toBeNull()
expect(screen.getByRole('button', { name: 'Options for Shared with me' })).toBeTruthy()
})
@@@ -4341,4 -3269,580 +4303,580 @@@
expect(listChildren).toHaveBeenCalledWith('folder-a', 'main', undefined)
expect(listChildren).toHaveBeenCalledWith('folder-b', 'main', undefined)
})
+
+ it('advances past subfolders whose prefetch failed instead of re-selecting them', async () => {
+ // `data === undefined` is also true of a FAILED prefetch, so the cached-key
+ // skip let the cap stall: the same first ten were re-selected on every
+ // `items` change and the folders behind them were never warmed. The
+ // existing cap test seeds only SUCCESS via `setQueryData`, which cannot
+ // reach an error state, so nothing held this.
+ //
+ // The rate limit is the case that matters. Ten failures and a loadMore
+ // page re-send the identical burst against the budget that just refused
+ // it — the feedback loop the per-actor budget exists to stop.
+ const doomed = new Set(
+ Array.from({ length: 10 }, (_, index) => `folder-${String(index).padStart(2, '0')}`)
+ )
+ const listChildren = vi.fn(async (resourceId: string) => {
+ if (doomed.has(resourceId)) {
+ throw new Error('429 Too Many Requests: Too Many Requests retryAfterSeconds=7')
+ }
+ return { items: [], nextCursor: null }
+ })
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { list: () => ({ items: [] }), download: vi.fn(), listChildren } },
+ })
+ const makeFolder = (index: number) => ({
+ resourceId: `folder-${String(index).padStart(2, '0')}`,
+ rid: `folder-${index}`,
+ gfsUri: `gfs://main/folder-${index}`,
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: `Folder ${index}`,
+ kind: 'directory',
+ path: `/Product/Folder ${index}`,
+ version: 1,
+ bytes: 0,
+ })
+ const current = {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ name: 'Product',
+ kind: 'directory',
+ version: 1,
+ }
+ const showFolders = (count: number) => {
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current,
+ items: Array.from({ length: count }, (_, index) => makeFolder(index)),
+ })
+ }
+
+ showFolders(14)
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ // A fresh element per pass: React bails out of re-rendering a root given
+ // the identical element reference, which would silently skip the effect
+ // this test exists to re-trigger.
+ const makeElement = () => (
+ <QueryClientProvider client={queryClient}>
+ <FilesPage />
+ </QueryClientProvider>
+ )
+ const { rerender } = render(makeElement())
+
+ // The first pass spends the whole cap on folders that all fail.
+ await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(10))
+ expect(listChildren.mock.calls.map(call => call[0])).toEqual([...doomed])
+
+ // A loadMore page changes `items` and re-runs the effect — the exact
+ // trigger the cached-key skip exists to survive.
+ showFolders(16)
+ rerender(makeElement())
+
+ await waitFor(() => expect(listChildren.mock.calls.map(call => call[0])).toContain('folder-10'))
+ const requested = listChildren.mock.calls.map(call => call[0])
+ // The four already-visible folders plus the two the new page added: the
+ // window really moved on rather than stalling on the failures.
+ expect(requested.slice(10)).toEqual([
+ 'folder-10',
+ 'folder-11',
+ 'folder-12',
+ 'folder-13',
+ 'folder-14',
+ 'folder-15',
+ ])
+ // Each failed folder was asked for exactly once, never re-sent.
+ doomed.forEach(resourceId => expect(requested.filter(id => id === resourceId)).toHaveLength(1))
+ expect(listChildren).toHaveBeenCalledTimes(16)
+ })
+
+ it('prefetches only the first ten uncached subfolders, skipping those already in cache', async () => {
+ // The mock carries the real signature so `calls.map(call => call[0])`
+ // below is typed as the resource id, not as an empty tuple.
+ const listChildren = vi.fn(async (_resourceId: string) => ({
+ items: [],
+ nextCursor: null,
+ }))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { list: () => ({ items: [] }), download: vi.fn(), listChildren } },
+ })
+ const scope = 'env-1:user-1:team-1'
+ const folders = Array.from({ length: 15 }, (_, index) => ({
+ resourceId: `folder-${String(index).padStart(2, '0')}`,
+ rid: `folder-${index}`,
+ gfsUri: `gfs://main/folder-${index}`,
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: `Folder ${index}`,
+ kind: 'directory',
+ path: `/Product/Folder ${index}`,
+ version: 1,
+ bytes: 0,
+ }))
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ name: 'Product',
+ kind: 'directory',
+ version: 1,
+ },
+ items: folders,
+ })
+
+ const cached = ['folder-02', 'folder-05', 'folder-09']
+ // Scattered, not leading: a cap applied before the skip would still get
+ // the first ten right if the cached ids were all at the front.
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ cached.forEach(resourceId =>
+ queryClient.setQueryData(desktopQueryKeys.gfsChildren(scope, resourceId, 'main'), {
+ pages: [{ items: [], nextCursor: null }],
+ pageParams: [undefined],
+ })
+ )
+ render(
+ <QueryClientProvider client={queryClient}>
+ <FilesPage />
+ </QueryClientProvider>
+ )
+
+ // Positive, and the witness: the effect ran and sent exactly the cap.
+ // Under production defaults `fetchInfiniteQuery` would serve the cached
+ // pages without a request anyway; this harness runs at `staleTime: 0`, so
+ // the explicit cached-key check is the only thing keeping those three out.
+ await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(10))
+ const requested = listChildren.mock.calls.map(call => call[0])
+ cached.forEach(resourceId => expect(requested).not.toContain(resourceId))
+ expect(requested).toEqual([
+ 'folder-00',
+ 'folder-01',
+ 'folder-03',
+ 'folder-04',
+ 'folder-06',
+ 'folder-07',
+ 'folder-08',
+ 'folder-10',
+ 'folder-11',
+ 'folder-12',
+ ])
+ })
+
+ it('renders a rate-limited discovery failure as a card with a retry countdown', async () => {
+ vi.useFakeTimers()
+ const retryDiscovery = vi.fn()
+ const rawMessage =
+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " +
+ 'Too Many Requests retryAfterSeconds=7'
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ authorityPending: true,
+ accessibleError: rawMessage,
+ discoveryFailure: {
+ kind: 'rate-limited',
+ message: rawMessage,
+ retryAvailableAt: Date.now() + 7_000,
+ },
+ retryDiscovery,
+ })
+
+ renderFilesPage()
+
+ expect(screen.getByTestId('gfs-discovery-retry-seconds').textContent).toBe('7')
+ // None of the three things the user saw during the incident.
+ expect(screen.queryByText('Loading files…')).toBeNull()
+ expect(screen.queryByText(/Error invoking remote method/)).toBeNull()
+ expect(screen.queryByText(/Automatic GFS discovery is not available/)).toBeNull()
+
+ const disabledRetry = screen.getByRole('button', { name: /retry/i }) as HTMLButtonElement
+ expect(disabledRetry.disabled).toBe(true)
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(7_000)
+ })
+
+ expect(screen.queryByTestId('gfs-discovery-retry-seconds')).toBeNull()
+ const enabledRetry = screen.getByRole('button', { name: /retry/i }) as HTMLButtonElement
+ expect(enabledRetry.disabled).toBe(false)
+
+ await act(async () => {
+ fireEvent.click(enabledRetry)
+ })
+ // Witness: the button is wired to the controller, not to a local no-op.
+ expect(retryDiscovery).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps an already-loaded listing when the NEXT discovery page is rate limited', () => {
+ // Discovery is an infinite query: TanStack populates `error` on a rejected
+ // `fetchNextPage` while `data` still holds every page already fetched. The
+ // card renders ahead of the grid, so without gating it on an empty listing
+ // a `Load more` that hit the budget wiped out the rows the user already
+ // had, to announce that a page they never saw had failed.
+ const rawMessage =
+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " +
+ 'Too Many Requests retryAfterSeconds=120'
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ // The first page succeeded, so the authority gate is closed and its rows
+ // are on screen; only the follow-up page was refused.
+ authorityPending: false,
+ accessibleResources: [
+ {
+ resourceId: 'folder-1',
+ rid: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ drive: 'main',
+ parentResourceId: null,
+ name: 'Product',
+ kind: 'directory',
+ path: '/Product',
+ version: 1,
+ bytes: 0,
+ sources: ['grant'],
+ permissions: ['read'],
+ coversDescendants: true,
+ },
+ ],
+ hasMoreAccessible: true,
+ accessibleError: rawMessage,
+ discoveryFailure: {
+ kind: 'rate-limited',
+ message: rawMessage,
+ retryAvailableAt: Date.now() + 120_000,
+ },
+ })
+
+ renderFilesPage()
+
+ // Witness: the loaded row really is rendered, so the absence of the card
+ // below is about a listing that survived and not about a page that never
+ // drew anything.
+ expect(screen.getByRole('button', { name: 'Product' })).toBeTruthy()
+ expect(screen.queryByTestId('gfs-discovery-retry-seconds')).toBeNull()
+ // The failure is still surfaced — as the banner, not by razing the page.
+ expect(screen.getByText(/Too many file requests/)).toBeTruthy()
+ })
+
+ it('leaves an unsupported discovery failure on the existing info notice, with no card', () => {
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ accessibleNotice:
+ 'Automatic GFS discovery is not available from this server yet. You can still open any GFS link you have.',
+ discoveryFailure: {
+ kind: 'unsupported',
+ message: '404 Not Found: Not Found',
+ retryAvailableAt: null,
+ },
+ })
+
+ renderFilesPage()
+
+ expect(screen.getByText(/Automatic GFS discovery is not available/)).toBeTruthy()
+ expect(screen.queryByTestId('gfs-discovery-retry-seconds')).toBeNull()
+ expect(screen.queryByRole('button', { name: /retry file listing/i })).toBeNull()
+ })
+
+ it('shows a server-side discovery failure without the IPC plumbing around it', () => {
+ // `kind: 'failed'` covers 5xx, network and timeout — everything that is
+ // neither a 404 nor a rate limit. It reaches the same card, so the card's
+ // body has to be presented rather than passed through: the raw value is an
+ // Electron wrapper around the verdict, and the seam test in this PR asserts
+ // that wrapper must never reach a user.
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ authorityPending: true,
+ accessibleError:
+ "Error invoking remote method 'gfs:listAccessible': Error: 503 Service Unavailable: upstream_unreachable",
+ discoveryFailure: {
+ kind: 'failed',
+ message:
+ "Error invoking remote method 'gfs:listAccessible': Error: 503 Service Unavailable: upstream_unreachable",
+ retryAvailableAt: null,
+ },
+ })
+
+ renderFilesPage()
+
+ // Liveness witness: the card really rendered, so the absence assertions
+ // below describe a presented failure and not an unmounted branch.
+ expect(screen.getByText('Could not load your files')).toBeTruthy()
+ expect(screen.getByText(/503 Service Unavailable: upstream_unreachable/)).toBeTruthy()
+ expect(screen.queryByText(/Error invoking remote method/)).toBeNull()
+ // No window was named, so nothing pretends to know one.
+ expect(screen.queryByTestId('gfs-discovery-retry-seconds')).toBeNull()
+ const retry = screen.getByRole('button', { name: /retry file listing/i }) as HTMLButtonElement
+ expect(retry.disabled).toBe(false)
+ })
+
+ it('stops reporting the drive as busy once discovery has settled into a failure', () => {
+ // authorityPending stays true after a 429 on purpose — a rate limit does
+ // not re-prove the session — so aria-busy had to stop deriving from it
+ // alone, or a screen reader announces a loading region that is showing a
+ // settled error with a Retry button.
+ const rawMessage =
+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " +
+ 'Too Many Requests retryAfterSeconds=7'
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ authorityPending: true,
+ accessibleError: rawMessage,
+ discoveryFailure: {
+ kind: 'rate-limited',
+ message: rawMessage,
+ retryAvailableAt: Date.now() + 7_000,
+ },
+ })
+
+ renderFilesPage()
+
- const drive = screen.getByLabelText('Global File System browser')
++ const drive = screen.getByLabelText('EvenDrive browser')
+ // Witness: this is the failure state, not a page that never rendered the
+ // drive region at all.
+ expect(screen.getByText('Too many file requests')).toBeTruthy()
+ expect(drive.getAttribute('aria-busy')).toBe('false')
+ })
+
+ // The five fixtures above all set `authorityPending: true`, no rows and
+ // `hasMoreAccessible: false` together, so nothing distinguishes the three
+ // clauses of the card's guard: swapping the empty-listing test for either
+ // sibling left the whole suite green. These two break that correlation, one
+ // clause at a time, and each holds one clause on its own.
+ it('keeps a loaded row while the authority gate is still pending', () => {
+ // Rows present, gate pending, and no further page to fetch. Only
+ // `visibleResources.length === 0` can decide here, so a guard rewritten to
+ // read `authorityPending` (or `!hasMoreAccessible`) wipes out a listing the
+ // user can see — the failure the empty-listing clause exists to prevent.
+ const rawMessage =
+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " +
+ 'Too Many Requests retryAfterSeconds=7'
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ authorityPending: true,
+ hasMoreAccessible: false,
+ accessibleResources: [
+ {
+ resourceId: 'folder-1',
+ rid: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ drive: 'main',
+ parentResourceId: null,
+ name: 'Product',
+ kind: 'directory',
+ path: '/Product',
+ version: 1,
+ bytes: 0,
+ sources: ['grant'],
+ permissions: ['read'],
+ coversDescendants: true,
+ },
+ ],
+ accessibleError: rawMessage,
+ discoveryFailure: {
+ kind: 'rate-limited',
+ message: rawMessage,
+ retryAvailableAt: Date.now() + 7_000,
+ },
+ })
+
+ renderFilesPage()
+
+ // Witness: the row is on screen, so the two absences below describe a
+ // listing that survived rather than a page that drew nothing at all.
+ expect(screen.getByRole('button', { name: 'Product' })).toBeTruthy()
+ expect(screen.queryByTestId('gfs-discovery-retry-seconds')).toBeNull()
+ expect(screen.queryByRole('button', { name: /retry file listing/i })).toBeNull()
+ })
+
+ it('shows the card for an empty listing once the authority gate has closed', () => {
+ // The mirror image: gate closed, no further page, and nothing to show. A
+ // guard that read `authorityPending` instead would skip the card and leave
+ // the user on "No shared files yet" for a listing that was refused.
+ const rawMessage =
+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " +
+ 'Too Many Requests retryAfterSeconds=120'
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ authorityPending: false,
+ hasMoreAccessible: false,
+ accessibleError: rawMessage,
+ discoveryFailure: {
+ kind: 'rate-limited',
+ message: rawMessage,
+ retryAvailableAt: Date.now() + 120_000,
+ },
+ })
+
+ renderFilesPage()
+
+ expect(screen.getByTestId('gfs-discovery-retry-seconds').textContent).toBe('120')
+ expect(screen.queryByText('No shared files yet')).toBeNull()
+ })
+
+ it('answers a 404 discovery failure with its own empty state, never a loader', () => {
+ // The original incident's symptom through a different door. An older
+ // control-api has no `listAccessible`, so the 404 leaves `authorityPending`
+ // true forever — correctly, since nothing re-proved the session — and the
+ // page used to spin "Loading files…" underneath the very notice explaining
+ // that discovery is unavailable. Two contradictory claims at once.
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ authorityPending: true,
+ accessibleNotice:
+ 'Automatic GFS discovery is not available from this server yet. You can still open any GFS link you have.',
+ discoveryFailure: {
+ kind: 'unsupported',
+ message: '404 Not Found: Not Found',
+ retryAvailableAt: null,
+ },
+ })
+
+ renderFilesPage()
+
+ // Witness: the settled state really rendered.
+ expect(screen.getByText('Files cannot be listed here')).toBeTruthy()
+ expect(screen.getByText(/That does not mean you have none/)).toBeTruthy()
+ expect(screen.queryByText('Loading files…')).toBeNull()
+ // No Retry: the endpoint does not appear because a button was pressed.
+ expect(screen.queryByRole('button', { name: /retry file listing/i })).toBeNull()
+ // The copy that would assert an empty library must not be the one shown.
+ expect(screen.queryByText('No shared files yet')).toBeNull()
+ })
+
+ it('reveals a file opened by link while discovery is still rate limited', () => {
+ // Opening a `gfs://` link does not go through discovery, so a 429 there has
+ // no bearing on whether the resolved file can be shown. It was shown only
+ // as a spinner, because the page called the pending authority gate a load
+ // in progress and the loader renders ahead of the file.
+ const rawMessage =
+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " +
+ 'Too Many Requests retryAfterSeconds=7'
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ authorityPending: true,
+ current: {
+ resourceId: 'file-1',
+ gfsUri: 'gfs://main/file-1',
+ name: 'quarterly.pdf',
+ kind: 'file',
+ version: 1,
+ bytes: 2048,
+ },
+ crumbs: [
+ {
+ resourceId: 'file-1',
+ gfsUri: 'gfs://main/file-1',
+ name: 'quarterly.pdf',
+ kind: 'file',
+ },
+ ],
+ accessibleError: rawMessage,
+ discoveryFailure: {
+ kind: 'rate-limited',
+ message: rawMessage,
+ retryAvailableAt: Date.now() + 7_000,
+ },
+ })
+
+ renderFilesPage()
+
+ // The heading, not the breadcrumb: the breadcrumb renders above the
+ // loader and would be present even while the spinner hid the file, so
+ // only the heading proves the file view itself was reached.
+ expect(screen.getByRole('heading', { name: 'quarterly.pdf' })).toBeTruthy()
+ expect(screen.queryByText('Loading files…')).toBeNull()
+ // The discovery failure belongs to the root listing, not to this file, so
+ // it must not take the surface over either.
+ expect(screen.queryByText('Too many file requests')).toBeNull()
+ })
+
+ it('answers a rate-limited folder listing with the card, not an empty folder', async () => {
+ vi.useFakeTimers()
+ const retryChildren = vi.fn()
+ const rawMessage =
+ "Error invoking remote method 'gfs:listChildren': Error: 429 Too Many Requests: " +
+ 'Too Many Requests retryAfterSeconds=7'
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'parent-1',
+ gfsUri: 'gfs://main/parent-1',
+ name: 'Workspace',
+ kind: 'directory',
+ version: 1,
+ bytes: 0,
+ },
+ items: [],
+ error: rawMessage,
+ errorUpdatedAt: Date.now(),
+ retryChildren,
+ })
+
+ renderFilesPage()
+
+ // "This folder is empty" states as fact the one thing the refused request
+ // could not establish, and offered nothing to retry.
+ expect(screen.queryByText('This folder is empty')).toBeNull()
+ expect(screen.getByText('Too many file requests')).toBeTruthy()
+ expect(screen.getByTestId('gfs-discovery-retry-seconds').textContent).toBe('7')
+ // The raw channel name stays out of the user's way on this plane too.
+ expect(screen.queryByText(/Error invoking remote method/)).toBeNull()
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(7_000)
+ })
+ const retry = screen.getByRole('button', { name: /retry file listing/i }) as HTMLButtonElement
+ expect(retry.disabled).toBe(false)
+ await act(async () => {
+ fireEvent.click(retry)
+ })
+ // Witness: the button retries the query that actually failed — the children
+ // listing — and not discovery, which was never asked anything here.
+ expect(retryChildren).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps a loaded folder listing when only its next page was refused', () => {
+ // The folder-plane sibling of the `Load more` case: rows already fetched
+ // must not be razed to report that the page behind them failed.
+ const rawMessage =
+ "Error invoking remote method 'gfs:listChildren': Error: 429 Too Many Requests: " +
+ 'Too Many Requests retryAfterSeconds=7'
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'parent-1',
+ gfsUri: 'gfs://main/parent-1',
+ name: 'Workspace',
+ kind: 'directory',
+ version: 1,
+ bytes: 0,
+ },
+ items: [
+ {
+ resourceId: 'file-child',
+ rid: 'file-child',
+ gfsUri: 'gfs://main/file-child',
+ drive: 'main',
+ parentResourceId: 'parent-1',
+ name: 'notes.txt',
+ kind: 'file',
+ path: '/notes.txt',
+ version: 1,
+ bytes: 12,
+ },
+ ],
+ error: rawMessage,
+ errorUpdatedAt: Date.now(),
+ })
+
+ renderFilesPage()
+
+ // Witness: the row survived the failure.
+ expect(screen.getByText('notes.txt')).toBeTruthy()
+ expect(screen.queryByTestId('gfs-discovery-retry-seconds')).toBeNull()
+ // Still surfaced, as the banner — and presented, not as the IPC wrapper.
+ expect(screen.getByText(/Too many file requests — try again in 7s\./)).toBeTruthy()
+ })
})