Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(gfs): restore session-scoped grants and upload paths
Miguelon Peluchonba3bbca6883c
diff --git a/control-ui/components/GfsImagePreview/index.tsx b/control-ui/components/GfsImagePreview/index.tsxindex 5ebca802d..91e5b4c62 100644--- a/control-ui/components/GfsImagePreview/index.tsx+++ b/control-ui/components/GfsImagePreview/index.tsx@@ -24,6 +24,7 @@ export function GfsImagePreview({const [previewError, setPreviewError] = useState<string | null>(null)const [copyState, setCopyState] = useState<'idle' | 'copied' | 'error'>('idle')const copyResetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const mountedRef = useRef(true)const { showToast } = useToast()useEffect(() => {@@ -69,42 +70,59 @@ export function GfsImagePreview({}, [byteLength, mimeType, rid])useEffect(() => {+ mountedRef.current = truereturn () => {+ mountedRef.current = falseif (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)}}, [])+ function markCopyState(state: 'copied' | 'error'): boolean {+ if (!mountedRef.current) return false+ setCopyState(state)+ if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)+ copyResetTimeoutRef.current = setTimeout(() => {+ if (mountedRef.current) setCopyState('idle')+ }, 2000)+ return true+ }+async function copyImageToClipboard(): Promise<void> {- if (!sourceBlob) return+ if (!sourceBlob || !mountedRef.current) returntry {if (typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {let clipboardBlob: Blob | null = sourceBlobif (!sourceBlob.type.includes('png')) {clipboardBlob = await convertBlobToPng(sourceBlob)}+ if (!mountedRef.current) returnif (clipboardBlob) {await navigator.clipboard.write([new ClipboardItem({ 'image/png': clipboardBlob })])- setCopyState('copied')- showToast(`Copied ${fileName} to the clipboard.`, { tone: 'success' })- if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)- copyResetTimeoutRef.current = setTimeout(() => setCopyState('idle'), 2000)+ if (!mountedRef.current) return+ if (markCopyState('copied')) {+ showToast(`Copied ${fileName} to the clipboard.`, { tone: 'success' })+ }return}}- if (navigator.clipboard?.writeText && previewUrl) {- await navigator.clipboard.writeText(previewUrl)- setCopyState('copied')- showToast(`Copied a ${fileName} link to the clipboard.`, { tone: 'success' })+ if (navigator.clipboard?.writeText) {+ const dataUrl = await blobToDataUrl(sourceBlob)+ if (!mountedRef.current) return+ await navigator.clipboard.writeText(dataUrl)+ if (!mountedRef.current) return+ if (markCopyState('copied')) {+ showToast(`Copied ${fileName} to the clipboard.`, { tone: 'success' })+ }} else {- setCopyState('error')- showToast('Copy failed — check browser clipboard permissions.', { tone: 'error' })+ if (markCopyState('error')) {+ showToast('Copy failed — check browser clipboard permissions.', { tone: 'error' })+ }}} catch {- setCopyState('error')- showToast('Copy failed — check browser clipboard permissions.', { tone: 'error' })+ if (markCopyState('error')) {+ showToast('Copy failed — check browser clipboard permissions.', { tone: 'error' })+ }}- if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)- copyResetTimeoutRef.current = setTimeout(() => setCopyState('idle'), 2000)}return createPortal(@@ -192,4 +210,15 @@ async function convertBlobToPng(blob: Blob): Promise<Blob | null> {}}+async function blobToDataUrl(blob: Blob): Promise<string> {+ const result = await new Promise<string | ArrayBuffer | null>((resolve, reject) => {+ const reader = new FileReader()+ reader.onload = () => resolve(reader.result)+ reader.onerror = () => reject(reader.error ?? new Error('Could not read the image'))+ reader.readAsDataURL(blob)+ })+ if (typeof result !== 'string') throw new Error('Could not read the image')+ return result+}+export type { GfsImagePreviewProps } from './types'diff --git a/control-ui/components/GfsMarkdownPreview/index.tsx b/control-ui/components/GfsMarkdownPreview/index.tsxindex 6ae45b8c1..d7fceccd0 100644--- a/control-ui/components/GfsMarkdownPreview/index.tsx+++ b/control-ui/components/GfsMarkdownPreview/index.tsx@@ -77,12 +77,15 @@ export function GfsMarkdownPreview({const [previewError, setPreviewError] = useState<string | null>(null)const [copyState, setCopyState] = useState<'idle' | 'copied' | 'error'>('idle')const copyResetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const mountedRef = useRef(true)const { showToast } = useToast()const blocks = useMemo(() => (source === null ? [] : parseVanillaMarkdown(source)), [source])const isPlainText = isPlainTextName(fileName)useEffect(() => {+ mountedRef.current = truereturn () => {+ mountedRef.current = falseif (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)}}, [])@@ -126,23 +129,35 @@ export function GfsMarkdownPreview({}}, [byteLength, rid])+ function markCopyState(state: 'copied' | 'error'): boolean {+ if (!mountedRef.current) return false+ setCopyState(state)+ if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)+ copyResetTimeoutRef.current = setTimeout(() => {+ if (mountedRef.current) setCopyState('idle')+ }, 2000)+ return true+ }+async function copySourceToClipboard(): Promise<void> {- if (source === null) return+ if (source === null || !mountedRef.current) returnif (!navigator.clipboard?.writeText) {- showToast('Clipboard is not available in this browser.', { tone: 'error' })- setCopyState('error')+ if (markCopyState('error')) {+ showToast('Clipboard is not available in this browser.', { tone: 'error' })+ }return}try {await navigator.clipboard.writeText(source)- setCopyState('copied')- showToast(`Copied ${fileName} to the clipboard.`, { tone: 'success' })+ if (!mountedRef.current) return+ if (markCopyState('copied')) {+ showToast(`Copied ${fileName} to the clipboard.`, { tone: 'success' })+ }} catch {- setCopyState('error')- showToast('Copy failed — check browser clipboard permissions.', { tone: 'error' })+ if (markCopyState('error')) {+ showToast('Copy failed — check browser clipboard permissions.', { tone: 'error' })+ }}- if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)- copyResetTimeoutRef.current = setTimeout(() => setCopyState('idle'), 2000)}return createPortal(diff --git a/desktop-app/ui/src/components/GfsImagePreview/index.tsx b/desktop-app/ui/src/components/GfsImagePreview/index.tsxindex d673dbb51..f19c11949 100644--- a/desktop-app/ui/src/components/GfsImagePreview/index.tsx+++ b/desktop-app/ui/src/components/GfsImagePreview/index.tsx@@ -20,6 +20,12 @@ export function GfsImagePreview({const [previewError, setPreviewError] = useState<string | null>(null)const [copyState, setCopyState] = useState<'idle' | 'copied' | 'error'>('idle')const copyResetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const mountedRef = useRef(true)+ const onDownloadErrorRef = useRef(onDownloadError)++ useEffect(() => {+ onDownloadErrorRef.current = onDownloadError+ }, [onDownloadError])useEffect(() => {closeButtonRef.current?.focus()@@ -46,7 +52,7 @@ export function GfsImagePreview({setPreviewUrl(objectUrl)} catch (error) {if (!active) return- onDownloadError?.(error)+ onDownloadErrorRef.current?.(error)setPreviewError(error instanceof Error ? error.message : 'Could not load the image preview')}}@@ -56,42 +62,54 @@ export function GfsImagePreview({active = falseif (objectUrl) URL.revokeObjectURL(objectUrl)}- }, [byteLength, gfsUri, mimeType, onDownloadError])+ }, [byteLength, gfsUri, mimeType])useEffect(() => {+ mountedRef.current = truereturn () => {+ mountedRef.current = falseif (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)}}, [])+ function markCopyState(state: 'copied' | 'error'): boolean {+ if (!mountedRef.current) return false+ setCopyState(state)+ if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)+ copyResetTimeoutRef.current = setTimeout(() => {+ if (mountedRef.current) setCopyState('idle')+ }, 2000)+ return true+ }+async function copyImageToClipboard(): Promise<void> {- if (!sourceBlob) return+ if (!sourceBlob || !mountedRef.current) returntry {if (typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {let clipboardBlob: Blob | null = sourceBlobif (!sourceBlob.type.includes('png')) {clipboardBlob = await convertBlobToPng(sourceBlob)}+ if (!mountedRef.current) returnif (clipboardBlob) {await navigator.clipboard.write([new ClipboardItem({ 'image/png': clipboardBlob })])- setCopyState('copied')- } else if (navigator.clipboard?.writeText && previewUrl) {- await navigator.clipboard.writeText(previewUrl)- setCopyState('copied')- } else {- setCopyState('error')+ if (!mountedRef.current) return+ markCopyState('copied')+ return}- } else if (navigator.clipboard?.writeText && previewUrl) {- await navigator.clipboard.writeText(previewUrl)- setCopyState('copied')+ }+ if (navigator.clipboard?.writeText) {+ const dataUrl = await blobToDataUrl(sourceBlob)+ if (!mountedRef.current) return+ await navigator.clipboard.writeText(dataUrl)+ if (!mountedRef.current) return+ markCopyState('copied')} else {- setCopyState('error')+ markCopyState('error')}} catch {- setCopyState('error')+ markCopyState('error')}- if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)- copyResetTimeoutRef.current = setTimeout(() => setCopyState('idle'), 2000)}return createPortal(@@ -171,4 +189,15 @@ async function convertBlobToPng(blob: Blob): Promise<Blob | null> {}}+async function blobToDataUrl(blob: Blob): Promise<string> {+ const result = await new Promise<string | ArrayBuffer | null>((resolve, reject) => {+ const reader = new FileReader()+ reader.onload = () => resolve(reader.result)+ reader.onerror = () => reject(reader.error ?? new Error('Could not read the image'))+ reader.readAsDataURL(blob)+ })+ if (typeof result !== 'string') throw new Error('Could not read the image')+ return result+}+export type { GfsImagePreviewProps } from './types'diff --git a/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsx b/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsxindex 8839ffc19..013c0ffea 100644--- a/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsx+++ b/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsx@@ -73,11 +73,19 @@ export function GfsMarkdownPreview({const [previewError, setPreviewError] = useState<string | null>(null)const [copyState, setCopyState] = useState<'idle' | 'copied' | 'error'>('idle')const copyResetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const mountedRef = useRef(true)+ const onDownloadErrorRef = useRef(onDownloadError)const blocks = useMemo(() => (source === null ? [] : parseVanillaMarkdown(source)), [source])const isPlainText = isPlainTextName(fileName)useEffect(() => {+ onDownloadErrorRef.current = onDownloadError+ }, [onDownloadError])++ useEffect(() => {+ mountedRef.current = truereturn () => {+ mountedRef.current = falseif (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)}}, [])@@ -103,7 +111,7 @@ export function GfsMarkdownPreview({if (active) setSource(markdown)} catch (error) {if (!active) return- onDownloadError?.(error)+ onDownloadErrorRef.current?.(error)setPreviewError(error instanceof Error ? error.message : 'Could not load the Markdown preview')@@ -114,22 +122,31 @@ export function GfsMarkdownPreview({return () => {active = false}- }, [byteLength, gfsUri, onDownloadError])+ }, [byteLength, gfsUri])++ function markCopyState(state: 'copied' | 'error'): boolean {+ if (!mountedRef.current) return false+ setCopyState(state)+ if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)+ copyResetTimeoutRef.current = setTimeout(() => {+ if (mountedRef.current) setCopyState('idle')+ }, 2000)+ return true+ }async function copySourceToClipboard(): Promise<void> {- if (source === null) return+ if (source === null || !mountedRef.current) returntry {if (navigator.clipboard?.writeText) {await navigator.clipboard.writeText(source)- setCopyState('copied')+ if (!mountedRef.current) return+ markCopyState('copied')} else {- setCopyState('error')+ markCopyState('error')}} catch {- setCopyState('error')+ markCopyState('error')}- if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)- copyResetTimeoutRef.current = setTimeout(() => setCopyState('idle'), 2000)}return createPortal(diff --git a/desktop-app/ui/src/components/GfsVideoPreview/index.tsx b/desktop-app/ui/src/components/GfsVideoPreview/index.tsxindex 2c5716a3c..46e4efb2f 100644--- a/desktop-app/ui/src/components/GfsVideoPreview/index.tsx+++ b/desktop-app/ui/src/components/GfsVideoPreview/index.tsx@@ -17,6 +17,11 @@ export function GfsVideoPreview({const closeButtonRef = useRef<HTMLButtonElement | null>(null)const [previewUrl, setPreviewUrl] = useState<string | null>(null)const [previewError, setPreviewError] = useState<string | null>(null)+ const onDownloadErrorRef = useRef(onDownloadError)++ useEffect(() => {+ onDownloadErrorRef.current = onDownloadError+ }, [onDownloadError])useEffect(() => {closeButtonRef.current?.focus()@@ -41,7 +46,7 @@ export function GfsVideoPreview({setPreviewUrl(objectUrl)} catch (error) {if (!active) return- onDownloadError?.(error)+ onDownloadErrorRef.current?.(error)setPreviewError(error instanceof Error ? error.message : 'Could not load the video preview')}}@@ -51,7 +56,7 @@ export function GfsVideoPreview({active = falseif (objectUrl) URL.revokeObjectURL(objectUrl)}- }, [byteLength, gfsUri, mimeType, onDownloadError])+ }, [byteLength, gfsUri, mimeType])return createPortal(<divdiff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsxindex f1bee87e7..ffd898502 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { AuthContext, type AuthContextValue } from '@contexts/AuthContext'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, cleanup, render, screen, waitFor } from '@testing-library/react'+import { desktopQueryKeys } from '../queryKeys'import { useGfsBrowserController } from '../useGfsBrowserController'const userA = {@@ -22,6 +23,8 @@ const userB = {teamName: 'Team B',}+let lastHarnessQueryClient: QueryClient | null = null+function authValue(me: AuthContextValue['me']): AuthContextValue {return {booting: false,@@ -133,6 +136,7 @@ function Harness({ children }: { children: ReactNode }) {const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: false } } }))+ lastHarnessQueryClient = clientreturn (<AuthContext.Provider value={authValue(me)}><QueryClientProvider client={client}>@@ -148,6 +152,7 @@ function Harness({ children }: { children: ReactNode }) {describe('useGfsBrowserController', () => {afterEach(() => {cleanup()+ lastHarnessQueryClient = nullvi.restoreAllMocks()})@@ -184,11 +189,16 @@ describe('useGfsBrowserController', () => {})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('refreshes cached affordances after permissions change outside Desktop', async () => {@@ -615,6 +625,7 @@ function ManageProbe() {describe('useGfsBrowserController — grants list / revoke / inherit (#826)', () => {afterEach(() => {cleanup()+ lastHarnessQueryClient = nullvi.restoreAllMocks()})@@ -670,6 +681,16 @@ describe('useGfsBrowserController — grants list / revoke / inherit (#826)', ()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 () => {diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.tsindex 7ea89878c..6858a72e7 100644--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts@@ -190,7 +190,11 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {// The grants listing is the revoke-id source (the grant PUT returns no ids),// so writes must refetch it. Enabled only while the Manage dialog is open.const grantsQuery = useQuery({- queryKey: ['gfs', DRIVE, current?.resourceId ?? '', 'grants'],+ queryKey: desktopQueryKeys.gfsGrants(+ sessionScope ?? 'anonymous',+ current?.resourceId ?? '',+ DRIVE+ ),queryFn: () => window.clerum.gfs.listGrants(current!.resourceId, DRIVE),enabled: Boolean(sessionScope) && Boolean(current) && grantsListEnabled,})@@ -199,9 +203,9 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {if (!resourceId) returnawait queryClient.invalidateQueries({exact: true,- queryKey: ['gfs', DRIVE, resourceId, 'grants'],+ queryKey: desktopQueryKeys.gfsGrants(sessionScope ?? 'anonymous', resourceId, DRIVE),})- }, [current?.resourceId, queryClient])+ }, [current?.resourceId, queryClient, sessionScope])const revokeGrantMutation = useMutation({mutationFn: (grantId: string) => window.clerum.gfs.revokeGrant(grantId),onSuccess: refreshGrants,@@ -227,6 +231,16 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {window.clerum.gfs.createFile(input.parentResourceId, input.name, input.encodedData, DRIVE),onSuccess: refreshGfs,})+ const createFileFromPathMutation = useMutation({+ mutationFn: (input: { parentResourceId: string; name: string; filePath: string }) =>+ window.clerum.gfs.createFileFromPath(+ input.parentResourceId,+ input.name,+ input.filePath,+ DRIVE+ ),+ onSuccess: refreshGfs,+ })const replaceFileMutation = useMutation({mutationFn: (input: { resourceId: string; encodedData: string; ifMatch?: number }) =>window.clerum.gfs.replaceFile(input.resourceId, input.encodedData, DRIVE, input.ifMatch),@@ -241,6 +255,22 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {await refreshGfs()},})+ const replaceFileFromPathMutation = useMutation({+ mutationFn: (input: { resourceId: string; filePath: string; ifMatch?: number }) =>+ window.clerum.gfs.replaceFileFromPath(input.resourceId, input.filePath, DRIVE, input.ifMatch),+ onSuccess: async (receipt, input) => {+ if (receipt.resultVersion !== undefined) {+ setCrumbs(prev =>+ prev.map(crumb =>+ crumb.resourceId === input.resourceId+ ? { ...crumb, version: receipt.resultVersion! }+ : crumb+ )+ )+ }+ await refreshGfs()+ },+ })const renameResourceMutation = useMutation({mutationFn: (input: { resourceId: string; name: string; ifMatch?: number }) =>window.clerum.gfs.renameResource(input.resourceId, input.name, DRIVE, input.ifMatch),@@ -384,7 +414,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {const reset = useCallback(() => {setCrumbs([])setOpenError(null)- void queryClient.removeQueries({ queryKey: ['desktop-app', 'gfs'] })+ void queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })}, [queryClient])// Delegation actions throw on server rejection (e.g. 403 escalation_rejected);@@ -460,8 +490,12 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {createFolder: (name: string) => createFolderMutation.mutateAsync(name),createFile: (parentResourceId: string, name: string, encodedData: string) =>createFileMutation.mutateAsync({ parentResourceId, name, encodedData }),+ createFileFromPath: (parentResourceId: string, name: string, filePath: string) =>+ createFileFromPathMutation.mutateAsync({ parentResourceId, name, filePath }),replaceFile: (resourceId: string, encodedData: string, ifMatch?: number) =>replaceFileMutation.mutateAsync({ resourceId, encodedData, ifMatch }),+ replaceFileFromPath: (resourceId: string, filePath: string, ifMatch?: number) =>+ replaceFileFromPathMutation.mutateAsync({ resourceId, filePath, ifMatch }),renameResource: (resourceId: string, name: string, ifMatch?: number) =>renameResourceMutation.mutateAsync({ resourceId, name, ifMatch }),moveResource: (resourceId: string, destinationId: string, ifMatch?: number) =>@@ -471,7 +505,9 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {mutating:createFolderMutation.isPending ||createFileMutation.isPending ||+ createFileFromPathMutation.isPending ||replaceFileMutation.isPending ||+ replaceFileFromPathMutation.isPending ||renameResourceMutation.isPending ||moveResourceMutation.isPending ||deleteResourceMutation.isPending,diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsxindex 903143d77..1ca22b3f9 100644--- a/desktop-app/ui/src/pages/FilesPage.tsx+++ b/desktop-app/ui/src/pages/FilesPage.tsx@@ -50,18 +50,6 @@ import type {MyAgentEntry,} from './FilesPage.types'-async function fileToEncodedData(file: File): Promise<string> {- assertGfsFileUploadSize(file.size)- const bytes = new Uint8Array(await file.arrayBuffer())- assertGfsFileUploadSize(bytes.byteLength)- let binary = ''- const chunkSize = 0x8000- for (let offset = 0; offset < bytes.length; offset += chunkSize) {- binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize))- }- return btoa(binary)-}-function hasBit(affordances: { held?: string[] } | null, bit: string): boolean {return Boolean(affordances?.held?.includes(bit))}@@ -70,14 +58,6 @@ function hasDraggedFiles(event: ReactDragEvent<HTMLElement>): boolean {return Array.from(event.dataTransfer.types || []).includes('Files')}-function isDroppedPreviewFile(file: File): boolean {- return (- file.type.toLowerCase().startsWith('image/') ||- gfsImagePreviewMimeType(file.name) !== null ||- isGfsMarkdownPreviewFile(file.name)- )-}-function isGfsPreviewFile(fileName: string): boolean {return (gfsImagePreviewMimeType(fileName) !== null ||@@ -197,7 +177,6 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:if (!sessionScope) returnconst folders = items.filter(item => item.kind === 'directory')if (folders.length === 0) return- let cancelled = falsevoid Promise.all(folders.map(folder =>queryClient@@ -212,12 +191,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:// real navigation will surface the error normally.}))- ).then(() => {- if (cancelled) return- })- return () => {- cancelled = true- }+ )}, [items, queryClient, sessionScope])const teamDirectoryQuery = useQuery({@@ -378,8 +352,11 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:anchor.click()setTimeout(() => URL.revokeObjectURL(url), 10_000)pushToast?.(`Downloaded ${name}`, 'success')- } catch (uploadError) {- pushToast?.(uploadError instanceof Error ? uploadError.message : String(uploadError), 'error')+ } catch (downloadError) {+ pushToast?.(+ downloadError instanceof Error ? downloadError.message : String(downloadError),+ 'error'+ )}}@@ -434,8 +411,11 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:) => {if (!file || !parentResourceId) returntry {+ assertGfsFileUploadSize(file.size)const name = await normalizeGfsResourceName(file.name)- await ctrl.createFile(parentResourceId, name, await fileToEncodedData(file))+ const filePath = window.clerum.gfs.getPathForFile(file)+ if (!filePath) throw new Error('Could not resolve the selected local file')+ await ctrl.createFileFromPath(parentResourceId, name, filePath)pushToast?.(`Uploaded ${name}`, 'success')} catch (uploadError) {pushToast?.(uploadError instanceof Error ? uploadError.message : String(uploadError), 'error')@@ -476,24 +456,16 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:}const droppedFiles = Array.from(event.dataTransfer.files || [])- const previewFiles = droppedFiles.filter(isDroppedPreviewFile)- if (!previewFiles.length) {- pushToast?.('Only image and Markdown files can be dropped here.', 'error')+ if (!droppedFiles.length) {+ pushToast?.('No files were dropped.', 'error')return}- setDroppedUploadCount(previewFiles.length)+ setDroppedUploadCount(droppedFiles.length)try {- for (const file of previewFiles) {+ for (const file of droppedFiles) {await handleUploadFile(file, destinationResourceId)}- const skippedCount = droppedFiles.length - previewFiles.length- if (skippedCount > 0) {- pushToast?.(- `${skippedCount} unsupported ${skippedCount === 1 ? 'file was' : 'files were'} skipped.`,- 'error'- )- }} finally {setDroppedUploadCount(0)}@@ -502,7 +474,10 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:const handleReplaceCurrentFile = async (file: File | null | undefined) => {if (!file || !current) returntry {- await ctrl.replaceFile(current.resourceId, await fileToEncodedData(file), current.version)+ assertGfsFileUploadSize(file.size)+ const filePath = window.clerum.gfs.getPathForFile(file)+ if (!filePath) throw new Error('Could not resolve the selected local file')+ await ctrl.replaceFileFromPath(current.resourceId, filePath, current.version)pushToast?.(`Replaced ${current.name}`, 'success')} catch (replaceError) {pushToast?.(@@ -731,7 +706,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:{droppedUploadCount > 0? `Uploading ${droppedUploadCount} ${droppedUploadCount === 1 ? 'file' : 'files'}…`: droppedUploadRestriction ||- `Drop images or Markdown files to upload to ${current?.name || 'this folder'}`}+ `Drop files to upload to ${current?.name || 'this folder'}`}</div>) : null}diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsxindex 6697e9c32..7e980a26e 100644--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdomimport { useState } from 'react'-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'import { GFS_FILE_UPLOAD_MAX_BYTES } from '@constants/gfsFileUpload'@@ -57,7 +57,9 @@ function baseController() {createShare: vi.fn(),createFolder: vi.fn(),createFile: vi.fn(),+ createFileFromPath: vi.fn(),replaceFile: vi.fn(),+ replaceFileFromPath: vi.fn(),renameResource: vi.fn(),moveResource: vi.fn(),deleteResource: vi.fn(),@@ -96,6 +98,17 @@ async function chooseManageAction(resourceName: string, actionName: string) {}describe('FilesPage', () => {+ beforeEach(() => {+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ gfs: {+ getPathForFile: vi.fn((file: File) => `/tmp/${file.name}`),+ },+ },+ })+ })+afterEach(() => {cleanup()vi.useRealTimers()@@ -403,9 +416,9 @@ describe('FilesPage', () => {expect(screen.queryByLabelText('Upload file')).toBeNull()})- it('uploads dropped images and Markdown files into the open writable folder', async () => {- const createFile = vi.fn(- async (_parentResourceId: string, _name: string, _encodedData: string) => undefined+ it('uploads dropped files into the open writable folder', async () => {+ const createFileFromPath = vi.fn(+ async (_parentResourceId: string, _name: string, _filePath: string) => undefined)const pushToast = vi.fn()hookMock.useGfsBrowserController.mockReturnValue({@@ -423,20 +436,19 @@ describe('FilesPage', () => {grantableBits: [],canCreateShare: false,},- createFile,+ createFileFromPath,})renderFilesPage(pushToast)const browser = screen.getByRole('region', { name: 'Global File System browser' })const image = new File(['desktop image'], 'diagram.png', { type: 'image/png' })const markdown = new File(['# Desktop notes'], 'notes.markdown', { type: 'text/markdown' })- const dataTransfer = { dropEffect: 'none', files: [image, markdown], types: ['Files'] }+ const video = new File(['desktop video'], 'clip.mov', { type: 'video/quicktime' })+ const dataTransfer = { dropEffect: 'none', files: [image, markdown, video], types: ['Files'] }fireEvent.dragEnter(browser, { dataTransfer })const dropStatus = screen.getByRole('status')- expect(dropStatus.textContent).toContain(- 'Drop images or Markdown files to upload to Team folder'- )+ expect(dropStatus.textContent).toContain('Drop files to upload to Team folder')expect(dropStatus.className).toContain('composer-drop-overlay')await act(async () => {@@ -445,15 +457,21 @@ describe('FilesPage', () => {})await waitFor(() =>- expect(createFile).toHaveBeenCalledWith('folder-1', 'diagram.png', 'ZGVza3RvcCBpbWFnZQ==')+ expect(createFileFromPath).toHaveBeenCalledWith('folder-1', 'diagram.png', '/tmp/diagram.png'))- expect(createFile).toHaveBeenCalledWith('folder-1', 'notes.markdown', 'IyBEZXNrdG9wIG5vdGVz')+ expect(createFileFromPath).toHaveBeenCalledWith(+ 'folder-1',+ 'notes.markdown',+ '/tmp/notes.markdown'+ )+ expect(createFileFromPath).toHaveBeenCalledWith('folder-1', 'clip.mov', '/tmp/clip.mov')expect(pushToast).toHaveBeenCalledWith('Uploaded diagram.png', 'success')expect(pushToast).toHaveBeenCalledWith('Uploaded notes.markdown', 'success')+ expect(pushToast).toHaveBeenCalledWith('Uploaded clip.mov', 'success')})it('allows a Markdown drop to retry immediately after an upload failure', async () => {- const createFile = vi+ const createFileFromPath = vi.fn().mockRejectedValueOnce(new Error('temporary upload failure')).mockResolvedValueOnce(undefined)@@ -473,7 +491,7 @@ describe('FilesPage', () => {grantableBits: [],canCreateShare: false,},- createFile,+ createFileFromPath,})renderFilesPage(pushToast)@@ -500,8 +518,12 @@ describe('FilesPage', () => {await Promise.resolve()})- await waitFor(() => expect(createFile).toHaveBeenCalledTimes(2))- expect(createFile).toHaveBeenLastCalledWith('folder-1', 'retry.md', 'IyBSZXRyeQ==')+ await waitFor(() => expect(createFileFromPath).toHaveBeenCalledTimes(2))+ expect(createFileFromPath).toHaveBeenLastCalledWith(+ 'folder-1',+ 'retry.md',+ '/tmp/retry.md'+ )expect(pushToast).toHaveBeenCalledWith('Uploaded retry.md', 'success')})@@ -527,8 +549,8 @@ describe('FilesPage', () => {path: '/shared',}let releaseFirstUpload: (() => void) | undefined- const createFile = vi.fn((_parentResourceId: string, _name: string, _encodedData: string) =>- createFile.mock.calls.length === 1+ const createFileFromPath = vi.fn((_parentResourceId: string, _name: string, _filePath: string) =>+ createFileFromPath.mock.calls.length === 1? new Promise<void>(resolve => {releaseFirstUpload = resolve})@@ -547,7 +569,7 @@ describe('FilesPage', () => {grantableBits: [],canCreateShare: false,},- createFile,+ createFileFromPath,openChild: (resource: typeof folderB) => setCurrent(resource),}}@@ -565,16 +587,16 @@ describe('FilesPage', () => {}fireEvent.drop(browser, { dataTransfer })- await waitFor(() => expect(createFile).toHaveBeenCalledTimes(1))+ await waitFor(() => expect(createFileFromPath).toHaveBeenCalledTimes(1))fireEvent.click(screen.getByRole('button', { name: 'Shared folder' }))releaseFirstUpload?.()- await waitFor(() => expect(createFile).toHaveBeenCalledTimes(2))- expect(createFile.mock.calls.map(call => call[0])).toEqual(['folder-a', 'folder-a'])+ await waitFor(() => expect(createFileFromPath).toHaveBeenCalledTimes(2))+ expect(createFileFromPath.mock.calls.map(call => call[0])).toEqual(['folder-a', 'folder-a'])})it('rejects oversized dropped files before reading or uploading them', async () => {- const createFile = vi.fn()+ const createFileFromPath = vi.fn()const pushToast = vi.fn()hookMock.useGfsBrowserController.mockReturnValue({...baseController(),@@ -591,11 +613,10 @@ describe('FilesPage', () => {grantableBits: [],canCreateShare: false,},- createFile,+ createFileFromPath,})const oversized = new File(['small fixture'], 'oversized.md', { type: 'text/markdown' })Object.defineProperty(oversized, 'size', { value: GFS_FILE_UPLOAD_MAX_BYTES + 1 })- const arrayBuffer = vi.spyOn(oversized, 'arrayBuffer')renderFilesPage(pushToast)fireEvent.drop(screen.getByRole('region', { name: 'Global File System browser' }), {@@ -605,12 +626,11 @@ describe('FilesPage', () => {await waitFor(() =>expect(pushToast).toHaveBeenCalledWith('GFS uploads are limited to 200 MB per file.', 'error'))- expect(arrayBuffer).not.toHaveBeenCalled()- expect(createFile).not.toHaveBeenCalled()+ expect(createFileFromPath).not.toHaveBeenCalled()})it('keeps cached write access available while affordances refresh', async () => {- const createFile = vi.fn(async () => undefined)+ const createFileFromPath = vi.fn(async () => undefined)hookMock.useGfsBrowserController.mockReturnValue({...baseController(),current: {@@ -627,7 +647,7 @@ describe('FilesPage', () => {canCreateShare: false,},loadingAffordances: true,- createFile,+ createFileFromPath,})renderFilesPage()@@ -639,17 +659,15 @@ describe('FilesPage', () => {}fireEvent.dragEnter(browser, { dataTransfer })- expect(screen.getByRole('status').textContent).toContain(- 'Drop images or Markdown files to upload to Team folder'- )+ expect(screen.getByRole('status').textContent).toContain('Drop files to upload to Team folder')fireEvent.drop(browser, { dataTransfer })await waitFor(() =>- expect(createFile).toHaveBeenCalledWith('folder-1', 'notes.md', 'IyBOb3Rlcw==')+ expect(createFileFromPath).toHaveBeenCalledWith('folder-1', 'notes.md', '/tmp/notes.md'))})it('explains why dropped preview files cannot be uploaded without folder write permission', () => {- const createFile = vi.fn()+ const createFileFromPath = vi.fn()const pushToast = vi.fn()hookMock.useGfsBrowserController.mockReturnValue({...baseController(),@@ -666,7 +684,7 @@ describe('FilesPage', () => {grantableBits: [],canCreateShare: false,},- createFile,+ createFileFromPath,})renderFilesPage(pushToast)@@ -680,7 +698,7 @@ describe('FilesPage', () => {expect(screen.getByRole('status').textContent).toContain(reason)fireEvent.drop(browser, { dataTransfer })- expect(createFile).not.toHaveBeenCalled()+ expect(createFileFromPath).not.toHaveBeenCalled()expect(pushToast).toHaveBeenCalledWith(reason, 'error')})@@ -723,7 +741,7 @@ describe('FilesPage', () => {})it('surfaces stale replace and rename precondition failures for the current file', async () => {- const replaceFile = vi.fn(async () => {+ const replaceFileFromPath = vi.fn(async () => {throw new Error('precondition_failed: stale file version')})const renameResource = vi.fn(async () => {@@ -745,7 +763,7 @@ describe('FilesPage', () => {grantableBits: [],canCreateShare: false,},- replaceFile,+ replaceFileFromPath,renameResource,})@@ -770,7 +788,7 @@ describe('FilesPage', () => {await Promise.resolve()})- expect(replaceFile).toHaveBeenCalledWith('file-1', 'cmVwbGFjZW1lbnQ=', 7)+ expect(replaceFileFromPath).toHaveBeenCalledWith('file-1', '/tmp/report.txt', 7)expect(renameResource).toHaveBeenCalledWith('file-1', 'report-renamed.txt', 7)expect(pushToast).toHaveBeenCalledWith('precondition_failed: stale file version', 'error')expect(pushToast).toHaveBeenCalledWith('precondition_failed: stale resource version', 'error')