Skip to content

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

TypeScript

fix(gfs): address review findings R3-H2/H3/M1/M2

Miguelon Peluchon93f211d08504
diff --git a/control-ui/components/GfsBrowser.tsx b/control-ui/components/GfsBrowser.tsx
index 841d809e8..00bd56904 100644
--- a/control-ui/components/GfsBrowser.tsx
+++ b/control-ui/components/GfsBrowser.tsx
@@ -273,46 +273,73 @@ export function GfsBrowser(): React.JSX.Element {
const current = crumbs[crumbs.length - 1]
const currentLabel = current?.name === '/' ? DRIVE : current?.name || DRIVE
- const load = useCallback(async (crumb: Crumb, cursor?: string): Promise<void> => {
- const appending = Boolean(cursor)
- if (appending) {
- setLoadingMore(true)
- } else {
- setLoading(true)
- setItems([])
- setNextCursor(null)
- }
- setError('')
- try {
- const path =
- crumb.id === null
- ? '/api/v1/gfs/tree'
- : `/api/v1/gfs/resources/${encodeURIComponent(crumb.id)}/children`
- const query: Record<string, string> = { drive: DRIVE }
- if (cursor) query.cursor = cursor
- const page = (await apiGet(path, query)) as TreePage
- if (crumb.id === null && page.rootResourceId) {
- setCrumbs(prev =>
- prev[0]?.id === null
- ? [
- { ...prev[0], id: page.rootResourceId, rid: ridOfResourceId(page.rootResourceId) },
- ...prev.slice(1),
- ]
- : prev
- )
+ const load = useCallback(
+ async (crumb: Crumb, cursor?: string, options?: { background?: boolean }): Promise<void> => {
+ const appending = Boolean(cursor)
+ const background = Boolean(options?.background)
+ // Only the newest load may apply results; a superseded navigation's
+ // response (including a background revalidation) must be dropped.
+ const seq = ++loadSeqRef.current
+ if (appending) {
+ setLoadingMore(true)
+ } else if (!background) {
+ setLoading(true)
+ setItems([])
+ setNextCursor(null)
}
- const sortedItems = sortChildrenWithDirectoriesFirst(page.items)
- setItems(prev => (cursor ? [...prev, ...sortedItems] : sortedItems))
- setNextCursor(page.nextCursor)
- } catch (err) {
- if (!isSilentApiError(err)) {
- setError(err instanceof Error ? err.message : 'Failed to load the Global File System')
+ if (!background) setError('')
+ try {
+ const path =
+ crumb.id === null
+ ? '/api/v1/gfs/tree'
+ : `/api/v1/gfs/resources/${encodeURIComponent(crumb.id)}/children`
+ const query: Record<string, string> = { drive: DRIVE }
+ if (cursor) query.cursor = cursor
+ const page = (await apiGet(path, query)) as TreePage
+ if (seq !== loadSeqRef.current) return
+ if (crumb.id === null && page.rootResourceId) {
+ setCrumbs(prev =>
+ prev[0]?.id === null
+ ? [
+ {
+ ...prev[0],
+ id: page.rootResourceId,
+ rid: ridOfResourceId(page.rootResourceId),
+ },
+ ...prev.slice(1),
+ ]
+ : prev
+ )
+ }
+ const sortedItems = sortChildrenWithDirectoriesFirst(page.items)
+ setItems(prev => (cursor ? [...prev, ...sortedItems] : sortedItems))
+ setNextCursor(page.nextCursor)
+ // Keep the folder cache coherent with what the server just returned:
+ // navigation, refresh-after-mutation, and pagination all land here, so
+ // a later openDirectory() can never serve rows older than this load.
+ if (crumb.id !== null) {
+ const existing = childCacheRef.current.get(crumb.id)
+ childCacheRef.current.set(crumb.id, {
+ items: cursor ? [...(existing?.items ?? []), ...page.items] : page.items,
+ nextCursor: page.nextCursor,
+ })
+ }
+ } catch (err) {
+ if (seq !== loadSeqRef.current) return
+ if (!isSilentApiError(err)) {
+ // Background revalidation keeps the (stale) rows visible but still
+ // surfaces the failure instead of silently ignoring it.
+ setError(err instanceof Error ? err.message : 'Failed to load the Global File System')
+ }
+ } finally {
+ if (seq === loadSeqRef.current) {
+ if (appending) setLoadingMore(false)
+ else if (!background) setLoading(false)
+ }
}
- } finally {
- if (appending) setLoadingMore(false)
- else setLoading(false)
- }
- }, [])
+ },
+ []
+ )
function sortChildrenWithDirectoriesFirst(children: GfsChild[]): GfsChild[] {
return [...children].sort((a, b) => {
@@ -321,15 +348,50 @@ export function GfsBrowser(): React.JSX.Element {
})
}
+ // ┌─────────────────────────────────────────────────────────────────────────┐
+ // │ GfsBrowser data-path decision table (keep behavior and tests aligned). │
+ // ├─────────────────────────────────────────────────────────────────────────┤
+ // │ UPLOAD TRANSPORT (create & replace) │
+ // │ • Default: resumable Upload v2 (createGfsUploadJob) for EVERY size; │
+ // │ the writer-advertised maxFileBytes (≤ 1 GiB protocol ceiling) is │
+ // │ enforced before any bytes move. 8 MiB streamed parts. │
+ // │ • Legacy contentBase64 runs ONLY for fresh (non-resume) uploads after │
+ // │ a capability error with allowLegacyFallback, and is refused above │
+ // │ the legacy 16 MiB raw limit. Persisted resume sessions never │
+ // │ downgrade (see tests: legacy-*.test, persisted-resume, >16 MiB). │
+ // ├─────────────────────────────────────────────────────────────────────────┤
+ // │ FOLDER CACHE (childCacheRef) — revalidate vs. invalidate │
+ // │ • Prefetch warms UNcached folder rows (best-effort, non-fatal) and │
+ // │ never overwrites an entry a load() wrote meanwhile. │
+ // │ • openDirectory serves a cached page instantly and marks the next │
+ // │ effect pass for BACKGROUND revalidation (stale-while-revalidate): │
+ // │ no spinner/row-clear; rows are replaced when the server diverged. │
+ // │ • Every completed load() (navigation, refresh-after-mutation, │
+ // │ pagination) writes the fresh page back into the cache, so uploads, │
+ // │ folder creation, rename, and delete keep cached folders coherent. │
+ // │ • Deleting a directory row drops its cache entry. │
+ // │ • Loads are sequence-guarded: a response from a superseded navigation │
+ // │ can no longer overwrite the folder on screen (covers the background │
+ // │ path too). │
+ // ├─────────────────────────────────────────────────────────────────────────┤
+ // │ AUTHORITATIVE SERVER STATE │
+ // │ • Listings, resource versions (ifMatch), grants, and share rows always │
+ // │ come from control-api responses; this cache is never an authority for │
+ // │ permissions or versions. │
+ // └─────────────────────────────────────────────────────────────────────────┘
+
// Cache of prefetched directory children, keyed by the folder's
// resourceId. Refs over state because we don't want to re-render
// every time a prefetch resolves — the data is consumed lazily in
// openDirectory(). Survives across navigation; cleared on unmount.
const childCacheRef = useRef<Map<string, TreePage>>(new Map())
- // True after openDirectory() served cached data; the next useEffect
- // pass skips the redundant load() so the user keeps seeing the
- // cached rows instead of a flash of empty items + spinner.
- const skipNextLoadRef = useRef(false)
+ // Monotonic load sequence: only the newest load() may apply its results,
+ // so a slow response cannot clobber the folder the user navigated to next.
+ const loadSeqRef = useRef(0)
+ // True after openDirectory() served cached data; the next useEffect pass
+ // runs a BACKGROUND revalidation instead of a clearing reload, so the user
+ // keeps the cached rows (no spinner) while the server state re-syncs.
+ const revalidateNextLoadRef = useRef(false)
// Warm the cache for every folder row visible in the current view.
// Re-runs whenever the listing changes (folder navigation, refresh,
@@ -346,6 +408,9 @@ export function GfsBrowser(): React.JSX.Element {
{ drive: DRIVE }
)) as TreePage | undefined
if (cancelled || !page) return
+ // A load() may have cached a fresher page while this prefetch was in
+ // flight (the user navigated into the folder); never overwrite it.
+ if (childCacheRef.current.has(folder.resourceId)) return
childCacheRef.current.set(folder.resourceId, page)
} catch {
/* ignore — openDirectory will surface the real error */
@@ -362,8 +427,11 @@ export function GfsBrowser(): React.JSX.Element {
}, [items])
useEffect(() => {
- if (skipNextLoadRef.current) {
- skipNextLoadRef.current = false
+ if (revalidateNextLoadRef.current) {
+ revalidateNextLoadRef.current = false
+ // Stale-while-revalidate: cached rows stay on screen (no spinner) while
+ // the server state re-syncs; divergence overwrites the rows in place.
+ void load(current, undefined, { background: true })
return
}
void load(current)
@@ -384,15 +452,14 @@ export function GfsBrowser(): React.JSX.Element {
setCrumbs(prev => [...prev, { id: child.resourceId, rid: child.rid, name: child.name }])
const cached = childCacheRef.current.get(child.resourceId)
if (cached) {
- // Render the cached listing immediately. The useEffect-driven
- // load() will refresh in the background and overwrite if the
- // server state diverged, so the user still gets fresh data —
- // they just don't see the loading spinner.
+ // Render the cached listing instantly; the effect-driven background
+ // revalidation refreshes in place if the server state diverged, so the
+ // user gets fresh data without a loading spinner (decision table above).
setItems(sortChildrenWithDirectoriesFirst(cached.items))
setNextCursor(cached.nextCursor)
setError('')
setLoading(false)
- skipNextLoadRef.current = true
+ revalidateNextLoadRef.current = true
return
}
setLoading(true)
@@ -823,6 +890,8 @@ export function GfsBrowser(): React.JSX.Element {
await apiSend('DELETE', `/api/v1/gfs/proxy/v1/resources/${encodeURIComponent(child.rid)}`, {
ifMatch: child.version,
})
+ // A deleted directory's cached children must never be served again.
+ if (child.kind === 'directory') childCacheRef.current.delete(child.resourceId)
showToast('Resource deleted.', { tone: 'success' })
setSelected(null)
await refreshCurrent()
diff --git a/control-ui/components/__tests__/GfsBrowser.test.tsx b/control-ui/components/__tests__/GfsBrowser.test.tsx
index d209ba508..4f8bc633d 100644
--- a/control-ui/components/__tests__/GfsBrowser.test.tsx
+++ b/control-ui/components/__tests__/GfsBrowser.test.tsx
@@ -965,6 +965,8 @@ describe('GfsBrowser', () => {
// The 'org' folder prefetch resolves with an empty children page
// so the cache holds something realistic.
.mockResolvedValueOnce({ items: [], nextCursor: null })
+ // Entering org serves that cache and revalidates in the background.
+ .mockResolvedValueOnce({ items: [], nextCursor: null })
// Navigate back: re-fetch the root listing.
.mockResolvedValueOnce({
items: [child('org', 'directory', 1), child('report.md', 'file', 2)],
@@ -1086,8 +1088,10 @@ describe('GfsBrowser', () => {
.mockResolvedValueOnce({ items: [child('org', 'directory', 1)], nextCursor: null })
// Prefetch returns org's children so the cache is populated.
.mockResolvedValueOnce({ items: [child('eng', 'directory', 3)], nextCursor: null })
- // After the click navigates into eng, the prefetcher also reaches
- // for eng's children. Empty page is fine — eng has no folders.
+ // Entering org serves the cache and revalidates in the background.
+ .mockResolvedValueOnce({ items: [child('eng', 'directory', 3)], nextCursor: null })
+ // After the revalidated view renders, the prefetcher reaches for eng's
+ // children. Empty page is fine — eng has no folders.
.mockResolvedValueOnce({ items: [], nextCursor: null })
// Navigate back: re-fetch the root listing.
.mockResolvedValueOnce({ items: [child('org', 'directory', 1)], nextCursor: null })
@@ -1106,6 +1110,89 @@ describe('GfsBrowser', () => {
await screen.findAllByRole('button', { name: 'org' })
})
+ it('revalidates a prefetched folder in the background when navigating into it', async () => {
+ mockApiGet
+ .mockResolvedValueOnce({ items: [child('org', 'directory', 1)], nextCursor: null }) // root listing
+ .mockResolvedValueOnce({ items: [child('stale.md', 'file', 3)], nextCursor: null }) // prefetch org
+ .mockResolvedValueOnce({ items: [child('fresh.md', 'file', 4)], nextCursor: null }) // background revalidation
+ renderBrowser()
+
+ fireEvent.click((await screen.findAllByRole('button', { name: 'org' }))[0])
+ // The cached page renders instantly — no spinner, stale rows visible…
+ await screen.findByText('stale.md')
+ expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull()
+ // …then the background revalidation replaces them with the server state.
+ await waitFor(() => expect(screen.getByText('fresh.md')).toBeTruthy())
+ await waitFor(() => expect(screen.queryByText('stale.md')).toBeNull())
+ expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resources/id-1/children', {
+ drive: 'main',
+ })
+ })
+
+ it('reflects mutations in the folder cache when returning to a folder', async () => {
+ const rootPage = { items: [child('org', 'directory', 1)], nextCursor: null }
+ mockApiGet
+ .mockResolvedValueOnce(rootPage) // initial root listing
+ .mockResolvedValueOnce({ items: [], nextCursor: null }) // prefetch org (empty)
+ .mockResolvedValueOnce({ items: [], nextCursor: null }) // background revalidation on entering org
+ .mockResolvedValueOnce({ items: [child('report.md', 'file', 3)], nextCursor: null }) // refresh after upload
+ .mockResolvedValueOnce(rootPage) // navigate back to the root
+ // Re-entering org revalidates in the background against fresh rows.
+ .mockResolvedValue({ items: [child('report.md', 'file', 3)], nextCursor: null })
+ renderBrowser()
+
+ fireEvent.click((await screen.findAllByRole('button', { name: 'org' }))[0])
+ await screen.findByText('No resources are visible in this folder.')
+
+ // Upload into org: the resumable job mock completes → refreshCurrent().
+ fireEvent.click(screen.getByRole('button', { name: /upload file/i }))
+ const uploadDialog = await screen.findByRole('dialog', { name: 'Upload file' })
+ fireEvent.change(within(uploadDialog).getByLabelText('Choose file to upload'), {
+ target: { files: [new File(['report'], 'report.md', { type: 'text/markdown' })] },
+ })
+ fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Upload' }))
+ await waitFor(() => expect(screen.getByText('report.md')).toBeTruthy())
+
+ // Navigate back to the root, then into org again: the served cache must
+ // hold the post-mutation rows, not the prefetched empty page.
+ const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })
+ fireEvent.click(within(breadcrumb).getAllByRole('button')[0])
+ await screen.findAllByRole('button', { name: 'org' })
+ fireEvent.click(screen.getByRole('button', { name: 'org' }))
+ await waitFor(() => expect(screen.getByText('report.md')).toBeTruthy())
+ })
+
+ it('routes files above the legacy limit through the resumable transport, not contentBase64', async () => {
+ const rootId = '11111111-1111-1111-1111-111111111111'
+ const rootRid = '11111111111111111111111111111111'
+ mockApiGet.mockResolvedValue({ rootResourceId: rootId, items: [], nextCursor: null })
+ renderBrowser()
+ await screen.findByText('No resources are visible in this folder.')
+
+ // One byte above the legacy raw ceiling: legacy transport must be
+ // impossible; the resumable job is the only path. The transport decision
+ // reads only `size`, so the fixture overrides it instead of allocating
+ // 16 MiB through jsdom's fireEvent serialization.
+ const bigFile = new File(['x'], 'big-report.bin')
+ Object.defineProperty(bigFile, 'size', { value: 16 * 1024 * 1024 + 1 })
+ fireEvent.click(screen.getByRole('button', { name: /upload file/i }))
+ const uploadDialog = await screen.findByRole('dialog', { name: 'Upload file' })
+ fireEvent.change(within(uploadDialog).getByLabelText('Choose file to upload'), {
+ target: { files: [bigFile] },
+ })
+ fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Upload' }))
+
+ await waitFor(() =>
+ expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: 'big-report.bin',
+ target: { operation: 'create', parentRid: rootRid },
+ })
+ )
+ )
+ expect(mockApiSend).not.toHaveBeenCalled()
+ })
+
it('keeps the new-folder modal open after an error and allows a retry', async () => {
const rootId = '11111111-1111-1111-1111-111111111111'
mockApiGet.mockResolvedValue({ rootResourceId: rootId, items: [], nextCursor: null })
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 4ac83d4a1..accdf57c0 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.450",
+ "version": "0.1.451",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.450",
+ "version": "0.1.451",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-ui/package.json b/control-ui/package.json
index 5fef329e3..1efd79c00 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.450",
+ "version": "0.1.451",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
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 ffd898502..c47ec80ce 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { AuthContext, type AuthContextValue } from '@contexts/AuthContext'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
+import { desktopQueryDefaults } from '@lib/queryClient'
import { desktopQueryKeys } from '../queryKeys'
import { useGfsBrowserController } from '../useGfsBrowserController'
@@ -73,6 +74,7 @@ function Probe() {
<div data-testid="current-name">{ctrl.current?.name ?? 'none'}</div>
<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="accessible-count">{ctrl.accessibleResources.length}</div>
<div data-testid="accessible-error">{ctrl.accessibleError ?? 'none'}</div>
<div data-testid="accessible-notice">{ctrl.accessibleNotice ?? 'none'}</div>
@@ -127,14 +129,38 @@ function Probe() {
>
replace current
</button>
+ <button
+ type="button"
+ onClick={() =>
+ ctrl.current
+ ? void ctrl.moveResource(ctrl.current.resourceId, 'destination-1', ctrl.current.version)
+ : undefined
+ }
+ >
+ move current
+ </button>
+ <button type="button" onClick={() => ctrl.retryAccess()}>
+ retry access
+ </button>
</>
)
}
-function Harness({ children }: { children: ReactNode }) {
+function Harness({
+ children,
+ productionQueryDefaults = false,
+}: {
+ children: ReactNode
+ productionQueryDefaults?: boolean
+}) {
const [me, setMe] = useState<AuthContextValue['me']>(userA)
const [client] = useState(
- () => new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ () =>
+ new QueryClient(
+ productionQueryDefaults
+ ? { defaultOptions: desktopQueryDefaults }
+ : { defaultOptions: { queries: { retry: false } } }
+ )
)
lastHarnessQueryClient = client
return (
@@ -149,6 +175,11 @@ function Harness({ children }: { children: ReactNode }) {
)
}
+/** Same harness, but with the REAL production query cache policy. */
+function ProductionHarness({ children }: { children: ReactNode }) {
+ return <Harness productionQueryDefaults>{children}</Harness>
+}
+
describe('useGfsBrowserController', () => {
afterEach(() => {
cleanup()
@@ -582,6 +613,243 @@ describe('useGfsBrowserController', () => {
expect(screen.getByTestId('accessible-error').textContent).toBe('none')
expect(screen.getByTestId('accessible-count').textContent).toBe('0')
})
+
+ it('reconciles the open folder after a move and feeds the returned version into follow-up actions', async () => {
+ const docsId = '11111111-1111-1111-1111-111111111111'
+ const rootId = '00000000-0000-0000-0000-00000000000a'
+ const projectsId = '00000000-0000-0000-0000-00000000000b'
+ const archiveId = '00000000-0000-0000-0000-00000000000c'
+ const rid = (id: string) => id.replace(/-/g, '')
+ interface ResolvedResource {
+ resourceId: string
+ parentResourceId: string | null
+ gfsUri: string
+ drive: string
+ name: string
+ kind: 'directory' | 'file'
+ version: number
+ }
+ // The server state flips together with the move: Docs starts under
+ // Projects and ends under Archive, with version 9 (the move receipt).
+ const docsBefore: ResolvedResource = {
+ resourceId: docsId,
+ parentResourceId: projectsId,
+ gfsUri: `gfs://main/${rid(docsId)}`,
+ drive: 'main',
+ name: 'Docs',
+ kind: 'directory',
+ version: 3,
+ }
+ const state = new Map<string, ResolvedResource>([
+ [`gfs://main/${rid(docsId)}`, docsBefore],
+ [
+ `gfs://main/${rid(projectsId)}`,
+ {
+ resourceId: projectsId,
+ parentResourceId: rootId,
+ gfsUri: `gfs://main/${rid(projectsId)}`,
+ drive: 'main',
+ name: 'Projects',
+ kind: 'directory',
+ version: 1,
+ },
+ ],
+ [
+ `gfs://main/${rid(archiveId)}`,
+ {
+ resourceId: archiveId,
+ parentResourceId: rootId,
+ gfsUri: `gfs://main/${rid(archiveId)}`,
+ drive: 'main',
+ name: 'Archive',
+ kind: 'directory',
+ version: 1,
+ },
+ ],
+ [
+ `gfs://main/${rid(rootId)}`,
+ {
+ resourceId: rootId,
+ parentResourceId: null,
+ gfsUri: `gfs://main/${rid(rootId)}`,
+ drive: 'main',
+ name: 'Root',
+ kind: 'directory',
+ version: 1,
+ },
+ ],
+ ])
+ const resolve = vi.fn(async (uri: string) => {
+ const resource = state.get(uri)
+ if (!resource) throw new Error(`Unexpected URI: ${uri}`)
+ return resource
+ })
+ const moveResource = vi.fn(async () => ({ resourceId: docsId, version: 9 }))
+ const renameResource = vi.fn(async () => ({ resourceId: docsId, version: 10 }))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible: vi.fn(async () => ({
+ items: [
+ {
+ resourceId: docsId,
+ rid: rid(docsId),
+ gfsUri: `gfs://main/${rid(docsId)}`,
+ drive: 'main',
+ parentResourceId: projectsId,
+ name: 'Docs',
+ kind: 'directory',
+ path: null,
+ version: 3,
+ bytes: 0,
+ sources: ['grant'],
+ permissions: ['read', 'write', 'delete'],
+ coversDescendants: true,
+ },
+ ],
+ nextCursor: null,
+ })),
+ resolve,
+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
+ affordances: vi.fn(async () => ({
+ held: ['read', 'write', 'delete'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ })),
+ moveResource,
+ renameResource,
+ },
+ },
+ })
+
+ render(<Probe />, { wrapper: Harness })
+
+ await waitFor(() => expect(screen.getByTestId('accessible-count').textContent).toBe('1'))
+ await act(async () => {
+ screen.getByRole('button', { name: 'open Docs' }).click()
+ })
+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe(docsId))
+ expect(screen.getByTestId('current-version').textContent).toBe('3')
+
+ // The server applies the move: Docs now lives under Archive with v9.
+ state.set(`gfs://main/${rid(docsId)}`, {
+ ...docsBefore,
+ parentResourceId: archiveId,
+ version: 9,
+ })
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'move current' }).click()
+ })
+ await waitFor(() =>
+ expect(moveResource).toHaveBeenCalledWith(docsId, 'destination-1', 'main', 3)
+ )
+ // Navigation reconciles to the new location and consumes the new version.
+ await waitFor(() =>
+ expect(screen.getByTestId('crumbs').textContent).toBe('Root / Archive / Docs')
+ )
+ expect(screen.getByTestId('current-version').textContent).toBe('9')
+
+ // A versioned action right after the move uses the post-move version.
+ await act(async () => {
+ screen.getByRole('button', { name: 'rename current' }).click()
+ })
+ await waitFor(() =>
+ expect(renameResource).toHaveBeenCalledWith(docsId, 'Renamed report.md', 'main', 9)
+ )
+ })
+
+ it('fails closed on an authorization failure and drops cached gfs state under production query defaults', async () => {
+ const listChildren = vi.fn(async () => ({ items: [], nextCursor: null }))
+ const affordances = vi.fn(async () => ({
+ held: ['read', 'write'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ }))
+ const renameResource = vi.fn(async () => ({ resourceId: 'root', version: 2 }))
+ 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,
+ affordances,
+ renameResource,
+ },
+ },
+ })
+
+ render(<Probe />, { wrapper: ProductionHarness })
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'open' }).click()
+ })
+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))
+ await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(1))
+
+ const childrenKey = desktopQueryKeys.gfsChildren(':user-a:team-a', 'root', 'main')
+ expect(lastHarnessQueryClient?.getQueryData(childrenKey)).toBeTruthy()
+
+ // Access is revoked server-side; the next refetch observes the 401.
+ listChildren.mockRejectedValue(new Error('401 Unauthorized: session rejected'))
+ affordances.mockRejectedValue(new Error('401 Unauthorized: session rejected'))
+
+ 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('current').textContent).toBe('none')
+ expect(screen.getByTestId('crumbs').textContent).toBe('')
+ // The cached listing must not outlive the access that produced it.
+ expect(lastHarnessQueryClient?.getQueryData(childrenKey)).toBeUndefined()
+ })
+
+ it('revalidates accessible resources on remount even under production cache defaults', async () => {
+ const listAccessible = vi.fn(async () => ({ items: [], nextCursor: null }))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible,
+ resolve: vi.fn(),
+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
+ affordances: vi.fn(async () => ({
+ held: [],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ })),
+ },
+ },
+ })
+
+ // One shared client with the REAL production defaults (Infinity staleTime,
+ // refetchOnMount disabled): the second mount must still hit the server.
+ const client = new QueryClient({ defaultOptions: desktopQueryDefaults })
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <AuthContext.Provider value={authValue(userA)}>
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ </AuthContext.Provider>
+ )
+
+ const first = render(<Probe />, { wrapper })
+ await waitFor(() => expect(listAccessible).toHaveBeenCalledTimes(1))
+ first.unmount()
+
+ render(<Probe />, { wrapper })
+ await waitFor(() => expect(listAccessible).toHaveBeenCalledTimes(2))
+ })
})
// The grants listing is gated by the `grantsListEnabled` hook option (the Manage
@@ -597,6 +865,7 @@ function ManageProbe() {
<>
<div data-testid="current">{ctrl.current?.resourceId ?? 'none'}</div>
<div data-testid="grants-count">{ctrl.grants.length}</div>
+ <div data-testid="shares-count">{ctrl.shares.length}</div>
<button type="button" onClick={() => void ctrl.openUri('gfs://main/root')}>
open root
</button>
@@ -618,6 +887,18 @@ function ManageProbe() {
<button type="button" onClick={() => void ctrl.grant(['team:qa'], ['read'], false)}>
grant inherit false
</button>
+ <button type="button" onClick={() => void ctrl.refreshShares()}>
+ refresh shares
+ </button>
+ <button type="button" onClick={() => void ctrl.revokeShare('share-42')}>
+ revoke share
+ </button>
+ <button
+ type="button"
+ onClick={() => void ctrl.createShare(['user:bob']).then(() => ctrl.refreshShares())}
+ >
+ create share
+ </button>
</>
)
}
@@ -685,12 +966,8 @@ describe('useGfsBrowserController — grants list / revoke / inherit (#826)', ()
lastHarnessQueryClient?.getQueryData(
desktopQueryKeys.gfsGrants(':user-a:team-a', 'root', 'main')
)
- ).toEqual([
- expect.objectContaining({ id: 'grant-42' }),
- ])
- expect(
- lastHarnessQueryClient?.getQueryData(['gfs', 'main', 'root', 'grants'])
- ).toBeUndefined()
+ ).toEqual([expect.objectContaining({ id: 'grant-42' })])
+ expect(lastHarnessQueryClient?.getQueryData(['gfs', 'main', 'root', 'grants'])).toBeUndefined()
})
it('refetches the grants list when refreshGrants runs', async () => {
@@ -838,4 +1115,183 @@ describe('useGfsBrowserController — grants list / revoke / inherit (#826)', ()
expect(grant).toHaveBeenCalledWith('root', ['team:qa'], ['read'], 'main', false)
)
})
+
+ it('lists direct shares when Manage opens and caches them session-scoped', async () => {
+ const listGrants = vi.fn(async () => [])
+ const listShares = vi.fn(async () => [
+ {
+ id: 'share-42',
+ drive: 'main',
+ resourceId: 'root',
+ subject: { type: 'user', id: 'bob' },
+ permissions: ['read'],
+ includeDescendants: false,
+ },
+ ])
+ 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', 'manage_acl', 'share'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: true,
+ })),
+ listGrants,
+ listShares,
+ },
+ },
+ })
+
+ render(<ManageProbe />, { wrapper: Harness })
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'open root' }).click()
+ })
+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))
+ expect(listShares).not.toHaveBeenCalled()
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'open manage' }).click()
+ })
+ await waitFor(() => expect(listShares).toHaveBeenCalledTimes(1))
+ expect(listShares).toHaveBeenCalledWith('root', 'main')
+ await waitFor(() => expect(screen.getByTestId('shares-count').textContent).toBe('1'))
+ // Shares live under the session-scoped key (never a cross-session leak).
+ expect(
+ lastHarnessQueryClient?.getQueryData(
+ desktopQueryKeys.gfsShares(':user-a:team-a', 'root', 'main')
+ )
+ ).toEqual([expect.objectContaining({ id: 'share-42' })])
+ })
+
+ it('revokes a direct share by id and refetches the shares list on success', async () => {
+ const share = {
+ id: 'share-42',
+ drive: 'main',
+ resourceId: 'root',
+ subject: { type: 'user', id: 'bob' },
+ permissions: ['read'],
+ includeDescendants: false,
+ }
+ const listShares = vi.fn(async () => [share])
+ const revokeShare = vi.fn(async () => undefined)
+ 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', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: false,
+ })),
+ listGrants: vi.fn(async () => []),
+ listShares,
+ revokeShare,
+ },
+ },
+ })
+
+ render(<ManageProbe />, { wrapper: Harness })
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'open root' }).click()
+ })
+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))
+ await act(async () => {
+ screen.getByRole('button', { name: 'open manage' }).click()
+ })
+ await waitFor(() => expect(listShares).toHaveBeenCalledTimes(1))
+ await waitFor(() => expect(screen.getByTestId('shares-count').textContent).toBe('1'))
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'revoke share' }).click()
+ })
+
+ await waitFor(() => expect(revokeShare).toHaveBeenCalledWith('share-42'))
+ // onSuccess: refreshShares invalidates the exact shares key → active refetch.
+ await waitFor(() => expect(listShares).toHaveBeenCalledTimes(2))
+ })
+
+ it('shows a newly created share without remounting (create → refreshShares)', async () => {
+ const created: unknown[] = []
+ const listShares = vi.fn(async () =>
+ created.length > 0
+ ? [
+ {
+ id: 'share-42',
+ drive: 'main',
+ resourceId: 'root',
+ subject: { type: 'user', id: 'bob' },
+ permissions: ['read'],
+ includeDescendants: false,
+ },
+ ]
+ : []
+ )
+ const createShare = vi.fn(async () => {
+ created.push(true)
+ })
+ 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', 'manage_acl', 'share'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: true,
+ })),
+ listGrants: vi.fn(async () => []),
+ listShares,
+ createShare,
+ },
+ },
+ })
+
+ render(<ManageProbe />, { wrapper: Harness })
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'open root' }).click()
+ })
+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))
+ await act(async () => {
+ screen.getByRole('button', { name: 'open manage' }).click()
+ })
+ await waitFor(() => expect(listShares).toHaveBeenCalledTimes(1))
+ expect(screen.getByTestId('shares-count').textContent).toBe('0')
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'create share' }).click()
+ })
+
+ await waitFor(() => expect(createShare).toHaveBeenCalledWith('root', ['user:bob'], 'main'))
+ await waitFor(() => expect(screen.getByTestId('shares-count').textContent).toBe('1'))
+ })
})
diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
index 6858a72e7..0feb71de5 100644
--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useAuthContext } from '@contexts/AuthContext'
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { GFS_BREADCRUMB_MAX_DEPTH } from '@constants/gfsBrowser'
-import type { GfsGrantListItem } from '@/gfs/delegation.types'
+import type { GfsGrantListItem, GfsShareListItem } from '@/gfs/delegation.types'
import { desktopQueryKeys } from './queryKeys'
/**
@@ -93,6 +93,46 @@ function isResourceDiscoveryUnavailable(message: string): boolean {
)
}
+const SESSION_AUTHORITY_ERROR_CODES = [
+ 'desktop_user_retired',
+ 'operator_link_inactive',
+ 'operator_link_invalid',
+ 'gfs_operator_link_invalid',
+] as const
+
+/**
+ * Only a session/authorization failure may invalidate the browser's
+ * session-local access state. Per-resource policy verdicts such as
+ * `manage_acl_required`, `escalation_rejected`, and `foreign_agent_forbidden`
+ * are expected 403s and must remain local to the attempted operation.
+ *
+ * - `discovery` (listAccessible): the shared-with-me listing is
+ * permission-derived session state, so a 401/403 there is an authority
+ * verdict and fails closed.
+ * - `operation` (children/affordances/grants/shares/resolve): a generic 403
+ * is usually a resource-policy denial and must NOT clear the session; only
+ * a bare 401 or a typed lifecycle code does.
+ */
+export function isGfsSessionAuthorityFailure(
+ message: string,
+ surface: 'discovery' | 'operation' = 'operation'
+): boolean {
+ const normalized = message.toLowerCase()
+ if (SESSION_AUTHORITY_ERROR_CODES.some(code => normalized.includes(code))) return true
+ if (surface !== 'discovery') {
+ return (
+ /(^|\D)401(\D|$)/.test(normalized) ||
+ normalized.includes('not authenticated') ||
+ normalized.includes('unauthenticated')
+ )
+ }
+ return (
+ /(^|\D)(401|403)(\D|$)/.test(normalized) ||
+ normalized.includes('unauthorized') ||
+ normalized.includes('forbidden')
+ )
+}
+
export function useGfsBrowserController(options: GfsBrowserControllerOptions = {}) {
const { grantsListEnabled = false } = options
const queryClient = useQueryClient()
@@ -100,6 +140,12 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
const [crumbs, setCrumbs] = useState<GfsCrumb[]>([])
const [openError, setOpenError] = useState<string | null>(null)
const [resolving, setResolving] = useState(false)
+ // Deliberately session-local. A server authorization failure must never
+ // leave cached GFS metadata (listings, affordances, grants, shares)
+ // visible: production query defaults keep data for 30 minutes without
+ // revalidation, so the only safe response is to drop it all. A later
+ // server-backed request (retryAccess) is the only way back in.
+ const [accessState, setAccessState] = useState<'active' | 'revoked'>('active')
const previousSessionScopeRef = useRef<string | null>(null)
const current = crumbs.length ? crumbs[crumbs.length - 1] : null
@@ -121,6 +167,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
if (previous !== null) {
setCrumbs([])
setOpenError(null)
+ setAccessState('active')
void queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })
}
}, [queryClient, sessionScope])
@@ -134,7 +181,12 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
}
return listAccessible(DRIVE, pageParam)
},
- enabled: Boolean(sessionScope) && canListAccessibleResources,
+ enabled: Boolean(sessionScope) && canListAccessibleResources && accessState === 'active',
+ // Accessible resources are permission-derived state. Another session can
+ // revoke a grant/share while this user is away from Files, so an
+ // Infinity-cached list must not survive a Files remount without a server
+ // check — even though the app-level client defaults disable refetching.
+ refetchOnMount: 'always',
initialPageParam: undefined as string | undefined,
getNextPageParam: lastPage => lastPage.nextCursor ?? undefined,
})
@@ -147,7 +199,8 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
),
queryFn: ({ pageParam }) =>
window.clerum.gfs.listChildren(current!.resourceId, DRIVE, pageParam),
- enabled: Boolean(sessionScope) && Boolean(current) && currentIsDirectory,
+ enabled:
+ Boolean(sessionScope) && Boolean(current) && currentIsDirectory && accessState === 'active',
initialPageParam: undefined as string | undefined,
getNextPageParam: lastPage => lastPage.nextCursor ?? undefined,
})
@@ -159,7 +212,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
DRIVE
),
queryFn: () => window.clerum.gfs.affordances(current!.resourceId, DRIVE),
- enabled: Boolean(sessionScope) && Boolean(current),
+ enabled: Boolean(sessionScope) && Boolean(current) && accessState === 'active',
})
const refreshAffordances = useCallback(async () => {
const resourceId = current?.resourceId
@@ -185,7 +238,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
DRIVE
),
queryFn: () => window.clerum.gfs.affordances(rowAffordancesResourceId!, DRIVE),
- enabled: Boolean(sessionScope) && Boolean(rowAffordancesResourceId),
+ enabled: Boolean(sessionScope) && Boolean(rowAffordancesResourceId) && accessState === 'active',
})
// The grants listing is the revoke-id source (the grant PUT returns no ids),
// so writes must refetch it. Enabled only while the Manage dialog is open.
@@ -196,7 +249,33 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
DRIVE
),
queryFn: () => window.clerum.gfs.listGrants(current!.resourceId, DRIVE),
- enabled: Boolean(sessionScope) && Boolean(current) && grantsListEnabled,
+ enabled:
+ Boolean(sessionScope) && Boolean(current) && grantsListEnabled && accessState === 'active',
+ })
+ // Direct URI shares are a separate server surface ("this route is never
+ // inferred from grants"), so the revoke-id source for shares is this list.
+ // Shares the Manage-dialog gating with grants.
+ const sharesQuery = useQuery({
+ queryKey: desktopQueryKeys.gfsShares(
+ sessionScope ?? 'anonymous',
+ current?.resourceId ?? '',
+ DRIVE
+ ),
+ queryFn: () => window.clerum.gfs.listShares(current!.resourceId, DRIVE),
+ enabled:
+ Boolean(sessionScope) && Boolean(current) && grantsListEnabled && accessState === 'active',
+ })
+ const refreshShares = useCallback(async () => {
+ const resourceId = current?.resourceId
+ if (!resourceId) return
+ await queryClient.invalidateQueries({
+ exact: true,
+ 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
@@ -219,6 +298,65 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
predicate: query => query.queryKey[3] !== 'affordances',
})
}, [queryClient])
+ /**
+ * Fail closed on a session/authorization failure: cached GFS metadata can
+ * never outlive the access that produced it. Clears navigation and removes
+ * every cached GFS response for this Desktop session (listings, roots,
+ * affordances, grants, shares). The `accessState` gate disables the query
+ * observers until an explicit retry re-enters through the server.
+ */
+ const clearGfsState = useCallback(() => {
+ setCrumbs([])
+ setOpenError(null)
+ queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })
+ }, [queryClient])
+ const revokeAccess = useCallback(() => {
+ setAccessState('revoked')
+ clearGfsState()
+ }, [clearGfsState])
+ const retryAccess = useCallback(() => {
+ // This restores no local capability; it only re-enables the queries so a
+ // server-side re-grant (or a fresh sign-in) is the sole way back in.
+ setAccessState('active')
+ }, [])
+ /** For imperative flows (openUri, revoke mutations): fail closed on a
+ * session-authority rejection; returns true when it did. */
+ const handleAuthorityFailure = useCallback(
+ (message: string, surface: 'discovery' | 'operation' = 'operation'): boolean => {
+ if (!isGfsSessionAuthorityFailure(message, surface)) return false
+ revokeAccess()
+ return true
+ },
+ [revokeAccess]
+ )
+ // Query-surfaced authorization failures (a refetch after revocation is the
+ // normal way the loss is discovered under Infinity staleTime). Discovery is
+ // the session/authority boundary; per-resource verdicts stay local.
+ const queryAuthorizationError = [
+ accessibleQuery.error
+ ? { message: toMessage(accessibleQuery.error), surface: 'discovery' as const }
+ : null,
+ childrenQuery.error
+ ? { message: toMessage(childrenQuery.error), surface: 'operation' as const }
+ : null,
+ affordancesQuery.error
+ ? { message: toMessage(affordancesQuery.error), surface: 'operation' as const }
+ : null,
+ grantsQuery.error
+ ? { message: toMessage(grantsQuery.error), surface: 'operation' as const }
+ : null,
+ sharesQuery.error
+ ? { message: toMessage(sharesQuery.error), surface: 'operation' as const }
+ : null,
+ ]
+ .filter(
+ (entry): entry is { message: string; surface: 'discovery' | 'operation' } => entry !== null
+ )
+ .find(entry => isGfsSessionAuthorityFailure(entry.message, entry.surface))
+ useEffect(() => {
+ if (!queryAuthorizationError || accessState === 'revoked') return
+ revokeAccess()
+ }, [accessState, queryAuthorizationError, revokeAccess])
const createFolderMutation = useMutation({
mutationFn: async (name: string) => {
if (!current) throw new Error('No folder selected')
@@ -293,16 +431,6 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
await refreshGfs()
},
})
- // Move refreshes the old parent's children, the destination's children, and
- // the accessible roots in one shot via refreshGfs. The moved resource's own
- // crumbs stay valid (its id does not change); only its parent does.
- const moveResourceMutation = useMutation({
- mutationFn: (input: { resourceId: string; destinationId: string; ifMatch?: number }) =>
- window.clerum.gfs.moveResource(input.resourceId, input.destinationId, DRIVE, input.ifMatch),
- onSuccess: async () => {
- await refreshGfs()
- },
- })
const items = useMemo<GfsBrowserChild[]>(
() => (childrenQuery.data?.pages ?? []).flatMap(page => page.items),
@@ -316,6 +444,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
[accessibleQuery.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
@@ -324,59 +453,89 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
? 'Automatic GFS discovery is not available from this server yet. You can still open any GFS link you have.'
: null
- const openUri = useCallback(async (uri: string) => {
- setOpenError(null)
- setResolving(true)
- try {
- const resource = await window.clerum.gfs.resolve(uri.trim())
- const crumb: GfsCrumb = {
- resourceId: resource.resourceId,
- gfsUri: resource.gfsUri,
- name: resource.name,
- kind: resource.kind === 'directory' ? 'directory' : 'file',
- version: resource.version ?? 0,
- // `resolve` may omit bytes (older servers) — crumbs display 0 then,
- // matching the `version ?? 0` handling above.
- bytes: resource.bytes ?? 0,
- }
- const ancestors: GfsCrumb[] = []
- const seenResourceIds = new Set([resource.resourceId])
- let parentResourceId = resource.parentResourceId
-
- while (parentResourceId && ancestors.length < GFS_BREADCRUMB_MAX_DEPTH) {
- if (seenResourceIds.has(parentResourceId)) break
- seenResourceIds.add(parentResourceId)
- try {
- const parentRid = parentResourceId.replace(/-/g, '').toLowerCase()
- const parent = await window.clerum.gfs.resolve(`gfs://${resource.drive}/${parentRid}`)
- if (parent.kind !== 'directory') break
- if (parent.name) {
- ancestors.push({
- resourceId: parent.resourceId,
- gfsUri: parent.gfsUri,
- name: parent.name,
- kind: 'directory',
- version: parent.version ?? 0,
- bytes: parent.bytes ?? 0,
- })
+ const openUri = useCallback(
+ async (uri: string) => {
+ setOpenError(null)
+ setResolving(true)
+ try {
+ const resource = await window.clerum.gfs.resolve(uri.trim())
+ const crumb: GfsCrumb = {
+ resourceId: resource.resourceId,
+ gfsUri: resource.gfsUri,
+ name: resource.name,
+ kind: resource.kind === 'directory' ? 'directory' : 'file',
+ version: resource.version ?? 0,
+ // `resolve` may omit bytes (older servers) — crumbs display 0 then,
+ // matching the `version ?? 0` handling above.
+ bytes: resource.bytes ?? 0,
+ }
+ const ancestors: GfsCrumb[] = []
+ const seenResourceIds = new Set([resource.resourceId])
+ let parentResourceId = resource.parentResourceId
+
+ while (parentResourceId && ancestors.length < GFS_BREADCRUMB_MAX_DEPTH) {
+ if (seenResourceIds.has(parentResourceId)) break
+ seenResourceIds.add(parentResourceId)
+ try {
+ const parentRid = parentResourceId.replace(/-/g, '').toLowerCase()
+ const parent = await window.clerum.gfs.resolve(`gfs://${resource.drive}/${parentRid}`)
+ if (parent.kind !== 'directory') break
+ if (parent.name) {
+ ancestors.push({
+ resourceId: parent.resourceId,
+ gfsUri: parent.gfsUri,
+ name: parent.name,
+ kind: 'directory',
+ version: parent.version ?? 0,
+ bytes: parent.bytes ?? 0,
+ })
+ }
+ parentResourceId = parent.parentResourceId
+ } catch {
+ // A direct file grant can be readable while its parent is not. Keep
+ // the file open and show only the ancestors the caller may resolve.
+ break
}
- parentResourceId = parent.parentResourceId
- } catch {
- // A direct file grant can be readable while its parent is not. Keep
- // the file open and show only the ancestors the caller may resolve.
- break
}
+
+ setCrumbs([...ancestors.reverse(), crumb])
+ return crumb
+ } catch (error) {
+ const message = toMessage(error)
+ // Opening a URI is an operation on one resource. A generic 403 may be
+ // a per-resource policy decision; only a session-authority failure
+ // (bare 401 / typed lifecycle code) fails the session closed.
+ if (!handleAuthorityFailure(message, 'operation')) setOpenError(message)
+ return false
+ } finally {
+ setResolving(false)
}
+ },
+ [handleAuthorityFailure]
+ )
- setCrumbs([...ancestors.reverse(), crumb])
- return crumb
- } catch (error) {
- setOpenError(toMessage(error))
- return false
- } finally {
- setResolving(false)
- }
- }, [])
+ // Move refreshes the old parent's children, the destination's children,
+ // and the accessible roots in one shot via refreshGfs. The moved resource's
+ // id does not change, but its version does, and when the OPEN folder (or
+ // file) itself moved, its breadcrumb trail is stale: the ancestors above it
+ // belong to the old location. Consume the returned version immediately and
+ // reconcile navigation to the new location (resolve + ancestor walk) so a
+ // follow-up Rename/Delete/Move runs with the post-move version, not the
+ // pre-move one (which would 409 on ifMatch).
+ const moveResourceMutation = useMutation({
+ mutationFn: (input: { resourceId: string; destinationId: string; ifMatch?: number }) =>
+ window.clerum.gfs.moveResource(input.resourceId, input.destinationId, DRIVE, input.ifMatch),
+ onSuccess: async (receipt, input) => {
+ const movedCrumb = crumbs.find(crumb => crumb.resourceId === input.resourceId)
+ setCrumbs(prev =>
+ prev.map(crumb =>
+ crumb.resourceId === input.resourceId ? { ...crumb, version: receipt.version } : crumb
+ )
+ )
+ await refreshGfs()
+ if (movedCrumb) await openUri(movedCrumb.gfsUri)
+ },
+ })
const openChild = useCallback((child: GfsBrowserChild) => {
if (child.kind !== 'directory') return
@@ -443,6 +602,11 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
/** Cache-scope key (env + user + team) so the move dialog's queries share
* the controller's cache and are dropped together on scope change. */
sessionScope: sessionScope ?? 'anonymous',
+ /** 'revoked' after a session-authority failure — queries are gated off
+ * and cached GFS state is gone until retryAccess re-enters the server. */
+ accessState,
+ retryAccess,
+ handleAuthorityFailure,
accessibleResources,
items,
affordances: (affordancesQuery.data as GfsBrowserAffordances | undefined) ?? null,
@@ -486,6 +650,14 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
refreshGrants,
revokeGrant: (grantId: string) => revokeGrantMutation.mutateAsync(grantId),
revoking: revokeGrantMutation.isPending,
+ shares,
+ // Raw error (not toMessage) so FilesPage maps server codes symmetrically
+ // with grantsError.
+ sharesError: sharesQuery.error,
+ loadingShares: sharesQuery.isFetching,
+ refreshShares,
+ revokeShare: (shareId: string) => revokeShareMutation.mutateAsync(shareId),
+ revokingShare: revokeShareMutation.isPending,
createShare,
createFolder: (name: string) => createFolderMutation.mutateAsync(name),
createFile: (parentResourceId: string, name: string, encodedData: string) =>
diff --git a/desktop-app/ui/src/lib/queryClient.ts b/desktop-app/ui/src/lib/queryClient.ts
index f1876c46b..392cb8ac8 100644
--- a/desktop-app/ui/src/lib/queryClient.ts
+++ b/desktop-app/ui/src/lib/queryClient.ts
@@ -1,14 +1,21 @@
import { QueryClient } from '@tanstack/react-query'
-export const desktopQueryClient = new QueryClient({
- defaultOptions: {
- queries: {
- gcTime: 30 * 60 * 1000,
- refetchOnMount: false,
- refetchOnReconnect: false,
- refetchOnWindowFocus: false,
- retry: false,
- staleTime: Infinity,
- },
+/**
+ * Production query defaults. Exported so tests can exercise GFS behavior
+ * under the REAL cache policy (Infinity staleTime, no background refetches)
+ * instead of a looser harness default.
+ */
+export const desktopQueryDefaults = {
+ queries: {
+ gcTime: 30 * 60 * 1000,
+ refetchOnMount: false,
+ refetchOnReconnect: false,
+ refetchOnWindowFocus: false,
+ retry: false,
+ staleTime: Infinity,
},
+} as const
+
+export const desktopQueryClient = new QueryClient({
+ defaultOptions: desktopQueryDefaults,
})
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index 1ca22b3f9..97a44e0ae 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -231,8 +231,13 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
() => (ctrl.grantsError ? describeGfsGrantError(ctrl.grantsError) : null),
[ctrl.grantsError]
)
- const canWriteCurrent = hasBit(affordances, 'write')
- const canDeleteCurrent = hasBit(affordances, 'delete')
+ const sharesError = useMemo(
+ () => (ctrl.sharesError ? describeGfsGrantError(ctrl.sharesError) : null),
+ [ctrl.sharesError]
+ )
+ const accessRevoked = ctrl.accessState === 'revoked'
+ const canWriteCurrent = !accessRevoked && hasBit(affordances, 'write')
+ const canDeleteCurrent = !accessRevoked && hasBit(affordances, 'delete')
const currentIsFolder = current?.kind === 'directory'
const currentIsFile = current?.kind === 'file'
const currentPreviewAvailable = currentIsFile && isGfsPreviewFile(current?.name ?? '')
@@ -335,11 +340,39 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
}
const handleCreateShare = async (subjectKeys: string[]) => {
- await ctrl.createShare(subjectKeys)
+ try {
+ await ctrl.createShare(subjectKeys)
+ } 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
+ return
+ }
pushToast?.(
`${subjectKeys.length} ${subjectKeys.length === 1 ? 'share' : 'shares'} created`,
'success'
)
+ // List-after-write: make the new share row visible without a remount.
+ await ctrl.refreshShares()
+ }
+
+ const handleRevokeShare = async (shareId: string, label: string) => {
+ try {
+ await ctrl.revokeShare(shareId)
+ pushToast?.(`Shared access revoked for ${label}`, 'success')
+ } catch (revokeError) {
+ ctrl.handleAuthorityFailure(
+ revokeError instanceof Error ? revokeError.message : String(revokeError),
+ 'operation'
+ )
+ pushToast?.(describeGfsGrantError(revokeError).message, 'error')
+ }
}
const handleDownload = async (uri: string, name: string) => {
@@ -711,9 +744,23 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
) : null}
{accessibleNotice ? <StatusBanner tone="info" text={accessibleNotice} /> : null}
- {visibleError ? <StatusBanner tone="error" text={visibleError} /> : null}
+ {visibleError && !accessRevoked ? (
+ <StatusBanner tone="error" text={visibleError} />
+ ) : null}
- {visibleLoading ? (
+ {accessRevoked ? (
+ <>
+ <EmptyState
+ title="File access is not authorized"
+ body="Your current Desktop session cannot access this location. Sign in again or contact an administrator."
+ />
+ <div className="da-gfs-footer-actions">
+ <Button onClick={() => ctrl.retryAccess()} size="sm" variant="outline">
+ Retry file access
+ </Button>
+ </div>
+ </>
+ ) : visibleLoading ? (
<div
className="da-gfs-loading"
role="status"
@@ -1164,7 +1211,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
<div>
<h4>Who has access</h4>
<p className="muted">
- Existing grants on this resource. Revoking is immediate.
+ Existing direct grants and shares on this resource. Revoking is immediate.
</p>
</div>
</div>
@@ -1172,9 +1219,13 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
agents={agentSubjects}
error={grantsError}
items={ctrl.grants}
- loading={ctrl.loadingGrants}
+ loading={ctrl.loadingGrants || ctrl.loadingShares}
onRevoke={(item, label) => void handleRevokeGrant(item.id, label)}
+ onRevokeShare={(item, label) => void handleRevokeShare(item.id, label)}
revoking={ctrl.revoking}
+ revokingShare={ctrl.revokingShare}
+ shareError={sharesError}
+ shares={ctrl.shares}
subjects={delegationSubjects}
/>
</section>
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index 1de0e6fe6..78527da48 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -54,6 +54,15 @@ function baseController() {
refreshGrants: vi.fn(),
revokeGrant: vi.fn(),
revoking: false,
+ shares: [],
+ sharesError: null,
+ loadingShares: false,
+ refreshShares: vi.fn(),
+ revokeShare: vi.fn(),
+ revokingShare: false,
+ accessState: 'active',
+ retryAccess: vi.fn(),
+ handleAuthorityFailure: vi.fn(() => false),
createShare: vi.fn(),
createFolder: vi.fn(),
createFile: vi.fn(),
@@ -1237,6 +1246,78 @@ describe('FilesPage', () => {
)
})
+ it('lists direct shares in the who-has-access list and revokes them', async () => {
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ agents: { listMine: vi.fn(async () => []) },
+ team: { directory: vi.fn(async () => ({ currentTeamId: 'team-1', items: [] })) },
+ },
+ })
+ const revokeShare = vi.fn(async () => undefined)
+ const pushToast = vi.fn()
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder',
+ name: 'Team folder',
+ kind: 'directory',
+ },
+ affordances: {
+ held: ['read', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: true,
+ },
+ grants: [],
+ shares: [
+ {
+ id: 'share-1',
+ drive: 'main',
+ resourceId: 'folder-1',
+ subject: { type: 'user', id: 'user-9' },
+ permissions: ['read'],
+ includeDescendants: true,
+ },
+ ],
+ revokeShare,
+ })
+
+ renderFilesPage(pushToast)
+ await openManageDialog('Team folder')
+
+ const shareRow = await screen.findByTestId('gfs-access-row-share-share-1')
+ expect(shareRow.textContent).toContain('Includes contents')
+ fireEvent.click(screen.getByRole('button', { name: 'Revoke shared access for user-9' }))
+
+ await waitFor(() => expect(revokeShare).toHaveBeenCalledWith('share-1'))
+ await waitFor(() =>
+ expect(pushToast).toHaveBeenCalledWith('Shared access revoked for user-9', 'success')
+ )
+ })
+
+ it('renders the fail-closed state when GFS access is revoked and retries on demand', async () => {
+ const retryAccess = vi.fn()
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ accessState: 'revoked',
+ retryAccess,
+ })
+
+ renderFilesPage()
+
+ expect(await screen.findByText('File access is not authorized')).toBeTruthy()
+ // Fail closed: no cached rows, no loading spinner — only the retry path.
+ expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull()
+ expect(screen.getByRole('button', { name: 'Shared with me' }).hasAttribute('disabled')).toBe(
+ true
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'Retry file access' }))
+ expect(retryAccess).toHaveBeenCalledTimes(1)
+ })
+
it('refreshes server affordances whenever the manage dialog opens', async () => {
const refreshAffordances = vi.fn(async () => undefined)
hookMock.useGfsBrowserController.mockReturnValue({