Skip to content

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

TypeScript

feat(control-ui): refresh GFS views from entity changes

Josuéc003d91bd6dc
diff --git a/control-ui/components/GfsBrowser.tsx b/control-ui/components/GfsBrowser.tsx
index 83de3bf29..03de764a2 100644
--- a/control-ui/components/GfsBrowser.tsx
+++ b/control-ui/components/GfsBrowser.tsx
@@ -34,6 +34,7 @@ import {
} from '@components/icons'
import { Button } from '@components/ui'
import { apiGet, apiSend, gfsDownload, isSilentApiError } from '@lib/api'
+import { parseEntityChangeFrame } from '@lib/entityChangeStream'
import { isGfsDocumentFile } from '@lib/gfsDocumentFile'
import {
GfsUploadCapabilityError,
@@ -72,6 +73,42 @@ interface TreePage {
rootResourceId?: string
}
+type OpenPreviewState =
+ | {
+ kind: 'image'
+ gfsUri: string
+ byteLength: number
+ fileName: string
+ mimeType: string
+ rid: string
+ version: number
+ unavailable: boolean
+ }
+ | {
+ kind: 'markdown'
+ gfsUri: string
+ byteLength: number
+ fileName: string
+ rid: string
+ version: number
+ unavailable: boolean
+ }
+ | {
+ kind: 'video'
+ gfsUri: string
+ byteLength: number
+ fileName: string
+ mimeType: string
+ rid: string
+ version: number
+ unavailable: boolean
+ }
+
+type ResolvedPreviewUpdate =
+ | Extract<OpenPreviewState, { kind: 'image' }>
+ | Extract<OpenPreviewState, { kind: 'markdown' }>
+ | Extract<OpenPreviewState, { kind: 'video' }>
+
interface Crumb {
/** null = the synthetic drive root (listed via /gfs/tree). */
id: string | null
@@ -238,23 +275,24 @@ export function GfsBrowser(): React.JSX.Element {
const [moveTarget, setMoveTarget] = useState<GfsChild | null>(null)
const draggingResourceRef = useRef<GfsChild | null>(null)
const movingResourceRef = useRef<string | null>(null)
- const [imagePreview, setImagePreview] = useState<{
- byteLength: number
- fileName: string
- mimeType: string
- rid: string
- } | null>(null)
- const [markdownPreview, setMarkdownPreview] = useState<{
- byteLength: number
- fileName: string
- rid: string
- } | null>(null)
- const [videoPreview, setVideoPreview] = useState<{
- byteLength: number
- fileName: string
- mimeType: string
- rid: string
- } | null>(null)
+ const [imagePreview, setImagePreview] = useState<Extract<
+ OpenPreviewState,
+ { kind: 'image' }
+ > | null>(null)
+ const [markdownPreview, setMarkdownPreview] = useState<Extract<
+ OpenPreviewState,
+ { kind: 'markdown' }
+ > | null>(null)
+ const [videoPreview, setVideoPreview] = useState<Extract<
+ OpenPreviewState,
+ { kind: 'video' }
+ > | null>(null)
+ const [previewReloadVersion, setPreviewReloadVersion] = useState(0)
+ const previewRefreshGenerationRef = useRef(0)
+ const openPreviewsRef = useRef<OpenPreviewState[]>([])
+ openPreviewsRef.current = [imagePreview, markdownPreview, videoPreview].filter(
+ (preview): preview is OpenPreviewState => preview !== null
+ )
// Resource IDs currently streaming a download (disables that row's button).
const [downloadingIds, setDownloadingIds] = useState<ReadonlySet<string>>(() => new Set())
@@ -295,6 +333,8 @@ export function GfsBrowser(): React.JSX.Element {
}, [])
const current = crumbs[crumbs.length - 1]
+ const currentCrumbRef = useRef(current)
+ currentCrumbRef.current = current
const currentLabel = current?.name === '/' ? DRIVE : current?.name || DRIVE
const load = useCallback(
@@ -416,6 +456,7 @@ export function GfsBrowser(): React.JSX.Element {
// runs a BACKGROUND revalidation instead of a clearing reload, so the user
// keeps the cached rows (no spinner) while the server state re-syncs.
const revalidateNextLoadRef = useRef(false)
+ const streamCursorRef = useRef<string | null>(null)
// Warm the cache for every folder row visible in the current view.
// Re-runs whenever the listing changes (folder navigation, refresh,
@@ -462,6 +503,151 @@ export function GfsBrowser(): React.JSX.Element {
// Reload whenever the current folder changes (navigation).
}, [current, load])
+ useEffect(() => {
+ const controller = new AbortController()
+ let retryTimer: ReturnType<typeof setTimeout> | null = null
+ let retryDelay = 500
+ let active = true
+
+ const invalidateVisibleState = (cursor?: string) => {
+ if (cursor) streamCursorRef.current = cursor
+ childCacheRef.current.clear()
+ revalidateNextLoadRef.current = false
+ setSelected(null)
+ setRenameTarget(null)
+ setDeleteOpen(false)
+ const previews = openPreviewsRef.current
+ if (previews.length > 0) {
+ const generation = ++previewRefreshGenerationRef.current
+ setImagePreview(preview => (preview ? { ...preview, unavailable: true } : preview))
+ setMarkdownPreview(preview => (preview ? { ...preview, unavailable: true } : preview))
+ setVideoPreview(preview => (preview ? { ...preview, unavailable: true } : preview))
+ setPreviewReloadVersion(version => version + 1)
+ void Promise.all<ResolvedPreviewUpdate | null>(
+ previews.map(async preview => {
+ try {
+ const resolved = (await apiGet('/api/v1/gfs/resolve', {
+ uri: preview.gfsUri,
+ })) as {
+ kind: string
+ name: string
+ bytes: number
+ version: number
+ rid: string
+ }
+ if (resolved.kind !== 'file') return null
+ const imageMimeType = gfsImagePreviewMimeType(resolved.name)
+ const videoMimeType = gfsVideoPreviewMimeType(resolved.name)
+ const shared = {
+ gfsUri: preview.gfsUri,
+ byteLength: resolved.bytes,
+ fileName: resolved.name,
+ rid: resolved.rid,
+ version: resolved.version,
+ unavailable: false,
+ }
+ if (preview.kind === 'image') {
+ return imageMimeType ? { ...shared, kind: 'image', mimeType: imageMimeType } : null
+ }
+ if (preview.kind === 'video') {
+ return videoMimeType ? { ...shared, kind: 'video', mimeType: videoMimeType } : null
+ }
+ return isGfsMarkdownPreviewFile(resolved.name)
+ ? { ...shared, kind: 'markdown' }
+ : null
+ } catch {
+ return null
+ }
+ })
+ ).then(updates => {
+ if (generation !== previewRefreshGenerationRef.current) return
+ for (const update of updates) {
+ if (!update) continue
+ if (update.kind === 'image') {
+ setImagePreview(current => (current?.gfsUri === update.gfsUri ? update : current))
+ } else if (update.kind === 'video') {
+ setVideoPreview(current => (current?.gfsUri === update.gfsUri ? update : current))
+ } else {
+ setMarkdownPreview(current => (current?.gfsUri === update.gfsUri ? update : current))
+ }
+ }
+ setPreviewReloadVersion(version => version + 1)
+ })
+ }
+ const visibleCrumb = currentCrumbRef.current
+ if (visibleCrumb) void load(visibleCrumb)
+ }
+
+ async function consume(): Promise<void> {
+ while (active && !controller.signal.aborted) {
+ try {
+ const cursor = streamCursorRef.current
+ const query = cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''
+ const response = await fetch(`/control-api/api/v1/gfs/entity-changes/stream${query}`, {
+ cache: 'no-store',
+ credentials: 'include',
+ headers: { accept: 'application/x-ndjson' },
+ signal: controller.signal,
+ })
+ if (!response.ok || !response.body) {
+ throw new Error(`Entity-change stream returned ${response.status}`)
+ }
+ retryDelay = 500
+ const reader = response.body.getReader()
+ const decoder = new TextDecoder()
+ let pending = ''
+ try {
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ pending += decoder.decode(value, { stream: true })
+ if (pending.length > 32 * 1024)
+ throw new Error('Entity-change frame exceeded its limit')
+ let newline = pending.indexOf('\n')
+ while (newline >= 0) {
+ const line = pending.slice(0, newline).replace(/\r$/, '')
+ pending = pending.slice(newline + 1)
+ const frame = parseEntityChangeFrame(line)
+ if (!frame) {
+ newline = pending.indexOf('\n')
+ continue
+ }
+ streamCursorRef.current = frame.cursor
+ if (frame.type === 'resync_required' || frame.type === 'scope.invalidated') {
+ invalidateVisibleState(frame.cursor)
+ } else if (frame.type === 'stream.closing') {
+ await reader.cancel()
+ break
+ }
+ newline = pending.indexOf('\n')
+ }
+ }
+ } finally {
+ reader.releaseLock()
+ }
+ if (!controller.signal.aborted) throw new Error('Entity-change stream ended')
+ } catch {
+ if (!active || controller.signal.aborted) return
+ // A reconnect may have missed commits. Refetch current authorized state
+ // before retrying rather than assuming the old cursor is complete.
+ invalidateVisibleState()
+ await new Promise<void>(resolve => {
+ retryTimer = setTimeout(resolve, retryDelay + Math.random() * retryDelay)
+ })
+ retryTimer = null
+ retryDelay = Math.min(retryDelay * 2, 15_000)
+ }
+ }
+ }
+
+ void consume()
+ return () => {
+ active = false
+ controller.abort()
+ if (retryTimer) clearTimeout(retryTimer)
+ }
+ }, [load])
+
useEffect(() => {
if ((!selected && !renameTarget) || imagePreview || markdownPreview || videoPreview) return
function handleKeyDown(event: KeyboardEvent) {
@@ -498,24 +684,40 @@ export function GfsBrowser(): React.JSX.Element {
const mimeType = gfsImagePreviewMimeType(child.name)
if (mimeType) {
setImagePreview({
+ kind: 'image',
+ gfsUri: child.gfsUri,
byteLength: child.bytes,
fileName: child.name,
mimeType,
rid: child.rid,
+ version: child.version,
+ unavailable: false,
})
return true
}
if (isGfsMarkdownPreviewFile(child.name)) {
- setMarkdownPreview({ byteLength: child.bytes, fileName: child.name, rid: child.rid })
+ setMarkdownPreview({
+ kind: 'markdown',
+ gfsUri: child.gfsUri,
+ byteLength: child.bytes,
+ fileName: child.name,
+ rid: child.rid,
+ version: child.version,
+ unavailable: false,
+ })
return true
}
const videoMimeType = gfsVideoPreviewMimeType(child.name)
if (videoMimeType) {
setVideoPreview({
+ kind: 'video',
+ gfsUri: child.gfsUri,
byteLength: child.bytes,
fileName: child.name,
mimeType: videoMimeType,
rid: child.rid,
+ version: child.version,
+ unavailable: false,
})
return true
}
@@ -1601,29 +1803,35 @@ export function GfsBrowser(): React.JSX.Element {
{imagePreview ? (
<GfsImagePreview
+ key={previewReloadVersion}
byteLength={imagePreview.byteLength}
fileName={imagePreview.fileName}
mimeType={imagePreview.mimeType}
rid={imagePreview.rid}
+ unavailable={imagePreview.unavailable}
onClose={() => setImagePreview(null)}
/>
) : null}
{markdownPreview ? (
<GfsMarkdownPreview
+ key={previewReloadVersion}
byteLength={markdownPreview.byteLength}
fileName={markdownPreview.fileName}
rid={markdownPreview.rid}
+ unavailable={markdownPreview.unavailable}
onClose={() => setMarkdownPreview(null)}
/>
) : null}
{videoPreview ? (
<GfsVideoPreview
+ key={previewReloadVersion}
byteLength={videoPreview.byteLength}
fileName={videoPreview.fileName}
mimeType={videoPreview.mimeType}
rid={videoPreview.rid}
+ unavailable={videoPreview.unavailable}
onClose={() => setVideoPreview(null)}
/>
) : null}
diff --git a/control-ui/components/GfsImagePreview/index.tsx b/control-ui/components/GfsImagePreview/index.tsx
index 91e5b4c62..b46ffbd66 100644
--- a/control-ui/components/GfsImagePreview/index.tsx
+++ b/control-ui/components/GfsImagePreview/index.tsx
@@ -16,6 +16,7 @@ export function GfsImagePreview({
mimeType,
onClose,
rid,
+ unavailable = false,
}: GfsImagePreviewProps): React.JSX.Element {
const titleId = useId()
const dialogRef = useRef<HTMLElement | null>(null)
@@ -46,6 +47,16 @@ export function GfsImagePreview({
let active = true
let objectUrl: string | null = null
+ if (unavailable) {
+ setPreviewUrl(null)
+ setSourceBlob(null)
+ setPreviewError(null)
+ setCopyState('idle')
+ return () => {
+ active = false
+ }
+ }
+
async function loadPreview(): Promise<void> {
try {
assertGfsImagePreviewSize(byteLength)
@@ -58,7 +69,14 @@ export function GfsImagePreview({
setPreviewUrl(objectUrl)
} catch (error) {
if (!active) return
- setPreviewError(error instanceof Error ? error.message : 'Could not load the image preview')
+ const status = (error as { status?: number } | null)?.status
+ setPreviewError(
+ status === 403 || status === 404
+ ? 'File unavailable.'
+ : error instanceof Error
+ ? error.message
+ : 'Could not load the image preview.'
+ )
}
}
@@ -67,7 +85,7 @@ export function GfsImagePreview({
active = false
if (objectUrl) URL.revokeObjectURL(objectUrl)
}
- }, [byteLength, mimeType, rid])
+ }, [byteLength, mimeType, rid, unavailable])
useEffect(() => {
mountedRef.current = true
@@ -141,7 +159,7 @@ export function GfsImagePreview({
aria-labelledby={titleId}
>
<header className="cu-gfs-image-preview-dialog__header">
- <h3 id={titleId}>{fileName}</h3>
+ <h3 id={titleId}>{unavailable ? 'File unavailable' : fileName}</h3>
<div className="cu-gfs-image-preview-dialog__header-actions">
<Button
className="cu-gfs-image-preview-dialog__copy"
@@ -149,7 +167,7 @@ export function GfsImagePreview({
aria-label={
copyState === 'copied' ? 'Copied image to clipboard' : 'Copy image to clipboard'
}
- disabled={!sourceBlob}
+ disabled={!sourceBlob || unavailable}
onClick={() => void copyImageToClipboard()}
>
<IconCopy width={18} height={18} />
@@ -169,17 +187,21 @@ export function GfsImagePreview({
</div>
</header>
<div className="cu-gfs-image-preview-dialog__body">
- {previewError ? (
+ {unavailable ? (
+ <div className="cu-gfs-image-preview-dialog__loading" role="status">
+ File unavailable.
+ </div>
+ ) : previewError ? (
<div className="cu-banner cu-banner--error" role="alert">
{previewError}
</div>
) : null}
- {!previewError && !previewUrl ? (
+ {!unavailable && !previewError && !previewUrl ? (
<div className="cu-gfs-image-preview-dialog__loading" role="status">
Loading image preview…
</div>
) : null}
- {previewUrl && !previewError ? (
+ {!unavailable && previewUrl && !previewError ? (
<img
alt={`Preview of ${fileName}`}
className="cu-gfs-image-preview-dialog__image"
diff --git a/control-ui/components/GfsImagePreview/types.ts b/control-ui/components/GfsImagePreview/types.ts
index c5675d483..206133b8c 100644
--- a/control-ui/components/GfsImagePreview/types.ts
+++ b/control-ui/components/GfsImagePreview/types.ts
@@ -2,6 +2,7 @@ export interface GfsImagePreviewProps {
byteLength: number
fileName: string
mimeType: string
+ unavailable?: boolean
onClose: () => void
rid: string
}
diff --git a/control-ui/components/GfsMarkdownPreview/index.tsx b/control-ui/components/GfsMarkdownPreview/index.tsx
index d7fceccd0..b32875868 100644
--- a/control-ui/components/GfsMarkdownPreview/index.tsx
+++ b/control-ui/components/GfsMarkdownPreview/index.tsx
@@ -70,6 +70,7 @@ export function GfsMarkdownPreview({
fileName,
onClose,
rid,
+ unavailable = false,
}: GfsMarkdownPreviewProps): React.JSX.Element {
const titleId = useId()
const dialogRef = useRef<HTMLElement | null>(null)
@@ -108,6 +109,15 @@ export function GfsMarkdownPreview({
useEffect(() => {
let active = true
+ if (unavailable) {
+ setSource(null)
+ setPreviewError(null)
+ setCopyState('idle')
+ return () => {
+ active = false
+ }
+ }
+
async function loadPreview(): Promise<void> {
try {
assertGfsMarkdownPreviewSize(byteLength)
@@ -117,8 +127,13 @@ export function GfsMarkdownPreview({
if (active) setSource(markdown)
} catch (error) {
if (!active) return
+ const status = (error as { status?: number } | null)?.status
setPreviewError(
- error instanceof Error ? error.message : 'Could not load the Markdown preview'
+ status === 403 || status === 404
+ ? 'File unavailable.'
+ : error instanceof Error
+ ? error.message
+ : 'Could not load the Markdown preview.'
)
}
}
@@ -127,7 +142,7 @@ export function GfsMarkdownPreview({
return () => {
active = false
}
- }, [byteLength, rid])
+ }, [byteLength, rid, unavailable])
function markCopyState(state: 'copied' | 'error'): boolean {
if (!mountedRef.current) return false
@@ -176,7 +191,7 @@ export function GfsMarkdownPreview({
aria-labelledby={titleId}
>
<header className="cu-gfs-markdown-preview-dialog__header">
- <h3 id={titleId}>{fileName}</h3>
+ <h3 id={titleId}>{unavailable ? 'File unavailable' : fileName}</h3>
<div className="cu-gfs-markdown-preview-dialog__header-actions">
<Button
className="cu-gfs-markdown-preview-dialog__copy"
@@ -186,7 +201,7 @@ export function GfsMarkdownPreview({
? 'Copied preview contents to clipboard'
: 'Copy preview contents to clipboard'
}
- disabled={source === null}
+ disabled={source === null || unavailable}
onClick={() => void copySourceToClipboard()}
>
<IconCopy width={18} height={18} />
@@ -206,17 +221,21 @@ export function GfsMarkdownPreview({
</div>
</header>
<div className="cu-gfs-markdown-preview-dialog__body">
- {previewError ? (
+ {unavailable ? (
+ <div className="cu-gfs-markdown-preview-dialog__loading" role="status">
+ File unavailable.
+ </div>
+ ) : previewError ? (
<div className="cu-banner cu-banner--error" role="alert">
{previewError}
</div>
) : null}
- {!previewError && source === null ? (
+ {!unavailable && !previewError && source === null ? (
<div className="cu-gfs-markdown-preview-dialog__loading" role="status">
Loading preview…
</div>
) : null}
- {source !== null && !previewError ? (
+ {!unavailable && source !== null && !previewError ? (
isPlainText ? (
<article
aria-label={`Text preview of ${fileName}`}
diff --git a/control-ui/components/GfsMarkdownPreview/types.ts b/control-ui/components/GfsMarkdownPreview/types.ts
index f8461feda..9b0aabcd1 100644
--- a/control-ui/components/GfsMarkdownPreview/types.ts
+++ b/control-ui/components/GfsMarkdownPreview/types.ts
@@ -1,6 +1,7 @@
export interface GfsMarkdownPreviewProps {
byteLength: number
fileName: string
+ unavailable?: boolean
onClose: () => void
rid: string
}
diff --git a/control-ui/components/GfsVideoPreview/index.tsx b/control-ui/components/GfsVideoPreview/index.tsx
index 31a72626c..26656943f 100644
--- a/control-ui/components/GfsVideoPreview/index.tsx
+++ b/control-ui/components/GfsVideoPreview/index.tsx
@@ -14,6 +14,7 @@ export function GfsVideoPreview({
mimeType,
onClose,
rid,
+ unavailable = false,
}: GfsVideoPreviewProps): React.JSX.Element {
const titleId = useId()
const dialogRef = useRef<HTMLElement | null>(null)
@@ -39,6 +40,14 @@ export function GfsVideoPreview({
let active = true
let objectUrl: string | null = null
+ if (unavailable) {
+ setPreviewUrl(null)
+ setPreviewError(null)
+ return () => {
+ active = false
+ }
+ }
+
async function loadPreview(): Promise<void> {
try {
assertGfsVideoPreviewSize(byteLength)
@@ -49,7 +58,14 @@ export function GfsVideoPreview({
setPreviewUrl(objectUrl)
} catch (error) {
if (!active) return
- setPreviewError(error instanceof Error ? error.message : 'Could not load the video preview')
+ const status = (error as { status?: number } | null)?.status
+ setPreviewError(
+ status === 403 || status === 404
+ ? 'File unavailable.'
+ : error instanceof Error
+ ? error.message
+ : 'Could not load the video preview.'
+ )
}
}
@@ -58,7 +74,7 @@ export function GfsVideoPreview({
active = false
if (objectUrl) URL.revokeObjectURL(objectUrl)
}
- }, [byteLength, mimeType, rid])
+ }, [byteLength, mimeType, rid, unavailable])
return createPortal(
<div
@@ -76,7 +92,7 @@ export function GfsVideoPreview({
aria-labelledby={titleId}
>
<header className="cu-gfs-video-preview-dialog__header">
- <h3 id={titleId}>{fileName}</h3>
+ <h3 id={titleId}>{unavailable ? 'File unavailable' : fileName}</h3>
<Button
className="cu-gfs-video-preview-dialog__close"
data-preview-close
@@ -88,17 +104,21 @@ export function GfsVideoPreview({
</Button>
</header>
<div className="cu-gfs-video-preview-dialog__body">
- {previewError ? (
+ {unavailable ? (
+ <div className="cu-gfs-video-preview-dialog__loading" role="status">
+ File unavailable.
+ </div>
+ ) : previewError ? (
<div className="cu-banner cu-banner--error" role="alert">
{previewError}
</div>
) : null}
- {!previewError && !previewUrl ? (
+ {!unavailable && !previewError && !previewUrl ? (
<div className="cu-gfs-video-preview-dialog__loading" role="status">
Loading video preview…
</div>
) : null}
- {previewUrl && !previewError ? (
+ {!unavailable && previewUrl && !previewError ? (
<video
aria-label={`Video preview of ${fileName}`}
className="cu-gfs-video-preview-dialog__video"
diff --git a/control-ui/components/GfsVideoPreview/types.ts b/control-ui/components/GfsVideoPreview/types.ts
index cd1971ec4..f9e6ce24d 100644
--- a/control-ui/components/GfsVideoPreview/types.ts
+++ b/control-ui/components/GfsVideoPreview/types.ts
@@ -2,6 +2,7 @@ export interface GfsVideoPreviewProps {
byteLength: number
fileName: string
mimeType: string
+ unavailable?: boolean
onClose: () => void
rid: string
}
diff --git a/control-ui/components/__tests__/GfsBrowser.test.tsx b/control-ui/components/__tests__/GfsBrowser.test.tsx
index 36deb76fb..118777eb7 100644
--- a/control-ui/components/__tests__/GfsBrowser.test.tsx
+++ b/control-ui/components/__tests__/GfsBrowser.test.tsx
@@ -136,6 +136,20 @@ describe('GfsBrowser', () => {
mockGetGfsShares.mockReset()
mockGetHosts.mockReset()
mockGetRecipes.mockReset()
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
+ },
+ })
+ return new Response(body, {
+ status: 200,
+ headers: { 'content-type': 'application/x-ndjson' },
+ })
+ })
+ )
mockPutGfsGrant.mockReset()
mockGfsDownload.mockReset()
mockGfsFetchFileBlob.mockReset()
@@ -407,6 +421,153 @@ describe('GfsBrowser', () => {
)
})
+ it('updates a second authenticated browser session from the coarse stream after a remote create', async () => {
+ const rootId = '11111111-1111-1111-1111-111111111111'
+ const streamControllers: ReadableStreamDefaultController<Uint8Array>[] = []
+ let created = false
+ mockApiGet.mockImplementation(async (path: string) => {
+ if (path === '/api/v1/gfs/tree') {
+ return { rootResourceId: rootId, items: [], nextCursor: null }
+ }
+ if (path.endsWith('/children')) {
+ return {
+ items: created ? [child('remote-folder', 'directory', 9)] : [],
+ nextCursor: null,
+ }
+ }
+ return { items: [], nextCursor: null }
+ })
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ streamControllers.push(controller)
+ init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
+ },
+ })
+ return new Response(body, {
+ status: 200,
+ headers: { 'content-type': 'application/x-ndjson' },
+ })
+ })
+ )
+ mockApiSend.mockImplementationOnce(async () => {
+ created = true
+ const frame = JSON.stringify({
+ schemaVersion: 1,
+ type: 'scope.invalidated',
+ cursor: 'd119f895-1ef8-4e73-8f08-f9754919682a',
+ scopes: ['gfs'],
+ })
+ const encoded = new TextEncoder().encode(`${frame}\n`)
+ for (const controller of streamControllers) controller.enqueue(encoded)
+ return { ok: true }
+ })
+
+ render(
+ <ToastProvider>
+ <div data-testid="operator-session-a">
+ <GfsBrowser />
+ </div>
+ <div data-testid="operator-session-b">
+ <GfsBrowser />
+ </div>
+ </ToastProvider>
+ )
+ const sessionA = within(screen.getByTestId('operator-session-a'))
+ const sessionB = within(screen.getByTestId('operator-session-b'))
+ await waitFor(() => expect(streamControllers).toHaveLength(2))
+ await sessionA.findAllByText('No resources are visible in this folder.')
+ await sessionB.findAllByText('No resources are visible in this folder.')
+
+ fireEvent.click(sessionA.getByRole('button', { name: 'New folder' }))
+ const dialog = await sessionA.findByRole('dialog', { name: 'New folder' })
+ fireEvent.change(within(dialog).getByLabelText('Folder name'), {
+ target: { value: 'remote-folder' },
+ })
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Create folder' }))
+
+ await waitFor(() => expect(mockApiSend).toHaveBeenCalledOnce())
+ expect(await sessionA.findByText('remote-folder')).toBeTruthy()
+ expect(await sessionB.findByText('remote-folder')).toBeTruthy()
+ expect(fetch).toHaveBeenCalledTimes(2)
+ expect(JSON.stringify(mockApiSend.mock.calls)).toContain('remote-folder')
+ })
+
+ it.each(['secret.png', 'secret.md', 'secret.mp4'])(
+ 'purges an open %s preview when the authoritative refetch denies access',
+ async fileName => {
+ const streamControllers: ReadableStreamDefaultController<Uint8Array>[] = []
+ mockApiGet.mockImplementation(async (path: string) => {
+ if (path === '/api/v1/gfs/tree') {
+ return {
+ rootResourceId: '11111111-1111-1111-1111-111111111111',
+ items: [child(fileName, 'file', 12)],
+ nextCursor: null,
+ }
+ }
+ if (path === '/api/v1/gfs/resolve') {
+ throw Object.assign(new Error('access revoked for sensitive subject'), { status: 403 })
+ }
+ return { items: [child(fileName, 'file', 12)], nextCursor: null }
+ })
+ mockGfsFetchFileBlob.mockResolvedValue(
+ new Blob(['# Private title\n\nclassified content'], { type: 'text/plain' })
+ )
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ streamControllers.push(controller)
+ init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
+ },
+ })
+ return new Response(body, {
+ status: 200,
+ headers: { 'content-type': 'application/x-ndjson' },
+ })
+ })
+ )
+
+ renderBrowser()
+ await waitFor(() => expect(streamControllers).toHaveLength(1))
+ fireEvent.click(await screen.findByRole('button', { name: fileName }))
+ const dialog = await screen.findByRole('dialog', { name: fileName })
+ if (fileName.endsWith('.png')) {
+ await within(dialog).findByRole('img', { name: `Preview of ${fileName}` })
+ } else if (fileName.endsWith('.md')) {
+ await within(dialog).findByRole('heading', { name: 'Private title' })
+ expect(within(dialog).getByText('classified content')).toBeTruthy()
+ } else {
+ await within(dialog).findByLabelText(`Video preview of ${fileName}`)
+ }
+
+ const frame = JSON.stringify({
+ schemaVersion: 1,
+ type: 'scope.invalidated',
+ cursor: 'd119f895-1ef8-4e73-8f08-f9754919682a',
+ scopes: ['authorization'],
+ })
+ await act(async () => {
+ streamControllers[0]!.enqueue(new TextEncoder().encode(`${frame}\n`))
+ })
+
+ const unavailableDialog = await screen.findByRole('dialog', { name: 'File unavailable' })
+ expect(unavailableDialog.textContent).not.toContain('access revoked for sensitive subject')
+ expect(unavailableDialog.textContent).not.toContain('classified content')
+ expect(within(unavailableDialog).queryByRole('img')).toBeNull()
+ expect(within(unavailableDialog).queryByLabelText(/Video preview/)).toBeNull()
+ if (!fileName.endsWith('.md')) {
+ await waitFor(() =>
+ expect(mockRevokeObjectUrl).toHaveBeenCalledWith('blob:gfs-image-preview')
+ )
+ }
+ expect(mockGfsFetchFileBlob).toHaveBeenCalledTimes(1)
+ }
+ )
+
it('shortens oversized folder and upload names before operator writes', async () => {
const rootId = '11111111-1111-1111-1111-111111111111'
const rootRid = '11111111111111111111111111111111'
diff --git a/control-ui/lib/__tests__/entityChangeStream.test.ts b/control-ui/lib/__tests__/entityChangeStream.test.ts
new file mode 100644
index 000000000..4ee1953bc
--- /dev/null
+++ b/control-ui/lib/__tests__/entityChangeStream.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest'
+import { parseEntityChangeFrame } from '../entityChangeStream'
+
+const CURSOR = 'a20c37c5-d996-48b0-8f49-a8e2f5f41234'
+
+describe('parseEntityChangeFrame', () => {
+ it('accepts only coarse invalidation scopes and never exposes other payload fields', () => {
+ expect(
+ parseEntityChangeFrame(
+ JSON.stringify({
+ schemaVersion: 1,
+ type: 'scope.invalidated',
+ cursor: CURSOR,
+ scopes: ['gfs', 'authorization', 'forbidden'],
+ entityId: 'must-not-be-forwarded',
+ path: '/private/name',
+ })
+ )
+ ).toEqual({
+ schemaVersion: 1,
+ type: 'scope.invalidated',
+ cursor: CURSOR,
+ scopes: ['gfs', 'authorization'],
+ })
+ })
+
+ it('turns unknown versions and event types into a full safe resynchronization', () => {
+ expect(
+ parseEntityChangeFrame(
+ JSON.stringify({ schemaVersion: 2, type: 'future.event', cursor: CURSOR })
+ )
+ ).toEqual({
+ schemaVersion: 1,
+ type: 'resync_required',
+ cursor: CURSOR,
+ scopes: ['gfs', 'authorization'],
+ })
+ })
+
+ it('rejects malformed JSON and invalid cursors', () => {
+ expect(() => parseEntityChangeFrame('{')).toThrow('Malformed entity-change frame')
+ expect(() =>
+ parseEntityChangeFrame(JSON.stringify({ schemaVersion: 1, type: 'heartbeat', cursor: '1' }))
+ ).toThrow('Invalid entity-change cursor')
+ })
+})
diff --git a/control-ui/lib/entityChangeStream.ts b/control-ui/lib/entityChangeStream.ts
new file mode 100644
index 000000000..ea6abf49e
--- /dev/null
+++ b/control-ui/lib/entityChangeStream.ts
@@ -0,0 +1,63 @@
+export const ENTITY_CHANGE_CURSOR_RE =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+
+export type EntityChangeFrame = {
+ schemaVersion: 1
+ type: 'resync_required' | 'scope.invalidated' | 'heartbeat' | 'stream.closing'
+ cursor: string
+ scopes?: Array<'gfs' | 'authorization'>
+ observedAt?: string
+ reason?: 'max_lifetime' | 'session_expired' | 'server_shutdown' | 'slow_consumer'
+}
+
+/** Parse one NDJSON frame. Unknown versions/types fail safe into full invalidation. */
+export function parseEntityChangeFrame(line: string): EntityChangeFrame | null {
+ if (!line.trim()) return null
+ let value: unknown
+ try {
+ value = JSON.parse(line)
+ } catch {
+ throw new Error('Malformed entity-change frame')
+ }
+ if (!value || typeof value !== 'object') throw new Error('Malformed entity-change frame')
+ const frame = value as Record<string, unknown>
+ if (typeof frame.cursor !== 'string' || !ENTITY_CHANGE_CURSOR_RE.test(frame.cursor)) {
+ throw new Error('Invalid entity-change cursor')
+ }
+ if (frame.schemaVersion !== 1 || typeof frame.type !== 'string') {
+ return {
+ schemaVersion: 1,
+ type: 'resync_required',
+ cursor: frame.cursor,
+ scopes: ['gfs', 'authorization'],
+ }
+ }
+ if (
+ frame.type === 'resync_required' ||
+ frame.type === 'scope.invalidated' ||
+ frame.type === 'heartbeat' ||
+ frame.type === 'stream.closing'
+ ) {
+ const scopes = Array.isArray(frame.scopes)
+ ? frame.scopes.filter(
+ (scope): scope is 'gfs' | 'authorization' => scope === 'gfs' || scope === 'authorization'
+ )
+ : undefined
+ return {
+ schemaVersion: 1,
+ type: frame.type,
+ cursor: frame.cursor,
+ ...(scopes ? { scopes } : {}),
+ ...(typeof frame.observedAt === 'string' ? { observedAt: frame.observedAt } : {}),
+ ...(typeof frame.reason === 'string'
+ ? { reason: frame.reason as EntityChangeFrame['reason'] }
+ : {}),
+ }
+ }
+ return {
+ schemaVersion: 1,
+ type: 'resync_required',
+ cursor: frame.cursor,
+ scopes: ['gfs', 'authorization'],
+ }
+}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index f00f3900c..2f7f229cf 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.608",
+ "version": "0.1.609",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.608",
+ "version": "0.1.609",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
diff --git a/control-ui/package.json b/control-ui/package.json
index fb19480cd..38857b5dc 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.608",
+ "version": "0.1.609",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",