Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
Merge origin/dev into fix/gfs-desktop
Miguelon Peluchon0cdf5867b220
diff --cc control-ui/components/GfsBrowser.tsxindex 42292eda0,75838c0c0..841d809e8--- a/control-ui/components/GfsBrowser.tsx+++ b/control-ui/components/GfsBrowser.tsx@@@ -15,9 -8,16 +15,17 @@@ importimport { useToast } from '@components/Toast'import { IconChevronRight, IconDownload, IconPaperclip, IconUpload, IconX } from '@components/icons'import { Button, TextInput } from '@components/ui'- import { GFS_UPLOAD_TIMEOUT_MS, apiGet, apiSend, gfsDownload, isSilentApiError } from '@lib/api'+ import { apiGet, apiSend, gfsDownload, isSilentApiError } from '@lib/api'+import { isGfsDocumentFile } from '@lib/gfsDocumentFile'- import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'+ import {+ GfsUploadCapabilityError,+ type GfsUploadJob,+ type GfsUploadJobInput,+ type GfsUploadJobSnapshot,+ assertGfsFileUploadSize,+ createGfsUploadJob,+ uploadGfsFileLegacy,+ } from '@lib/gfsFileUpload'import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'import { isGfsMarkdownPreviewFile } from '@lib/gfsMarkdownPreview'import { normalizeGfsResourceName } from '@lib/gfsResourceName'@@@ -166,6 -194,44 +234,42 @@@ export function GfsBrowser(): React.JSX// Resource IDs currently streaming a download (disables that row's button).const [downloadingIds, setDownloadingIds] = useState<ReadonlySet<string>>(() => new Set())+ /**- * The uploader already emits the exact aggregate of committed bytes plus- * each part's maximum in-flight observation. Keep a small monotonic guard- * only for two stale `uploading` snapshots arriving out of order; terminal- * or paused snapshots, and direct progress observations, must be accepted- * exactly so a failed retry cannot leave the bar overstated.++ * Keep progress truthful when in-flight part observations arrive out of++ * order. Only stale uploading snapshots are monotonic; direct progress and++ * terminal/paused snapshots are accepted exactly.+ */+ const mergeUploadSnapshot = useCallback((next: GfsUploadJobSnapshot): void => {+ setUploadSnapshot(previous => {+ if (!previous) return next+ const previousUploadId = previous.session?.uploadId+ const nextUploadId = next.session?.uploadId+ if (+ (previousUploadId && nextUploadId && previousUploadId !== nextUploadId) ||+ previous.totalBytes !== next.totalBytes+ )+ return next+ const uploadedBytes =+ previous.state === 'uploading' && next.state === 'uploading'+ ? Math.max(previous.uploadedBytes, next.uploadedBytes)+ : next.uploadedBytes+ return {+ ...next,+ uploadedBytes: Math.min(Math.max(0, uploadedBytes), next.totalBytes),+ }+ })+ }, [])++ const mergeUploadProgress = useCallback((uploadedBytes: number): void => {+ setUploadSnapshot(previous => {+ if (!previous) return previous+ return {+ ...previous,+ uploadedBytes: Math.min(Math.max(0, uploadedBytes), previous.totalBytes),+ }+ })+ }, [])+const current = crumbs[crumbs.length - 1]const currentLabel = current?.name === '/' ? DRIVE : current?.name || DRIVE@@@ -375,20 -444,49 +557,47 @@@const rid = current?.rid ?? (current?.id ? ridOfResourceId(current.id) : null)if (!rid || !file) returnsetUploading(true)+ let resumeUploadId: string | undefinedtry {+ assertGfsFileUploadSize(file.size)const name = await normalizeGfsResourceName(file.name)- await apiSend(- 'POST',- `/api/v1/gfs/proxy/v1/resources/${encodeURIComponent(rid)}/children`,- {- name,- kind: 'file',- contentBase64: await fileToEncodedData(file),+ const target = { operation: 'create' as const, parentRid: rid }+ resumeUploadId = matchingPendingResumeUploadId(file, target, name)+ const job = createGfsUploadJob({+ file,+ name,+ target,+ resumeUploadId,+ onPersistPending: record => {+ persistPendingGfsUpload({+ idempotencyKey: record.idempotencyKey,+ fileName: record.fileName,+ fileSize: record.fileSize,+ lastModified: record.lastModified,+ target: record.target,+ name: record.name,+ })},- {},- {},- { timeoutMs: GFS_UPLOAD_TIMEOUT_MS }- )- onProgress: progress => {- mergeUploadProgress(progress.uploadedBytes)- },++ onProgress: progress => mergeUploadProgress(progress.uploadedBytes),+ onState: snapshot => mergeUploadSnapshot(snapshot),+ onPersist: record => {+ persistPendingGfsUpload({+ uploadId: record.uploadId,+ fileName: record.fileName,+ fileSize: record.fileSize,+ lastModified: record.lastModified,+ target: record.target,+ name: record.name,+ })+ },+ onClearPersisted: uploadId => clearPendingGfsUpload(uploadId),+ })+ uploadJobRef.current = job+ const receipt = await job.start()+ if (receipt.state === 'paused') {+ setUploading(false)+ return+ }showToast('File uploaded.', { tone: 'success' })setUploadCandidate(null)setUploadOpen(false)@@@ -502,6 -693,27 +750,57 @@@}}- async function uploadFileToFolder(- folder: GfsChild,- file: File | null | undefined- ): Promise<void> {- if (!file || folder.kind !== 'directory') return++ async function pauseUpload(): Promise<void> {++ const job = uploadJobRef.current++ if (!job) return+ try {- const name = await normalizeGfsResourceName(file.name)- const target = { operation: 'create' as const, parentRid: folder.rid }- const state = await uploadWithCompatibility({- file,- name,- target,- resumeUploadId: matchingPendingResumeUploadId(file, target, name),- })- if (state === 'completed') showToast('File uploaded.', { tone: 'success' })- else showToast('Upload paused. Resume it from the upload panel.', { tone: 'info' })++ await job.pause()++ setUploading(false)+ } catch (err) {- showToast(err instanceof Error ? err.message : 'Could not upload file.', { tone: 'error' })++ showToast(err instanceof Error ? err.message : 'Could not pause upload.', { tone: 'error' })++ }++ }++++ async function resumeUpload(): Promise<void> {++ const job = uploadJobRef.current++ if (!job) return++ setUploading(true)++ try {++ const receipt = await job.resume()++ if (receipt.state === 'completed') {++ showToast('File uploaded.', { tone: 'success' })++ setUploadCandidate(null)++ setUploadOpen(false)++ setUploadSnapshot(null)++ uploadJobRef.current = null++ await refreshCurrent()++ }++ } catch (err) {++ showToast(err instanceof Error ? err.message : 'Could not resume upload.', { tone: 'error' })++ } finally {++ setUploading(false)++ }++ }++++ async function cancelUpload(): Promise<void> {++ const job = uploadJobRef.current++ if (!job) {++ closeUploadModal()++ return++ }++ try {++ await job.cancel()++ setUploading(false)++ setUploadSnapshot(null)++ setUploadCandidate(null)++ setUploadOpen(false)++ uploadJobRef.current = null++ } catch (err) {++ showToast(err instanceof Error ? err.message : 'Could not cancel upload.', { tone: 'error' })++ setUploading(false)+ }+ }+async function downloadFile(child: GfsChild): Promise<void> {if (downloadingIds.has(child.resourceId)) returnsetDownloadingIds(prev => new Set(prev).add(child.resourceId))@@@ -963,7 -1145,17 +1262,19 @@@fileSummary={uploadCandidate ? `${formatBytes(uploadCandidate.size)} selected` : undefined}- guidance="GFS uploads are limited to 10 MB per file."+ guidance="The writer advertises the Upload v2 file limit (up to the 1 GiB protocol maximum); each request is streamed in 8 MiB parts (16 MiB hard maximum)."+ progress={+ uploadSnapshot+ ? {+ uploadedBytes: uploadSnapshot.uploadedBytes,+ totalBytes: uploadSnapshot.totalBytes,+ state: uploadSnapshot.state,+ }+ : undefined+ }+ onCancelUpload={() => void cancelUpload()}++ onPauseUpload={() => void pauseUpload()}++ onResumeUpload={() => void resumeUpload()}onClose={closeUploadModal}onFileChange={setUploadCandidate}onUpload={() => void uploadFile(uploadCandidate)}diff --cc control-ui/components/__tests__/GfsBrowser.test.tsxindex 2422c4db0,f345c8f4f..d209ba508--- a/control-ui/components/__tests__/GfsBrowser.test.tsx+++ b/control-ui/components/__tests__/GfsBrowser.test.tsx@@@ -14,9 -14,14 +14,15 @@@ importgetRecipes,gfsDownload,gfsFetchFileBlob,+ postGfsShare,putGfsGrant,} from '@lib/api'+ import {+ GfsUploadCapabilityError,+ createGfsUploadJob,+ normalizeUploadProductMaxBytes,+ uploadGfsFile,+ } from '@lib/gfsFileUpload'import { normalizeGfsResourceName } from '@lib/gfsResourceName'import { GfsBrowser } from '../GfsBrowser'import { ToastProvider } from '../Toast'@@@ -38,6 -42,25 +44,26 @@@ vi.mock('@lib/api', () => (putGfsGrant: vi.fn(),}))+ vi.mock('@lib/gfsFileUpload', async importOriginal => ({+ ...(await importOriginal<typeof import('@lib/gfsFileUpload')>()),+ uploadGfsFile: vi.fn().mockResolvedValue({ state: 'completed' }),+ createGfsUploadJob: vi.fn((input: { file: File; onState?: (snapshot: unknown) => void }) => ({+ start: vi.fn(async () => {+ input.onState?.({+ state: 'completed',+ session: { uploadId: 'test-upload', state: 'completed' },+ uploadedBytes: input.file.size,+ totalBytes: input.file.size,+ })+ return { state: 'completed', uploadId: 'test-upload' }+ }),+ pause: vi.fn(),+ resume: vi.fn(),+ cancel: vi.fn(),++ snapshot: vi.fn(() => ({ state: 'failed' })),+ })),+ }))+const mockApiGet = apiGet as unknown as ReturnType<typeof vi.fn>const mockApiSend = apiSend as unknown as ReturnType<typeof vi.fn>const mockGetAdminUsers = vi.mocked(getAdminUsers)@@@ -49,7 -72,8 +75,9 @@@ const mockGetRecipes = vi.mocked(getRecconst mockPutGfsGrant = putGfsGrant as unknown as ReturnType<typeof vi.fn>const mockGfsDownload = gfsDownload as unknown as ReturnType<typeof vi.fn>const mockGfsFetchFileBlob = gfsFetchFileBlob as unknown as ReturnType<typeof vi.fn>+const mockPostGfsShare = vi.mocked(postGfsShare)+ const mockUploadGfsFile = uploadGfsFile as unknown as ReturnType<typeof vi.fn>+ const mockCreateGfsUploadJob = createGfsUploadJob as unknown as ReturnType<typeof vi.fn>const mockCreateObjectUrl = vi.fn((_blob: Blob) => 'blob:gfs-image-preview')const mockRevokeObjectUrl = vi.fn()@@@ -114,7 -138,15 +142,16 @@@ describe('GfsBrowser', () =>mockPutGfsGrant.mockReset()mockGfsDownload.mockReset()mockGfsFetchFileBlob.mockReset()+ mockPostGfsShare.mockReset()+ mockCreateGfsUploadJob.mockClear()+ mockUploadGfsFile.mockReset()+ window.localStorage.clear()+ mockUploadGfsFile.mockImplementation(async ({ file }: { file: File }) => {+ if (file.size > GFS_FILE_UPLOAD_PROTOCOL_MAX_BYTES) {+ throw new Error('GFS uploads cannot exceed the 1 GiB Upload v2 protocol maximum.')+ }+ return { state: 'completed' }+ })mockCreateObjectUrl.mockReset()mockCreateObjectUrl.mockReturnValue('blob:gfs-image-preview')mockRevokeObjectUrl.mockReset()@@@ -386,17 -313,52 +425,11 @@@fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Upload' }))await waitFor(() =>- expect(mockApiSend).toHaveBeenLastCalledWith(- 'POST',- `/api/v1/gfs/proxy/v1/resources/${rootRid}/children`,- {+ expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(+ expect.objectContaining({name: fileName,- kind: 'file',- contentBase64: 'b3BlcmF0b3IgdXBsb2Fk',- },- {},- {},- { timeoutMs: 300000 }+ target: { operation: 'create', parentRid: rootRid },- file: expect.any(File),- })- )- )- })-- it('reuses a matching persisted session from the button upload path', async () => {- const rootId = '11111111-1111-1111-1111-111111111111'- const rootRid = '11111111111111111111111111111111'- const uploadId = '88888888-8888-4888-8888-888888888888'- const lastModified = 1_725_000_000_000- const fileName = 'button-resume.md'- window.localStorage.setItem(- 'evenfire:gfs-upload-v2:pending',- JSON.stringify({- uploadId,- fileName,- fileSize: 11,- lastModified,- target: { operation: 'create', parentRid: rootRid },- name: fileName,- })- )- mockApiGet.mockResolvedValue({ rootResourceId: rootId, items: [], nextCursor: null })- renderBrowser()- await screen.findByText('No resources are visible in this folder.')-- fireEvent.click(screen.getByRole('button', { name: /upload file/i }))- const dialog = await screen.findByRole('dialog', { name: 'Upload file' })- fireEvent.change(within(dialog).getByLabelText('Choose file to upload'), {- target: { files: [new File(['button data'], fileName, { lastModified })] },- })- fireEvent.click(within(dialog).getByRole('button', { name: 'Upload' }))-- await waitFor(() =>- expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(- expect.objectContaining({- file: expect.any(File),- name: fileName,- resumeUploadId: uploadId,- target: { operation: 'create', parentRid: rootRid },+ })))})@@@ -426,48 -387,256 +459,223 @@@fireEvent.drop(browser.querySelector('.cu-gfs-card')!, { dataTransfer })-- await waitFor(() =>- expect(mockApiSend).toHaveBeenCalledWith(- 'POST',- `/api/v1/gfs/proxy/v1/resources/${rootRid}/children`,- {- expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(++ await waitFor(() => {++ expect(mockCreateGfsUploadJob).toHaveBeenCalledTimes(3)++ expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(++ 1,+ expect.objectContaining({name: 'diagram.png',- kind: 'file',- contentBase64: 'b3BlcmF0b3IgaW1hZ2U=',- },- {},- {},- { timeoutMs: 300000 }+ target: { operation: 'create', parentRid: rootRid },+ }))-- )- await waitFor(() => {- expect(mockApiSend).toHaveBeenCalledWith(- 'POST',- `/api/v1/gfs/proxy/v1/resources/${rootRid}/children`,- {- expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(- expect.objectContaining({- name: 'notes.md',- target: { operation: 'create', parentRid: rootRid },- })- )- })-- it('reuses the matching persisted session when a file is resumed through drag-and-drop', async () => {- const rootId = '11111111-1111-1111-1111-111111111111'- const rootRid = '11111111111111111111111111111111'- const uploadId = '55555555-5555-4555-8555-555555555555'- const lastModified = 1_725_000_000_000- window.localStorage.setItem(- 'evenfire:gfs-upload-v2:pending',- JSON.stringify({- uploadId,- fileName: 'resume.md',- fileSize: 11,- lastModified,- target: { operation: 'create', parentRid: rootRid },- name: 'resume.md',- })- )- mockApiGet.mockResolvedValue({- rootResourceId: rootId,- items: [],- nextCursor: null,- })- renderBrowser()- await screen.findByText('No resources are visible in this folder.')-- const browser = screen.getByRole('region', { name: 'Global File System browser' })- const file = new File(['resume data'], 'resume.md', {- type: 'text/markdown',- lastModified,- })- const dataTransfer = { dropEffect: 'none', files: [file], types: ['Files'] }- fireEvent.drop(browser.querySelector('.cu-gfs-card')!, { dataTransfer })-- await waitFor(() =>- expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(++ expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(++ 2,+ expect.objectContaining({- file,- resumeUploadId: uploadId,+ name: 'notes.md',- kind: 'file',- contentBase64: 'IyBPcGVyYXRvciBub3Rlcw==',- },- {},- {},- { timeoutMs: 300000 }+ target: { operation: 'create', parentRid: rootRid },+ }))- expect(mockApiSend).toHaveBeenCalledWith(- 'POST',- `/api/v1/gfs/proxy/v1/resources/${rootRid}/children`,- {- )++ expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(++ 3,++ expect.objectContaining({+ name: 'report.pdf',- kind: 'file',- contentBase64: 'JVBERiBvcGVyYXRvciByZXBvcnQ=',- },- {},- {},- { timeoutMs: 300000 }++ target: { operation: 'create', parentRid: rootRid },++ })+ )+ })})+ it('keeps a persisted drag-and-drop session when resumable capabilities are unavailable', async () => {+ const rootId = '11111111-1111-1111-1111-111111111111'+ const rootRid = '11111111111111111111111111111111'+ const uploadId = '77777777-7777-4777-8777-777777777777'+ const lastModified = 1_725_000_000_000+ window.localStorage.setItem(+ 'evenfire:gfs-upload-v2:pending',+ JSON.stringify({+ uploadId,+ fileName: 'resume.md',+ fileSize: 11,+ lastModified,+ target: { operation: 'create', parentRid: rootRid },+ name: 'resume.md',+ })+ )+ mockApiGet.mockResolvedValue({ rootResourceId: rootId, items: [], nextCursor: null })+ mockCreateGfsUploadJob.mockImplementationOnce(() => ({+ start: vi+ .fn()+ .mockRejectedValue(+ new GfsUploadCapabilityError('writer unavailable', { allowLegacyFallback: true })+ ),+ snapshot: vi.fn(() => ({ state: 'failed' })),+ pause: vi.fn(),+ resume: vi.fn(),+ cancel: vi.fn(),+ }))+ renderBrowser()+ await screen.findByText('No resources are visible in this folder.')++ const browser = screen.getByRole('region', { name: 'Global File System browser' })+ const file = new File(['resume data'], 'resume.md', {+ type: 'text/markdown',+ lastModified,+ })+ fireEvent.drop(browser.querySelector('.cu-gfs-card')!, {+ dataTransfer: { dropEffect: 'none', files: [file], types: ['Files'] },+ })++ await waitFor(() =>+ expect(screen.getByText(/persisted resumable session cannot be resumed/i)).toBeTruthy()+ )+ expect(mockApiSend).not.toHaveBeenCalled()+ expect(+ JSON.parse(window.localStorage.getItem('evenfire:gfs-upload-v2:pending')!)+ ).toMatchObject({+ uploadId,+ })+ })++ it('fails loudly without legacy fallback for malformed resumable capabilities', async () => {+ const rootId = '11111111-1111-1111-1111-111111111111'+ mockApiGet.mockResolvedValue({ rootResourceId: rootId, items: [], nextCursor: null })+ let malformed: unknown+ try {+ normalizeUploadProductMaxBytes(0)+ } catch (error) {+ malformed = error+ }+ expect(malformed).toBeInstanceOf(GfsUploadCapabilityError)+ mockCreateGfsUploadJob.mockImplementationOnce(() => ({+ start: vi.fn().mockRejectedValue(malformed),+ snapshot: vi.fn(() => ({ state: 'failed' })),+ pause: vi.fn(),+ resume: vi.fn(),+ cancel: vi.fn(),+ }))+ renderBrowser()+ await screen.findByText('No resources are visible in this folder.')++ const browser = screen.getByRole('region', { name: 'Global File System browser' })+ fireEvent.drop(browser.querySelector('.cu-gfs-card')!, {+ dataTransfer: {+ dropEffect: 'none',+ files: [new File(['payload'], 'payload.bin')],+ types: ['Files'],+ },+ })++ await waitFor(() => expect(screen.getByText((malformed as Error).message)).toBeTruthy())+ expect(mockApiSend).not.toHaveBeenCalled()+ expect(screen.queryByText(/using the legacy 16 MiB path/i)).toBeNull()+ })++ it('shows byte progress and exposes pause/resume/cancel through the visible upload modal', async () => {+ const rootId = '11111111-1111-1111-1111-111111111111'+ const rootRid = '11111111111111111111111111111111'+ mockApiGet.mockResolvedValue({ rootResourceId: rootId, items: [], nextCursor: null })+ const completed = {+ uploadId: '55555555-5555-4555-8555-555555555555',+ state: 'completed',+ expectedBytes: 4,+ committedBytes: 4,+ }+ const paused = { ...completed, state: 'paused', committedBytes: 2 }+ let resolveStart: ((value: typeof completed) => void) | undefined+ let uploadInput:+ | {+ onState?: (snapshot: unknown) => void+ onProgress?: (progress: { uploadedBytes: number }) => void+ }+ | undefined+ const job = {+ start: vi.fn(() => {+ uploadInput?.onState?.({+ state: 'uploading',+ session: { ...completed, state: 'uploading' },+ uploadedBytes: 2,+ totalBytes: 4,+ })+ // Simulate an out-of-order in-flight part reporting a later absolute+ // offset before the accumulator commits the lower-numbered part.+ uploadInput?.onProgress?.({ uploadedBytes: 3 })+ // A failed retry clears that part's in-flight contribution. The UI+ // intentionally permits the truthful downward correction; the+ // monotonic guard applies only to stale uploading snapshots.+ uploadInput?.onProgress?.({ uploadedBytes: 1 })+ uploadInput?.onState?.({+ state: 'uploading',+ session: { ...completed, state: 'uploading' },+ uploadedBytes: 2,+ totalBytes: 4,+ })+ return new Promise<typeof completed>(resolve => {+ resolveStart = resolve+ })+ }),+ pause: vi.fn(async () => {+ uploadInput?.onState?.({+ state: 'paused',+ session: paused,+ uploadedBytes: 2,+ totalBytes: 4,+ })+ return paused+ }),+ resume: vi.fn(async () => {+ uploadInput?.onState?.({+ state: 'uploading',+ session: { ...completed, state: 'uploading' },+ uploadedBytes: 2,+ totalBytes: 4,+ })+ uploadInput?.onState?.({+ state: 'completed',+ session: completed,+ uploadedBytes: 4,+ totalBytes: 4,+ })+ resolveStart?.(completed)+ return completed+ }),+ cancel: vi.fn(async () => undefined),+ }+ mockCreateGfsUploadJob.mockImplementationOnce(+ (input: {+ onState?: (snapshot: unknown) => void+ onProgress?: (progress: { uploadedBytes: number }) => void+ }) => {+ uploadInput = input+ return job+ }+ )+ renderBrowser()+ await screen.findByText('No resources are visible in this folder.')+ fireEvent.click(screen.getByRole('button', { name: /upload file/i }))+ const uploadDialog = await screen.findByRole('dialog', { name: 'Upload file' })+ fireEvent.change(within(uploadDialog).getByLabelText('Choose file to upload'), {+ target: { files: [new File(['data'], 'payload.bin')] },+ })+ fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Upload' }))+ const progress = await within(uploadDialog).findByRole('progressbar', {+ name: /Upload progress/,+ })+ expect(progress).toHaveAttribute('value', '2')+ expect(progress).toHaveAttribute('aria-valuemin', '0')+ expect(progress).toHaveAttribute('aria-valuemax', '4')+ expect(progress).toHaveAttribute('aria-valuenow', '2')+ fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Pause' }))+ await waitFor(() => expect(job.pause).toHaveBeenCalledTimes(1))+ expect(await within(uploadDialog).findByRole('button', { name: 'Resume' })).toBeTruthy()+ fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Resume' }))+ await waitFor(() => expect(job.resume).toHaveBeenCalledTimes(1))+ await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Upload file' })).toBeNull())+ expect(job.cancel).not.toHaveBeenCalled()+ expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(+ expect.objectContaining({ target: { operation: 'create', parentRid: rootRid } })+ )+ })+it('rejects oversized dropped files before reading or uploading them', async () => {const rootId = '11111111-1111-1111-1111-111111111111'mockApiGet.mockResolvedValue({@@@ -782,16 -865,12 +992,11 @@@})await waitFor(() =>- expect(mockApiSend).toHaveBeenCalledWith(- 'PUT',- '/api/v1/gfs/proxy/v1/resources/r2/content',- {- contentBase64: 'cmVwbGFjZW1lbnQ=',- ifMatch: 0,- },- {},- {},- { timeoutMs: 300000 }+ expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'report.md',- file: expect.any(File),+ target: { operation: 'replace', resourceRid: 'r2', ifMatch: 0 },+ })))})diff --cc desktop-app/src/gfs/upload.test.tsindex 260e318c3,8625d9b90..00f2d3eaa--- a/desktop-app/src/gfs/upload.test.ts+++ b/desktop-app/src/gfs/upload.test.ts@@@ -1,6 -1,6 +1,6 @@@- import { describe, expect, it } from 'vitest'+ import { describe, expect, it, vi } from 'vitest'import { createHash } from 'node:crypto'- import { mkdtemp, rm, utimes, writeFile } from 'node:fs/promises'-import { mkdtemp, rm, stat, truncate, writeFile } from 'node:fs/promises'++import { mkdtemp, rm, stat, truncate, utimes, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'import {diff --cc desktop-app/ui/src/pages/__tests__/FilesPage.test.tsxindex 7e980a26e,c0b8e20ed..1de0e6fe6--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx@@@ -3,10 -3,10 +3,10 @@@ import { useState } from 'reactimport { 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'+ import { GFS_FILE_UPLOAD_PROTOCOL_MAX_BYTES } from '@constants/gfsFileUpload'import { GFS_IMAGE_PREVIEW_MAX_BYTES } from '@constants/gfsImagePreview'import { GFS_MARKDOWN_PREVIEW_MAX_BYTES } from '@constants/gfsMarkdownPreview'-import { type GfsCrumb, isGfsSessionAuthorityFailure } from '@hooks/domain/useGfsBrowserController'+import type { GfsCrumb } from '@hooks/domain/useGfsBrowserController'import type { Tone } from '@/uiTypes'import { FilesPage } from '../FilesPage'@@@ -518,12 -649,8 +518,8 @@@ describe('FilesPage', () =>await Promise.resolve()})- await waitFor(() => expect(createFile).toHaveBeenCalledTimes(2))- expect(createFile).toHaveBeenLastCalledWith('folder-1', 'retry.md', 'retry.md')+ await waitFor(() => expect(createFileFromPath).toHaveBeenCalledTimes(2))- expect(createFileFromPath).toHaveBeenLastCalledWith(- 'folder-1',- 'retry.md',- '/tmp/retry.md'- )++ expect(createFileFromPath).toHaveBeenLastCalledWith('folder-1', 'retry.md', '/tmp/retry.md')expect(pushToast).toHaveBeenCalledWith('Uploaded retry.md', 'success')})@@@ -549,12 -676,12 +545,13 @@@path: '/shared',}let releaseFirstUpload: (() => void) | undefined- const createFileFromPath = vi.fn((_parentResourceId: string, _name: string, _filePath: string) =>- createFileFromPath.mock.calls.length === 1- const createFile = vi.fn((_parentResourceId: string, _name: string, _filePath: string) =>- createFile.mock.calls.length === 1-- ? new Promise<void>(resolve => {-- releaseFirstUpload = resolve-- })-- : Promise.resolve()++ const createFileFromPath = vi.fn(++ (_parentResourceId: string, _name: string, _filePath: string) =>++ createFileFromPath.mock.calls.length === 1++ ? new Promise<void>(resolve => {++ releaseFirstUpload = resolve++ })++ : Promise.resolve())function useChangingFolderController() {@@@ -613,10 -740,11 +610,11 @@@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 })+ Object.defineProperty(oversized, 'size', { value: GFS_FILE_UPLOAD_PROTOCOL_MAX_BYTES + 1 })+ const arrayBuffer = vi.spyOn(oversized, 'arrayBuffer')renderFilesPage(pushToast)fireEvent.drop(screen.getByRole('region', { name: 'Global File System browser' }), {@@@ -624,9 -752,13 +622,13 @@@})await waitFor(() =>- expect(pushToast).toHaveBeenCalledWith('GFS uploads are limited to 200 MB per file.', 'error')+ expect(pushToast).toHaveBeenCalledWith(+ 'GFS uploads cannot exceed the 1 GiB Upload v2 protocol maximum.',+ 'error'+ ))+ expect(arrayBuffer).not.toHaveBeenCalled()- expect(createFile).not.toHaveBeenCalled()+ expect(createFileFromPath).not.toHaveBeenCalled()})it('keeps cached write access available while affordances refresh', async () => {