Skip to content

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

TypeScript

feat(desktop-app): refresh GFS state from entity changes

Josué6771aafc5f50
diff --git a/desktop-app/src/__tests__/appService.entityChanges.test.ts b/desktop-app/src/__tests__/appService.entityChanges.test.ts
new file mode 100644
index 000000000..e0209f3cf
--- /dev/null
+++ b/desktop-app/src/__tests__/appService.entityChanges.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, it, vi } from 'vitest'
+import { AppService } from '../appService.js'
+import type { EntityChangeStreamEvent } from '../types.js'
+
+vi.mock('electron', () => ({
+ app: {
+ isReady: vi.fn(() => false),
+ getPath: vi.fn(() => '/tmp/clerum-desktop-test'),
+ },
+ safeStorage: {
+ isEncryptionAvailable: vi.fn(() => false),
+ encryptString: vi.fn(),
+ decryptString: vi.fn(),
+ },
+ shell: { openExternal: vi.fn() },
+}))
+
+async function flushAsyncWork(iterations = 6): Promise<void> {
+ for (let index = 0; index < iterations; index += 1) await Promise.resolve()
+}
+
+describe('AppService entity-change fan-out', () => {
+ it('owns one session stream and fans validated invalidations to two renderers', async () => {
+ const service = new AppService() as any
+ service.sessionToken = 'session-token'
+ let publish!: (event: EntityChangeStreamEvent) => void
+ let finishStream!: () => void
+ const streamFinished = new Promise<void>(resolve => {
+ finishStream = resolve
+ })
+ service.authClient = {
+ openEntityChangeStream: vi.fn().mockImplementation(async (_token, _cursor, onEvent) => {
+ publish = onEvent
+ await streamFinished
+ }),
+ }
+ const first: EntityChangeStreamEvent[] = []
+ const second: EntityChangeStreamEvent[] = []
+ service.startEntityChangeStream('stream-a', 11, (event: EntityChangeStreamEvent) =>
+ first.push(event)
+ )
+ service.startEntityChangeStream('stream-b', 22, (event: EntityChangeStreamEvent) =>
+ second.push(event)
+ )
+ await flushAsyncWork()
+ publish({ type: 'open' })
+ publish({
+ type: 'scope.invalidated',
+ schemaVersion: 1,
+ cursor: 'd119f895-1ef8-4e73-8f08-f9754919682a',
+ scopes: ['gfs'],
+ })
+ await flushAsyncWork()
+
+ expect(service.authClient.openEntityChangeStream).toHaveBeenCalledOnce()
+ expect(service.authClient.openEntityChangeStream).toHaveBeenCalledWith(
+ 'session-token',
+ null,
+ expect.any(Function),
+ expect.any(AbortSignal)
+ )
+ expect(first.map(event => event.type)).toEqual(['open', 'scope.invalidated'])
+ expect(second.map(event => event.type)).toEqual(['open', 'scope.invalidated'])
+
+ expect(service.stopEntityChangeStream('stream-a', 22)).toBe(false)
+ expect(service.stopEntityChangeStream('stream-a', 11)).toBe(true)
+ finishStream()
+ expect(service.stopEntityChangeStream('stream-b', 22)).toBe(true)
+ })
+
+ it('restarts with a cleared watermark when the authenticated session is replaced', async () => {
+ const service = new AppService() as any
+ service.sessionToken = 'old-session-token'
+ const opens: Array<{
+ token: string
+ cursor: string | null
+ onEvent: (event: EntityChangeStreamEvent) => void
+ signal: AbortSignal
+ }> = []
+ service.authClient = {
+ openEntityChangeStream: vi.fn(
+ (
+ token: string,
+ cursor: string | null,
+ onEvent: (event: EntityChangeStreamEvent) => void,
+ signal: AbortSignal
+ ) => {
+ opens.push({ token, cursor, onEvent, signal })
+ return new Promise<void>(resolve => {
+ signal.addEventListener('abort', () => resolve(), { once: true })
+ })
+ }
+ ),
+ }
+ service.startEntityChangeStream('stream-a', 11, vi.fn())
+ await flushAsyncWork()
+ opens[0]?.onEvent({
+ type: 'scope.invalidated',
+ schemaVersion: 1,
+ cursor: 'd119f895-1ef8-4e73-8f08-f9754919682a',
+ scopes: ['gfs'],
+ })
+ service.sessionToken = 'new-session-token'
+
+ service.restartEntityChangeStreamForSessionReplacement()
+ await flushAsyncWork()
+
+ expect(opens[0]?.signal.aborted).toBe(true)
+ expect(opens[1]).toMatchObject({ token: 'new-session-token', cursor: null })
+ service.stopEntityChangeStream('stream-a', 11)
+ })
+})
diff --git a/desktop-app/src/__tests__/authClient.entityChanges.test.ts b/desktop-app/src/__tests__/authClient.entityChanges.test.ts
new file mode 100644
index 000000000..070ffd9bf
--- /dev/null
+++ b/desktop-app/src/__tests__/authClient.entityChanges.test.ts
@@ -0,0 +1,79 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { AuthClient } from '../authClient.js'
+
+vi.mock('../config.js', () => ({
+ config: { externalRestApiBaseUrl: 'http://rest', requestTimeoutMs: 60_000 },
+}))
+
+const CURSOR = 'd119f895-1ef8-4e73-8f08-f9754919682a'
+
+function stream(lines: unknown[]): ReadableStream<Uint8Array> {
+ const encoder = new TextEncoder()
+ return new ReadableStream({
+ start(controller) {
+ for (const line of lines) controller.enqueue(encoder.encode(`${JSON.stringify(line)}\n`))
+ controller.close()
+ },
+ })
+}
+
+describe('AuthClient.openEntityChangeStream', () => {
+ beforeEach(() => vi.unstubAllGlobals())
+
+ it('validates coarse feed frames and turns unknown versions into full resync', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue({
+ ok: true,
+ body: stream([
+ { schemaVersion: 1, type: 'scope.invalidated', cursor: CURSOR, scopes: ['gfs'] },
+ { schemaVersion: 2, type: 'future.event', cursor: CURSOR, entityId: 'private-id' },
+ ]),
+ })
+ )
+ const events: Array<Record<string, unknown>> = []
+ await new AuthClient().openEntityChangeStream(
+ 'session-token',
+ null,
+ event => events.push(event as unknown as Record<string, unknown>),
+ new AbortController().signal
+ )
+ expect(events).toEqual([
+ { type: 'open' },
+ { schemaVersion: 1, type: 'scope.invalidated', cursor: CURSOR, scopes: ['gfs'] },
+ {
+ schemaVersion: 1,
+ type: 'resync_required',
+ cursor: CURSOR,
+ scopes: ['gfs', 'authorization'],
+ },
+ ])
+ expect(JSON.stringify(events)).not.toContain('private-id')
+ expect(fetch).toHaveBeenCalledWith(
+ new URL('http://rest/api/v1/entity-changes/stream'),
+ expect.objectContaining({
+ headers: expect.objectContaining({ authorization: 'Bearer session-token' }),
+ })
+ )
+ })
+
+ it('rejects malformed cursors rather than exposing arbitrary stream payloads', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue({
+ ok: true,
+ body: stream([
+ { schemaVersion: 1, type: 'heartbeat', cursor: 'not-a-cursor', observedAt: 'now' },
+ ]),
+ })
+ )
+ await expect(
+ new AuthClient().openEntityChangeStream(
+ 'session-token',
+ null,
+ () => undefined,
+ new AbortController().signal
+ )
+ ).rejects.toThrow('unsupported frame')
+ })
+})
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index 83f1860fb..4116b4b56 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -47,6 +47,7 @@ import {
DesktopAppInfo,
DesktopReleaseStatus,
DesktopRuntimeConfig,
+ EntityChangeStreamEvent,
ExternalChannelsSummary,
HostActivitySnapshot,
HostActivityStreamEvent,
@@ -925,6 +926,12 @@ export class AppService {
stop: (opts?: { silent?: boolean }) => void
}
>()
+ private readonly entityChangeSubscribers = new Map<
+ string,
+ { ownerId: number; onEvent: (event: EntityChangeStreamEvent) => void }
+ >()
+ private entityChangeConnectionStop: ((opts?: { silent?: boolean }) => void) | null = null
+ private entityChangeCursor: string | null = null
private progressStreams = new Map<
string,
{ ownerId: number; stop: (opts?: { silent?: boolean }) => void }
@@ -1489,6 +1496,7 @@ export class AppService {
this.sessionGeneration += 1
this.sessionToken = result.token
this.me = result.me
+ this.restartEntityChangeStreamForSessionReplacement()
await this.bindCurrentChatStore(result.me.id)
this.accessCatalog = null
this.teamDirectoryCache = null
@@ -2749,6 +2757,101 @@ export class AppService {
return result
}
+ startEntityChangeStream(
+ streamId: string,
+ ownerId: number,
+ onEvent: (event: EntityChangeStreamEvent) => void
+ ): void {
+ this.entityChangeSubscribers.set(streamId, { ownerId, onEvent })
+ this.ensureEntityChangeConnection()
+ }
+
+ private emitEntityChangeEvent(event: EntityChangeStreamEvent): void {
+ if ('cursor' in event) this.entityChangeCursor = event.cursor
+ for (const subscriber of Array.from(this.entityChangeSubscribers.values())) {
+ try {
+ subscriber.onEvent(event)
+ } catch {
+ // A destroyed renderer must not interrupt delivery to other windows.
+ }
+ }
+ }
+
+ private ensureEntityChangeConnection(): void {
+ if (this.entityChangeConnectionStop || this.entityChangeSubscribers.size === 0) return
+ let closed = false
+ let abortController: AbortController | null = null
+ let retryTimer: NodeJS.Timeout | null = null
+ let backoffMs = 1000
+ const clearRetry = () => {
+ if (retryTimer) clearTimeout(retryTimer)
+ retryTimer = null
+ }
+ const stop = (opts?: { silent?: boolean }) => {
+ if (closed) return
+ closed = true
+ clearRetry()
+ abortController?.abort()
+ if (this.entityChangeConnectionStop === stop) this.entityChangeConnectionStop = null
+ if (!opts?.silent) this.emitEntityChangeEvent({ type: 'closed' })
+ }
+ this.entityChangeConnectionStop = stop
+
+ const connect = async () => {
+ if (closed) return
+ abortController = new AbortController()
+ try {
+ await this.authClient.openEntityChangeStream(
+ this.requireSessionToken(),
+ this.entityChangeCursor,
+ event => {
+ if (closed) return
+ if (event.type === 'open') backoffMs = 1000
+ this.emitEntityChangeEvent(event)
+ },
+ abortController.signal
+ )
+ } catch {
+ if (!closed) {
+ this.emitEntityChangeEvent({
+ type: 'error',
+ message: 'Live updates disconnected; reconnecting.',
+ })
+ }
+ } finally {
+ if (closed) return
+ clearRetry()
+ const delay = backoffMs + Math.floor(Math.random() * Math.max(1, backoffMs * 0.2))
+ backoffMs = Math.min(backoffMs * 2, 15_000)
+ retryTimer = setTimeout(() => void connect(), delay)
+ }
+ }
+
+ void connect()
+ }
+
+ private restartEntityChangeStreamForSessionReplacement(): void {
+ this.entityChangeCursor = null
+ this.entityChangeConnectionStop?.({ silent: true })
+ this.ensureEntityChangeConnection()
+ }
+
+ stopEntityChangeStream(streamId: string, requesterOwnerId?: number): boolean {
+ const subscriber = this.entityChangeSubscribers.get(streamId)
+ if (!subscriber) return true
+ if (requesterOwnerId !== undefined && subscriber.ownerId !== requesterOwnerId) return false
+ this.entityChangeSubscribers.delete(streamId)
+ if (this.entityChangeSubscribers.size === 0) this.entityChangeConnectionStop?.({ silent: true })
+ return true
+ }
+
+ stopEntityChangeStreamsForOwner(ownerId: number): void {
+ for (const [streamId, subscriber] of this.entityChangeSubscribers) {
+ if (subscriber.ownerId === ownerId) this.entityChangeSubscribers.delete(streamId)
+ }
+ if (this.entityChangeSubscribers.size === 0) this.entityChangeConnectionStop?.({ silent: true })
+ }
+
startWorkflowNotificationStream(
streamId: string,
ownerId: number,
@@ -2897,6 +3000,9 @@ export class AppService {
for (const entry of Array.from(this.hostActivityStreams.values())) entry.stop({ silent: true })
for (const entry of Array.from(this.hostStatusStreams.values())) entry.stop({ silent: true })
for (const entry of Array.from(this.notificationStreams.values())) entry.stop({ silent: true })
+ this.entityChangeSubscribers.clear()
+ this.entityChangeConnectionStop?.({ silent: true })
+ this.entityChangeCursor = null
}
getWorkflowNotificationStreamStatus(): {
diff --git a/desktop-app/src/authClient.ts b/desktop-app/src/authClient.ts
index 74901a6c3..e3c182ace 100644
--- a/desktop-app/src/authClient.ts
+++ b/desktop-app/src/authClient.ts
@@ -3,6 +3,7 @@ import { ApiError, requestJson } from './httpClient.js'
import {
DesktopEnvironmentDiscovery,
DesktopReleasePolicy,
+ EntityChangeStreamEvent,
ExternalChannelAccount,
ExternalChannelTarget,
LoginResult,
@@ -34,6 +35,69 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value && typeof value === 'object' && !Array.isArray(value))
}
+function parseEntityChangeStreamFrame(value: unknown): EntityChangeStreamEvent | null {
+ if (!isRecord(value)) return null
+ const cursor = typeof value.cursor === 'string' ? value.cursor : ''
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(cursor)) {
+ return null
+ }
+ if (value.schemaVersion !== 1 || typeof value.type !== 'string') {
+ return {
+ type: 'resync_required',
+ schemaVersion: 1,
+ cursor,
+ scopes: ['gfs', 'authorization'],
+ }
+ }
+ if (value.type === 'resync_required' || value.type === 'scope.invalidated') {
+ if (!Array.isArray(value.scopes) || value.scopes.length === 0) {
+ return null
+ }
+ const scopes = value.scopes.filter(
+ (scope): scope is 'gfs' | 'authorization' => scope === 'gfs' || scope === 'authorization'
+ )
+ if (scopes.length === 0) return null
+ return {
+ type: value.type,
+ schemaVersion: 1,
+ cursor,
+ scopes,
+ }
+ }
+ if (value.type === 'heartbeat') {
+ if (typeof value.observedAt !== 'string') {
+ return null
+ }
+ return {
+ type: 'heartbeat',
+ schemaVersion: 1,
+ cursor,
+ observedAt: value.observedAt,
+ }
+ }
+ if (value.type === 'stream.closing') {
+ const reasons = ['max_lifetime', 'session_expired', 'server_shutdown', 'slow_consumer']
+ if (typeof value.reason !== 'string' || !reasons.includes(value.reason)) {
+ return null
+ }
+ return {
+ type: 'stream.closing',
+ schemaVersion: 1,
+ cursor,
+ reason: value.reason as Extract<
+ EntityChangeStreamEvent,
+ { type: 'stream.closing' }
+ >['reason'],
+ }
+ }
+ return {
+ type: 'resync_required',
+ schemaVersion: 1,
+ cursor,
+ scopes: ['gfs', 'authorization'],
+ }
+}
+
function parsePendingWorkflowApproval(value: unknown): PendingWorkflowApproval | null {
if (!isRecord(value)) return null
const payload = isRecord(value.payload) ? value.payload : null
@@ -507,6 +571,80 @@ export class AuthClient {
if (trailing) processChunk(trailing)
}
+ async openEntityChangeStream(
+ sessionToken: string,
+ cursor: string | null,
+ onEvent: (event: EntityChangeStreamEvent) => void,
+ signal: AbortSignal
+ ): Promise<void> {
+ const streamUrl = new URL(url('/api/v1/entity-changes/stream'))
+ if (cursor) streamUrl.searchParams.set('cursor', cursor)
+ const response = await fetch(streamUrl, {
+ method: 'GET',
+ headers: {
+ accept: 'application/x-ndjson',
+ authorization: `Bearer ${sessionToken}`,
+ },
+ signal,
+ })
+ if (!response.ok) {
+ const body = await readErrorBody(response)
+ throw new ApiError(
+ `Entity change stream failed (${response.status}): ${body || response.statusText}`,
+ response.status,
+ body
+ )
+ }
+ if (!response.body) throw new Error('Entity change stream missing response body')
+
+ onEvent({ type: 'open' })
+ const reader = response.body.getReader()
+ const decoder = new TextDecoder()
+ let buffer = ''
+ const processFrame = (rawLine: string) => {
+ if (!rawLine.trim()) return
+ let decoded: unknown
+ try {
+ decoded = JSON.parse(rawLine) as unknown
+ } catch {
+ throw new Error('Entity change stream contained invalid JSON')
+ }
+ const frame = parseEntityChangeStreamFrame(decoded)
+ if (!frame) throw new Error('Entity change stream contained an unsupported frame')
+ onEvent(frame)
+ }
+ const processChunk = (chunk: string) => {
+ buffer += chunk
+ if (buffer.length > 16 * 1024 && !buffer.includes('\n')) {
+ throw new Error('Entity change stream frame exceeded the size limit')
+ }
+ while (true) {
+ const newline = buffer.indexOf('\n')
+ if (newline === -1) break
+ const line = buffer.slice(0, newline)
+ buffer = buffer.slice(newline + 1)
+ if (line.length > 16 * 1024)
+ throw new Error('Entity change stream frame exceeded the size limit')
+ processFrame(line)
+ }
+ }
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read()
+ if (done) break
+ processChunk(decoder.decode(value, { stream: true }))
+ }
+ processChunk(decoder.decode())
+ if (buffer.trim()) processFrame(buffer)
+ } catch (error) {
+ await reader.cancel().catch(() => undefined)
+ throw error
+ } finally {
+ reader.releaseLock()
+ }
+ }
+
async listWorkflows(sessionToken: string): Promise<WorkflowRecipeListResult> {
return requestJson<WorkflowRecipeListResult>('GET', url('/api/v1/workflows'), {
token: sessionToken,
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index 88b88ba2e..ffc47a330 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -23,6 +23,7 @@ import {
} from './pluginSdkProtocol.js'
import {
DesktopRuntimeConfig,
+ EntityChangeStreamEvent,
HostActivityStreamEvent,
HostMessageRequest,
HostStatusStreamEvent,
@@ -215,6 +216,7 @@ function sanitizeDesktopNotificationActions(
export function registerIpcHandlers(service: AppService): void {
const streamOwnerCleanupRegistered = new Set<number>()
+ const entityChangeOwnerCleanupRegistered = new Set<number>()
const activeDesktopNotifications = new Map<string, Notification>()
ipcMain.handle('auth:getSessionState', async event => {
@@ -805,6 +807,36 @@ export function registerIpcHandlers(service: AppService): void {
return { streamId }
})
+ ipcMain.handle('entityChanges:streamStart', async event => {
+ assertTrustedSender(event)
+ const streamId = randomUUID()
+ const ownerId = event.sender.id
+ service.startEntityChangeStream(streamId, ownerId, (streamEvent: EntityChangeStreamEvent) => {
+ try {
+ event.sender.send('entityChanges:streamEvent', { streamId, event: streamEvent })
+ } catch {
+ /* sender destroyed */
+ }
+ })
+ if (!entityChangeOwnerCleanupRegistered.has(ownerId)) {
+ entityChangeOwnerCleanupRegistered.add(ownerId)
+ event.sender.once('destroyed', () => {
+ service.stopEntityChangeStreamsForOwner(ownerId)
+ entityChangeOwnerCleanupRegistered.delete(ownerId)
+ })
+ }
+ return { streamId }
+ })
+
+ ipcMain.handle('entityChanges:streamStop', async (event, payload: { streamId: string }) => {
+ assertTrustedSender(event)
+ const streamId = sanitizeString(payload?.streamId)
+ if (!streamId) return { ok: true }
+ const stopped = service.stopEntityChangeStream(streamId, event.sender.id)
+ if (!stopped) throw new Error('Forbidden: cannot stop entity-change subscription')
+ return { ok: true }
+ })
+
ipcMain.handle('notifications:streamStop', async (event, payload: { streamId: string }) => {
assertTrustedSender(event)
const streamId = sanitizeString(payload?.streamId)
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 79a047e4f..34101cfad 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -2,6 +2,7 @@ import { contextBridge, ipcRenderer, webUtils } from 'electron'
import type { DesktopCommandId, DesktopCommandSource } from './desktopCommands.js'
import type { PluginConsentRequest } from './pluginSdkProtocol.js'
import type {
+ EntityChangeStreamEvent,
HostMessageRequest,
ProfileSettingsOpenOptions,
SandboxUiDeepLinkEnvelope,
@@ -290,6 +291,41 @@ const clerum = Object.freeze({
status: string
}>,
},
+ entityChanges: {
+ subscribe: async (onEvent: (event: EntityChangeStreamEvent) => void) => {
+ let streamId = ''
+ const pending: unknown[] = []
+ const listener = (_event: unknown, payload: unknown) => {
+ const parsed = payload as { streamId?: string; event?: EntityChangeStreamEvent }
+ if (!streamId) {
+ if (pending.length < 100) pending.push(payload)
+ return
+ }
+ if (parsed?.streamId === streamId && parsed.event) onEvent(parsed.event)
+ }
+ ipcRenderer.on('entityChanges:streamEvent', listener)
+ try {
+ const started = (await ipcRenderer.invoke('entityChanges:streamStart')) as {
+ streamId: string
+ }
+ streamId = String(started?.streamId || '').trim()
+ if (!streamId) throw new Error('Failed to start entity-change stream')
+ for (const item of pending) {
+ const parsed = item as { streamId?: string; event?: EntityChangeStreamEvent }
+ if (parsed?.streamId === streamId && parsed.event) onEvent(parsed.event)
+ }
+ pending.length = 0
+ } catch (error) {
+ ipcRenderer.removeListener('entityChanges:streamEvent', listener)
+ throw error
+ }
+
+ return async () => {
+ ipcRenderer.removeListener('entityChanges:streamEvent', listener)
+ await ipcRenderer.invoke('entityChanges:streamStop', { streamId })
+ }
+ },
+ },
notificationPreferences: {
get: () => ipcRenderer.invoke('notificationPreferences:get'),
update: (payload: {
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index 1b9ba4585..3bc69ca54 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -16,6 +16,7 @@ import {
DesktopReleaseStatus,
DesktopRuntimeConfig,
DesktopRuntimeConfigState,
+ EntityChangeStreamEvent,
ExternalChannelsSummary,
HostActivitySnapshot,
HostActivityStreamEvent,
@@ -451,6 +452,11 @@ declare global {
onFailed: (callback: (payload: { id: string; error: string }) => void) => () => void
ack: (notificationId: string) => Promise<{ ok: boolean; status: string }>
}
+ entityChanges: {
+ subscribe: (
+ onEvent: (event: EntityChangeStreamEvent) => void
+ ) => Promise<() => Promise<void>>
+ }
notificationPreferences: {
get: () => Promise<import('./types').UserNotificationPreferences>
update: (payload: {
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index 42d99f7cf..cba55e47b 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -238,6 +238,37 @@ export type WorkflowNotificationStreamEvent =
type: 'closed'
}
+export type EntityChangeScope = 'gfs' | 'authorization'
+
+export type EntityChangeStreamEvent =
+ | { type: 'open' }
+ | {
+ type: 'resync_required'
+ schemaVersion: 1
+ cursor: string
+ scopes: EntityChangeScope[]
+ }
+ | {
+ type: 'scope.invalidated'
+ schemaVersion: 1
+ cursor: string
+ scopes: EntityChangeScope[]
+ }
+ | {
+ type: 'heartbeat'
+ schemaVersion: 1
+ cursor: string
+ observedAt: string
+ }
+ | {
+ type: 'stream.closing'
+ schemaVersion: 1
+ cursor: string
+ reason: 'max_lifetime' | 'session_expired' | 'server_shutdown' | 'slow_consumer'
+ }
+ | { type: 'error'; message: string }
+ | { type: 'closed' }
+
export type WorkflowInputContractProperty = {
type: 'string' | 'integer' | 'number' | 'boolean'
default?: string | number | boolean
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 14be2aca8..58745e25d 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -27,6 +27,7 @@ import { TitlebarActionsPortal, WindowTitleBar } from '@components/WindowTitleBa
import { WorkspaceTabStrip } from '@components/WorkspaceTabStrip'
import { DESKTOP_ROUTES, SIDEBAR_COLLAPSED_KEY } from '@constants/navigation'
import { THEME_STORAGE_KEY } from '@constants/theme'
+import { desktopQueryKeys } from '@hooks/domain/queryKeys'
import { useAgentChatActionsValue } from '@hooks/useAgentChatActionsValue'
import { useAppController } from '@hooks/useAppController'
import {
@@ -37,7 +38,9 @@ import {
import { useWindowFocusBridge } from '@hooks/useWindowFocusBridge'
import type { ChatLocalMatch } from '@lib/chatLocalSearch'
import { buildLoadedChatSemanticModels } from '@lib/chatMessageSemantics'
+import { EntityChangeRegistry } from '@lib/entityChangeRegistry'
import { resolveGfsPreview } from '@lib/gfsPreview'
+import { desktopQueryClient } from '@lib/queryClient'
import {
canProcessSandboxUiDeepLinks,
resolveSandboxUiDeepLinkApp,
@@ -68,6 +71,7 @@ import {
newChatTab,
openAppTab,
reconcileWorkspaceChatTab,
+ refreshPreviewTab,
reorderWorkspaceTab,
selectLastWorkspaceTab,
selectWorkspaceTab,
@@ -278,6 +282,8 @@ function DesktopUpdateRequiredDialog({
export function App() {
const vm = useAppController()
+ const queryClient = desktopQueryClient
+ const entityChangeRegistry = React.useMemo(() => new EntityChangeRegistry(), [])
// Electron never fires `visibilitychange` on OS-window switching; bridge
// DOM focus/blur so focus-aware query revalidation actually runs.
useWindowFocusBridge()
@@ -836,7 +842,15 @@ export function App() {
name: string
bytes: number
mimeType: string
+ version?: number
+ reloadVersion: number
+ unavailable?: boolean
} | null>(null)
+ const pluginGfsPreviewRef = React.useRef(pluginGfsPreview)
+ pluginGfsPreviewRef.current = pluginGfsPreview
+ const previewRefreshGenerationRef = React.useRef(new Map<string, number>())
+ const previewRetryTimersRef = React.useRef(new Map<string, number>())
+ const previewRetryAttemptRef = React.useRef(new Map<string, number>())
React.useEffect(() => {
const off = window.clerum.pluginSdk?.onOpenGfsResource?.(resource => {
@@ -862,6 +876,8 @@ export function App() {
name: preview.name,
bytes: preview.bytes,
mimeType: preview.mimeType,
+ ...(preview.version !== undefined ? { version: preview.version } : {}),
+ reloadVersion: 0,
})
return
}
@@ -911,6 +927,182 @@ export function App() {
[setWorkspaceTabs]
)
+ const refreshOpenPreview = React.useCallback(
+ async (gfsUri: string, fromRetry = false) => {
+ if (!fromRetry) {
+ const existingTimer = previewRetryTimersRef.current.get(gfsUri)
+ if (existingTimer !== undefined) window.clearTimeout(existingTimer)
+ previewRetryTimersRef.current.delete(gfsUri)
+ previewRetryAttemptRef.current.delete(gfsUri)
+ }
+ const generation = (previewRefreshGenerationRef.current.get(gfsUri) ?? 0) + 1
+ previewRefreshGenerationRef.current.set(gfsUri, generation)
+ // Invalidation is intentionally coarse, so purge/hide cached preview
+ // content before resolving the current authorization and metadata. This
+ // prevents revoked/deleted bytes from remaining visible during a slow
+ // authoritative refetch; a successful resolve remounts the generic body.
+ setWorkspaceTabs(state =>
+ refreshPreviewTab(state, gfsUri, {
+ status: 'unavailable',
+ shellTitle: 'File unavailable',
+ })
+ )
+ setPluginGfsPreview(current =>
+ current?.gfsUri === gfsUri
+ ? { ...current, unavailable: true, reloadVersion: current.reloadVersion + 1 }
+ : current
+ )
+ try {
+ const resource = await window.clerum.gfs.resolve(gfsUri)
+ if (previewRefreshGenerationRef.current.get(gfsUri) !== generation) return
+ const preview =
+ resource.kind === 'file'
+ ? resolveGfsPreview({
+ gfsUri: resource.gfsUri,
+ name: resource.name,
+ bytes: resource.bytes ?? 0,
+ version: resource.version,
+ })
+ : null
+ if (!preview) {
+ setWorkspaceTabs(state =>
+ refreshPreviewTab(state, gfsUri, {
+ status: 'unavailable',
+ shellTitle: 'Preview unavailable',
+ })
+ )
+ setPluginGfsPreview(current =>
+ current?.gfsUri === gfsUri
+ ? { ...current, unavailable: true, reloadVersion: current.reloadVersion + 1 }
+ : current
+ )
+ return
+ }
+ const refreshed = {
+ status: 'available' as const,
+ title: preview.name,
+ fileKind: preview.kind,
+ byteLength: preview.bytes,
+ resourceVersion: resource.version,
+ ...('mimeType' in preview ? { mimeType: preview.mimeType } : {}),
+ }
+ setWorkspaceTabs(state => refreshPreviewTab(state, gfsUri, refreshed))
+ setPluginGfsPreview(current => {
+ if (current?.gfsUri !== gfsUri) return current
+ if (
+ preview.version !== undefined &&
+ current.version !== undefined &&
+ preview.version < current.version
+ )
+ return current
+ if (preview.kind !== 'image') {
+ return { ...current, unavailable: true, reloadVersion: current.reloadVersion + 1 }
+ }
+ if (
+ !current.unavailable &&
+ current.name === preview.name &&
+ current.bytes === preview.bytes &&
+ current.mimeType === preview.mimeType &&
+ current.version === preview.version
+ )
+ return current
+ return {
+ gfsUri,
+ name: preview.name,
+ bytes: preview.bytes,
+ mimeType: preview.mimeType,
+ ...(preview.version !== undefined ? { version: preview.version } : {}),
+ reloadVersion: current.reloadVersion + 1,
+ }
+ })
+ const retryTimer = previewRetryTimersRef.current.get(gfsUri)
+ if (retryTimer !== undefined) window.clearTimeout(retryTimer)
+ previewRetryTimersRef.current.delete(gfsUri)
+ previewRetryAttemptRef.current.delete(gfsUri)
+ } catch {
+ if (previewRefreshGenerationRef.current.get(gfsUri) !== generation) return
+ setWorkspaceTabs(state =>
+ refreshPreviewTab(state, gfsUri, {
+ status: 'unavailable',
+ shellTitle: 'File unavailable',
+ })
+ )
+ setPluginGfsPreview(current =>
+ current?.gfsUri === gfsUri
+ ? { ...current, unavailable: true, reloadVersion: current.reloadVersion + 1 }
+ : current
+ )
+ queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })
+ const attempt = (previewRetryAttemptRef.current.get(gfsUri) ?? 0) + 1
+ previewRetryAttemptRef.current.set(gfsUri, attempt)
+ const delayMs = Math.min(5000 * 2 ** Math.min(attempt - 1, 4), 60_000)
+ const retryTimer = window.setTimeout(() => {
+ previewRetryTimersRef.current.delete(gfsUri)
+ void refreshOpenPreview(gfsUri, true)
+ }, delayMs)
+ previewRetryTimersRef.current.set(gfsUri, retryTimer)
+ }
+ },
+ [queryClient, setWorkspaceTabs]
+ )
+
+ React.useEffect(() => {
+ if (!vm.isAuthenticated) return
+ const entityChangeBridge = window.clerum?.entityChanges
+ if (typeof entityChangeBridge?.subscribe !== 'function') return
+ let active = true
+ let stopSubscription: (() => Promise<void>) | null = null
+ const unsubscribeGfs = entityChangeRegistry.subscribe(['gfs', 'authorization'], event => {
+ if (event.scopes.includes('authorization')) {
+ void queryClient.resetQueries({ queryKey: desktopQueryKeys.gfsRoot })
+ } else {
+ void queryClient.invalidateQueries({
+ queryKey: desktopQueryKeys.gfsRoot,
+ refetchType: 'active',
+ })
+ }
+ const resources = new Set(
+ workspaceTabsRef.current.tabs
+ .filter(tab => tab.kind === 'preview' && tab.preview)
+ .map(tab => tab.preview!.gfsUri)
+ )
+ const pluginPreview = pluginGfsPreviewRef.current
+ if (pluginPreview) resources.add(pluginPreview.gfsUri)
+ for (const gfsUri of resources) void refreshOpenPreview(gfsUri)
+ })
+ void entityChangeBridge
+ .subscribe(event => entityChangeRegistry.dispatch(event))
+ .then(stop => {
+ if (active) stopSubscription = stop
+ else void stop()
+ })
+ .catch(() => undefined)
+ return () => {
+ active = false
+ unsubscribeGfs()
+ if (stopSubscription) void stopSubscription()
+ for (const [uri, timer] of previewRetryTimersRef.current) {
+ window.clearTimeout(timer)
+ }
+ for (const uri of previewRefreshGenerationRef.current.keys()) {
+ previewRefreshGenerationRef.current.set(
+ uri,
+ (previewRefreshGenerationRef.current.get(uri) ?? 0) + 1
+ )
+ }
+ previewRetryTimersRef.current.clear()
+ previewRetryAttemptRef.current.clear()
+ }
+ }, [
+ entityChangeRegistry,
+ queryClient,
+ refreshOpenPreview,
+ vm.authenticatedPrincipalIdentity,
+ vm.currentTeamId,
+ vm.isAuthenticated,
+ vm.runtimeConfigState?.envKey,
+ ])
+
// Preview tab render seam (spec 18 §3.B.1). Only the ACTIVE preview tab mounts
// a FilePreviewPage, keyed by that tab's id so switching preview tabs remounts
// with the incoming file's payload. Unlike an app tab, a preview tab is a plain
@@ -2605,6 +2797,8 @@ export function App() {
fileKind={activePreviewPayload.fileKind}
mimeType={activePreviewPayload.mimeType}
byteLength={activePreviewPayload.byteLength}
+ reloadVersion={activePreviewPayload.reloadVersion}
+ unavailable={activePreviewPayload.unavailable}
/>
)}
{vm.navItem === DESKTOP_ROUTES.connectors && <McpServersPage />}
@@ -2725,10 +2919,12 @@ export function App() {
) : null}
{pluginGfsPreview ? (
<GfsImagePreview
+ key={`${pluginGfsPreview.gfsUri}:${pluginGfsPreview.reloadVersion}`}
byteLength={pluginGfsPreview.bytes}
fileName={pluginGfsPreview.name}
gfsUri={pluginGfsPreview.gfsUri}
mimeType={pluginGfsPreview.mimeType}
+ unavailable={pluginGfsPreview.unavailable}
onClose={closePluginGfsPreview}
/>
) : null}
diff --git a/desktop-app/ui/src/components/GfsImagePreview/index.tsx b/desktop-app/ui/src/components/GfsImagePreview/index.tsx
index 610b1446c..c89772834 100644
--- a/desktop-app/ui/src/components/GfsImagePreview/index.tsx
+++ b/desktop-app/ui/src/components/GfsImagePreview/index.tsx
@@ -1,6 +1,7 @@
import { useEffect, useId, useRef } from 'react'
import { createPortal } from 'react-dom'
import { Button } from '@components/Common'
+import { EmptyState } from '@components/Common'
import { IconClose } from '@components/SidebarNav/icons'
import { useWorkspaceModalStyle } from '@hooks/useWorkspaceModalStyle'
import { GfsImagePreviewBody } from './Body'
@@ -18,6 +19,8 @@ export function GfsImagePreview({
gfsUri,
mimeType,
onClose,
+ reloadVersion,
+ unavailable = false,
onDownloadError,
}: GfsImagePreviewProps) {
const titleId = useId()
@@ -48,27 +51,32 @@ export function GfsImagePreview({
aria-modal="true"
aria-labelledby={titleId}
>
- <GfsImagePreviewBody
- byteLength={byteLength}
- fileName={fileName}
- gfsUri={gfsUri}
- mimeType={mimeType}
- onDownloadError={onDownloadError}
- titleId={titleId}
- headerActions={
- <Button
- className="da-gfs-image-preview-dialog__close"
- data-preview-close
- ref={closeButtonRef}
- aria-label="Close image preview"
- color="neutral"
- onClick={onClose}
- variant="ghost"
- >
- <IconClose width={18} height={18} />
- </Button>
- }
- />
+ {unavailable ? (
+ <EmptyState title="File unavailable" body="This item is no longer available." />
+ ) : (
+ <GfsImagePreviewBody
+ key={`${gfsUri}:${reloadVersion ?? 0}`}
+ byteLength={byteLength}
+ fileName={fileName}
+ gfsUri={gfsUri}
+ mimeType={mimeType}
+ onDownloadError={onDownloadError}
+ titleId={titleId}
+ headerActions={
+ <Button
+ className="da-gfs-image-preview-dialog__close"
+ data-preview-close
+ ref={closeButtonRef}
+ aria-label="Close image preview"
+ color="neutral"
+ onClick={onClose}
+ variant="ghost"
+ >
+ <IconClose width={18} height={18} />
+ </Button>
+ }
+ />
+ )}
</section>
</div>,
document.body
diff --git a/desktop-app/ui/src/components/GfsImagePreview/types.ts b/desktop-app/ui/src/components/GfsImagePreview/types.ts
index 03226508d..8e2827353 100644
--- a/desktop-app/ui/src/components/GfsImagePreview/types.ts
+++ b/desktop-app/ui/src/components/GfsImagePreview/types.ts
@@ -6,6 +6,8 @@ export type GfsImagePreviewProps = {
gfsUri: string
mimeType: string
onClose: () => void
+ reloadVersion?: number
+ unavailable?: boolean
onDownloadError?: (error: unknown) => void
}
diff --git a/desktop-app/ui/src/hooks/domain/useNavigationController.ts b/desktop-app/ui/src/hooks/domain/useNavigationController.ts
index 4913fadef..9d4f00370 100644
--- a/desktop-app/ui/src/hooks/domain/useNavigationController.ts
+++ b/desktop-app/ui/src/hooks/domain/useNavigationController.ts
@@ -178,6 +178,7 @@ export function useNavigationController() {
gfsUri: preview.gfsUri,
fileKind: preview.kind,
byteLength: preview.bytes,
+ ...(preview.version !== undefined ? { resourceVersion: preview.version } : {}),
...('mimeType' in preview ? { mimeType: preview.mimeType } : {}),
})
)
diff --git a/desktop-app/ui/src/lib/__tests__/entityChangeRegistry.test.ts b/desktop-app/ui/src/lib/__tests__/entityChangeRegistry.test.ts
new file mode 100644
index 000000000..542c01a7c
--- /dev/null
+++ b/desktop-app/ui/src/lib/__tests__/entityChangeRegistry.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it, vi } from 'vitest'
+import { EntityChangeRegistry } from '../entityChangeRegistry'
+
+describe('EntityChangeRegistry', () => {
+ it('dispatches generic scope invalidations only to matching adapters', () => {
+ const registry = new EntityChangeRegistry()
+ const gfs = vi.fn()
+ const authorization = vi.fn()
+ registry.subscribe(['gfs'], gfs)
+ registry.subscribe(['authorization'], authorization)
+
+ registry.dispatch({
+ schemaVersion: 1,
+ type: 'scope.invalidated',
+ cursor: '00000000-0000-0000-0000-000000000001',
+ scopes: ['gfs'],
+ })
+
+ expect(gfs).toHaveBeenCalledOnce()
+ expect(authorization).not.toHaveBeenCalled()
+ })
+
+ it('coalesces duplicate handler registrations for one multi-scope frame', () => {
+ const registry = new EntityChangeRegistry()
+ const adapter = vi.fn()
+ registry.subscribe(['gfs', 'authorization'], adapter)
+
+ registry.dispatch({
+ schemaVersion: 1,
+ type: 'resync_required',
+ cursor: '00000000-0000-0000-0000-000000000001',
+ scopes: ['gfs', 'authorization'],
+ })
+
+ expect(adapter).toHaveBeenCalledOnce()
+ })
+})
diff --git a/desktop-app/ui/src/lib/entityChangeRegistry.ts b/desktop-app/ui/src/lib/entityChangeRegistry.ts
new file mode 100644
index 000000000..4681fd934
--- /dev/null
+++ b/desktop-app/ui/src/lib/entityChangeRegistry.ts
@@ -0,0 +1,38 @@
+import type { EntityChangeScope, EntityChangeStreamEvent } from '../../../src/types'
+
+export type EntityChangeInvalidation = Extract<
+ EntityChangeStreamEvent,
+ { type: 'scope.invalidated' | 'resync_required' }
+>
+
+type ScopeHandler = (event: EntityChangeInvalidation) => void
+
+/** Renderer-side adapter registry; concrete entity families stay transport-agnostic. */
+export class EntityChangeRegistry {
+ private readonly handlers = new Map<EntityChangeScope, Set<ScopeHandler>>()
+
+ subscribe(scopes: readonly EntityChangeScope[], handler: ScopeHandler): () => void {
+ const uniqueScopes = Array.from(new Set(scopes))
+ for (const scope of uniqueScopes) {
+ const handlers = this.handlers.get(scope) ?? new Set<ScopeHandler>()
+ handlers.add(handler)
+ this.handlers.set(scope, handlers)
+ }
+ return () => {
+ for (const scope of uniqueScopes) {
+ const handlers = this.handlers.get(scope)
+ handlers?.delete(handler)
+ if (handlers?.size === 0) this.handlers.delete(scope)
+ }
+ }
+ }
+
+ dispatch(event: EntityChangeStreamEvent): void {
+ if (event.type !== 'scope.invalidated' && event.type !== 'resync_required') return
+ const uniqueHandlers = new Set<ScopeHandler>()
+ for (const scope of event.scopes) {
+ for (const handler of this.handlers.get(scope) ?? []) uniqueHandlers.add(handler)
+ }
+ for (const handler of uniqueHandlers) handler(event)
+ }
+}
diff --git a/desktop-app/ui/src/lib/gfsPreview.ts b/desktop-app/ui/src/lib/gfsPreview.ts
index 0a860b81d..fb28f9959 100644
--- a/desktop-app/ui/src/lib/gfsPreview.ts
+++ b/desktop-app/ui/src/lib/gfsPreview.ts
@@ -11,6 +11,7 @@ import { gfsVideoPreviewMimeType } from './gfsVideoPreview'
* "previewable, and as what" (spec 18 §3.B.2).
*/
export type GfsPreviewResource = Pick<GfsDriveResource, 'bytes' | 'gfsUri' | 'name'> &
+ Partial<Pick<GfsDriveResource, 'version'>> &
({ kind: 'image'; mimeType: string } | { kind: 'markdown' } | { kind: 'video'; mimeType: string })
/**
@@ -22,7 +23,8 @@ export type GfsPreviewResource = Pick<GfsDriveResource, 'bytes' | 'gfsUri' | 'na
* falls back to download).
*/
export function resolveGfsPreview(
- resource: Pick<GfsDriveResource, 'bytes' | 'gfsUri' | 'name'>
+ resource: Pick<GfsDriveResource, 'bytes' | 'gfsUri' | 'name'> &
+ Partial<Pick<GfsDriveResource, 'version'>>
): GfsPreviewResource | null {
const imageMimeType = gfsImagePreviewMimeType(resource.name)
if (imageMimeType) {
@@ -32,10 +34,17 @@ export function resolveGfsPreview(
mimeType: imageMimeType,
name: resource.name,
bytes: resource.bytes,
+ ...(resource.version !== undefined ? { version: resource.version } : {}),
}
}
if (isGfsMarkdownPreviewFile(resource.name)) {
- return { gfsUri: resource.gfsUri, kind: 'markdown', name: resource.name, bytes: resource.bytes }
+ return {
+ gfsUri: resource.gfsUri,
+ kind: 'markdown',
+ name: resource.name,
+ bytes: resource.bytes,
+ ...(resource.version !== undefined ? { version: resource.version } : {}),
+ }
}
const videoMimeType = gfsVideoPreviewMimeType(resource.name)
if (videoMimeType) {
@@ -45,6 +54,7 @@ export function resolveGfsPreview(
mimeType: videoMimeType,
name: resource.name,
bytes: resource.bytes,
+ ...(resource.version !== undefined ? { version: resource.version } : {}),
}
}
return null
diff --git a/desktop-app/ui/src/lib/workspaceTabs.ts b/desktop-app/ui/src/lib/workspaceTabs.ts
index e85248063..8ffdf69b3 100644
--- a/desktop-app/ui/src/lib/workspaceTabs.ts
+++ b/desktop-app/ui/src/lib/workspaceTabs.ts
@@ -312,6 +312,7 @@ export function openPreviewTab(
gfsUri: input.gfsUri,
fileKind: input.fileKind,
byteLength: input.byteLength,
+ ...(input.resourceVersion !== undefined ? { resourceVersion: input.resourceVersion } : {}),
...(input.mimeType !== undefined ? { mimeType: input.mimeType } : {}),
}
if (existing) {
@@ -330,7 +331,10 @@ export function openPreviewTab(
p.gfsUri === nextPreview.gfsUri &&
p.fileKind === nextPreview.fileKind &&
p.byteLength === nextPreview.byteLength &&
- p.mimeType === nextPreview.mimeType
+ p.mimeType === nextPreview.mimeType &&
+ p.unavailable !== true &&
+ p.reloadVersion === undefined &&
+ p.resourceVersion === nextPreview.resourceVersion
return {
tabs: unchanged
? state.tabs
@@ -349,6 +353,80 @@ export function openPreviewTab(
return { tabs: [...state.tabs, tab], activeTabId: input.id }
}
+export type PreviewTabRemoteRefresh =
+ | {
+ status: 'available'
+ title: string
+ fileKind: PreviewTabPayload['fileKind']
+ mimeType?: string
+ byteLength: number
+ resourceVersion?: number
+ }
+ | { status: 'unavailable'; shellTitle: 'File unavailable' | 'Preview unavailable' }
+
+/** Apply current authorized metadata to every tab for one stable GFS URI. */
+export function refreshPreviewTab(
+ state: WorkspaceTabsState,
+ gfsUri: string,
+ refresh: PreviewTabRemoteRefresh
+): WorkspaceTabsState {
+ const targets = state.tabs.filter(
+ (tab): tab is WorkspaceTab & { preview: PreviewTabPayload } =>
+ tab.kind === 'preview' && tab.preview?.gfsUri === gfsUri
+ )
+ if (targets.length === 0) return state
+ let changed = false
+ const tabs = state.tabs.map(tab => {
+ if (tab.kind !== 'preview' || tab.preview?.gfsUri !== gfsUri) return tab
+ const previous = tab.preview
+ if (refresh.status === 'unavailable') {
+ if (previous.unavailable && tab.title === refresh.shellTitle) return tab
+ changed = true
+ return {
+ ...tab,
+ title: refresh.shellTitle,
+ preview: {
+ ...previous,
+ unavailable: true,
+ reloadVersion: (previous.reloadVersion ?? 0) + 1,
+ },
+ }
+ }
+ if (
+ refresh.resourceVersion !== undefined &&
+ previous.resourceVersion !== undefined &&
+ refresh.resourceVersion < previous.resourceVersion
+ ) {
+ return tab
+ }
+ const safeTitle = sanitizeAppTabTitle(refresh.title) || 'Preview'
+ const unchanged =
+ !previous.unavailable &&
+ tab.title === safeTitle &&
+ previous.fileKind === refresh.fileKind &&
+ previous.mimeType === refresh.mimeType &&
+ previous.byteLength === refresh.byteLength &&
+ previous.resourceVersion === refresh.resourceVersion
+ if (unchanged) return tab
+ changed = true
+ return {
+ ...tab,
+ title: safeTitle,
+ preview: {
+ gfsUri,
+ fileKind: refresh.fileKind,
+ byteLength: refresh.byteLength,
+ ...(refresh.mimeType !== undefined ? { mimeType: refresh.mimeType } : {}),
+ ...(refresh.resourceVersion !== undefined
+ ? { resourceVersion: refresh.resourceVersion }
+ : {}),
+ reloadVersion: (previous.reloadVersion ?? 0) + 1,
+ },
+ }
+ })
+ return changed ? { ...state, tabs } : state
+}
+
/** Settings: unique per `section` — focus the existing section tab (R6). */
export function openSettingsTab(
state: WorkspaceTabsState,
diff --git a/desktop-app/ui/src/lib/workspaceTabs.types.ts b/desktop-app/ui/src/lib/workspaceTabs.types.ts
index 6d9bb9479..1c22c5b5a 100644
--- a/desktop-app/ui/src/lib/workspaceTabs.types.ts
+++ b/desktop-app/ui/src/lib/workspaceTabs.types.ts
@@ -37,6 +37,11 @@ export type PreviewTabPayload = {
fileKind: 'image' | 'markdown' | 'video'
mimeType?: string
byteLength: number
+ resourceVersion?: number
+ /** Incremented by generic entity invalidation to remount the preview body. */
+ reloadVersion?: number
+ /** Fail-closed shell for deletion, denial, or a file that is no longer previewable. */
+ unavailable?: boolean
}
/**
@@ -105,6 +110,7 @@ export type OpenPreviewTabInput = {
fileKind: 'image' | 'markdown' | 'video'
mimeType?: string
byteLength: number
+ resourceVersion?: number
}
/**
diff --git a/desktop-app/ui/src/pages/FilePreviewPage.tsx b/desktop-app/ui/src/pages/FilePreviewPage.tsx
index d5c2bc1e1..86d1f17e8 100644
--- a/desktop-app/ui/src/pages/FilePreviewPage.tsx
+++ b/desktop-app/ui/src/pages/FilePreviewPage.tsx
@@ -56,6 +56,8 @@ export function FilePreviewPage({
fileKind,
mimeType,
byteLength,
+ reloadVersion,
+ unavailable = false,
}: FilePreviewPageProps) {
const ctrl = useGfsBrowserController()
const [reloadToken, setReloadToken] = useState(0)
@@ -67,6 +69,10 @@ export function FilePreviewPage({
setDenied(null)
}, [gfsUri])
+ useEffect(() => {
+ if (unavailable) setDenied(null)
+ }, [unavailable])
+
// R-4: when the authority controller detects a revocation while this tab is
// mounted, bump the reload token so the body re-fetches and fails closed
// instead of leaving already-rendered bytes on screen.
@@ -105,13 +111,13 @@ export function FilePreviewPage({
// Remounting the body on a reload bump discards any stale bytes and re-runs the
// fetch from scratch — the simplest correct "re-dispatch the fetch" (§3.B.3).
- const bodyKey = `${gfsUri}:${reloadToken}`
+ const bodyKey = `${gfsUri}:${reloadToken}:${reloadVersion ?? 0}`
return (
<section className="page">
<div className="da-gfs-preview-page">
- {denied ? (
- <EmptyState title="You no longer have access to this file" body={denied} />
+ {denied || unavailable || accessRevoked ? (
+ <EmptyState title="File unavailable" body="This item is no longer available." />
) : (
<>
{fileKind === 'image' ? (
diff --git a/desktop-app/ui/src/pages/FilePreviewPage.types.ts b/desktop-app/ui/src/pages/FilePreviewPage.types.ts
index 57f0d1a7b..3f53dedca 100644
--- a/desktop-app/ui/src/pages/FilePreviewPage.types.ts
+++ b/desktop-app/ui/src/pages/FilePreviewPage.types.ts
@@ -7,4 +7,8 @@ export interface FilePreviewPageProps {
mimeType?: string
/** File size in bytes, for the per-kind size-guard (not the bytes). */
byteLength: number
+ /** Changes on remote invalidation so all current preview bodies remount generically. */
+ reloadVersion?: number
+ /** Set when an authoritative re-resolve denies access or the file is no longer previewable. */
+ unavailable?: boolean
}
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index d33d66002..6f0d9401f 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -467,7 +467,7 @@ export function FilesPage({
// old modal-era contract. When no `onOpenPreview` is wired, it reports
// "not previewable" so the caller downloads instead of silently doing nothing.
const openFilePreview = (
- resource: Pick<GfsDriveResource, 'bytes' | 'gfsUri' | 'name'>
+ resource: Pick<GfsDriveResource, 'bytes' | 'gfsUri' | 'name' | 'version'>
): boolean => {
const preview = resolveGfsPreview(resource)
if (!preview || !onOpenPreview) return false
diff --git a/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsx
index a9df975fb..2a5b438da 100644
--- a/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsx
@@ -114,18 +114,13 @@ describe('FilePreviewPage', () => {
})
// R-4 (spec 18 §3.B.5): the preview tab must NOT close when access is revoked;
- // the revocation signal re-fetches the body so stale bytes are replaced by the
- // fail-closed error. Here the second fetch (after revocation) returns 403.
- it('re-fetches and fails closed when authority is revoked while the tab is mounted', async () => {
- let revoked = false
- const downloadPreview = stubDownload(async () => {
- if (revoked) throw new Error('403 Forbidden')
- return { bytes: new Uint8Array([1, 2, 3]).buffer }
- })
+ // stale bytes are purged and replaced by a non-sensitive unavailable shell.
+ it('purges the open preview when authority reports a revoked resource', async () => {
+ const downloadPreview = stubDownload(async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer }))
const controllerState = controller('active')
hookMock.useGfsBrowserController.mockReturnValue(controllerState)
- // A fresh element per render pass so the mutated mock is observed.
+ // A fresh element per render pass so the authority update is observed.
const makeElement = () => (
<FilePreviewPage
gfsUri="gfs://main/secret"
@@ -142,16 +137,16 @@ describe('FilePreviewPage', () => {
expect(downloadPreview).toHaveBeenCalledTimes(1)
// Access is revoked out-of-band → the authority controller reports revoked.
- revoked = true
controllerState.accessState = 'revoked'
rerender(makeElement())
- // The tab stays mounted (heading still present) but the stale image is gone
- // and the revoke reason is shown — no accessible content survives the revoke.
+ // The tab stays mounted, but sensitive preview bytes, filename, and denial
+ // details are removed when authorization is no longer available.
await waitFor(() => expect(screen.queryByAltText('Preview of secret.png')).toBeNull())
- expect(await screen.findByText('403 Forbidden')).toBeTruthy()
- expect(screen.getByRole('heading', { name: 'secret.png', level: 2 })).toBeTruthy()
- expect(downloadPreview).toHaveBeenCalledTimes(2)
+ expect(await screen.findByRole('heading', { name: 'File unavailable', level: 3 })).toBeTruthy()
+ expect(screen.queryByText('403 Forbidden')).toBeNull()
+ expect(screen.queryByText('secret.png')).toBeNull()
+ expect(downloadPreview).toHaveBeenCalledTimes(1)
})
// R1-H6: a persistent preview tab outlives the grant that opened it. A
@@ -191,11 +186,13 @@ describe('FilePreviewPage', () => {
// The file is unshared out-of-band → the next focus re-check 403s.
fireEvent.focus(window)
- // The image AND the Copy affordance are gone (observable UI — T4), the
- // denial reason renders, and the tab was never remounted.
+ // The image, Copy affordance, filename, and denial details are gone; the
+ // tab remains mounted behind a generic unavailable shell.
await waitFor(() => expect(screen.queryByAltText('Preview of secret.png')).toBeNull())
expect(screen.queryByRole('button', { name: 'Copy image to clipboard' })).toBeNull()
- expect(screen.getByText(deniedMessage)).toBeTruthy()
+ expect(screen.getByRole('heading', { name: 'File unavailable', level: 3 })).toBeTruthy()
+ expect(screen.queryByText(deniedMessage)).toBeNull()
+ expect(screen.queryByText('secret.png')).toBeNull()
expect(resolve).toHaveBeenCalledWith('gfs://main/secret')
// A per-resource 403 is NOT a session-authority failure: it was routed
// through handleAuthorityFailure (which declined) and did not revoke.
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index 005832755..4fda53428 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -2939,6 +2939,7 @@ describe('FilesPage', () => {
mimeType: 'image/png',
name: 'diagram.PNG',
bytes: 3,
+ version: 1,
})
// No modal, and FilesPage itself never fetches the bytes.
expect(screen.queryByRole('dialog', { name: 'diagram.PNG' })).toBeNull()
@@ -2960,6 +2961,7 @@ describe('FilesPage', () => {
kind: 'markdown',
name: 'README.md',
bytes: 12,
+ version: 1,
})
})
@@ -2979,6 +2981,7 @@ describe('FilesPage', () => {
mimeType: 'video/mp4',
name: 'demo.mp4',
bytes: 3,
+ version: 1,
})
})
@@ -3052,6 +3055,7 @@ describe('FilesPage', () => {
mimeType: 'image/svg+xml',
name: 'architecture.svg',
bytes: 4,
+ version: 1,
})
)
await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Open GFS link' })).toBeNull())