Skip to content

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

TypeScript

fix(gfs): enforce fail-closed authority, independent grants/shares, paginated move (r4)

Miguelon Peluchon2dc5ec904a64
diff --git a/desktop-app/ui/src/gfs/GfsGrantList/index.tsx b/desktop-app/ui/src/gfs/GfsGrantList/index.tsx
index 417615bcc..45af8572c 100644
--- a/desktop-app/ui/src/gfs/GfsGrantList/index.tsx
+++ b/desktop-app/ui/src/gfs/GfsGrantList/index.tsx
@@ -49,107 +49,127 @@ export function GfsGrantList({
revoking = false,
revokingShare = false,
}: GfsGrantListProps) {
- if (error || shareError) {
- return (
- <div className="da-gfs-grant-list__errors" data-testid="gfs-access-list-error">
- {error ? (
- <StatusBanner tone={error.severity === 'quiet' ? 'info' : 'error'} text={error.message} />
- ) : null}
- {shareError ? (
- <StatusBanner
- tone={shareError.severity === 'quiet' ? 'info' : 'error'}
- text={shareError.message}
- />
- ) : null}
- </div>
- )
- }
- if (loading && items.length === 0 && shares.length === 0) {
- return <p className="muted">Loading access…</p>
- }
- if (items.length === 0 && shares.length === 0) {
- return <p className="muted">No direct grants or shares yet.</p>
- }
+ // Grants and shares are independent server surfaces with independent
+ // failure modes (R4 spec §2): one list's error suppresses only its own rows
+ // and never the other list's rows or revoke actions.
+ const showGrantRows = !error && items.length > 0
+ const showShareRows = !shareError && shares.length > 0
+ const hasRows = showGrantRows || showShareRows
+ const hasAnyError = Boolean(error || shareError)
return (
- <ul className="da-gfs-grant-list" aria-label="Resource access">
- {items.map(item => {
- const label = subjectLabel(item.subject, agents, subjects)
- return (
- <li
- className="da-gfs-grant-list__row"
- data-testid={`gfs-access-row-grant-${item.id}`}
- key={`grant:${item.id}`}
- >
- <span className="da-gfs-grant-list__identity">
- <span className="da-gfs-grant-list__label">{label}</span>
- <span className="da-gfs-grant-list__subject-type">
- Direct grant · {item.subject.type}
- </span>
- </span>
- <span className="da-gfs-grant-list__meta">
- <span className="da-gfs-grant-list__chips">
- {item.permissions.map(permission => (
- <Pill key={permission} size="xs" tone="neutral">
- {GFS_PERMISSION_LABELS[permission] ?? permission}
- </Pill>
- ))}
- </span>
- {item.inherit ? <Badge tone="accent">Includes contents</Badge> : null}
- </span>
- <IconButton
- color="danger"
- className="da-gfs-grant-list__revoke"
- data-testid={`gfs-revoke-grant-${item.id}`}
- disabled={revoking}
- label={`Revoke access for ${label}`}
- onClick={() => void onRevoke(item, label)}
- size="xs"
- variant="ghost"
- >
- X
- </IconButton>
- </li>
- )
- })}
- {shares.map(item => {
- const label = subjectLabel(item.subject, agents, subjects)
- return (
- <li
- className="da-gfs-grant-list__row"
- data-testid={`gfs-access-row-share-${item.id}`}
- key={`share:${item.id}`}
- >
- <span className="da-gfs-grant-list__identity">
- <span className="da-gfs-grant-list__label">{label}</span>
- <span className="da-gfs-grant-list__subject-type">Share · {item.subject.type}</span>
- </span>
- <span className="da-gfs-grant-list__meta">
- <span className="da-gfs-grant-list__chips">
- {item.permissions.map(permission => (
- <Pill key={permission} size="xs" tone="neutral">
- {GFS_PERMISSION_LABELS[permission] ?? permission}
- </Pill>
- ))}
- </span>
- {item.includeDescendants ? <Badge tone="accent">Includes contents</Badge> : null}
- </span>
- <IconButton
- color="danger"
- className="da-gfs-grant-list__revoke"
- data-testid={`gfs-revoke-share-${item.id}`}
- disabled={revokingShare || !onRevokeShare}
- label={`Revoke shared access for ${label}`}
- onClick={() => void onRevokeShare?.(item, label)}
- size="xs"
- variant="ghost"
- >
- X
- </IconButton>
- </li>
+ <>
+ {hasAnyError ? (
+ <div className="da-gfs-grant-list__errors" data-testid="gfs-access-list-error">
+ {error ? (
+ <StatusBanner
+ tone={error.severity === 'quiet' ? 'info' : 'error'}
+ text={error.message}
+ />
+ ) : null}
+ {shareError ? (
+ <StatusBanner
+ tone={shareError.severity === 'quiet' ? 'info' : 'error'}
+ text={shareError.message}
+ />
+ ) : null}
+ </div>
+ ) : null}
+ {hasRows ? (
+ <ul className="da-gfs-grant-list" aria-label="Resource access">
+ {showGrantRows
+ ? items.map(item => {
+ const label = subjectLabel(item.subject, agents, subjects)
+ return (
+ <li
+ className="da-gfs-grant-list__row"
+ data-testid={`gfs-access-row-grant-${item.id}`}
+ key={`grant:${item.id}`}
+ >
+ <span className="da-gfs-grant-list__identity">
+ <span className="da-gfs-grant-list__label">{label}</span>
+ <span className="da-gfs-grant-list__subject-type">
+ Direct grant · {item.subject.type}
+ </span>
+ </span>
+ <span className="da-gfs-grant-list__meta">
+ <span className="da-gfs-grant-list__chips">
+ {item.permissions.map(permission => (
+ <Pill key={permission} size="xs" tone="neutral">
+ {GFS_PERMISSION_LABELS[permission] ?? permission}
+ </Pill>
+ ))}
+ </span>
+ {item.inherit ? <Badge tone="accent">Includes contents</Badge> : null}
+ </span>
+ <IconButton
+ color="danger"
+ className="da-gfs-grant-list__revoke"
+ data-testid={`gfs-revoke-grant-${item.id}`}
+ disabled={revoking}
+ label={`Revoke access for ${label}`}
+ onClick={() => void onRevoke(item, label)}
+ size="xs"
+ variant="ghost"
+ >
+ X
+ </IconButton>
+ </li>
+ )
+ })
+ : null}
+ {showShareRows
+ ? shares.map(item => {
+ const label = subjectLabel(item.subject, agents, subjects)
+ return (
+ <li
+ className="da-gfs-grant-list__row"
+ data-testid={`gfs-access-row-share-${item.id}`}
+ key={`share:${item.id}`}
+ >
+ <span className="da-gfs-grant-list__identity">
+ <span className="da-gfs-grant-list__label">{label}</span>
+ <span className="da-gfs-grant-list__subject-type">
+ Share · {item.subject.type}
+ </span>
+ </span>
+ <span className="da-gfs-grant-list__meta">
+ <span className="da-gfs-grant-list__chips">
+ {item.permissions.map(permission => (
+ <Pill key={permission} size="xs" tone="neutral">
+ {GFS_PERMISSION_LABELS[permission] ?? permission}
+ </Pill>
+ ))}
+ </span>
+ {item.includeDescendants ? (
+ <Badge tone="accent">Includes contents</Badge>
+ ) : null}
+ </span>
+ <IconButton
+ color="danger"
+ className="da-gfs-grant-list__revoke"
+ data-testid={`gfs-revoke-share-${item.id}`}
+ disabled={revokingShare || !onRevokeShare}
+ label={`Revoke shared access for ${label}`}
+ onClick={() => void onRevokeShare?.(item, label)}
+ size="xs"
+ variant="ghost"
+ >
+ X
+ </IconButton>
+ </li>
+ )
+ })
+ : null}
+ </ul>
+ ) : !hasAnyError ? (
+ loading ? (
+ <p className="muted">Loading access…</p>
+ ) : (
+ <p className="muted">No direct grants or shares yet.</p>
)
- })}
- </ul>
+ ) : null}
+ </>
)
}
diff --git a/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx b/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx
index d7a4a8082..c6ffbc8ed 100644
--- a/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx
+++ b/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx
@@ -178,4 +178,55 @@ describe('GfsGrantList', () => {
expect(screen.getByText('No direct grants or shares yet.')).toBeTruthy()
})
+
+ // R4 spec §2 — grants and shares fail independently: a share-list error
+ // must not hide successful grant rows or their revoke actions, and vice
+ // versa. Regression for the early-return that swallowed grants whenever
+ // listShares failed.
+ it('keeps grants visible and revocable when only the share list fails', () => {
+ const onRevoke = vi.fn()
+ const grant = grantItem({ id: 'grant-1' })
+ render(
+ <GfsGrantList
+ agents={agents}
+ error={null}
+ items={[grant]}
+ onRevoke={onRevoke}
+ shareError={{ code: null, message: 'listShares exploded', severity: 'error' }}
+ shares={[]}
+ subjects={subjects}
+ />
+ )
+
+ // The share failure is visible…
+ const banner = screen.getByText('listShares exploded')
+ expect(banner.closest('.status-banner')?.className).toContain('tone-error')
+ // …but the grant row and its revoke action stay available and work.
+ const grantRow = screen.getByTestId('gfs-access-row-grant-grant-1')
+ expect(within(grantRow).getByText('Chat LLM')).toBeTruthy()
+ fireEvent.click(screen.getByRole('button', { name: 'Revoke access for Chat LLM' }))
+ expect(onRevoke).toHaveBeenCalledWith(grant, 'Chat LLM')
+ })
+
+ it('keeps shares visible and revocable when only the grants list fails', () => {
+ const onRevokeShare = vi.fn()
+ const share = shareItem({})
+ render(
+ <GfsGrantList
+ agents={agents}
+ error={{ code: null, message: 'listGrants exploded', severity: 'error' }}
+ items={[]}
+ onRevoke={vi.fn()}
+ onRevokeShare={onRevokeShare}
+ shares={[share]}
+ subjects={subjects}
+ />
+ )
+
+ expect(screen.getByText('listGrants exploded')).toBeTruthy()
+ const shareRow = screen.getByTestId('gfs-access-row-share-share-1')
+ expect(within(shareRow).getByText('Core Team')).toBeTruthy()
+ fireEvent.click(screen.getByRole('button', { name: 'Revoke shared access for Core Team' }))
+ expect(onRevokeShare).toHaveBeenCalledWith(share, 'Core Team')
+ })
})
diff --git a/desktop-app/ui/src/gfs/__tests__/moveDialog.test.tsx b/desktop-app/ui/src/gfs/__tests__/moveDialog.test.tsx
new file mode 100644
index 000000000..ad55d82b5
--- /dev/null
+++ b/desktop-app/ui/src/gfs/__tests__/moveDialog.test.tsx
@@ -0,0 +1,148 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
+import type { GfsBrowserChild, GfsCrumb } from '@hooks/domain/useGfsBrowserController'
+import { GfsMoveDialog } from '../moveDialog'
+
+/**
+ * R4 spec §3 — Move destination navigation is paginated: destinations beyond
+ * page one must be reachable through an observable Load-more control, and a
+ * page-two destination commits like any other. Cycle prevention (never offer
+ * the moved resource itself; never commit through its own subtree) must hold
+ * across pages.
+ */
+
+afterEach(cleanup)
+
+const target = { resourceId: 'file-1', name: 'notes.txt', kind: 'file' as const }
+
+function folder(id: string, name: string): GfsBrowserChild {
+ return {
+ resourceId: id,
+ rid: id,
+ gfsUri: `gfs://main/${id}`,
+ drive: 'main',
+ parentResourceId: null,
+ name,
+ kind: 'directory',
+ path: `/${name}`,
+ version: 1,
+ bytes: 0,
+ }
+}
+
+const parentCrumb: GfsCrumb = {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ name: 'Product',
+ kind: 'directory',
+ version: 1,
+ bytes: 0,
+}
+
+function renderDialog(
+ producers: { listAccessible?: () => Promise<unknown>; listChildren?: () => Promise<unknown> },
+ props: Partial<Parameters<typeof GfsMoveDialog>[0]> = {}
+) {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible:
+ producers.listAccessible ??
+ (vi.fn(async () => ({ items: [], nextCursor: null })) as () => Promise<unknown>),
+ listChildren:
+ producers.listChildren ??
+ (vi.fn(async () => ({ items: [], nextCursor: null })) as () => Promise<unknown>),
+ },
+ },
+ })
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <GfsMoveDialog
+ target={target}
+ initialCrumbs={[]}
+ onMove={vi.fn(async () => undefined)}
+ onClose={vi.fn()}
+ {...props}
+ />
+ </QueryClientProvider>
+ )
+}
+
+describe('GfsMoveDialog pagination', () => {
+ it('loads page two of the root destinations and commits a move to a page-two folder', async () => {
+ const onMove = vi.fn(async () => undefined)
+ let call = 0
+ const listAccessible = vi.fn(async () => {
+ call += 1
+ return call === 1
+ ? { items: [folder('arch-1', 'Archive')], nextCursor: 'page-2' }
+ : { items: [folder('deep-9', 'Deep Storage')], nextCursor: null }
+ })
+
+ renderDialog({ listAccessible }, { onMove })
+
+ const dialog = await screen.findByRole('dialog', { name: 'Move file notes.txt' })
+ expect(await within(dialog).findByRole('button', { name: 'Archive' })).toBeTruthy()
+ // Page two is not silently fetched, but reachable through Load more.
+ expect(within(dialog).queryByRole('button', { name: 'Deep Storage' })).toBeNull()
+ expect(within(dialog).getByRole('button', { name: 'Load more' })).toBeTruthy()
+
+ await fireEvent.click(within(dialog).getByRole('button', { name: 'Load more' }))
+
+ expect(await within(dialog).findByRole('button', { name: 'Deep Storage' })).toBeTruthy()
+ // Page-one rows stay rendered while additional pages load.
+ expect(within(dialog).getByRole('button', { name: 'Archive' })).toBeTruthy()
+ expect(within(dialog).queryByRole('button', { name: 'Load more' })).toBeNull()
+
+ // A page-two destination selects and commits like a page-one row.
+ await fireEvent.click(within(dialog).getByRole('button', { name: 'Deep Storage' }))
+ await fireEvent.click(within(dialog).getByRole('button', { name: 'Move here (Deep Storage)' }))
+
+ expect(onMove).toHaveBeenCalledWith('deep-9', 'Deep Storage')
+ })
+
+ it('loads page two inside a child folder listing and keeps cycle prevention', async () => {
+ const directoryTarget = { resourceId: 'moved-folder', name: 'Docs', kind: 'directory' as const }
+ const onMove = vi.fn(async () => undefined)
+ let call = 0
+ const listChildren = vi.fn(async () => {
+ call += 1
+ return call === 1
+ ? {
+ items: [folder('moved-folder', 'Docs'), folder('arch-1', 'Archive')],
+ nextCursor: 'p2',
+ }
+ : { items: [folder('nested-7', 'Nested Vault')], nextCursor: null }
+ })
+
+ renderDialog(
+ { listChildren },
+ { target: directoryTarget, initialCrumbs: [parentCrumb], onMove }
+ )
+
+ const dialog = await screen.findByRole('dialog', { name: 'Move folder Docs' })
+ expect(await within(dialog).findByRole('button', { name: 'Archive' })).toBeTruthy()
+ // The moved resource itself is never offered as a destination — on any page.
+ expect(within(dialog).queryByRole('button', { name: 'Docs' })).toBeNull()
+
+ await fireEvent.click(within(dialog).getByRole('button', { name: 'Load more' }))
+ expect(await within(dialog).findByRole('button', { name: 'Nested Vault' })).toBeTruthy()
+
+ await fireEvent.click(within(dialog).getByRole('button', { name: 'Nested Vault' }))
+ await fireEvent.click(within(dialog).getByRole('button', { name: 'Move here (Nested Vault)' }))
+
+ expect(onMove).toHaveBeenCalledWith('nested-7', 'Nested Vault')
+ })
+
+ it('keeps the empty notice when the listing has no next page', async () => {
+ renderDialog({})
+
+ const dialog = await screen.findByRole('dialog', { name: 'Move file notes.txt' })
+ expect(await within(dialog).findByText('No folders here.')).toBeTruthy()
+ expect(within(dialog).queryByRole('button', { name: 'Load more' })).toBeNull()
+ })
+})
diff --git a/desktop-app/ui/src/gfs/moveDialog.tsx b/desktop-app/ui/src/gfs/moveDialog.tsx
index 7a6cdd82b..15579d514 100644
--- a/desktop-app/ui/src/gfs/moveDialog.tsx
+++ b/desktop-app/ui/src/gfs/moveDialog.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import { useInfiniteQuery } from '@tanstack/react-query'
import { Button, IconButton, StatusBanner } from '@components/Common'
import { IconClose, IconContexts } from '@components/SidebarNav/icons'
@@ -25,6 +25,7 @@ export function GfsMoveDialog({
onMove,
onClose,
busy = false,
+ onAuthorityFailure,
}: GfsMoveDialogProps) {
const [crumbs, setCrumbs] = useState<GfsCrumb[]>(initialCrumbs)
const [error, setError] = useState<string | null>(null)
@@ -48,11 +49,26 @@ export function GfsMoveDialog({
initialPageParam: undefined as string | undefined,
getNextPageParam: lastPage => lastPage.nextCursor ?? undefined,
})
+ // Both listings are cursor-paginated; whichever one is active drives the
+ // Load-more control so destinations beyond page one stay reachable (R4
+ // spec §3). Fetching the next page keeps already-rendered rows in place.
+ const activeQuery = current === null ? accessibleQuery : childrenQuery
+ const hasMoreDestinations = Boolean(activeQuery.hasNextPage)
+ const loadingMoreDestinations = activeQuery.isFetchingNextPage
const folders = useMemo(() => {
- const source: Array<GfsBrowserChild & { kind: 'file' | 'directory' }> =
+ // Accessible-root items normalize their optional wire fields; children
+ // items are already GfsBrowserChild. Both flows converge on the same
+ // destination shape before filtering.
+ const source: GfsBrowserChild[] =
current === null
- ? (accessibleQuery.data?.pages ?? []).flatMap(page => page.items)
+ ? (accessibleQuery.data?.pages ?? [])
+ .flatMap(page => page.items)
+ .map(item => ({
+ ...item,
+ drive: item.drive ?? GFS_DRIVE_MAIN,
+ parentResourceId: item.parentResourceId ?? null,
+ }))
: (childrenQuery.data?.pages ?? []).flatMap(page => page.items)
return source.filter(item => item.kind === 'directory' && item.resourceId !== target.resourceId)
}, [accessibleQuery.data, childrenQuery.data, current, target.resourceId])
@@ -64,6 +80,13 @@ export function GfsMoveDialog({
current === null
? (accessibleQuery.error?.message ?? null)
: (childrenQuery.error?.message ?? null)
+ // Destination listings are session-scoped GFS reads: an authority failure
+ // here must reach the same fail-closed boundary as the page's queries (the
+ // page then closes this dialog via its revocation effect). Policy errors
+ // return false and render as the dialog's in-place banner below.
+ useEffect(() => {
+ if (listError) onAuthorityFailure?.(listError)
+ }, [listError, onAuthorityFailure])
const enterFolder = (folder: GfsBrowserChild) => {
setError(null)
@@ -148,19 +171,33 @@ export function GfsMoveDialog({
<div className="da-gfs-move-dialog__list" role="list">
{loading && folders.length === 0 ? (
<p className="muted">Loading folders…</p>
- ) : folders.length === 0 ? (
+ ) : folders.length === 0 && !hasMoreDestinations ? (
<p className="muted">No folders here.</p>
) : (
- folders.map(folder => (
- <div className="da-gfs-move-dialog__row" role="listitem" key={folder.resourceId}>
- <span className="da-gfs-move-dialog__row-icon" aria-hidden="true">
- <IconContexts />
- </span>
- <Button align="start" block onClick={() => enterFolder(folder)} variant="text">
- {folder.name}
- </Button>
- </div>
- ))
+ <>
+ {folders.map(folder => (
+ <div className="da-gfs-move-dialog__row" role="listitem" key={folder.resourceId}>
+ <span className="da-gfs-move-dialog__row-icon" aria-hidden="true">
+ <IconContexts />
+ </span>
+ <Button align="start" block onClick={() => enterFolder(folder)} variant="text">
+ {folder.name}
+ </Button>
+ </div>
+ ))}
+ {hasMoreDestinations ? (
+ <div className="da-gfs-move-dialog__more">
+ <Button
+ loading={loadingMoreDestinations}
+ onClick={() => void activeQuery.fetchNextPage()}
+ size="sm"
+ variant="outline"
+ >
+ Load more
+ </Button>
+ </div>
+ ) : null}
+ </>
)}
</div>
<div className="da-gfs-move-dialog__actions">
diff --git a/desktop-app/ui/src/gfs/moveDialog.types.ts b/desktop-app/ui/src/gfs/moveDialog.types.ts
index 90c8e8979..cfe218f3d 100644
--- a/desktop-app/ui/src/gfs/moveDialog.types.ts
+++ b/desktop-app/ui/src/gfs/moveDialog.types.ts
@@ -12,4 +12,8 @@ export type GfsMoveDialogProps = {
onMove: (destinationId: string, destinationName: string) => Promise<void>
onClose: () => void
busy?: boolean
+ /** Central fail-closed boundary (R4 spec §1): destination-listing authority
+ * failures must revoke the session even though the dialog owns these
+ * query observers. Policy verdicts return false and stay local. */
+ onAuthorityFailure?: (message: string) => boolean
}
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
index c47ec80ce..f6c7c8df0 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
@@ -75,7 +75,9 @@ function Probe() {
<div data-testid="current-version">{ctrl.current?.version ?? 'none'}</div>
<div data-testid="crumbs">{ctrl.crumbs.map(crumb => crumb.name).join(' / ')}</div>
<div data-testid="access-state">{ctrl.accessState}</div>
+ <div data-testid="authority-pending">{ctrl.authorityPending ? 'pending' : 'ready'}</div>
<div data-testid="accessible-count">{ctrl.accessibleResources.length}</div>
+ <div data-testid="items-count">{ctrl.items.length}</div>
<div data-testid="accessible-error">{ctrl.accessibleError ?? 'none'}</div>
<div data-testid="accessible-notice">{ctrl.accessibleNotice ?? 'none'}</div>
<div data-testid="held-permissions">{ctrl.affordances?.held.join(',') ?? 'none'}</div>
@@ -99,7 +101,9 @@ function Probe() {
type="button"
onClick={() =>
ctrl.current
- ? void ctrl.createFile(ctrl.current.resourceId, 'notes.md', 'IyBOb3Rlcw==')
+ ? void ctrl
+ .createFile(ctrl.current.resourceId, 'notes.md', 'IyBOb3Rlcw==')
+ .catch(() => {})
: undefined
}
>
@@ -109,11 +113,9 @@ function Probe() {
type="button"
onClick={() =>
ctrl.current
- ? void ctrl.renameResource(
- ctrl.current.resourceId,
- 'Renamed report.md',
- ctrl.current.version
- )
+ ? void ctrl
+ .renameResource(ctrl.current.resourceId, 'Renamed report.md', ctrl.current.version)
+ .catch(() => {})
: undefined
}
>
@@ -123,7 +125,9 @@ function Probe() {
type="button"
onClick={() =>
ctrl.current
- ? void ctrl.replaceFile(ctrl.current.resourceId, 'aGVsbG8=', ctrl.current.version)
+ ? void ctrl
+ .replaceFile(ctrl.current.resourceId, 'aGVsbG8=', ctrl.current.version)
+ .catch(() => {})
: undefined
}
>
@@ -133,7 +137,9 @@ function Probe() {
type="button"
onClick={() =>
ctrl.current
- ? void ctrl.moveResource(ctrl.current.resourceId, 'destination-1', ctrl.current.version)
+ ? void ctrl
+ .moveResource(ctrl.current.resourceId, 'destination-1', ctrl.current.version)
+ .catch(() => {})
: undefined
}
>
@@ -850,6 +856,185 @@ describe('useGfsBrowserController', () => {
render(<Probe />, { wrapper })
await waitFor(() => expect(listAccessible).toHaveBeenCalledTimes(2))
})
+
+ // R4 spec §1 — the authority revocation scenario: caches are fully
+ // populated (roots, children, grants, shares), then the session's authority
+ // is revoked server-side. The remounted browser must not render ANY of it —
+ // not before the (deferred) discovery response lands, and not after it
+ // fails with 401 — and the failure must purge every session-scoped cache.
+ it('withholds cached gfs state while authority revalidates and purges it when discovery fails 401', async () => {
+ const scope = ':user-a:team-a'
+ const client = new QueryClient({ defaultOptions: desktopQueryDefaults })
+ const accessiblePage = {
+ pages: [
+ {
+ items: [
+ {
+ resourceId: 'folder-x',
+ rid: 'folderx',
+ gfsUri: 'gfs://main/folderx',
+ drive: 'main',
+ parentResourceId: null,
+ name: 'Folder X',
+ kind: 'directory',
+ path: '/folder-x',
+ version: 1,
+ bytes: 0,
+ sources: ['grant'],
+ permissions: ['read'],
+ coversDescendants: true,
+ },
+ ],
+ nextCursor: null,
+ },
+ ],
+ pageParams: [undefined],
+ }
+ client.setQueryData(desktopQueryKeys.gfsAccessible(scope, 'main'), accessiblePage)
+ client.setQueryData(desktopQueryKeys.gfsChildren(scope, 'folder-x', 'main'), accessiblePage)
+ client.setQueryData(desktopQueryKeys.gfsGrants(scope, 'folder-x', 'main'), [
+ {
+ id: 'grant-1',
+ drive: 'main',
+ resourceId: 'folder-x',
+ subject: { type: 'user', id: 'u' },
+ permissions: ['read'],
+ inherit: false,
+ },
+ ])
+ client.setQueryData(desktopQueryKeys.gfsShares(scope, 'folder-x', 'main'), [
+ {
+ id: 'share-1',
+ drive: 'main',
+ resourceId: 'folder-x',
+ subject: { type: 'user', id: 'u' },
+ permissions: ['read'],
+ includeDescendants: false,
+ },
+ ])
+ expect(
+ client.getQueryData(desktopQueryKeys.gfsChildren(scope, 'folder-x', 'main'))
+ ).toBeTruthy()
+
+ // Deferred discovery: authority is being rechecked but the server has
+ // not answered yet.
+ let failDiscovery: ((error: Error) => void) | undefined
+ const listAccessible = vi.fn(
+ () =>
+ new Promise<never>((_, reject) => {
+ failDiscovery = reject
+ })
+ )
+ const listChildren = vi.fn(async () => ({ items: [], nextCursor: null }))
+ const affordances = vi.fn(async () => ({
+ held: ['read'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ }))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible,
+ resolve: vi.fn(async () => ({
+ resourceId: 'folder-x',
+ gfsUri: 'gfs://main/folderx',
+ name: 'Folder X',
+ kind: 'directory',
+ version: 1,
+ })),
+ listChildren,
+ affordances,
+ },
+ },
+ })
+
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <AuthContext.Provider value={authValue(userA)}>
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ </AuthContext.Provider>
+ )
+ render(<Probe />, { wrapper })
+
+ // BEFORE the failure: cached roots/children must be withheld from render.
+ await waitFor(() => expect(listAccessible).toHaveBeenCalledTimes(1))
+ expect(screen.getByTestId('authority-pending').textContent).toBe('pending')
+ expect(screen.getByTestId('accessible-count').textContent).toBe('0')
+
+ // Entering the prefetched child cannot bypass revalidation either: the
+ // children cache is populated, but its rows stay withheld.
+ await act(async () => {
+ screen.getByRole('button', { name: 'open' }).click()
+ })
+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('folder-x'))
+ expect(screen.getByTestId('authority-pending').textContent).toBe('pending')
+ expect(screen.getByTestId('items-count').textContent).toBe('0')
+
+ // AFTER the failure: the 401 fails the session closed — every cached
+ // surface is purged and navigation state is gone.
+ await act(async () => {
+ failDiscovery?.(new Error('401 Unauthorized: session rejected'))
+ })
+ await waitFor(() => expect(screen.getByTestId('access-state').textContent).toBe('revoked'))
+ expect(screen.getByTestId('current').textContent).toBe('none')
+ expect(screen.getByTestId('crumbs').textContent).toBe('')
+ expect(client.getQueryData(desktopQueryKeys.gfsAccessible(scope, 'main'))).toBeUndefined()
+ expect(
+ client.getQueryData(desktopQueryKeys.gfsChildren(scope, 'folder-x', 'main'))
+ ).toBeUndefined()
+ expect(
+ client.getQueryData(desktopQueryKeys.gfsGrants(scope, 'folder-x', 'main'))
+ ).toBeUndefined()
+ expect(
+ client.getQueryData(desktopQueryKeys.gfsShares(scope, 'folder-x', 'main'))
+ ).toBeUndefined()
+ })
+
+ it('fails a mutation-carrying session closed when an imperative operation reports 401', async () => {
+ const renameResource = vi.fn(async () => {
+ throw new Error('401 Unauthorized: session rejected')
+ })
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
+ resolve: vi.fn(async () => ({
+ resourceId: 'root',
+ gfsUri: 'gfs://main/root',
+ name: 'Root',
+ kind: 'directory',
+ })),
+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
+ affordances: vi.fn(async () => ({
+ held: ['read'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ })),
+ renameResource,
+ },
+ },
+ })
+
+ render(<Probe />, { wrapper: Harness })
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'open' }).click()
+ })
+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))
+ await waitFor(() => expect(screen.getByTestId('access-state').textContent).toBe('active'))
+
+ // The mutation's rejection propagates to the caller AND the shared
+ // mutation onError boundary fails the session closed.
+ await act(async () => {
+ screen.getByRole('button', { name: 'rename current' }).click()
+ })
+ await waitFor(() => expect(renameResource).toHaveBeenCalled())
+ await waitFor(() => expect(screen.getByTestId('access-state').textContent).toBe('revoked'))
+ expect(screen.getByTestId('crumbs').textContent).toBe('')
+ })
})
// The grants listing is gated by the `grantsListEnabled` hook option (the Manage
diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
index 0feb71de5..53339dd1f 100644
--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
@@ -147,6 +147,11 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
// server-backed request (retryAccess) is the only way back in.
const [accessState, setAccessState] = useState<'active' | 'revoked'>('active')
const previousSessionScopeRef = useRef<string | null>(null)
+ // Per controller-mount timestamp: discovery (`refetchOnMount: 'always'`) must
+ // land a response newer than this before cached GFS state may render again.
+ // Between mount and that fresh response the browser withholds cached rows
+ // (authority revalidation window — R4 spec §1).
+ const authorityEpochRef = useRef(Date.now())
const current = crumbs.length ? crumbs[crumbs.length - 1] : null
const currentIsDirectory = current?.kind === 'directory'
@@ -191,6 +196,20 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
getNextPageParam: lastPage => lastPage.nextCursor ?? undefined,
})
+ // Authority revalidation window (R4 spec §1): true from mount/session-return
+ // until discovery lands a response NEWER than this mount. While true, every
+ // cached GFS surface this controller exposes is withheld so prefetched or
+ // 30-minute-cached state cannot render before the session is re-proved. If
+ // discovery fails with an authority error, the query-error boundary revokes
+ // (which clears the same caches); a policy error stays a local banner. When
+ // the runtime has no discovery, there is nothing to revalidate against and
+ // per-resource operations still fail closed through handleAuthorityFailure.
+ const authorityPending =
+ Boolean(sessionScope) &&
+ canListAccessibleResources &&
+ accessState === 'active' &&
+ accessibleQuery.dataUpdatedAt < authorityEpochRef.current
+
const childrenQuery = useInfiniteQuery({
queryKey: desktopQueryKeys.gfsChildren(
sessionScope ?? 'anonymous',
@@ -273,10 +292,6 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
queryKey: desktopQueryKeys.gfsShares(sessionScope ?? 'anonymous', resourceId, DRIVE),
})
}, [current?.resourceId, queryClient, sessionScope])
- const revokeShareMutation = useMutation({
- mutationFn: (shareId: string) => window.clerum.gfs.revokeShare(shareId),
- onSuccess: refreshShares,
- })
const refreshGrants = useCallback(async () => {
const resourceId = current?.resourceId
if (!resourceId) return
@@ -285,10 +300,6 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
queryKey: desktopQueryKeys.gfsGrants(sessionScope ?? 'anonymous', resourceId, DRIVE),
})
}, [current?.resourceId, queryClient, sessionScope])
- const revokeGrantMutation = useMutation({
- mutationFn: (grantId: string) => window.clerum.gfs.revokeGrant(grantId),
- onSuccess: refreshGrants,
- })
const refreshGfs = useCallback(async () => {
await queryClient.invalidateQueries({
queryKey: desktopQueryKeys.gfsRoot,
@@ -342,6 +353,9 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
affordancesQuery.error
? { message: toMessage(affordancesQuery.error), surface: 'operation' as const }
: null,
+ rowAffordancesQuery.error
+ ? { message: toMessage(rowAffordancesQuery.error), surface: 'operation' as const }
+ : null,
grantsQuery.error
? { message: toMessage(grantsQuery.error), surface: 'operation' as const }
: null,
@@ -357,17 +371,38 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
if (!queryAuthorizationError || accessState === 'revoked') return
revokeAccess()
}, [accessState, queryAuthorizationError, revokeAccess])
+ // All GFS mutations share the central fail-closed boundary: an authority
+ // rejection (401 / typed lifecycle code) revokes the session even when the
+ // caller would only have toasted. Policy verdicts (403/412) stay local.
+ const failClosedOnMutationError = useCallback(
+ (error: unknown) => {
+ handleAuthorityFailure(toMessage(error), 'operation')
+ },
+ [handleAuthorityFailure]
+ )
+ const revokeGrantMutation = useMutation({
+ mutationFn: (grantId: string) => window.clerum.gfs.revokeGrant(grantId),
+ onSuccess: refreshGrants,
+ onError: failClosedOnMutationError,
+ })
+ const revokeShareMutation = useMutation({
+ mutationFn: (shareId: string) => window.clerum.gfs.revokeShare(shareId),
+ onSuccess: refreshShares,
+ onError: failClosedOnMutationError,
+ })
const createFolderMutation = useMutation({
mutationFn: async (name: string) => {
if (!current) throw new Error('No folder selected')
return window.clerum.gfs.createFolder(current.resourceId, name, DRIVE)
},
onSuccess: refreshGfs,
+ onError: failClosedOnMutationError,
})
const createFileMutation = useMutation({
mutationFn: (input: { parentResourceId: string; name: string; encodedData: string }) =>
window.clerum.gfs.createFile(input.parentResourceId, input.name, input.encodedData, DRIVE),
onSuccess: refreshGfs,
+ onError: failClosedOnMutationError,
})
const createFileFromPathMutation = useMutation({
mutationFn: (input: { parentResourceId: string; name: string; filePath: string }) =>
@@ -378,6 +413,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
DRIVE
),
onSuccess: refreshGfs,
+ onError: failClosedOnMutationError,
})
const replaceFileMutation = useMutation({
mutationFn: (input: { resourceId: string; encodedData: string; ifMatch?: number }) =>
@@ -392,6 +428,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
)
await refreshGfs()
},
+ onError: failClosedOnMutationError,
})
const replaceFileFromPathMutation = useMutation({
mutationFn: (input: { resourceId: string; filePath: string; ifMatch?: number }) =>
@@ -422,6 +459,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
)
await refreshGfs()
},
+ onError: failClosedOnMutationError,
})
const deleteResourceMutation = useMutation({
mutationFn: (input: { resourceId: string; ifMatch?: number }) =>
@@ -430,21 +468,34 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
setCrumbs(prev => prev.filter(crumb => crumb.resourceId !== input.resourceId))
await refreshGfs()
},
+ onError: failClosedOnMutationError,
})
+ // Cached GFS state is a rendering optimization only (R4 spec §1): while the
+ // authority revalidation window is open, nothing cached may be exposed —
+ // rows, affordances, grants, and shares all stay withheld until discovery
+ // re-proves the session (or an authority failure clears everything).
const items = useMemo<GfsBrowserChild[]>(
- () => (childrenQuery.data?.pages ?? []).flatMap(page => page.items),
- [childrenQuery.data]
+ () => (authorityPending ? [] : (childrenQuery.data?.pages ?? []).flatMap(page => page.items)),
+ [authorityPending, childrenQuery.data]
)
const accessibleResources = useMemo<GfsAccessibleResource[]>(
() =>
- (accessibleQuery.data?.pages ?? []).flatMap(page =>
- page.items.map(normalizeAccessibleResource)
- ),
- [accessibleQuery.data]
+ authorityPending
+ ? []
+ : (accessibleQuery.data?.pages ?? []).flatMap(page =>
+ page.items.map(normalizeAccessibleResource)
+ ),
+ [accessibleQuery.data, authorityPending]
+ )
+ const grants = useMemo<GfsGrantListItem[]>(
+ () => (authorityPending ? [] : (grantsQuery.data ?? [])),
+ [authorityPending, grantsQuery.data]
+ )
+ const shares = useMemo<GfsShareListItem[]>(
+ () => (authorityPending ? [] : (sharesQuery.data ?? [])),
+ [authorityPending, sharesQuery.data]
)
- const grants = useMemo<GfsGrantListItem[]>(() => grantsQuery.data ?? [], [grantsQuery.data])
- const shares = useMemo<GfsShareListItem[]>(() => sharesQuery.data ?? [], [sharesQuery.data])
const accessibleErrorMessage = accessibleQuery.error ? toMessage(accessibleQuery.error) : null
const accessibleNotice =
sessionScope && !canListAccessibleResources
@@ -535,6 +586,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
await refreshGfs()
if (movedCrumb) await openUri(movedCrumb.gfsUri)
},
+ onError: failClosedOnMutationError,
})
const openChild = useCallback((child: GfsBrowserChild) => {
@@ -605,20 +657,32 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
/** 'revoked' after a session-authority failure — queries are gated off
* and cached GFS state is gone until retryAccess re-enters the server. */
accessState,
+ /** True while discovery re-proves the session after mount/session return;
+ * cached GFS state is withheld (R4 spec §1). FilesPage renders loading. */
+ authorityPending,
retryAccess,
handleAuthorityFailure,
accessibleResources,
items,
- affordances: (affordancesQuery.data as GfsBrowserAffordances | undefined) ?? null,
+ affordances:
+ authorityPending || accessState === 'revoked'
+ ? null
+ : ((affordancesQuery.data as GfsBrowserAffordances | undefined) ?? null),
affordancesError: affordancesQuery.error ? toMessage(affordancesQuery.error) : null,
loadingAffordances: affordancesQuery.isFetching,
rowAffordancesResourceId,
setRowAffordancesResourceId,
- rowAffordances: (rowAffordancesQuery.data as GfsBrowserAffordances | undefined) ?? null,
+ rowAffordances:
+ authorityPending || accessState === 'revoked'
+ ? null
+ : ((rowAffordancesQuery.data as GfsBrowserAffordances | undefined) ?? null),
rowAffordancesError: rowAffordancesQuery.error ? toMessage(rowAffordancesQuery.error) : null,
- loading: childrenQuery.isFetching && items.length === 0,
+ loading: (authorityPending || childrenQuery.isFetching) && items.length === 0,
loadingAccessible:
- canListAccessibleResources && accessibleQuery.isFetching && accessibleResources.length === 0,
+ (authorityPending && canListAccessibleResources) ||
+ (canListAccessibleResources &&
+ accessibleQuery.isFetching &&
+ accessibleResources.length === 0),
error: childrenQuery.error ? toMessage(childrenQuery.error) : null,
accessibleError: accessibleNotice ? null : accessibleErrorMessage,
accessibleNotice,
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index 97a44e0ae..160e82c46 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -236,6 +236,32 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
[ctrl.sharesError]
)
const accessRevoked = ctrl.accessState === 'revoked'
+ // R4 spec §1: on an authority failure every local surface that could show
+ // or act on stale GFS data must close — preview bytes, Manage, Move, rename,
+ // delete, open-link, and the inline create-folder form.
+ useEffect(() => {
+ if (!accessRevoked) return
+ setFilePreview(null)
+ setManageOpen(false)
+ setMoveTarget(null)
+ setRenameTarget(null)
+ setDeleteTarget(null)
+ setOpenLinkOpen(false)
+ setCreateFolderOpen(false)
+ setRenameOpen(false)
+ setDeleteOpen(false)
+ }, [accessRevoked])
+ /** Central imperative boundary: route any non-query GFS failure through the
+ * controller's authority classifier before toasting. Returns true when the
+ * session failed closed (caller should stop; the revoked state takes over). */
+ const failClosedOnAuthorizationError = useCallback(
+ (error: unknown): boolean =>
+ ctrl.handleAuthorityFailure(
+ error instanceof Error ? error.message : String(error),
+ 'operation'
+ ),
+ [ctrl]
+ )
const canWriteCurrent = !accessRevoked && hasBit(affordances, 'write')
const canDeleteCurrent = !accessRevoked && hasBit(affordances, 'delete')
const currentIsFolder = current?.kind === 'directory'
@@ -265,6 +291,15 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
void refreshAffordances()
}, [current?.resourceId, manageOpen, refreshAffordances])
+ // Preview byte-fetches are imperative downloads: an authority failure must
+ // reach the central fail-closed boundary, not just the in-dialog error.
+ const handlePreviewDownloadError = useCallback(
+ (error: unknown) => {
+ failClosedOnAuthorizationError(error)
+ },
+ [failClosedOnAuthorizationError]
+ )
+
const openFilePreview = (
resource: Pick<GfsDriveResource, 'bytes' | 'gfsUri' | 'name'>
): boolean => {
@@ -321,7 +356,12 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
// agents are capped to read/write inside the panel. Inherit is honored for
// directories (default ON) and forced false for files.
const handleGrant = async (subjectKeys: string[], bits: string[], inherit: boolean) => {
- await ctrl.grant(subjectKeys, bits, inherit)
+ try {
+ await ctrl.grant(subjectKeys, bits, inherit)
+ } catch (grantError) {
+ if (failClosedOnAuthorizationError(grantError)) return
+ throw grantError
+ }
pushToast?.(
`Access granted to ${subjectKeys.length} ${subjectKeys.length === 1 ? 'subject' : 'subjects'}`,
'success'
@@ -335,6 +375,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
await ctrl.revokeGrant(grantId)
pushToast?.(`Access revoked for ${label}`, 'success')
} catch (revokeError) {
+ if (failClosedOnAuthorizationError(revokeError)) return
pushToast?.(describeGfsGrantError(revokeError).message, 'error')
}
}
@@ -345,13 +386,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
} catch (error) {
// A session-authority rejection fails the browser closed; anything
// else re-throws to the delegation panel's own error surface.
- if (
- !ctrl.handleAuthorityFailure(
- error instanceof Error ? error.message : String(error),
- 'operation'
- )
- )
- throw error
+ if (!failClosedOnAuthorizationError(error)) throw error
return
}
pushToast?.(
@@ -367,10 +402,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
await ctrl.revokeShare(shareId)
pushToast?.(`Shared access revoked for ${label}`, 'success')
} catch (revokeError) {
- ctrl.handleAuthorityFailure(
- revokeError instanceof Error ? revokeError.message : String(revokeError),
- 'operation'
- )
+ if (failClosedOnAuthorizationError(revokeError)) return
pushToast?.(describeGfsGrantError(revokeError).message, 'error')
}
}
@@ -386,6 +418,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
setTimeout(() => URL.revokeObjectURL(url), 10_000)
pushToast?.(`Downloaded ${name}`, 'success')
} catch (downloadError) {
+ if (failClosedOnAuthorizationError(downloadError)) return
pushToast?.(
downloadError instanceof Error ? downloadError.message : String(downloadError),
'error'
@@ -434,6 +467,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
setCreateFolderOpen(false)
pushToast?.(`Folder ${name} created`, 'success')
} catch (createError) {
+ if (failClosedOnAuthorizationError(createError)) return
pushToast?.(createError instanceof Error ? createError.message : String(createError), 'error')
}
}
@@ -451,6 +485,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
await ctrl.createFileFromPath(parentResourceId, name, filePath)
pushToast?.(`Uploaded ${name}`, 'success')
} catch (uploadError) {
+ if (failClosedOnAuthorizationError(uploadError)) return
pushToast?.(uploadError instanceof Error ? uploadError.message : String(uploadError), 'error')
}
}
@@ -513,6 +548,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
await ctrl.replaceFileFromPath(current.resourceId, filePath, current.version)
pushToast?.(`Replaced ${current.name}`, 'success')
} catch (replaceError) {
+ if (failClosedOnAuthorizationError(replaceError)) return
pushToast?.(
replaceError instanceof Error ? replaceError.message : String(replaceError),
'error'
@@ -531,6 +567,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
setRenameOpen(false)
pushToast?.(`Renamed to ${name}`, 'success')
} catch (renameError) {
+ if (failClosedOnAuthorizationError(renameError)) return
pushToast?.(renameError instanceof Error ? renameError.message : String(renameError), 'error')
}
}
@@ -543,6 +580,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
setManageOpen(false)
pushToast?.(`Deleted ${current.name}`, 'success')
} catch (deleteError) {
+ if (failClosedOnAuthorizationError(deleteError)) return
pushToast?.(deleteError instanceof Error ? deleteError.message : String(deleteError), 'error')
}
}
@@ -552,7 +590,12 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
await ctrl.deleteResource(resource.resourceId, resource.version)
pushToast?.(`Deleted ${resource.name}`, 'success')
} catch (deleteError) {
- pushToast?.(deleteError instanceof Error ? deleteError.message : String(deleteError), 'error')
+ if (!failClosedOnAuthorizationError(deleteError)) {
+ pushToast?.(
+ deleteError instanceof Error ? deleteError.message : String(deleteError),
+ 'error'
+ )
+ }
} finally {
setDeleteTarget(null)
}
@@ -586,11 +629,21 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
}
/** Move commits bubble their failure back to the dialog (in-place banner);
- * success toasts and closes it. ifMatch pins the resource version. */
+ * success toasts and closes it. An authority rejection instead fails the
+ * session closed and closes the dialog — the revoked state takes over.
+ * ifMatch pins the resource version. */
const handleMoveTarget = async (destinationId: string, destinationName: string) => {
if (!moveTarget) return
const target = moveTarget
- await ctrl.moveResource(target.resourceId, destinationId, target.version)
+ try {
+ await ctrl.moveResource(target.resourceId, destinationId, target.version)
+ } catch (moveError) {
+ if (failClosedOnAuthorizationError(moveError)) {
+ setMoveTarget(null)
+ return
+ }
+ throw moveError
+ }
setMoveTarget(null)
pushToast?.(`Moved ${target.name} to ${destinationName}`, 'success')
}
@@ -617,6 +670,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
setRenameTarget(null)
pushToast?.(`Renamed to ${name}`, 'success')
} catch (renameError) {
+ if (failClosedOnAuthorizationError(renameError)) return
pushToast?.(renameError instanceof Error ? renameError.message : String(renameError), 'error')
}
}
@@ -635,7 +689,11 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
return (left.name || left.drive).localeCompare(right.name || right.drive)
})
}, [accessibleResources, currentIsFile, currentIsFolder, items])
- const visibleLoading = currentIsFolder ? loading : !current ? loadingAccessible : false
+ // authorityPending keeps the loading state up: cached rows must not render
+ // (and must not be mistaken for an empty folder) until discovery re-proves
+ // the session (R4 spec §1).
+ const visibleLoading =
+ ctrl.authorityPending || (currentIsFolder ? loading : !current ? loadingAccessible : false)
const visibleError = currentIsFolder ? error : !current ? accessibleError : null
const hasMoreVisible = currentIsFolder ? ctrl.hasMore : !current && ctrl.hasMoreAccessible
const loadingMoreVisible = currentIsFolder ? ctrl.isFetchingMore : ctrl.isFetchingMoreAccessible
@@ -1241,6 +1299,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
gfsUri={filePreview.gfsUri}
mimeType={filePreview.mimeType}
onClose={() => setFilePreview(null)}
+ onDownloadError={handlePreviewDownloadError}
/>
) : null}
@@ -1250,6 +1309,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
fileName={filePreview.name}
gfsUri={filePreview.gfsUri}
onClose={() => setFilePreview(null)}
+ onDownloadError={handlePreviewDownloadError}
/>
) : null}
@@ -1260,6 +1320,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
gfsUri={filePreview.gfsUri}
mimeType={filePreview.mimeType}
onClose={() => setFilePreview(null)}
+ onDownloadError={handlePreviewDownloadError}
/>
) : null}
@@ -1286,6 +1347,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
}
onClose={() => setMoveTarget(null)}
onMove={handleMoveTarget}
+ onAuthorityFailure={message => ctrl.handleAuthorityFailure(message, 'operation')}
sessionScope={sessionScope}
target={moveTarget}
/>
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index 78527da48..4453c782c 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -1318,6 +1318,127 @@ describe('FilesPage', () => {
expect(retryAccess).toHaveBeenCalledTimes(1)
})
+ // R4 spec §1 — on revocation, every local surface that could show or act on
+ // stale GFS data must close. Here: an open image preview (already-fetched
+ // bytes) and an open Move dialog.
+ it('closes an open preview when authority is revoked mid-session', async () => {
+ const download = vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer }))
+ const createObjectURL = vi.fn(() => 'blob:gfs-image-preview')
+ 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: { download } },
+ })
+ const controllerState = {
+ ...baseController(),
+ accessibleResources: [
+ {
+ resourceId: 'image-1',
+ rid: 'image-1',
+ gfsUri: 'gfs://main/image-1',
+ drive: 'main',
+ parentResourceId: null,
+ name: 'secret.PNG',
+ kind: 'file',
+ path: '/secret.PNG',
+ version: 1,
+ bytes: 3,
+ sources: ['grant'],
+ permissions: ['read'],
+ coversDescendants: false,
+ },
+ ],
+ }
+ hookMock.useGfsBrowserController.mockReturnValue(controllerState)
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ // A fresh element per render pass: rerendering the identical element
+ // reference would bail out and never observe the mutated mock.
+ const makeElement = () => (
+ <QueryClientProvider client={queryClient}>
+ <FilesPage />
+ </QueryClientProvider>
+ )
+ const { rerender } = render(makeElement())
+
+ fireEvent.click(screen.getByRole('button', { name: 'secret.PNG' }))
+ expect(await screen.findByRole('dialog', { name: 'secret.PNG' })).toBeTruthy()
+
+ controllerState.accessState = 'revoked'
+ rerender(makeElement())
+
+ await waitFor(() => expect(screen.queryByRole('dialog', { name: 'secret.PNG' })).toBeNull())
+ expect(await screen.findByText('File access is not authorized')).toBeTruthy()
+ })
+
+ it('closes the move dialog and manage dialog when authority is revoked mid-session', async () => {
+ const moveResource = vi.fn(async () => ({}))
+ const controllerState = {
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ name: 'Product',
+ kind: 'directory',
+ version: 1,
+ bytes: 0,
+ },
+ crumbs: [
+ {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ name: 'Product',
+ kind: 'directory',
+ version: 1,
+ bytes: 0,
+ },
+ ],
+ affordances: {
+ held: ['read', 'write', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: true,
+ },
+ moveResource,
+ }
+ hookMock.useGfsBrowserController.mockReturnValue(controllerState)
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ // A fresh element per render pass: rerendering the identical element
+ // reference would bail out and never observe the mutated mock.
+ const makeElement = () => (
+ <QueryClientProvider client={queryClient}>
+ <FilesPage />
+ </QueryClientProvider>
+ )
+ const { rerender } = render(makeElement())
+
+ // Open the manage dialog, then the move dialog from its menu.
+ await openManageDialog('Product')
+ await act(async () => {
+ fireEvent.click(
+ within(screen.getByRole('dialog', { name: 'Manage folder Product' })).getByRole('button', {
+ name: 'Options for Product',
+ })
+ )
+ })
+ await act(async () => {
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Move to…' }))
+ })
+ expect(await screen.findByRole('dialog', { name: 'Move folder Product' })).toBeTruthy()
+
+ controllerState.accessState = 'revoked'
+ rerender(makeElement())
+
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog', { name: 'Move folder Product' })).toBeNull()
+ )
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog', { name: 'Manage folder Product' })).toBeNull()
+ )
+ expect(await screen.findByText('File access is not authorized')).toBeTruthy()
+ expect(moveResource).not.toHaveBeenCalled()
+ })
+
it('refreshes server affordances whenever the manage dialog opens', async () => {
const refreshAffordances = vi.fn(async () => undefined)
hookMock.useGfsBrowserController.mockReturnValue({
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index b853098cd..bd9f0975d 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -14774,6 +14774,12 @@ pre {
gap: var(--space-2);
}
+.da-gfs-move-dialog__more {
+ display: flex;
+ justify-content: center;
+ padding-top: var(--space-1);
+}
+
.da-gfs-move-dialog__row-icon {
display: grid;
place-items: center;
diff --git a/work-tracker/specs/gfs-authority-grants-shares-move-r4.md b/work-tracker/specs/gfs-authority-grants-shares-move-r4.md
new file mode 100644
index 000000000..0ddc792fb
--- /dev/null
+++ b/work-tracker/specs/gfs-authority-grants-shares-move-r4.md
@@ -0,0 +1,117 @@
+# GFS Desktop — authority lifecycle, grants/shares independence, Move pagination (R4 spec)
+
+Status: implemented (R4 fix round)
+Scope: `desktop-app/ui` — `useGfsBrowserController`, `FilesPage`, `GfsGrantList`, `GfsMoveDialog`
+Supercedes: the ad-hoc corrective patches from the R3 fix round (`93f211d08`). This document
+is the durable contract for the three behavior areas below; future changes to these files
+must keep this spec true or update it in the same commit.
+
+## 1. GFS authority / cache / error lifecycle
+
+### Roles
+
+- **Server is the only authority.** Permissions (affordances), listings, grants, shares,
+ and versions (`ifMatch`) are always server responses. No client cache may be treated as
+ an authorization fact.
+- **Discovery (`listAccessible`) is the session/authority boundary.** It is
+ permission-derived session state, so on every controller mount it is revalidated
+ (`refetchOnMount: 'always'`) even though the production client otherwise never
+ refetches (`staleTime: Infinity`, `refetchOnMount: false`).
+- **`accessState`** (`'active' | 'revoked'`) is session-local UI state owned by the
+ controller. `'revoked'` gates every GFS query observer (`enabled`) and is the only
+ fail-closed verdict; `retryAccess()` merely re-enables the queries — a fresh server
+ success is the only way data returns.
+
+### What the UI may render while authority is being revalidated
+
+- `authorityPending` is true from controller mount (or session-scope return) until the
+ first fresh discovery response lands (success or failure), whenever discovery is
+ available in the runtime.
+- While `authorityPending`, the controller withholds all cached GFS state it exposes:
+ `accessibleResources`, `items`, `affordances`, `rowAffordances`, `grants`, and `shares`
+ are reported as empty/`null`. FilesPage renders the loading state, never cached rows.
+ Prefetched children therefore cannot bypass revalidation: their cache may exist, but it
+ is not rendered until discovery re-proves the session.
+- Local navigation chrome (breadcrumb trail titles typed by the user's own navigation)
+ is not server-derived data and may remain; it is cleared on failure (below).
+
+### Which queries/caches are cleared on authority failure
+
+- Every session-scoped GFS query is removed via `queryClient.removeQueries({ queryKey:
+desktopQueryKeys.gfsRoot })` — accessible roots, folder children (including prefetch),
+ affordances (dialog + row), grants, and shares. The Move dialog deliberately shares
+ these exact keys, so its destination listings are purged too.
+- Removal (not invalidation) is required: under production defaults an invalidated-but-
+ cached query would keep rendering its stale data.
+
+### Which local UI state is cleared on authority failure
+
+- Controller: `crumbs`, `openError` (`clearGfsState`), and `accessState → 'revoked'`.
+- FilesPage (via effect on `accessState === 'revoked'`): file preview state (dialog +
+ already-fetched bytes), Manage dialog, Move dialog target, rename dialog target +
+ inline rename form, delete confirm, open-link dialog, and the inline create-folder form.
+ Anything that could display or act on stale GFS data must close.
+
+### How 401 / typed authority failures reach one boundary
+
+- One classifier: `isGfsSessionAuthorityFailure(message, surface)`.
+ - `surface: 'discovery'` — 401 **or** 403/unauthorized/forbidden fail closed (the
+ discovery listing itself is permission-derived).
+ - `surface: 'operation'` — only a bare 401 / "not authenticated" / "unauthenticated"
+ or a typed lifecycle code (`desktop_user_retired`, `operator_link_inactive`,
+ `operator_link_invalid`, `gfs_operator_link_invalid`) fails closed. A generic 403 on
+ one resource is a policy verdict (e.g. `manage_acl_required`, `escalation_rejected`)
+ and stays local to that operation.
+- **Query path**: errors from accessible, children, affordances, row-affordances,
+ grants, and shares queries are collected and routed into the same boundary effect.
+- **Imperative path**: `handleAuthorityFailure` is wired into `openUri`, every
+ controller mutation (`onError`), and every FilesPage imperative catch (grant, revoke
+ grant/share, create share, create folder, upload, replace, rename, delete, move,
+ download) plus preview byte-fetch failures (`onDownloadError`). A Move commit failure
+ first passes the boundary: an authority failure closes the dialog and fails the
+ session; anything else remains the dialog's in-place banner (403/412 policy verdicts).
+
+### Cached data under production `staleTime: Infinity`
+
+- Cache is a rendering optimization only. It may be served while `active` and not
+ `authorityPending`, must be withheld during authority revalidation, and is deleted on
+ any authority failure. Content mutations refresh listings through explicit
+ invalidation; permission affordances are refreshed when Manage opens or a row menu
+ resolves.
+
+## 2. Grants / shares partial-failure independence
+
+- `listGrants` and `listShares` are independent surfaces with independent failure modes.
+- `GfsGrantList` renders grant rows and share rows as independent sections:
+ - A grants-list error shows the grants banner (quiet for `manage_acl_required`) and
+ suppresses grant rows only; share rows and their revoke actions still render.
+ - A shares-list error shows the shares banner and suppresses share rows only; grant
+ rows and their revoke actions still render.
+ - The combined "Loading access…"/empty notices appear only when neither list errored.
+- Neither source's failure may hide, disable, or suppress the other's rows or actions.
+
+## 3. Paginated Move destination navigation
+
+- The Move dialog browses the same session-scoped caches as the Files page
+ (`gfsAccessible` at the root, `gfsChildren` inside folders).
+- Both listings are cursor-paginated. Whenever the active listing reports a next page,
+ a "Load more" control is visible; fetching the next page preserves the rows already
+ rendered, shows pending state on the control, and surfaces fetch errors through the
+ dialog's existing error banner.
+- Destinations loaded from any page are selectable identically to page-one rows.
+- Cycle prevention is unchanged: the moved resource itself never appears as a
+ destination, and "Move here" stays disabled while the dialog path passes through the
+ target's own subtree; a server 403/412 remains an in-dialog banner.
+
+## Regression coverage map
+
+| Decision | Tests |
+| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
+| Withhold cache during authority revalidation; purge + revoke on 401 (production query defaults) | `useGfsBrowserController.test.tsx` — "withholds cached GFS state … until discovery revalidates" / "fails closed … drops cached gfs state" |
+| Query + imperative + preview paths reach one boundary | `useGfsBrowserController.test.tsx` (mutation 401), `FilesPage.test.tsx` ("fails closed and closes previews/dialogs when authority is revoked") |
+| FilesPage local UI cleared on revocation | `FilesPage.test.tsx` — previews/manage/move/rename/delete state |
+| Grants/shares independence | `GfsGrantList.test.tsx` — "a share-list failure does not hide grants" |
+| Move pagination + page-two selection | `moveDialog.test.tsx` — root and child two-page listings |
+
+Previous-buggy-head evidence: all new tests above fail on `93f211d08` (recorded in the R4
+fix commit message).