Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
// @vitest-environment jsdom
import { type ReactNode, useState } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { AuthContext, type AuthContextValue } from '@contexts/AuthContext'
import {
QueryClient,
QueryClientProvider,
focusManager,
useQueryClient,
} from '@tanstack/react-query'
import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
import { desktopQueryDefaults } from '@lib/queryClient'
import {
affordancesResult,
childView,
grantsListPage,
heldAffordances,
listAccessiblePage,
listChildrenPage,
listGrantsFailureMessage,
listSharesFailureMessage,
resolveDeniedMessage,
resolveResource,
resolvedDirectory,
resolvedFile,
sharesListPage,
} from '@/gfs/__fixtures__/gfsProducerFixtures'
import { shouldRevalidateGfsQuery } from '@/lib/gfsEntityChangeState'
import { readGfsOpenLocations } from '@/lib/gfsOpenLocations'
import { desktopQueryKeys } from '../queryKeys'
import { useGfsBrowserController } from '../useGfsBrowserController'
// Fire-and-forget UI actions in these probes mirror the production callers,
// which await the same promises inside try/catch (see FilesPage). Swallow
// rejections here so a late/rejected mutation — e.g. a createFolder that runs
// once `current` has cleared and throws "No folder selected" — never escapes as
// an unhandled rejection and fails an unrelated test later in the full suite.
const swallow = (promise: Promise<unknown>): void => {
void promise.catch(() => {})
}
const userA = {
id: 'user-a',
email: '[email protected]',
name: 'User A',
picture: null,
teamId: 'team-a',
teamName: 'Team A',
role: 'member' as const,
}
const userB = {
...userA,
teamId: 'team-b',
teamName: 'Team B',
}
let lastHarnessQueryClient: QueryClient | null = null
function authValue(me: AuthContextValue['me']): AuthContextValue {
return {
booting: false,
busy: false,
statusText: '',
statusTone: 'info',
isAuthenticated: Boolean(me),
me,
email: me?.email ?? '',
password: '',
desktopSetupAuthorizationToken: '',
desktopSetupStarted: false,
desktopEnvironmentSetupComplete: true,
runtimeConfigSetupName: '',
runtimeConfigSetupExternalRestApiBaseUrl: '',
runtimeConfigSetupRpcProxyBaseUrl: '',
authTransitioning: false,
runtimeConfigState: null,
desktopReleaseStatus: null,
pendingDesktopEnvironmentSetup: null,
backendSwitchHint: null,
runtimeConfigMissing: false,
showRuntimeConfigSelector: false,
dependencyHealth: null,
hasDependencyOutage: false,
setBooting: vi.fn(),
setEmail: vi.fn(),
setPassword: vi.fn(),
setDesktopSetupAuthorizationToken: vi.fn(),
setDesktopEnvironmentSetupComplete: vi.fn(),
setPendingDesktopEnvironmentSetup: vi.fn(),
setRuntimeConfigSetupName: vi.fn(),
setRuntimeConfigSetupExternalRestApiBaseUrl: vi.fn(),
setRuntimeConfigSetupRpcProxyBaseUrl: vi.fn(),
setStatus: vi.fn(),
loadSession: vi.fn(),
handlePasswordLogin: vi.fn(),
handleSwitchLoginBackend: vi.fn(),
handleStartDesktopSetup: vi.fn(),
handleCompleteDesktopSetup: vi.fn(),
handleSaveRuntimeConfig: vi.fn(),
handleDeleteRuntimeConfig: vi.fn(),
handleSelectRuntimeConfig: vi.fn(),
handleClearRuntimeConfigSelection: vi.fn(),
handleCancelDesktopEnvironmentSetup: vi.fn(),
handleConfirmDesktopEnvironmentSetup: vi.fn(),
handleOpenDesktopRelease: vi.fn(),
handleLogout: vi.fn(),
}
}
function Probe() {
const ctrl = useGfsBrowserController()
const queryClient = useQueryClient()
const [backgroundRefreshOutcome, setBackgroundRefreshOutcome] = useState('not-run')
return (
<>
<div data-testid="current">{ctrl.current?.resourceId ?? 'none'}</div>
<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="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="children-error">{ctrl.error ?? 'none'}</div>
<div data-testid="accessible-error">{ctrl.accessibleError ?? 'none'}</div>
<div data-testid="accessible-notice">{ctrl.accessibleNotice ?? 'none'}</div>
<div data-testid="discovery-failure-kind">{ctrl.discoveryFailure?.kind ?? 'none'}</div>
<div data-testid="discovery-failure-retry-at">
{ctrl.discoveryFailure?.retryAvailableAt ?? 'none'}
</div>
<div data-testid="affordances-error">{ctrl.affordancesError ?? 'none'}</div>
<div data-testid="open-error">{ctrl.openError ?? 'none'}</div>
<div data-testid="loading">{ctrl.loading ? 'loading' : 'idle'}</div>
<div data-testid="loading-accessible">{ctrl.loadingAccessible ? 'loading' : 'idle'}</div>
<div data-testid="background-refresh-outcome">{backgroundRefreshOutcome}</div>
<div data-testid="row-affordances">{ctrl.rowAffordances?.held.join(',') ?? 'none'}</div>
<div data-testid="held-permissions">{ctrl.affordances?.held.join(',') ?? 'none'}</div>
{ctrl.items.map(item => (
<div key={item.resourceId} data-testid={`row-affordances-${item.resourceId}`}>
{ctrl.rowAffordancesByResourceId[item.resourceId]?.held.join(',') ?? 'none'}
</div>
))}
{ctrl.accessibleResources.map(resource => (
<button key={resource.resourceId} type="button" onClick={() => ctrl.openResource(resource)}>
open {resource.name}
</button>
))}
{ctrl.crumbs.map((crumb, index) => (
<button key={crumb.resourceId} type="button" onClick={() => ctrl.goToCrumb(index)}>
crumb {crumb.name}
</button>
))}
{ctrl.items.map(item => (
<button key={item.resourceId} type="button" onClick={() => ctrl.openChild(item)}>
child {item.name}
</button>
))}
<button type="button" onClick={() => swallow(ctrl.openUri('gfs://main/root'))}>
open
</button>
<button type="button" onClick={() => swallow(ctrl.openUri('gfs://main/denied-link'))}>
open denied link
</button>
<button type="button" onClick={() => swallow(ctrl.refreshCurrentLocation())}>
refresh current location
</button>
<button
type="button"
onClick={() => {
void ctrl
.refreshCurrentLocation({ background: true })
.then(updated => setBackgroundRefreshOutcome(updated ? 'updated' : 'superseded'))
.catch(() => setBackgroundRefreshOutcome('failed'))
}}
>
background refresh current location
</button>
<button type="button" onClick={() => swallow(ctrl.openUri('gfs://main/folder-b'))}>
open user destination
</button>
<button type="button" onClick={() => swallow(ctrl.refreshAffordances())}>
refresh permissions
</button>
<button
type="button"
onClick={() =>
void queryClient.invalidateQueries({
queryKey: desktopQueryKeys.gfsRoot,
predicate: query => shouldRevalidateGfsQuery(query.queryKey),
refetchType: 'active',
})
}
>
revalidate GFS scope
</button>
<button type="button" onClick={() => ctrl.loadMore()}>
load more
</button>
<button
type="button"
onClick={() =>
ctrl.current
? swallow(ctrl.createFile(ctrl.current.resourceId, 'notes.md', 'IyBOb3Rlcw=='))
: undefined
}
>
upload current
</button>
<button
type="button"
onClick={() =>
ctrl.current
? swallow(
ctrl.renameResource(
ctrl.current.resourceId,
'Renamed report.md',
ctrl.current.version
)
)
: undefined
}
>
rename current
</button>
<button
type="button"
onClick={() =>
ctrl.current
? swallow(ctrl.replaceFile(ctrl.current.resourceId, 'aGVsbG8=', ctrl.current.version))
: undefined
}
>
replace current
</button>
<button
type="button"
onClick={() =>
ctrl.current
? swallow(
ctrl.replaceFileFromPath(
ctrl.current.resourceId,
'/tmp/replacement.bin',
ctrl.current.version
)
)
: undefined
}
>
replace current from path
</button>
<button
type="button"
onClick={() =>
ctrl.current
? swallow(
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,
productionQueryDefaults = false,
}: {
children: ReactNode
productionQueryDefaults?: boolean
}) {
const [me, setMe] = useState<AuthContextValue['me']>(userA)
const [client] = useState(
() =>
new QueryClient(
productionQueryDefaults
? { defaultOptions: desktopQueryDefaults }
: { defaultOptions: { queries: { retry: false } } }
)
)
lastHarnessQueryClient = client
return (
<AuthContext.Provider value={authValue(me)}>
<QueryClientProvider client={client}>
{children}
<button type="button" onClick={() => setMe(userB)}>
switch team
</button>
</QueryClientProvider>
</AuthContext.Provider>
)
}
/** Same harness, but with the REAL production query cache policy. */
function ProductionHarness({ children }: { children: ReactNode }) {
return <Harness productionQueryDefaults>{children}</Harness>
}
describe('useGfsBrowserController', () => {
it('keeps loaded pages and avoids per-row reads during a scope revalidation', async () => {
const root = await resolveResource(
resolvedDirectory('root', 'Root', { gfsUri: 'gfs://main/root' })
)
const firstPageItems = Array.from({ length: 30 }, (_, index) =>
childView(`row-${index}`, `row-${index}.md`, 'file', { parentResourceId: 'root' })
)
const secondPageItems = [childView('row-30', 'row-30.md', 'file', { parentResourceId: 'root' })]
const firstPage = await listChildrenPage(firstPageItems, 'next-page')
const secondPage = await listChildrenPage(secondPageItems)
let finishFirstRefresh!: (page: typeof firstPage) => void
let finishSecondRefresh!: (page: typeof secondPage) => void
const pendingFirstRefresh = new Promise<typeof firstPage>(resolve => {
finishFirstRefresh = resolve
})
const pendingSecondRefresh = new Promise<typeof secondPage>(resolve => {
finishSecondRefresh = resolve
})
const listChildren = vi.fn((_resourceId: string, _drive: string, cursor?: string) => {
const call = listChildren.mock.calls.length
if (call === 3) return pendingFirstRefresh
if (call === 4) return pendingSecondRefresh
return cursor ? secondPage : firstPage
})
const listAccessible = 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 () => root), listChildren, affordances },
},
})
render(<Probe />, { wrapper: ProductionHarness })
await act(async () => screen.getByRole('button', { name: 'open' }).click())
await waitFor(() => expect(screen.getByTestId('items-count').textContent).toBe('30'))
await waitFor(() => expect(affordances).toHaveBeenCalledTimes(31))
await act(async () => screen.getByRole('button', { name: 'load more' }).click())
await waitFor(() => expect(screen.getByTestId('items-count').textContent).toBe('31'))
await waitFor(() => expect(affordances).toHaveBeenCalledTimes(32))
const childrenKey = desktopQueryKeys.gfsChildren(':user-a:team-a', 'root', 'main')
const affordanceKey = desktopQueryKeys.gfsAffordances(':user-a:team-a', 'row-0', 'main')
await act(async () => screen.getByRole('button', { name: 'revalidate GFS scope' }).click())
await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(3))
expect(screen.getByTestId('items-count').textContent).toBe('31')
expect(affordances).toHaveBeenCalledTimes(32)
const cachedChildren = lastHarnessQueryClient?.getQueryData<{
pages: Array<{ items: Array<{ resourceId: string }> }>
}>(childrenKey)
expect(cachedChildren?.pages).toHaveLength(2)
expect(cachedChildren?.pages[0]?.items).toEqual(
expect.arrayContaining([expect.objectContaining({ resourceId: 'row-0' })])
)
expect(cachedChildren?.pages[1]?.items).toEqual([
expect.objectContaining({ resourceId: 'row-30' }),
])
await act(async () => finishFirstRefresh(firstPage))
await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(4))
expect(screen.getByTestId('items-count').textContent).toBe('31')
await act(async () => finishSecondRefresh(secondPage))
await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(4))
await waitFor(() => expect(affordances).toHaveBeenCalledTimes(32))
// Two retained pages are refetched, but the 31 cached row permission
// queries are not repeated on a periodic scope tick.
expect(listAccessible).toHaveBeenCalledTimes(2)
expect(affordances).toHaveBeenCalledTimes(32)
expect(screen.getByTestId('items-count').textContent).toBe('31')
expect(shouldRevalidateGfsQuery(childrenKey)).toBe(true)
expect(shouldRevalidateGfsQuery(affordanceKey)).toBe(false)
})
afterEach(() => {
cleanup()
lastHarnessQueryClient = null
vi.restoreAllMocks()
vi.useRealTimers()
})
it('resets visible GFS state when the authenticated session scope changes', async () => {
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: [],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await act(async () => {
screen.getByRole('button', { name: 'open' }).click()
})
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))
const grantsKey = desktopQueryKeys.gfsGrants(':user-a:team-a', 'root', 'main')
lastHarnessQueryClient?.setQueryData(grantsKey, ['session-a-grant'])
expect(lastHarnessQueryClient?.getQueryData(grantsKey)).toEqual(['session-a-grant'])
await act(async () => {
screen.getByRole('button', { name: 'switch team' }).click()
})
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('none'))
expect(lastHarnessQueryClient?.getQueryData(grantsKey)).toBeUndefined()
})
it('preserves a failed link error when a background refresh resolves the current folder', async () => {
const root = await resolveResource(
resolvedDirectory('root', 'Root', { gfsUri: 'gfs://main/root' })
)
const resolve = vi
.fn()
.mockResolvedValueOnce(root)
.mockRejectedValueOnce(new Error(await resolveDeniedMessage('gfs://main/denied-link')))
.mockResolvedValue(root)
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
resolve,
listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
affordances: vi.fn(async () => ({
held: [],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await act(async () => screen.getByRole('button', { name: 'open' }).click())
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))
await act(async () => screen.getByRole('button', { name: 'open denied link' }).click())
await waitFor(() => expect(screen.getByTestId('open-error').textContent).not.toBe('none'))
const linkError = screen.getByTestId('open-error').textContent
await act(async () =>
screen.getByRole('button', { name: 'background refresh current location' }).click()
)
await waitFor(() => expect(resolve).toHaveBeenCalledTimes(3))
expect(screen.getByTestId('current').textContent).toBe('root')
expect(screen.getByTestId('open-error').textContent).toBe(linkError)
})
it.each(['success', 'denial'] as const)(
'keeps a newly opened child folder when an older refresh completes with %s',
async completion => {
const folderA = await resolveResource(
resolvedDirectory('folder-a', 'Folder A', { gfsUri: 'gfs://main/root' })
)
const folderAChildren = await listChildrenPage([
childView('folder-b', 'Folder B', 'directory', { parentResourceId: 'folder-a' }),
])
let resolveRefresh!: (resource: typeof folderA) => void
let rejectRefresh!: (reason?: unknown) => void
const deferredRefresh = new Promise<typeof folderA>((resolve, reject) => {
resolveRefresh = resolve
rejectRefresh = reject
})
const resolve = vi
.fn()
.mockResolvedValueOnce(folderA)
.mockImplementationOnce(() => deferredRefresh)
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
resolve,
listChildren: vi.fn(async (resourceId: string) =>
resourceId === 'folder-a' ? folderAChildren : { items: [], nextCursor: null }
),
affordances: vi.fn(async () => ({
held: [],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await act(async () => screen.getByRole('button', { name: 'open' }).click())
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('folder-a'))
await screen.findByRole('button', { name: 'child Folder B' })
screen.getByRole('button', { name: 'refresh current location' }).click()
await waitFor(() => expect(resolve).toHaveBeenCalledTimes(2))
screen.getByRole('button', { name: 'child Folder B' }).click()
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('folder-b'))
if (completion === 'success') {
await act(async () => resolveRefresh(folderA))
} else {
const denied = await resolveDeniedMessage('gfs://main/root')
await act(async () => rejectRefresh(new Error(denied)))
}
await waitFor(() => {
expect(screen.getByTestId('current').textContent).toBe('folder-b')
expect(screen.getByTestId('crumbs').textContent).toBe('Folder A / Folder B')
})
}
)
it('does not let a live background refresh supersede a pending user navigation', async () => {
const folderA = await resolveResource(
resolvedDirectory('folder-a', 'Folder A', { gfsUri: 'gfs://main/root' })
)
const folderB = await resolveResource(
resolvedDirectory('folder-b', 'Folder B', { gfsUri: 'gfs://main/folder-b' })
)
let finishUserNavigation!: (resource: typeof folderB) => void
const deferredUserNavigation = new Promise<typeof folderB>(resolve => {
finishUserNavigation = resolve
})
const resolve = vi
.fn()
.mockResolvedValueOnce(folderA)
.mockImplementationOnce(() => deferredUserNavigation)
.mockImplementationOnce(() => new Promise<typeof folderA>(() => {}))
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
resolve,
listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
affordances: vi.fn(async () => ({
held: [],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await act(async () => screen.getByRole('button', { name: 'open' }).click())
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('folder-a'))
screen.getByRole('button', { name: 'open user destination' }).click()
await waitFor(() => expect(resolve).toHaveBeenCalledTimes(2))
await act(async () => {
screen.getByRole('button', { name: 'background refresh current location' }).click()
})
await waitFor(() =>
expect(screen.getByTestId('background-refresh-outcome').textContent).toBe('superseded')
)
expect(resolve).toHaveBeenCalledTimes(2)
await act(async () => finishUserNavigation(folderB))
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('folder-b'))
expect(screen.getByTestId('current-name').textContent).toBe('Folder B')
})
it('exposes the presented verdict for a failed affordances read, not the IPC wrapper', async () => {
// Every rejection that crosses ipcRenderer.invoke arrives wrapped in
// "Error invoking remote method '<channel>': ", which names our own
// main/renderer split. FilesPage renders this field straight into a
// StatusBanner and interpolates it into the drag-overlay copy, so the raw
// string put the channel name — and a bare status line for a rate limit —
// in front of the user.
const affordances = vi.fn(async () => {
throw new Error(
"Error invoking remote method 'gfs:affordances': Error: 429 Too Many Requests: " +
'Too Many Requests retryAfterSeconds=7'
)
})
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,
},
},
})
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('affordances-error').textContent).toBe(
'Too many file requests — try again in 7s.'
)
)
// Liveness witness: the read really ran and really rejected, so the
// assertion above is about how the failure is presented and not about a
// field that stayed at its 'none' default.
expect(affordances).toHaveBeenCalled()
})
it('exposes the presented verdict for a failed open, not the IPC wrapper', async () => {
const resolve = vi.fn(async () => {
throw new Error(
"Error invoking remote method 'gfs:resolve': Error: 503 Service Unavailable: " +
'upstream_unreachable'
)
})
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
resolve,
listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
affordances: vi.fn(async () => ({
held: [],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await act(async () => {
screen.getByRole('button', { name: 'open' }).click()
})
// The server verdict survives in full — fail loud — and only the wrapper
// naming our own process boundary is gone.
await waitFor(() =>
expect(screen.getByTestId('open-error').textContent).toBe(
'503 Service Unavailable: upstream_unreachable'
)
)
// Liveness witness: the open really was attempted, and the session was not
// failed closed by this non-authority failure.
expect(resolve).toHaveBeenCalledTimes(1)
expect(screen.getByTestId('access-state').textContent).toBe('active')
})
it('refreshes cached affordances after permissions change outside Desktop', async () => {
let held = ['read']
const affordances = vi.fn(async () => ({
held,
canDelegate: held.includes('manage_acl'),
grantableBits: held,
canCreateShare: 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,
},
},
})
render(<Probe />, { wrapper: Harness })
await act(async () => {
screen.getByRole('button', { name: 'open' }).click()
})
await waitFor(() => expect(screen.getByTestId('held-permissions').textContent).toBe('read'))
held = ['read', 'write', 'delete', 'manage_acl', 'share']
await act(async () => {
screen.getByRole('button', { name: 'refresh permissions' }).click()
})
await waitFor(() =>
expect(screen.getByTestId('held-permissions').textContent).toBe(
'read,write,delete,manage_acl,share'
)
)
expect(affordances).toHaveBeenCalledTimes(2)
})
it('refreshes folder content after upload without invalidating permission affordances', async () => {
const listChildren = vi.fn(async () => ({ items: [], nextCursor: null }))
const affordances = vi.fn(async () => ({
held: ['read', 'write'],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
}))
const createFile = 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,
affordances,
createFile,
},
},
})
render(<Probe />, { wrapper: Harness })
await act(async () => {
screen.getByRole('button', { name: 'open' }).click()
})
await waitFor(() => expect(affordances).toHaveBeenCalledTimes(1))
await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(1))
await act(async () => {
screen.getByRole('button', { name: 'upload current' }).click()
})
await waitFor(() =>
expect(createFile).toHaveBeenCalledWith('root', 'notes.md', 'IyBOb3Rlcw==', 'main')
)
await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(2))
expect(affordances).toHaveBeenCalledTimes(1)
})
it('resolves affordances for every visible child row', async () => {
const parent = {
resourceId: 'folder-root',
rid: 'folder-root',
gfsUri: 'gfs://main/folder-root',
drive: 'main',
parentResourceId: null,
name: 'Workspace',
kind: 'directory' as const,
path: '/Workspace',
version: 1,
bytes: 0,
sources: ['grant'],
permissions: ['read'],
coversDescendants: true,
}
const childFolder = {
resourceId: 'child-folder',
rid: 'child-folder',
gfsUri: 'gfs://main/child-folder',
drive: 'main',
parentResourceId: 'folder-root',
name: 'Assets',
kind: 'directory' as const,
path: '/Workspace/Assets',
version: 2,
bytes: 0,
}
const childFile = {
resourceId: 'child-file',
rid: 'child-file',
gfsUri: 'gfs://main/child-file',
drive: 'main',
parentResourceId: 'folder-root',
name: 'report.txt',
kind: 'file' as const,
path: '/Workspace/report.txt',
version: 3,
bytes: 12,
}
const readonlyFile = {
...childFile,
resourceId: 'readonly-file',
rid: 'readonly-file',
gfsUri: 'gfs://main/readonly-file',
name: 'readonly.txt',
}
const listChildren = vi.fn(async () => ({
items: [childFolder, childFile, readonlyFile],
nextCursor: null,
}))
const affordances = vi.fn(async (resourceId: string) => {
const held =
resourceId === 'readonly-file'
? ['read']
: resourceId === 'folder-root'
? ['read']
: ['read', 'write', 'manage_acl']
return {
held,
canDelegate: held.includes('manage_acl'),
grantableBits: [],
canCreateShare: false,
}
})
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({ items: [parent], nextCursor: null })),
listChildren,
affordances,
},
},
})
render(<Probe />, { wrapper: Harness })
await waitFor(() => expect(screen.getByRole('button', { name: 'open Workspace' })).toBeTruthy())
await act(async () => {
screen.getByRole('button', { name: 'open Workspace' }).click()
})
await waitFor(() => expect(listChildren).toHaveBeenCalledWith('folder-root', 'main', undefined))
await waitFor(() => {
expect(screen.getByTestId('row-affordances-child-folder').textContent).toBe(
'read,write,manage_acl'
)
expect(screen.getByTestId('row-affordances-child-file').textContent).toBe(
'read,write,manage_acl'
)
expect(screen.getByTestId('row-affordances-readonly-file').textContent).toBe('read')
})
expect(affordances).toHaveBeenCalledWith('child-folder', 'main')
expect(affordances).toHaveBeenCalledWith('child-file', 'main')
expect(affordances).toHaveBeenCalledWith('readonly-file', 'main')
})
/**
* Row affordances are one request per visible child. Under `'always'` every
* folder re-entry paid that cost again against data the production default
* keeps fresh forever — 40 redundant requests on a 45-child folder, 47% of
* the affordances traffic in the incident behind #681.
*
* The clock is moved with `toFake: ['Date']` only, so `waitFor` keeps running
* on real timers; a full fake-timer install would stall it.
*/
it('serves cached row affordances on folder re-entry and refetches them past the freshness bound', async () => {
const parent = {
resourceId: 'folder-root',
rid: 'folder-root',
gfsUri: 'gfs://main/folder-root',
drive: 'main',
parentResourceId: null,
name: 'Workspace',
kind: 'directory' as const,
path: '/Workspace',
version: 1,
bytes: 0,
sources: ['grant'],
permissions: ['read'],
coversDescendants: true,
}
const children = ['child-a', 'child-b', 'child-c'].map((resourceId, index) => ({
resourceId,
rid: resourceId,
gfsUri: `gfs://main/${resourceId}`,
drive: 'main',
parentResourceId: 'folder-root',
name: `file-${index}.txt`,
kind: 'file' as const,
path: `/Workspace/file-${index}.txt`,
version: index + 2,
bytes: 10,
}))
const listChildren = vi.fn(async () => ({ items: children, nextCursor: null }))
// The open folder and its rows answer differently, so a row asserted below
// can only have been filled by that row's own query.
const affordances = vi.fn(async (resourceId: string) => ({
held: resourceId === 'folder-root' ? ['read'] : ['read', 'write'],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
}))
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({ items: [parent], nextCursor: null })),
listChildren,
affordances,
},
},
})
// Count only the ROW queries. The open folder has an affordances query of
// its own, and folding both into one total would hide which of the two
// this change is about.
const rowCalls = () =>
affordances.mock.calls.filter(([resourceId]) => resourceId.startsWith('child-')).length
// One client across all three mounts, with the REAL production defaults.
// A client per mount would make every count below meaningless.
const client = new QueryClient({ defaultOptions: desktopQueryDefaults })
const wrapper = ({ children: node }: { children: ReactNode }) => (
<AuthContext.Provider value={authValue(userA)}>
<QueryClientProvider client={client}>{node}</QueryClientProvider>
</AuthContext.Provider>
)
const enterWorkspace = async () => {
await waitFor(() =>
expect(screen.getByRole('button', { name: 'open Workspace' })).toBeTruthy()
)
await act(async () => {
screen.getByRole('button', { name: 'open Workspace' }).click()
})
}
vi.useFakeTimers({ toFake: ['Date'] })
const mountedAt = Date.now()
const first = render(<Probe />, { wrapper })
await enterWorkspace()
await waitFor(() => expect(rowCalls()).toBe(3))
expect(listChildren).toHaveBeenCalledTimes(1)
first.unmount()
vi.setSystemTime(mountedAt + 17_000)
const second = render(<Probe />, { wrapper })
await enterWorkspace()
await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(2))
await waitFor(() =>
// Witness, and the reason this is not a test that passes by rendering
// nothing: the rows are on screen with their cached bits. `listChildren`
// at 2 is the second witness — the remount happened and the children
// query's own `'always'` still fired.
children.forEach(child =>
expect(screen.getByTestId(`row-affordances-${child.resourceId}`).textContent).toBe(
'read,write'
)
)
)
expect(rowCalls()).toBe(3)
second.unmount()
// Past the 60s bound the bits are stale, so a permission change made
// outside this page is still picked up — the bound is a delay, not a
// suppression.
vi.setSystemTime(mountedAt + 70_000)
render(<Probe />, { wrapper })
await enterWorkspace()
await waitFor(() => expect(rowCalls()).toBe(6))
})
it('loads accessible GFS resources and opens one without a pasted link', async () => {
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({
items: [
{
resourceId: 'team-folder',
rid: 'teamfolder',
gfsUri: 'gfs://main/teamfolder',
drive: 'main',
parentResourceId: null,
name: 'Team folder tree',
kind: 'directory',
path: '/org/team-folder-tree',
version: 1,
bytes: 0,
sources: ['grant'],
permissions: ['read'],
coversDescendants: true,
},
{
resourceId: 'external-file',
rid: 'externalfile',
gfsUri: 'gfs://main/externalfile',
drive: 'main',
parentResourceId: 'other-tree',
name: 'External report.pdf',
kind: 'file',
path: '/other-org/reports/External report.pdf',
version: 1,
bytes: 42,
sources: ['share'],
permissions: ['read'],
coversDescendants: false,
},
],
nextCursor: null,
})),
resolve: vi.fn(),
listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
affordances: vi.fn(async () => ({
held: [],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await waitFor(() => expect(screen.getByTestId('accessible-count').textContent).toBe('2'))
await act(async () => {
screen.getByRole('button', { name: 'open Team folder tree' }).click()
})
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('team-folder'))
})
it('suppresses directly-shared files that live inside accessible folders (virtual-root hygiene)', async () => {
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({
items: [
{
resourceId: 'marketing',
rid: 'marketing',
gfsUri: 'gfs://main/marketing',
drive: 'main',
parentResourceId: null,
name: 'Marketing',
kind: 'directory',
path: '/Marketing',
version: 1,
bytes: 0,
sources: ['grant'],
permissions: ['read'],
coversDescendants: true,
},
{
resourceId: 'shared-file',
rid: 'sharedfile',
gfsUri: 'gfs://main/sharedfile',
drive: 'main',
parentResourceId: 'marketing',
name: 'enterprise-ai-agents-mockup.txt',
kind: 'file',
path: '/Marketing/enterprise-ai-agents-mockup.txt',
version: 1,
bytes: 7633,
sources: ['grant'],
permissions: ['read', 'share'],
coversDescendants: false,
},
{
// Nested under an accessible folder even though its immediate
// parent is not itself directly listed.
resourceId: 'nested-file',
rid: 'nestedfile',
gfsUri: 'gfs://main/nestedfile',
drive: 'main',
parentResourceId: 'not-listed-subfolder',
name: 'nested.txt',
kind: 'file',
path: '/Marketing/Assets/nested.txt',
version: 1,
bytes: 12,
sources: ['share'],
permissions: ['read'],
coversDescendants: false,
},
{
// Orphan share: location not reachable — must stay listed.
resourceId: 'orphan-file',
rid: 'orphanfile',
gfsUri: 'gfs://main/orphanfile',
drive: 'main',
parentResourceId: null,
name: 'lonely.md',
kind: 'file',
path: '/lonely.md',
version: 1,
bytes: 8,
sources: ['share'],
permissions: ['read'],
coversDescendants: false,
},
],
nextCursor: null,
})),
resolve: vi.fn(),
listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
affordances: vi.fn(async () => ({
held: [],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
// The Marketing folder and the unreachable orphan stay; the two files
// reachable by navigating into Marketing are suppressed from the root.
await waitFor(() => expect(screen.getByTestId('accessible-count').textContent).toBe('2'))
expect(screen.getByRole('button', { name: 'open Marketing' })).toBeTruthy()
expect(screen.getByRole('button', { name: 'open lonely.md' })).toBeTruthy()
expect(
screen.queryByRole('button', { name: 'open enterprise-ai-agents-mockup.txt' })
).toBeNull()
expect(screen.queryByRole('button', { name: 'open nested.txt' })).toBeNull()
})
it('revalidates folder listings on revisit and window focus under production cache defaults', async () => {
const marketingFolder = {
resourceId: 'folder-a',
rid: 'foldera',
gfsUri: 'gfs://main/foldera',
drive: 'main',
parentResourceId: null,
name: 'Marketing',
kind: 'directory' as const,
path: '/Marketing',
version: 1,
bytes: 0,
sources: ['grant'],
permissions: ['read'],
coversDescendants: true,
}
const financeFolder = {
...marketingFolder,
resourceId: 'folder-b',
rid: 'folderb',
gfsUri: 'gfs://main/folderb',
name: 'Finance',
path: '/Finance',
}
const file = (id: string, name: string) => ({
resourceId: id,
rid: id,
gfsUri: `gfs://main/${id}`,
drive: 'main',
parentResourceId: 'folder-a',
name,
kind: 'file' as const,
path: `/Marketing/${name}`,
version: 1,
bytes: 10,
})
// The out-of-band writer (an agent with a host grant, or an operator).
let marketingItems = [file('file-1', 'report.txt')]
const listChildren = vi.fn(async (resourceId: string) =>
resourceId === 'folder-a'
? { items: marketingItems, nextCursor: null }
: { items: [], nextCursor: null }
)
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({
items: [marketingFolder, financeFolder],
nextCursor: null,
})),
listChildren,
affordances: vi.fn(async () => ({
held: [],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
resolve: vi.fn(),
},
},
})
render(<Probe />, { wrapper: ProductionHarness })
await waitFor(() => expect(screen.getByRole('button', { name: 'open Marketing' })).toBeTruthy())
await act(async () => {
screen.getByRole('button', { name: 'open Marketing' }).click()
})
await waitFor(() => expect(screen.getByTestId('items-count').textContent).toBe('1'))
// An agent creates a second file while the app is open.
marketingItems = [file('file-1', 'report.txt'), file('file-2', 'northstar.md')]
// Navigating away and back revalidates — no hard reload needed.
await act(async () => {
screen.getByRole('button', { name: 'open Finance' }).click()
})
await waitFor(() => expect(screen.getByTestId('items-count').textContent).toBe('0'))
await act(async () => {
screen.getByRole('button', { name: 'open Marketing' }).click()
})
await waitFor(() => expect(screen.getByTestId('items-count').textContent).toBe('2'))
// Focusing the window while the folder stays open revalidates in place.
marketingItems = [
file('file-1', 'report.txt'),
file('file-2', 'northstar.md'),
file('file-3', 'northstar-wordmark.svg'),
]
await act(async () => {
focusManager.setFocused(false)
focusManager.setFocused(true)
})
await waitFor(() => expect(screen.getByTestId('items-count').textContent).toBe('3'))
})
it('hydrates readable parent folders for a directly opened file', async () => {
const rootId = '00000000-0000-0000-0000-000000000001'
const projectsId = '00000000-0000-0000-0000-000000000002'
const assetsId = '00000000-0000-0000-0000-000000000003'
const fileId = '00000000-0000-0000-0000-000000000004'
const byUri = new Map([
[
'gfs://main/root',
{
resourceId: fileId,
parentResourceId: assetsId,
gfsUri: `gfs://main/${fileId.replace(/-/g, '')}`,
drive: 'main',
name: 'avatar.png',
kind: 'file',
version: 4,
},
],
[
`gfs://main/${assetsId.replace(/-/g, '')}`,
{
resourceId: assetsId,
parentResourceId: projectsId,
gfsUri: `gfs://main/${assetsId.replace(/-/g, '')}`,
drive: 'main',
name: 'Assets',
kind: 'directory',
version: 3,
},
],
[
`gfs://main/${projectsId.replace(/-/g, '')}`,
{
resourceId: projectsId,
parentResourceId: rootId,
gfsUri: `gfs://main/${projectsId.replace(/-/g, '')}`,
drive: 'main',
name: 'Projects',
kind: 'directory',
version: 2,
},
],
[
`gfs://main/${rootId.replace(/-/g, '')}`,
{
resourceId: rootId,
parentResourceId: null,
gfsUri: `gfs://main/${rootId.replace(/-/g, '')}`,
drive: 'main',
name: '',
kind: 'directory',
version: 1,
},
],
])
const resolve = vi.fn(async (uri: string) => {
const resource = byUri.get(uri)
if (!resource) throw new Error(`Unexpected URI: ${uri}`)
return resource
})
const listChildren = vi.fn(async () => ({ items: [], nextCursor: null }))
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
resolve,
listChildren,
affordances: vi.fn(async () => ({
held: ['read'],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await act(async () => {
screen.getByRole('button', { name: 'open' }).click()
})
await waitFor(() =>
expect(screen.getByTestId('crumbs').textContent).toBe('Projects / Assets / avatar.png')
)
await act(async () => {
screen.getByRole('button', { name: 'crumb Assets' }).click()
})
expect(screen.getByTestId('current-name').textContent).toBe('Assets')
await waitFor(() => expect(listChildren).toHaveBeenCalledWith(assetsId, 'main', undefined))
})
it('keeps the visible current resource in sync after rename and replace mutations', async () => {
const fileResource = {
resourceId: 'file-1',
rid: 'file1',
gfsUri: 'gfs://main/file1',
drive: 'main',
parentResourceId: 'folder-1',
name: 'Draft report.md',
kind: 'file' as const,
path: '/Draft report.md',
version: 1,
bytes: 12,
sources: ['grant'],
permissions: ['read', 'write'],
coversDescendants: false,
}
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({ items: [fileResource], nextCursor: null })),
resolve: vi.fn(),
listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
affordances: vi.fn(async () => ({
held: ['read', 'write'],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
renameResource: vi.fn(async () => ({ resourceId: 'file-1', version: 2 })),
replaceFile: vi.fn(async () => ({
...fileResource,
name: 'Renamed report.md',
version: 3,
bytes: 5,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await waitFor(() => expect(screen.getByTestId('accessible-count').textContent).toBe('1'))
await act(async () => {
screen.getByRole('button', { name: 'open Draft report.md' }).click()
})
await waitFor(() =>
expect(screen.getByTestId('current-name').textContent).toBe('Draft report.md')
)
await act(async () => {
screen.getByRole('button', { name: 'rename current' }).click()
await Promise.resolve()
})
await waitFor(() =>
expect(screen.getByTestId('current-name').textContent).toBe('Renamed report.md')
)
expect(screen.getByTestId('current-version').textContent).toBe('2')
await act(async () => {
screen.getByRole('button', { name: 'replace current' }).click()
await Promise.resolve()
})
await waitFor(() => expect(screen.getByTestId('current-version').textContent).toBe('3'))
expect(screen.getByTestId('current-name').textContent).toBe('Renamed report.md')
})
it('treats a runtime without automatic resource discovery as a non-error state', async () => {
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
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: [],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await waitFor(() => expect(screen.getByTestId('accessible-count').textContent).toBe('0'))
expect(screen.getByTestId('accessible-error').textContent).toBe('none')
expect(screen.getByTestId('accessible-notice').textContent).toContain(
'Automatic GFS discovery is not available in this desktop runtime'
)
await act(async () => {
screen.getByRole('button', { name: 'open' }).click()
})
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))
})
it('maps an older server discovery 404 to a notice instead of a red error', async () => {
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => {
throw new Error('404 Not Found: Not Found')
}),
resolve: vi.fn(),
listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
affordances: vi.fn(async () => ({
held: [],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await waitFor(() =>
expect(screen.getByTestId('accessible-notice').textContent).toContain(
'Automatic GFS discovery is not available from this server yet'
)
)
expect(screen.getByTestId('accessible-error').textContent).toBe('none')
expect(screen.getByTestId('accessible-count').textContent).toBe('0')
// Pin the classification, not only the copy it happens to produce. The page
// suppresses its retry card on `kind === 'unsupported'` and is tested
// against a hand-written controller, so without this assertion a 404 could
// start classifying as 'failed' and both suites would stay green while the
// user got a retry card with a raw 404 in it.
expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('unsupported')
})
it('does not call a server unsupported because its error body quoted a 404', async () => {
// `httpClient` copies the RAW response body into the message whenever the
// JSON carries no top-level `error`/`message`, so a path, a filename or a
// log line from the failing server reaches the classifier verbatim. Under
// `\b` the phrase below was a word-boundary match — `/` and `-` are
// boundaries — and a 500 was reported as a server with no discovery
// endpoint. That verdict has no way back: `unsupported` offers no retry,
// so the user was told their files cannot be listed by a server that
// would have answered the next request.
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => {
throw new Error(
'500 Internal Server Error: render failed for /docs/404 Not Found.md - upstream'
)
}),
resolve: vi.fn(),
listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
affordances: vi.fn(async () => ({
held: [],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await waitFor(() =>
expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('failed')
)
// Liveness witness: the failure really reached the classifier — the notice
// that `unsupported` produces is absent because this branch was NOT taken,
// not because discovery never ran.
expect(screen.getByTestId('accessible-notice').textContent).toBe('none')
expect(screen.getByTestId('accessible-error').textContent).toContain('404 Not Found.md')
})
it('classifies a rate-limited discovery failure instead of calling the server unsupported', async () => {
// Electron's ipcRenderer.invoke always prefixes a rejection with
// "Error invoking remote method '<channel>'", so classifying on that
// substring matched every failure of this call, a 429 included.
const listAccessible = vi.fn(async () => {
throw new Error(
"Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " +
'Too Many Requests retryAfterSeconds=7'
)
})
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,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await waitFor(() => {
// The notice assertion is the one that fails against the substring
// classifier, which reports this 429 as "discovery is not available".
expect(screen.getByTestId('accessible-notice').textContent).toBe('none')
expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('rate-limited')
})
// The parsed window, asserted through the field the UI actually counts
// down from. The seam used to publish the duration alongside the deadline
// and this assertion read that copy — so the number was verified in a
// spelling no screen consumed, and the one the card reads went unchecked.
// `retryAvailableAt` is `errorUpdatedAt + 7s` and the query settled just
// now, so the remaining wait is 7s less the test's own elapsed time; the
// lower bound absorbs that without admitting 0, null or the 120s fixture.
const remainingMs =
Number(screen.getByTestId('discovery-failure-retry-at').textContent) - Date.now()
expect(remainingMs).toBeLessThanOrEqual(7_000)
expect(remainingMs).toBeGreaterThan(6_000)
// The authority revalidation gate must not open on a 429: a rate-limit
// verdict does not re-prove the session. Written as a positive assertion
// so it cannot pass by the field disappearing.
expect(screen.getByTestId('authority-pending').textContent).toBe('pending')
expect(screen.getByTestId('access-state').textContent).toBe('active')
expect(screen.getByTestId('items-count').textContent).toBe('0')
expect(screen.getByTestId('row-affordances').textContent).toBe('none')
expect(screen.getByTestId('loading-accessible').textContent).toBe('idle')
// Liveness witness: discovery really ran, and exactly once.
expect(listAccessible).toHaveBeenCalledTimes(1)
})
it('suppresses the window-focus discovery refetch until the rate-limit window expires', async () => {
const listAccessible = vi.fn(async () => {
throw new Error(
"Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " +
'Too Many Requests retryAfterSeconds=7'
)
})
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,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await waitFor(() =>
expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('rate-limited')
)
expect(listAccessible).toHaveBeenCalledTimes(1)
// Fake only Date, and only after the waits above: the pause predicate reads
// Date.now(), while RTL's waitFor needs a real clock to time out rather
// than hang. vi.useFakeTimers seeds the fake clock from the real one, so
// the 7 s window opened a moment ago is still open here.
vi.useFakeTimers({ toFake: ['Date'] })
const pausedAt = Date.now()
await act(async () => {
focusManager.setFocused(false)
focusManager.setFocused(true)
})
expect(listAccessible).toHaveBeenCalledTimes(1)
// Witness: the controller is still mounted and still holding the verdict,
// so the unchanged count above is a suppressed refetch, not a dead tree.
expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('rate-limited')
// Past the window, focus revalidates again. This is what makes the
// negative assertion above non-vacuous.
vi.setSystemTime(pausedAt + 8_000)
await act(async () => {
focusManager.setFocused(false)
focusManager.setFocused(true)
})
await act(async () => {
await new Promise(resolve => globalThis.setTimeout(resolve, 0))
})
expect(listAccessible).toHaveBeenCalledTimes(2)
// That second attempt was refused with a BYTE-IDENTICAL message, which is
// the normal case: the server keeps saying the same thing while its window
// is open. Nothing derived from the message alone changes, so a verdict
// memoized on the message keeps its object identity and every effect keyed
// on it stays silent — leaving the pause at the FIRST failure's expired
// deadline and letting every later focus spend another request. Re-arming
// has to key off the error's timestamp.
expect(screen.getByTestId('discovery-failure-retry-at').textContent).toBe(
String(pausedAt + 8_000 + 7_000)
)
vi.setSystemTime(pausedAt + 9_000)
await act(async () => {
focusManager.setFocused(false)
focusManager.setFocused(true)
})
await act(async () => {
await new Promise(resolve => globalThis.setTimeout(resolve, 0))
})
expect(listAccessible).toHaveBeenCalledTimes(2)
expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('rate-limited')
// And the re-armed window opens in turn, so the assertion above is a
// suppression rather than a controller that stopped refetching for good.
vi.setSystemTime(pausedAt + 16_000)
await act(async () => {
focusManager.setFocused(false)
focusManager.setFocused(true)
})
await act(async () => {
await new Promise(resolve => globalThis.setTimeout(resolve, 0))
})
expect(listAccessible).toHaveBeenCalledTimes(3)
})
it('reveals a folder listing that landed while discovery was still refused', async () => {
// The authority window exists to keep PREFETCHED or 30-minute-cached state
// from rendering before the session is re-proved. A children page fetched
// after this mount's epoch is neither — it is a fresh authorized read —
// and withholding it made the page state "This folder is empty", the one
// thing the successful listing disproves. Reachable without a deep link:
// discovery is refused with a 429, the root menu is still mounted, and
// Open GFS link on a folder resolves and lists it.
const child = {
resourceId: 'child-1',
rid: 'rid-child-1',
gfsUri: 'gfs://main/child-1',
drive: 'main',
parentResourceId: 'root',
name: 'report.md',
kind: 'file' as const,
path: '/report.md',
version: 1,
bytes: 10,
}
const listChildren = vi.fn(async () => ({ items: [child], nextCursor: null }))
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => {
throw new Error(
"Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " +
'Too Many Requests retryAfterSeconds=7'
)
}),
resolve: vi.fn(async () => ({
resourceId: 'root',
gfsUri: 'gfs://main/root',
name: 'Root',
kind: 'directory',
})),
listChildren,
affordances: vi.fn(async () => ({
held: ['read'],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await waitFor(() =>
expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('rate-limited')
)
await act(async () => {
screen.getByRole('button', { name: 'open' }).click()
})
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))
// Liveness witness: the children read really happened and really answered
// with a row. Without it the row assertion below would pass just as well on
// a listing that never ran.
await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(1))
// The gate is still shut — this is not a test of discovery recovering.
expect(screen.getByTestId('authority-pending').textContent).toBe('pending')
// And the three states the page reads to decide what to render. Rows, no
// error, no load in flight: the empty-folder copy must have no input left
// that would justify it.
expect(screen.getByTestId('items-count').textContent).toBe('1')
expect(screen.getByTestId('children-error').textContent).toBe('none')
expect(screen.getByTestId('loading').textContent).toBe('idle')
// Discovery's own surface stays withheld: the fresh evidence is the folder
// listing, and it says nothing about what the session may see at the root.
expect(screen.getByTestId('accessible-count').textContent).toBe('0')
})
it("suppresses the window-focus folder refetch until the folder's own window expires", async () => {
// `listAccessible` and `listChildren` are refused by ONE server budget, so
// a folder 429 has to arm the same pause a discovery 429 does. Arming only
// from discovery left this open: the card says Evenfire will wait out the
// server's window while every window focus spent another request against
// it, each refusal re-dating the countdown the user is watching.
const listChildren = vi.fn(async () => {
throw new Error(
"Error invoking remote method 'gfs:listChildren': Error: 429 Too Many Requests: " +
'Too Many Requests retryAfterSeconds=7'
)
})
const listAccessible = vi.fn(async () => ({ items: [], nextCursor: null }))
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible,
resolve: vi.fn(async () => ({
resourceId: 'root',
gfsUri: 'gfs://main/root',
name: 'Root',
kind: 'directory',
})),
listChildren,
affordances: vi.fn(async () => ({
held: ['read'],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
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(listChildren).toHaveBeenCalledTimes(1))
// Liveness witness: the folder listing really carries the budget verdict.
// Discovery succeeded here, which is the whole point — the pause may not
// depend on discovery being the one that failed.
await waitFor(() => expect(screen.getByTestId('children-error').textContent).toContain('429'))
expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('none')
vi.useFakeTimers({ toFake: ['Date'] })
const pausedAt = Date.now()
await act(async () => {
focusManager.setFocused(false)
focusManager.setFocused(true)
})
await act(async () => {
await new Promise(resolve => globalThis.setTimeout(resolve, 0))
})
expect(listChildren).toHaveBeenCalledTimes(1)
// The shared budget means discovery waits too, even though its own last
// answer was a success.
expect(listAccessible).toHaveBeenCalledTimes(1)
// Past the window both resume, which is what keeps the two assertions
// above a suppression rather than a controller that stopped refetching.
vi.setSystemTime(pausedAt + 8_000)
await act(async () => {
focusManager.setFocused(false)
focusManager.setFocused(true)
})
await act(async () => {
await new Promise(resolve => globalThis.setTimeout(resolve, 0))
})
expect(listChildren).toHaveBeenCalledTimes(2)
})
it('pauses focus revalidation for a rate limit that names no window', async () => {
// An upstream proxy or CDN answers 429 with its own body, which carries no
// retryAfterSeconds for us to parse. Treating an unknown window as "no wait
// needed" put focus revalidation straight back on an exhausted budget.
const listAccessible = vi.fn(async () => {
throw new Error(
"Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " +
'<html><body>429 Too Many Requests</body></html>'
)
})
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,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await waitFor(() =>
expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('rate-limited')
)
// The window really is unknown — this is the case under test, not a 429
// that happened to carry a hint.
expect(screen.getByTestId('discovery-failure-retry-at').textContent).toBe('none')
expect(listAccessible).toHaveBeenCalledTimes(1)
vi.useFakeTimers({ toFake: ['Date'] })
const pausedAt = Date.now()
await act(async () => {
focusManager.setFocused(false)
focusManager.setFocused(true)
})
expect(listAccessible).toHaveBeenCalledTimes(1)
expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('rate-limited')
// Past the default window, revalidation resumes.
vi.setSystemTime(pausedAt + 61_000)
await act(async () => {
focusManager.setFocused(false)
focusManager.setFocused(true)
})
await act(async () => {
await new Promise(resolve => globalThis.setTimeout(resolve, 0))
})
expect(listAccessible).toHaveBeenCalledTimes(2)
})
it('keeps reporting the children load while discovery is rate limited', async () => {
// `loading` is the children query's state. Gating it on a discovery error
// hid the spinner while a folder was genuinely loading, so the consumer
// that derives its loading state from this field alone flashed an empty
// folder at the user.
let releaseChildren: (page: { items: never[]; nextCursor: null }) => void = () => {}
const listChildren = vi.fn(
() =>
new Promise<{ items: never[]; nextCursor: null }>(resolve => {
releaseChildren = resolve
})
)
const listAccessible = vi.fn(async () => {
throw new Error(
"Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " +
'Too Many Requests retryAfterSeconds=7'
)
})
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible,
listChildren,
resolve: vi.fn(async () => ({
resourceId: 'root',
gfsUri: 'gfs://main/root',
name: 'Root',
kind: 'directory',
})),
affordances: vi.fn(async () => ({
held: ['read'],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await waitFor(() =>
expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('rate-limited')
)
await act(async () => {
screen.getByRole('button', { name: 'open' }).click()
})
// Witness: the children request is genuinely in flight, so "loading" below
// describes a pending load and not a tree that never started one.
await waitFor(() => expect(listChildren).toHaveBeenCalled())
expect(screen.getByTestId('loading').textContent).toBe('loading')
await act(async () => {
releaseChildren({ items: [], nextCursor: null })
})
// Settled, and reported as settled. The R4 authority gate is still open —
// a 429 never advances the discovery query's `dataUpdatedAt`, so the
// session is not re-proved and every cached GFS surface stays withheld —
// but that is a statement about what may be SHOWN, not about whether a
// request is outstanding. While the two shared this field, a folder that
// had already answered went on reporting a load nothing would ever end,
// and the consumers that read it alone sat on "Loading files…" forever.
//
// `idle` is awaited, not read after one tick: TanStack Query delivers the
// settled fetch through its own `setTimeout(0)` notifier, which a loaded
// machine can schedule after the tick the `act` above waits for (#756).
// A hook that never settles still fails here, on the `waitFor` timeout.
//
// `authority-pending` is asserted once `idle` holds, and deliberately: it
// is the witness that the gate itself was not falsified to buy `idle`.
await waitFor(() => expect(screen.getByTestId('loading').textContent).toBe('idle'))
expect(screen.getByTestId('authority-pending').textContent).toBe('pending')
})
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, undefined)
)
// 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('keeps a folder listing during revalidation, then purges it after authoritative 403', async () => {
const root = await resolveResource(
resolvedDirectory('root', 'Root', { gfsUri: 'gfs://main/root' })
)
const accessibleRoot = childView('other-root', 'Other folder', 'directory')
const child = childView('private-child', 'private.md', 'file', { parentResourceId: 'root' })
let denyRefresh!: (error: Error) => void
const deniedRefresh = new Promise<never>((_resolve, reject) => {
denyRefresh = reject
})
const listChildren = vi
.fn()
.mockResolvedValueOnce(await listChildrenPage([child]))
.mockImplementationOnce(() => deniedRefresh)
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({ items: [accessibleRoot], nextCursor: null })),
resolve: vi.fn(async () => root),
listChildren,
affordances: vi.fn(async () => ({
held: ['read'],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
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(screen.getByTestId('items-count').textContent).toBe('1'))
const childrenKey = desktopQueryKeys.gfsChildren(':user-a:team-a', 'root', 'main')
void lastHarnessQueryClient?.invalidateQueries({ queryKey: childrenKey })
await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(2))
expect(screen.getByTestId('current').textContent).toBe('root')
expect(screen.getByTestId('items-count').textContent).toBe('1')
await act(async () => denyRefresh(new Error(await resolveDeniedMessage('gfs://main/root'))))
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('none'))
expect(screen.getByTestId('items-count').textContent).toBe('0')
expect(screen.getByTestId('open-error').textContent).toBe(
'This folder or file is no longer available.'
)
expect(screen.getByTestId('access-state').textContent).toBe('active')
expect(screen.getByTestId('accessible-count').textContent).toBe('1')
await waitFor(() => expect(lastHarnessQueryClient?.getQueryData(childrenKey)).toBeUndefined())
})
it('does not let an old folder denial cancel a pending destination navigation', async () => {
const root = await resolveResource(
resolvedDirectory('root', 'Root', { gfsUri: 'gfs://main/root' })
)
const folderB = await resolveResource(
resolvedDirectory('folder-b', 'Folder B', { gfsUri: 'gfs://main/folder-b' })
)
let finishNavigation!: (resource: typeof folderB) => void
const pendingNavigation = new Promise<typeof folderB>(resolve => {
finishNavigation = resolve
})
const resolve = vi
.fn()
.mockResolvedValueOnce(root)
.mockImplementationOnce(() => pendingNavigation)
const listChildren = vi
.fn()
.mockResolvedValueOnce(await listChildrenPage([childView('leaf', 'leaf.md', 'file')]))
.mockRejectedValueOnce(new Error(await resolveDeniedMessage('gfs://main/root')))
.mockResolvedValue({ items: [], nextCursor: null })
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
resolve,
listChildren,
affordances: vi.fn(async () => ({
held: ['read'],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
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))
screen.getByRole('button', { name: 'open user destination' }).click()
await waitFor(() => expect(resolve).toHaveBeenCalledTimes(2))
void lastHarnessQueryClient?.invalidateQueries({
exact: true,
queryKey: desktopQueryKeys.gfsChildren(':user-a:team-a', 'root', 'main'),
})
await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(2))
await act(async () => finishNavigation(folderB))
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('folder-b'))
expect(screen.getByTestId('current-name').textContent).toBe('Folder B')
expect(screen.getByTestId('open-error').textContent).toBe('none')
})
it('keeps the complete breadcrumb trail and retries a transient ancestor failure', async () => {
const parent = await resolveResource(
resolvedDirectory('parent', 'Parent', { gfsUri: 'gfs://main/parent', path: '/Parent' })
)
const leaf = await resolveResource(
resolvedDirectory('leaf', 'Leaf', {
gfsUri: 'gfs://main/root',
path: '/Parent/Leaf',
parentResourceId: 'parent',
})
)
const resolve = vi
.fn()
.mockResolvedValueOnce(leaf)
.mockResolvedValueOnce(parent)
.mockResolvedValueOnce(leaf)
.mockRejectedValueOnce(new Error('503 Service Unavailable'))
.mockResolvedValueOnce(leaf)
.mockResolvedValueOnce(parent)
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
resolve,
listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
affordances: vi.fn(async () => ({
held: [],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await act(async () => screen.getByRole('button', { name: 'open' }).click())
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('leaf'))
expect(screen.getByTestId('crumbs').textContent).toBe('Parent / Leaf')
await act(async () => {
screen.getByRole('button', { name: 'background refresh current location' }).click()
})
await waitFor(() => expect(resolve).toHaveBeenCalledTimes(4))
expect(screen.getByTestId('crumbs').textContent).toBe('Parent / Leaf')
await waitFor(() => expect(resolve).toHaveBeenCalledTimes(6), { timeout: 2000 })
expect(screen.getByTestId('crumbs').textContent).toBe('Parent / Leaf')
})
it('drops only an authoritatively denied ancestor while keeping the readable location open', async () => {
const parent = await resolveResource(
resolvedDirectory('parent', 'Parent', { gfsUri: 'gfs://main/parent', path: '/Parent' })
)
const leaf = await resolveResource(
resolvedDirectory('leaf', 'Leaf', {
gfsUri: 'gfs://main/root',
path: '/Parent/Leaf',
parentResourceId: 'parent',
})
)
const resolve = vi
.fn()
.mockResolvedValueOnce(leaf)
.mockResolvedValueOnce(parent)
.mockResolvedValueOnce(leaf)
.mockRejectedValueOnce(new Error('403 Forbidden: httpStatus=403'))
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
resolve,
listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
affordances: vi.fn(async () => ({
held: [],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
},
},
})
render(<Probe />, { wrapper: Harness })
await act(async () => screen.getByRole('button', { name: 'open' }).click())
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('leaf'))
expect(screen.getByTestId('crumbs').textContent).toBe('Parent / Leaf')
await act(async () => {
screen.getByRole('button', { name: 'background refresh current location' }).click()
})
await waitFor(() => expect(resolve).toHaveBeenCalledTimes(4))
expect(screen.getByTestId('current').textContent).toBe('leaf')
expect(screen.getByTestId('crumbs').textContent).toBe('Leaf')
expect(screen.getByTestId('open-error').textContent).toBe('none')
})
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))
})
// 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()
// The authority window compares cache timestamps against the controller
// mount clock; sleep past millisecond granularity so the seeded data is
// strictly older than the mount (a same-ms seed would read as fresh).
await new Promise(resolve => setTimeout(resolve, 5))
// 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('')
})
// Completes the R3-M1 defect class: the path-based replace — the one
// mutation that had escaped the shared onError boundary — must fail the
// session closed under the REAL production cache policy, purge every
// session-scoped GFS cache, and drop navigation/resource state.
it('fails closed when replaceFileFromPath is rejected with 401 under production query defaults', async () => {
const scope = ':user-a:team-a'
const client = new QueryClient({ defaultOptions: desktopQueryDefaults })
const emptyPage = {
pages: [{ items: [], nextCursor: null }],
pageParams: [undefined],
}
client.setQueryData(desktopQueryKeys.gfsAccessible(scope, 'main'), {
pages: [
{
items: [
{
resourceId: 'file-9',
rid: 'file9',
gfsUri: 'gfs://main/file9',
drive: 'main',
parentResourceId: null,
name: 'report.md',
kind: 'file',
path: '/report.md',
version: 4,
bytes: 12,
sources: ['grant'],
permissions: ['read', 'write'],
coversDescendants: false,
},
],
nextCursor: null,
},
],
pageParams: [undefined],
})
client.setQueryData(desktopQueryKeys.gfsChildren(scope, 'root', 'main'), emptyPage)
client.setQueryData(desktopQueryKeys.gfsGrants(scope, 'root', 'main'), [
{
id: 'grant-1',
drive: 'main',
resourceId: 'root',
subject: { type: 'user', id: 'u' },
permissions: ['read'],
inherit: false,
},
])
client.setQueryData(desktopQueryKeys.gfsShares(scope, 'root', 'main'), [
{
id: 'share-1',
drive: 'main',
resourceId: 'root',
subject: { type: 'user', id: 'u' },
permissions: ['read'],
includeDescendants: false,
},
])
const replaceFileFromPath = 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',
version: 1,
})),
listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
affordances: vi.fn(async () => ({
held: ['read', 'write'],
canDelegate: false,
grantableBits: [],
canCreateShare: false,
})),
replaceFileFromPath,
},
},
})
const wrapper = ({ children }: { children: ReactNode }) => (
<AuthContext.Provider value={authValue(userA)}>
<QueryClientProvider client={client}>{children}</QueryClientProvider>
</AuthContext.Provider>
)
render(<Probe />, { wrapper })
// Navigate in; the session is active and caches hold real data.
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'))
expect(client.getQueryData(desktopQueryKeys.gfsChildren(scope, 'root', 'main'))).toBeTruthy()
// The path-based replace is rejected with a bare 401.
await act(async () => {
screen.getByRole('button', { name: 'replace current from path' }).click()
})
await waitFor(() =>
expect(replaceFileFromPath).toHaveBeenCalledWith('root', '/tmp/replacement.bin', 'main', 1)
)
// Authority revoked, caches purged, navigation gone — nothing stale kept.
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, 'root', 'main'))).toBeUndefined()
expect(client.getQueryData(desktopQueryKeys.gfsGrants(scope, 'root', 'main'))).toBeUndefined()
expect(client.getQueryData(desktopQueryKeys.gfsShares(scope, 'root', 'main'))).toBeUndefined()
})
})
// The grants listing is gated by the `grantsListEnabled` hook option (the Manage
// dialog is the only consumer, so the query runs only while it is open). This
// probe drives that option through local state so a test can flip Manage
// open/closed, and it reuses the real QueryClient from `Harness` so invalidation
// genuinely refetches — mocking the client would hide the load-after-write wiring
// this block exists to protect.
function ManageProbe() {
const [manageOpen, setManageOpen] = useState(false)
const ctrl = useGfsBrowserController({ grantsListEnabled: manageOpen })
return (
<>
<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>
<div data-testid="inherited-error">{ctrl.inheritedAccessError ?? 'none'}</div>
<div data-testid="inherited-coverage">{ctrl.inheritedCoverage ?? 'none'}</div>
<div data-testid="access-state">{ctrl.accessState}</div>
<div data-testid="crumbs">{ctrl.crumbs.map(crumb => crumb.name).join(' / ')}</div>
<div data-testid="held-permissions">{ctrl.affordances?.held.join(',') ?? 'none'}</div>
<button type="button" onClick={() => swallow(ctrl.openUri('gfs://main/root'))}>
open root
</button>
<button type="button" onClick={() => setManageOpen(true)}>
open manage
</button>
<button type="button" onClick={() => setManageOpen(false)}>
close manage
</button>
<button type="button" onClick={() => swallow(ctrl.refreshGrants())}>
refresh grants
</button>
<button type="button" onClick={() => swallow(ctrl.revokeGrant('grant-42'))}>
revoke grant
</button>
<button type="button" onClick={() => swallow(ctrl.grant(['user:bob'], ['read'], true))}>
grant inherit true
</button>
<button type="button" onClick={() => swallow(ctrl.grant(['team:qa'], ['read'], false))}>
grant inherit false
</button>
<button type="button" onClick={() => swallow(ctrl.refreshShares())}>
refresh shares
</button>
<button
type="button"
onClick={() =>
swallow(
ctrl.convergeCommittedMove(
{
resourceId: ctrl.crumbs[0]?.resourceId ?? '',
destinationId: 'destination-1',
oldParentId: null,
},
{ version: 2 }
)
)
}
>
move oldest ancestor
</button>
<button type="button" onClick={() => swallow(ctrl.revokeShare('share-42'))}>
revoke share
</button>
<button
type="button"
onClick={() => swallow(ctrl.createShare(['user:bob']).then(() => ctrl.refreshShares()))}
>
create share
</button>
</>
)
}
describe('useGfsBrowserController — grants list / revoke / inherit (#826)', () => {
afterEach(() => {
cleanup()
lastHarnessQueryClient = null
vi.restoreAllMocks()
})
it('does not list grants while Manage is closed and lists them once it opens', async () => {
const affordances = vi.fn(async () => ({
held: ['read', 'manage_acl'],
canDelegate: true,
grantableBits: ['read'],
canCreateShare: false,
}))
const listGrants = vi.fn(async () => [
{
id: 'grant-42',
drive: 'main',
resourceId: 'root',
subject: { type: 'user', id: 'bob' },
permissions: ['read'],
inherit: 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,
listGrants,
},
},
})
render(<ManageProbe />, { wrapper: Harness })
await act(async () => {
screen.getByRole('button', { name: 'open root' }).click()
})
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))
// The open cycle has run (affordances fetched), so any grants fetch would have
// fired by now — but Manage is closed, so the grants list must stay dormant.
await waitFor(() => expect(affordances).toHaveBeenCalled())
expect(listGrants).not.toHaveBeenCalled()
await act(async () => {
screen.getByRole('button', { name: 'open manage' }).click()
})
await waitFor(() => expect(listGrants).toHaveBeenCalledTimes(1))
expect(listGrants).toHaveBeenCalledWith('root', 'main')
await waitFor(() => expect(screen.getByTestId('grants-count').textContent).toBe('1'))
expect(
lastHarnessQueryClient?.getQueryData(
desktopQueryKeys.gfsGrants(':user-a:team-a', 'root', 'main')
)
).toEqual([expect.objectContaining({ id: 'grant-42' })])
expect(lastHarnessQueryClient?.getQueryData(['gfs', 'main', 'root', 'grants'])).toBeUndefined()
})
it('refetches the grants list when refreshGrants runs', async () => {
const listGrants = vi.fn(async () => [])
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,
},
},
})
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(listGrants).toHaveBeenCalledTimes(1))
await act(async () => {
screen.getByRole('button', { name: 'refresh grants' }).click()
})
await waitFor(() => expect(listGrants).toHaveBeenCalledTimes(2))
})
it('revokes a grant by id and refetches the grants list on success', async () => {
const revokeGrant = vi.fn(async () => undefined)
const listGrants = vi.fn(async () => [
{
id: 'grant-42',
drive: 'main',
resourceId: 'root',
subject: { type: 'user', id: 'bob' },
permissions: ['read'],
inherit: 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'],
canDelegate: true,
grantableBits: ['read'],
canCreateShare: false,
})),
listGrants,
revokeGrant,
},
},
})
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(listGrants).toHaveBeenCalledTimes(1))
await act(async () => {
screen.getByRole('button', { name: 'revoke grant' }).click()
})
await waitFor(() => expect(revokeGrant).toHaveBeenCalledWith('grant-42'))
// onSuccess: refreshGrants invalidates the exact grants key → active refetch.
await waitFor(() => expect(listGrants).toHaveBeenCalledTimes(2))
})
it('forwards the inherit flag (true and false) to window.clerum.gfs.grant', async () => {
const grant = 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,
})),
grant,
},
},
})
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: 'grant inherit true' }).click()
})
await waitFor(() =>
expect(grant).toHaveBeenCalledWith('root', ['user:bob'], ['read'], 'main', true)
)
await act(async () => {
screen.getByRole('button', { name: 'grant inherit false' }).click()
})
await waitFor(() =>
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'))
})
// R1-M3 — a total inherited-derivation failure (the file itself cannot be
// re-resolved for the walk) must surface as controller error state instead
// of silently collapsing to an empty list.
// R1-H3: a classified mid-walk failure no longer throws — the coverage
// state ('unavailable') tells the dialog which notice to show, and only a
// raw session 401 still surfaces through inheritedAccessError.
it('exposes inheritedCoverage unavailable when a mid-walk resolve fails', async () => {
let resolveCalls = 0
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
// The navigation resolve succeeds; the derivation's own resolve of
// the same file then fails outright.
resolve: vi.fn(async () => {
resolveCalls += 1
if (resolveCalls > 1) throw new Error('Error: 500 resolve_failed')
return {
resourceId: 'file-1',
parentResourceId: 'folder-1',
gfsUri: 'gfs://main/file-1',
name: 'report.txt',
kind: 'file',
version: 1,
}
}),
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: vi.fn(async () => []),
},
},
})
render(<ManageProbe />, { wrapper: Harness })
await act(async () => {
screen.getByRole('button', { name: 'open root' }).click()
})
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('file-1'))
await act(async () => {
screen.getByRole('button', { name: 'open manage' }).click()
})
await waitFor(() =>
expect(screen.getByTestId('inherited-coverage').textContent).toBe('unavailable')
)
expect(screen.getByTestId('inherited-error').textContent).toBe('none')
})
// An 'unavailable' coverage is a FAILED walk, not an observation. Caching it
// under the app's Infinity staleTime would keep the failure on screen as if
// it were authoritative; reopening Share must retry the walk.
it('retries an unavailable inherited derivation when Share is reopened', async () => {
const resolve = vi.fn(async (uri: string) => {
// The navigation resolve succeeds; every later resolve (the derivation's
// own walk) fails transiently.
if (uri.endsWith('/root')) {
return {
resourceId: 'file-1',
parentResourceId: 'folder-1',
gfsUri: 'gfs://main/file-1',
name: 'report.txt',
kind: 'file',
version: 1,
}
}
throw new Error('Error: 500 resolve_failed')
})
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
resolve,
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: vi.fn(async () => []),
},
},
})
render(<ManageProbe />, { wrapper: Harness })
await act(async () => {
screen.getByRole('button', { name: 'open root' }).click()
})
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('file-1'))
await act(async () => {
screen.getByRole('button', { name: 'open manage' }).click()
})
await waitFor(() =>
expect(screen.getByTestId('inherited-coverage').textContent).toBe('unavailable')
)
await act(async () => {
screen.getByRole('button', { name: 'close manage' }).click()
})
const before = resolve.mock.calls.length
await act(async () => {
screen.getByRole('button', { name: 'open manage' }).click()
})
// The failed walk is retried on reopen instead of being served from cache.
await waitFor(() => expect(resolve.mock.calls.length).toBeGreaterThan(before))
})
// A move changes the ANCESTRY of the open resource, and the open
// Share/Manage dialog shows rows derived from that ancestry. The dialog must
// re-read them: keeping the pre-move observation would present inherited
// access that no longer exists.
it('re-reads the open inherited access when a move affects its ancestry', async () => {
const listGrants = vi.fn(async () => [])
const listShares = vi.fn(async () => [])
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
resolve: vi.fn(async (uri: string) => {
const id = uri.split('/').pop()!
if (id === 'folder1') {
return {
resourceId: 'folder-1',
parentResourceId: null,
gfsUri: 'gfs://main/folder1',
name: 'Team docs',
kind: 'directory',
version: 1,
}
}
return {
resourceId: 'file-1',
parentResourceId: 'folder-1',
gfsUri: 'gfs://main/file1',
name: 'report.txt',
kind: 'file',
version: 1,
}
}),
listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
affordances: vi.fn(async () => ({
held: ['read', 'manage_acl'],
canDelegate: true,
grantableBits: ['read'],
canCreateShare: false,
})),
listGrants,
listShares,
},
},
})
render(<ManageProbe />, { wrapper: Harness })
await act(async () => {
screen.getByRole('button', { name: 'open root' }).click()
})
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('file-1'))
await act(async () => {
screen.getByRole('button', { name: 'open manage' }).click()
})
await waitFor(() => expect(listGrants).toHaveBeenCalled())
const client = lastHarnessQueryClient!
const scope = ':user-a:team-a'
const inheritedKey = desktopQueryKeys.gfsInheritedAccess(scope, 'file-1', 'main')
const inheritedQuery = client.getQueryCache().find({ queryKey: inheritedKey })!
const before = inheritedQuery.state.dataUpdatedAt
expect(before).toBeGreaterThan(0)
// The oldest crumb is an ancestor of the open resource: moving it changes
// what the open resource inherits.
await act(async () => {
screen.getByRole('button', { name: 'move oldest ancestor' }).click()
})
await waitFor(() => expect(inheritedQuery.state.dataUpdatedAt).not.toBe(before))
})
// Every response and rejection crosses the real client/HTTP fixture seam.
// The observable contract is session state and protected metadata, not a
// briefly presented error string before the authority boundary clears it.
for (const route of ['resolve', 'grants', 'shares'] as const) {
for (const [status, code] of [
[401, 'unauthorized'],
[403, 'desktop_user_retired'],
[403, 'gfs_operator_link_invalid'],
[403, 'manage_acl_required'],
] as const) {
it(`handles inherited ${route} ${code} through the correct authority boundary`, async () => {
const targetId = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
const parentId = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'
const target = await resolveResource(
resolvedFile(targetId, 'report.txt', {
parentResourceId: parentId,
})
)
const parent = await resolveResource(resolvedDirectory(parentId, 'team-docs'))
const body = { code, message: code }
const failure =
route === 'resolve'
? await resolveDeniedMessage(target.gfsUri, body, status)
: route === 'grants'
? await listGrantsFailureMessage(status, body)
: await listSharesFailureMessage(status, body)
expect(failure).toContain(`httpStatus=${status}`)
expect(failure).toContain(code)
const directGrants = await grantsListPage([
{
id: 'direct-grant',
drive: 'main',
resourceId: targetId,
subject: { type: 'user', id: 'bob' },
permissions: ['read'],
inherit: false,
},
])
const directShares = await sharesListPage([
{
id: 'direct-share',
drive: 'main',
resourceId: targetId,
subject: { type: 'user', id: 'carol' },
permissions: ['read'],
includeDescendants: false,
},
])
const emptyGrants = await grantsListPage([])
const emptyShares = await sharesListPage([])
const accessible = await listAccessiblePage([])
const children = await listChildrenPage([])
const affordances = await affordancesResult(heldAffordances(['read', 'manage_acl']))
let manageReadStarted = false
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => accessible),
resolve: vi.fn(async (uri: string) => {
if (uri.endsWith(parentId.replace(/-/g, '')) || uri.endsWith(parentId))
return parent
if (manageReadStarted && route === 'resolve') throw new Error(failure)
return target
}),
listChildren: vi.fn(async () => children),
affordances: vi.fn(async () => affordances),
listGrants: vi.fn(async (resourceId: string) => {
if (resourceId === targetId) return directGrants
if (route === 'grants') throw new Error(failure)
return emptyGrants
}),
listShares: vi.fn(async (resourceId: string) => {
if (resourceId === targetId) return directShares
if (route === 'shares') throw new Error(failure)
return emptyShares
}),
},
},
})
render(<ManageProbe />, { wrapper: Harness })
await act(async () => screen.getByRole('button', { name: 'open root' }).click())
await waitFor(() => expect(screen.getByTestId('current').textContent).toBe(targetId))
const client = lastHarnessQueryClient!
const scope = ':user-a:team-a'
const grantsKey = desktopQueryKeys.gfsGrants(scope, targetId, 'main')
const sharesKey = desktopQueryKeys.gfsShares(scope, targetId, 'main')
await act(async () => {
client.setQueryData(grantsKey, directGrants)
client.setQueryData(sharesKey, directShares)
})
expect(client.getQueryData(grantsKey)).toEqual(directGrants)
expect(client.getQueryData(sharesKey)).toEqual(directShares)
manageReadStarted = true
await act(async () => screen.getByRole('button', { name: 'open manage' }).click())
if (code === 'manage_acl_required') {
await waitFor(() =>
expect(screen.getByTestId('inherited-coverage').textContent).toBe(
route === 'resolve' ? 'read-boundary' : 'acl-limited'
)
)
expect(screen.getByTestId('access-state').textContent).toBe('active')
expect(screen.getByTestId('current').textContent).toBe(targetId)
expect(screen.getByTestId('grants-count').textContent).toBe('1')
expect(screen.getByTestId('shares-count').textContent).toBe('1')
} else {
await waitFor(() =>
expect(screen.getByTestId('access-state').textContent).toBe('revoked')
)
expect(screen.getByTestId('current').textContent).toBe('none')
expect(screen.getByTestId('crumbs').textContent).toBe('')
expect(screen.getByTestId('held-permissions').textContent).toBe('none')
expect(screen.getByTestId('grants-count').textContent).toBe('0')
expect(screen.getByTestId('shares-count').textContent).toBe('0')
expect(client.getQueryData(grantsKey)).toBeUndefined()
expect(client.getQueryData(sharesKey)).toBeUndefined()
}
})
}
}
})
// A move committed by ONE surface must reach the Share/Manage dialog ANOTHER
// surface has open. The Files page opened a deep descendant by URI — its
// ancestry lives in ITS controller, and the children caches that could
// connect it to the moved ancestor were never loaded — while the sidebar, a
// SEPARATE controller with its own crumbs, moves that ancestor.
function TwoSurfaceProbe() {
const [manageOpen, setManageOpen] = useState(false)
const files = useGfsBrowserController({ grantsListEnabled: manageOpen })
const sidebar = useGfsBrowserController()
return (
<>
<div data-testid="files-current">{files.current?.resourceId ?? 'none'}</div>
<div data-testid="files-crumbs">
{files.crumbs.map(crumb => crumb.resourceId).join(' / ')}
</div>
<button type="button" onClick={() => swallow(files.openUri('gfs://main/leaf1'))}>
open leaf
</button>
<button type="button" onClick={() => setManageOpen(true)}>
open manage
</button>
<button
type="button"
onClick={() =>
swallow(
sidebar.convergeCommittedMove(
{
resourceId: 'ancestor-1',
destinationId: 'destination-1',
oldParentId: null,
},
{ version: 2 }
)
)
}
>
move ancestor
</button>
</>
)
}
describe('useGfsBrowserController — cross-surface move convergence (RP-005)', () => {
afterEach(() => {
cleanup()
lastHarnessQueryClient = null
vi.restoreAllMocks()
})
it("re-reads another surface's open inherited access when a move affects its ancestry", async () => {
const listGrants = vi.fn(async () => [])
const listShares = vi.fn(async () => [])
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
resolve: vi.fn(async (uri: string) => {
const id = uri.split('/').pop()!
if (id === 'leaf1') {
return {
resourceId: 'leaf-1',
parentResourceId: 'parent-1',
gfsUri: 'gfs://main/leaf1',
name: 'leaf.txt',
kind: 'file',
version: 1,
}
}
if (id === 'parent1') {
return {
resourceId: 'parent-1',
parentResourceId: 'ancestor-1',
gfsUri: 'gfs://main/parent1',
name: 'Parent',
kind: 'directory',
version: 1,
}
}
return {
resourceId: 'ancestor-1',
parentResourceId: null,
gfsUri: 'gfs://main/ancestor1',
name: 'Ancestor',
kind: 'directory',
version: 1,
}
}),
// No children listing is ever loaded, so the shared cache holds no
// child→parent link that could connect the open leaf to its
// ancestor: the ancestry exists only in the Files controller.
listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
affordances: vi.fn(async () => ({
held: ['read', 'manage_acl'],
canDelegate: true,
grantableBits: ['read'],
canCreateShare: false,
})),
listGrants,
listShares,
},
},
})
render(<TwoSurfaceProbe />, { wrapper: Harness })
await act(async () => {
screen.getByRole('button', { name: 'open leaf' }).click()
})
await waitFor(() => expect(screen.getByTestId('files-current').textContent).toBe('leaf-1'))
expect(screen.getByTestId('files-crumbs').textContent).toBe('ancestor-1 / parent-1 / leaf-1')
await act(async () => {
screen.getByRole('button', { name: 'open manage' }).click()
})
await waitFor(() => expect(listGrants).toHaveBeenCalled())
const client = lastHarnessQueryClient!
const scope = ':user-a:team-a'
const inheritedKey = desktopQueryKeys.gfsInheritedAccess(scope, 'leaf-1', 'main')
const inheritedQuery = client.getQueryCache().find({ queryKey: inheritedKey })!
const before = inheritedQuery.state.dataUpdatedAt
expect(before).toBeGreaterThan(0)
// The OTHER surface moves the open leaf's ancestor.
await act(async () => {
screen.getByRole('button', { name: 'move ancestor' }).click()
})
await waitFor(() => expect(inheritedQuery.state.dataUpdatedAt).not.toBe(before))
})
it('publishes the open location in the registry order the relocation helper assumes', async () => {
// The controller's CRUMBS are root-first (ancestor-1 / parent-1 / leaf-1),
// but the shared open-location registry documents — and the relocation
// helper slice()s — a NEAREST-FIRST chain. Publishing the crumbs without
// reversing them made a relocation of an intermediate ancestor keep the
// stale ancestors ABOVE it and drop the still-real ones BELOW it.
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
gfs: {
listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
resolve: vi.fn(async (uri: string) => {
const id = uri.split('/').pop()!
if (id === 'leaf1') {
return {
resourceId: 'leaf-1',
parentResourceId: 'parent-1',
gfsUri: 'gfs://main/leaf1',
name: 'leaf.txt',
kind: 'file',
version: 1,
}
}
if (id === 'parent1') {
return {
resourceId: 'parent-1',
parentResourceId: 'ancestor-1',
gfsUri: 'gfs://main/parent1',
name: 'Parent',
kind: 'directory',
version: 1,
}
}
return {
resourceId: 'ancestor-1',
parentResourceId: null,
gfsUri: 'gfs://main/ancestor1',
name: 'Ancestor',
kind: 'directory',
version: 1,
}
}),
listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
},
},
})
render(<TwoSurfaceProbe />, { wrapper: Harness })
await act(async () => {
screen.getByRole('button', { name: 'open leaf' }).click()
})
await waitFor(() => expect(screen.getByTestId('files-current').textContent).toBe('leaf-1'))
expect(screen.getByTestId('files-crumbs').textContent).toBe('ancestor-1 / parent-1 / leaf-1')
const client = lastHarnessQueryClient!
// Nearest first: parent-1 before ancestor-1. The sidebar mount has
// nothing open, so the files mount is the registry's only entry.
expect(readGfsOpenLocations(client, ':user-a:team-a')).toEqual([
{ resourceId: 'leaf-1', ancestorResourceIds: ['parent-1', 'ancestor-1'] },
])
})
})