Skip to content

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

TypeScript
219 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { EventEmitter } from 'node:events'
import { normalizeGfsResourceName } from '@clerum/gfs-interaction-policy'
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 {
  apiGet,
  apiSend,
  getAdminTeams,
  getAdminUsers,
  getGfsGrants,
  getGfsResourceByPath,
  getGfsShares,
  getHosts,
  getRecipes,
  gfsDownload,
  gfsFetchFileBlob,
  handleControlUIUnauthorized,
  putGfsGrant,
} from '@lib/api'
import {
  GfsUploadCapabilityError,
  createGfsUploadJob,
  normalizeUploadProductMaxBytes,
  uploadGfsFile,
} from '@lib/gfsFileUpload'
import { toChildView } from '../../../control-api/src/gfs/tree.js'
import {
  closeActiveEntityChangeStreams,
  streamEntityChanges,
} from '../../../control-api/src/routes/entityChangeStream.js'
import { toResolveView } from '../../../control-api/src/routes/gfs/resolve.js'
import { GfsBrowser } from '../GfsBrowser'
import { ToastProvider } from '../Toast'

vi.mock('@lib/api', () => ({
  apiGet: vi.fn(),
  apiSend: vi.fn(),
  controlApiUrl: (path: string) => `/control-api${path}`,
  handleControlUIUnauthorized: vi.fn(),
  AuthExpiredError: class AuthExpiredError extends Error {
    constructor(message = 'Auth expired') {
      super(message)
      this.name = 'AuthExpiredError'
    }
  },
  GFS_UPLOAD_TIMEOUT_MS: 300000,
  getAdminTeams: vi.fn(),
  getAdminUsers: vi.fn(),
  getGfsGrants: vi.fn(),
  getGfsResourceByPath: vi.fn(),
  getGfsShares: vi.fn(),
  getHosts: vi.fn(),
  getRecipes: vi.fn(),
  gfsDownload: vi.fn(),
  gfsFetchFileBlob: vi.fn(),
  isSilentApiError: () => false,
  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 controlApiProducer = vi.hoisted(() => ({
  isEntityChangeCursor: vi.fn(),
  readEntityChangeCheckpoint: vi.fn(),
  subscribeEntityChangeFeedWake: vi.fn(),
}))
const controlApiProducerConfig = vi.hoisted(() => ({
  entityChangeStreamHeartbeatMs: 20_000,
  entityChangeStreamMaxLifetimeMs: 600_000,
  entityChangeStreamPollMs: 250,
}))
const controlApiProducerMetrics = vi.hoisted(() => ({
  entityChangeStreamConnectionsActive: { inc: vi.fn(), dec: vi.fn() },
  entityChangeStreamDisconnectsTotal: { inc: vi.fn(), dec: vi.fn() },
  entityChangeStreamFramesSentTotal: { inc: vi.fn(), dec: vi.fn() },
  entityChangeStreamResyncRequiredTotal: { inc: vi.fn(), dec: vi.fn() },
}))

vi.mock('../../../control-api/src/config.js', () => ({ config: controlApiProducerConfig }))
vi.mock('../../../control-api/src/db.js', () => ({ pool: {} }))
vi.mock('../../../control-api/src/middleware/controlUIAuth.js', () => ({
  requireAuthForControlUI: vi.fn(),
}))
vi.mock('../../../control-api/src/services/entityChangeService.js', () => controlApiProducer)
vi.mock('../../../control-api/src/observability/logger.js', () => ({
  rootLogger: { child: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }) },
}))
vi.mock('../../../control-api/src/observability/metrics.js', () => controlApiProducerMetrics)

const mockApiGet = apiGet as unknown as ReturnType<typeof vi.fn>
const mockApiSend = apiSend as unknown as ReturnType<typeof vi.fn>
const mockHandleControlUIUnauthorized = vi.mocked(handleControlUIUnauthorized)
const mockGetAdminUsers = vi.mocked(getAdminUsers)
const mockGetAdminTeams = vi.mocked(getAdminTeams)
const mockGetGfsGrants = vi.mocked(getGfsGrants)
const mockGetGfsResourceByPath = getGfsResourceByPath as unknown as ReturnType<typeof vi.fn>
const mockGetGfsShares = vi.mocked(getGfsShares)
const mockGetHosts = vi.mocked(getHosts)
const mockGetRecipes = vi.mocked(getRecipes)
const 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 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()

class ControlApiProducerRequest extends EventEmitter {
  query: Record<string, unknown> = {}
  setTimeout = vi.fn()
}

class ControlApiProducerResponse extends EventEmitter {
  statusCode = 200
  headersSent = false
  destroyed = false
  writableEnded = false
  writableLength = 0
  frames: string[] = []
  status(code: number): this {
    this.statusCode = code
    return this
  }
  setHeader(): this {
    return this
  }
  flushHeaders(): void {
    this.headersSent = true
  }
  write(frame: string): boolean {
    this.frames.push(frame)
    return true
  }
  end(): void {
    this.writableEnded = true
    this.emit('close')
  }
  json(): this {
    return this
  }
}

async function controlApiProducerFrame(
  scopes: Array<'gfs' | 'authorization'> = ['gfs']
): Promise<string> {
  const cursor = 'd119f895-1ef8-4e73-8f08-f9754919682a'
  controlApiProducer.readEntityChangeCheckpoint.mockResolvedValue({
    resyncRequired: false,
    cursor,
    scopes,
  })
  const req = new ControlApiProducerRequest()
  const res = new ControlApiProducerResponse()
  streamEntityChanges(
    req as unknown as Parameters<typeof streamEntityChanges>[0],
    res as unknown as Parameters<typeof streamEntityChanges>[1],
    null,
    async () => true,
    'operator'
  )
  await vi.waitFor(() => expect(res.frames.length).toBeGreaterThan(0))
  closeActiveEntityChangeStreams()
  await vi.waitFor(() => expect(res.writableEnded).toBe(true))
  const frame = res.frames
    .map(value => value.trim())
    .find(value => {
      return (JSON.parse(value) as { type?: string }).type === 'scope.invalidated'
    })
  if (!frame) throw new Error('Control API producer did not emit a scope invalidation')
  return frame
}

async function controlApiSessionExpiredProducerFrame(): Promise<string> {
  const cursor = 'd119f895-1ef8-4e73-8f08-f9754919682a'
  controlApiProducer.readEntityChangeCheckpoint.mockResolvedValue({
    resyncRequired: false,
    cursor,
    scopes: ['gfs'],
  })
  let authorizationChecks = 0
  const req = new ControlApiProducerRequest()
  const res = new ControlApiProducerResponse()
  streamEntityChanges(
    req as unknown as Parameters<typeof streamEntityChanges>[0],
    res as unknown as Parameters<typeof streamEntityChanges>[1],
    null,
    async () => ++authorizationChecks === 1,
    'operator',
    'operator-session-expiry-test'
  )
  await vi.waitFor(() => expect(res.writableEnded).toBe(true))
  const frame = res.frames
    .map(value => value.trim())
    .find(value => {
      const parsed = JSON.parse(value) as { type?: string; reason?: string }
      return parsed.type === 'stream.closing' && parsed.reason === 'session_expired'
    })
  if (!frame) throw new Error('Control API producer did not emit session_expired')
  return frame
}

function renderBrowser() {
  return render(
    <ToastProvider>
      <GfsBrowser />
    </ToastProvider>
  )
}

async function openSubjectPicker() {
  const subjectInput = await screen.findByRole('combobox', {
    name: 'Add people, teams, agents, or workflows',
  })
  fireEvent.focus(subjectInput)
}

function selectPermission(label: string) {
  fireEvent.click(screen.getByRole('button', { name: 'Access role for selected recipients' }))
  fireEvent.click(screen.getByRole('option', { name: label === 'Read' ? 'Read' : 'Editor' }))
}

async function openResourceMenu(resourceName: string) {
  fireEvent.click(await screen.findByRole('button', { name: `Actions for ${resourceName}` }))
}

async function openManage(resourceName: string) {
  await openResourceMenu(resourceName)
  fireEvent.click(screen.getByRole('menuitem', { name: 'Share' }))
  fireEvent.click(
    within(screen.getByRole('menu', { name: `Share options for ${resourceName}` })).getByRole(
      'menuitem',
      { name: 'Share' }
    )
  )
}

function child(name: string, kind: string, n: number, version = 0) {
  return {
    resourceId: `id-${n}`,
    rid: `r${n}`,
    gfsUri: `gfs://main/r${n}`,
    name,
    kind,
    path: `/${name}`,
    bytes: 0,
    version,
  }
}

function resolvedFolderView(resourceId: string, name: string, path: string, version: number) {
  return toResolveView({
    resourceId,
    drive: 'main',
    name,
    kind: 'directory',
    pathCache: path,
    bytes: 0,
    version,
    updatedAt: '2026-09-28T00:00:00.000Z',
  })
}

function listedFolder(resourceId: string, name: string, path: string, version: number) {
  return toChildView('main', {
    resourceId,
    name,
    kind: 'directory',
    pathCache: path,
    bytes: 0,
    version,
    updatedAt: '2026-09-28T00:00:00.000Z',
  })
}

describe('GfsBrowser', () => {
  beforeEach(() => {
    controlApiProducer.isEntityChangeCursor.mockImplementation((value: string) =>
      /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)
    )
    controlApiProducer.readEntityChangeCheckpoint.mockReset()
    controlApiProducer.subscribeEntityChangeFeedWake.mockReset().mockReturnValue(vi.fn())
    mockApiGet.mockReset()
    mockApiSend.mockReset()
    mockHandleControlUIUnauthorized.mockReset()
    mockGetAdminUsers.mockReset()
    mockGetAdminTeams.mockReset()
    mockGetGfsGrants.mockReset()
    mockGetGfsShares.mockReset()
    mockGetHosts.mockReset()
    mockGetRecipes.mockReset()
    vi.stubGlobal(
      'fetch',
      vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
        const body = new ReadableStream<Uint8Array>({
          start(controller) {
            init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
          },
        })
        return new Response(body, {
          status: 200,
          headers: { 'content-type': 'application/x-ndjson' },
        })
      })
    )
    mockPutGfsGrant.mockReset()
    mockGfsDownload.mockReset()
    mockGfsFetchFileBlob.mockReset()
    mockCreateGfsUploadJob.mockReset()
    mockCreateGfsUploadJob.mockImplementation(
      (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' })),
      })
    )
    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()
    Object.defineProperty(URL, 'createObjectURL', {
      configurable: true,
      value: mockCreateObjectUrl,
    })
    Object.defineProperty(URL, 'revokeObjectURL', {
      configurable: true,
      value: mockRevokeObjectUrl,
    })
    mockGetAdminUsers.mockResolvedValue({
      items: [
        {
          id: '11111111-1111-1111-1111-111111111111',
          email: '[email protected]',
          name: 'Ada Lovelace',
          displayName: 'Ada Lovelace',
          picture: null,
          activeTeamCount: 1,
        },
      ],
    })
    mockGetAdminTeams.mockResolvedValue({
      items: [{ id: '22222222-2222-2222-2222-222222222222', name: 'Research', memberCount: 2 }],
    })
    mockGetHosts.mockResolvedValue({ items: [{ metadata: { name: 'chatllm' } }] })
    mockGetRecipes.mockResolvedValue({
      items: [{ metadata: { namespace: 'sandbox-recipes', name: 'sandbox-ui-hello' } }],
    })
    mockGetGfsGrants.mockResolvedValue({ items: [] })
    mockGetGfsShares.mockResolvedValue({ items: [] })
  })

  afterEach(() => {
    closeActiveEntityChangeStreams()
    vi.unstubAllGlobals()
  })

  it('loads the root tree and renders directories + files', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('org', 'directory', 1), child('readme.md', 'file', 2)],
      nextCursor: null,
    })
    renderBrowser()
    await screen.findAllByText(/org/)
    await screen.findAllByText(/readme\.md/)
    expect(screen.getByRole('navigation', { name: 'Breadcrumb' })).toBeTruthy()
    expect(screen.queryByText('Drive map')).toBeNull()

    const orgRow = screen
      .getByRole('list', { name: 'Current folder resources' })
      .querySelector('li')
    expect(orgRow?.querySelector('svg path')?.getAttribute('d')).toContain(
      'M464 128H272l-64-64H48C21.49 64 0 85.49 0 112v288'
    )

    await openResourceMenu('readme.md')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Share' }))
    const shareMenu = screen.getByRole('menu', { name: 'Share options for readme.md' })
    expect(
      within(shareMenu).getByRole('menuitem', { name: 'Copy link' }).getAttribute('title')
    ).toBe('gfs://main/r2')
    expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/tree', { drive: 'main' })
  })

  it('does not append a pending root page into a cached folder opened meanwhile', async () => {
    const alpha = child('alpha', 'directory', 1)
    let resolveRootPage: ((value: unknown) => void) | undefined
    const pendingRootPage = new Promise<unknown>(resolve => {
      resolveRootPage = resolve
    })
    mockApiGet.mockImplementation((path: string, query?: Record<string, string>) => {
      if (path === '/api/v1/gfs/tree') {
        return query?.cursor === 'root-page-2'
          ? pendingRootPage
          : Promise.resolve({
              items: [alpha],
              nextCursor: 'root-page-2',
            })
      }
      if (path === '/api/v1/gfs/resources/id-1/children') {
        return Promise.resolve({ items: [child('alpha-only.txt', 'file', 3)], nextCursor: null })
      }
      return Promise.resolve({ items: [], nextCursor: null })
    })

    renderBrowser()
    const folderButton = await screen.findByRole('button', { name: 'alpha' })
    await waitFor(() =>
      expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resources/id-1/children', {
        drive: 'main',
      })
    )
    await act(async () => Promise.resolve())

    fireEvent.click(screen.getByRole('button', { name: 'Load more' }))
    await screen.findByText('Loading…')
    fireEvent.click(folderButton)
    await screen.findByText('alpha-only.txt')

    await act(async () => {
      resolveRootPage?.({ items: [child('root-page-2.txt', 'file', 2)], nextCursor: null })
      await pendingRootPage
    })

    const visibleItems = screen.getByRole('list', { name: 'Current folder resources' })
    expect(visibleItems).toHaveTextContent('alpha-only.txt')
    expect(visibleItems).not.toHaveTextContent('root-page-2.txt')
  })

  it('orders directories first, then files, both alphabetically', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [
        child('zebra.md', 'file', 4),
        child('beta', 'directory', 2),
        child('apple.md', 'file', 3),
        child('alpha', 'directory', 1),
      ],
      nextCursor: null,
    })
    renderBrowser()

    const list = await screen.findByRole('list', { name: 'Current folder resources' })
    const resourceNamesInOrder = Array.from(list.querySelectorAll('.cu-gfs-list__name'))
      .map(node => node.textContent?.trim() ?? '')
      .filter(name => /^(alpha|beta|apple|zebra)/.test(name))
    expect(resourceNamesInOrder).toEqual(['alpha', 'beta', 'apple.md', 'zebra.md'])
  })

  it('renders the solid Font Awesome folder glyph inside the directory row', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('alpha', 'directory', 1)],
      nextCursor: null,
    })
    renderBrowser()

    const list = await screen.findByRole('list', { name: 'Current folder resources' })
    const folderSvg = list.querySelector('.cu-gfs-list__icon svg')
    expect(folderSvg?.getAttribute('viewBox')).toBe('0 0 512 512')
    expect(folderSvg?.getAttribute('fill')).toBe('currentColor')
    expect(folderSvg?.getAttribute('stroke-width')).toBe('0')
    expect(folderSvg?.getAttribute('data-solid')).toBe('true')
    const path = folderSvg?.querySelector('path')
    expect(path?.getAttribute('d')).toContain('M464 128H272l-64-64H48C21.49 64')
  })

  it('keeps the outlined document glyph visible next to .pdf files', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('report.pdf', 'file', 2)],
      nextCursor: null,
    })
    renderBrowser()

    const list = await screen.findByRole('list', { name: 'Current folder resources' })
    const fileSvg = list.querySelector('.cu-gfs-list__icon svg')
    // Document glyph is outline-only — should NOT receive the solid opt-in.
    expect(fileSvg?.getAttribute('data-solid')).not.toBe('true')
    expect(fileSvg?.getAttribute('viewBox')).toBe('0 0 512 512')
    const path = fileSvg?.querySelector('path')
    expect(path?.getAttribute('fill')).toBe('none')
    expect(path?.getAttribute('stroke-width')).toBe('32')
  })

  it('prefetches every folder child into the in-memory cache', async () => {
    mockApiGet
      .mockResolvedValueOnce({
        items: [
          child('alpha', 'directory', 1),
          child('beta', 'directory', 2),
          child('notes.md', 'file', 3),
        ],
        nextCursor: null,
      })
      // The prefetch effect fans out one request per directory row.
      .mockResolvedValue({ items: [], nextCursor: null })

    renderBrowser()

    await waitFor(() => expect(mockApiGet).toHaveBeenCalledTimes(3))
    expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resources/id-1/children', {
      drive: 'main',
    })
    expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resources/id-2/children', {
      drive: 'main',
    })
  })

  it('uses the hard-drive header, labels the root as main, and ignores current-crumb clicks', async () => {
    mockApiGet.mockResolvedValueOnce({ items: [], nextCursor: null })
    renderBrowser()
    await screen.findByText('No resources are visible in this folder.')

    const title = screen.getByText('EvenDrive').closest('.cu-panel-title')
    expect(title?.querySelector('path')).toHaveAttribute(
      'd',
      'M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z'
    )

    const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })
    expect(within(breadcrumb).queryByText('Drive', { exact: true })).toBeNull()
    const rootCrumb = within(breadcrumb).getByRole('button', { name: 'main' })
    expect(rootCrumb).toHaveAttribute('aria-current', 'page')

    fireEvent.click(rootCrumb)

    expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull()
    expect(mockApiGet).toHaveBeenCalledTimes(1)
  })

  it('shows the subtle loader during initial load and folder navigation', async () => {
    let resolveRoot: ((value: unknown) => void) | undefined
    let resolveFolder: ((value: unknown) => void) | undefined
    mockApiGet
      .mockReturnValueOnce(
        new Promise(resolve => {
          resolveRoot = resolve
        })
      )
      .mockReturnValueOnce(
        new Promise(resolve => {
          resolveFolder = resolve
        })
      )
    renderBrowser()

    const initialLoader = screen.getByRole('status', { name: 'Loading files' })
    expect(initialLoader).toHaveClass('cu-gfs-loading')
    expect(initialLoader.querySelectorAll('.cu-gfs-loading__dot')).toHaveLength(3)
    expect(screen.queryByText('Loading resources...')).toBeNull()

    await act(async () => {
      resolveRoot?.({
        items: [child('org', 'directory', 1)],
        nextCursor: null,
      })
    })
    fireEvent.click((await screen.findAllByRole('button', { name: 'org' }))[0])

    expect(screen.getByRole('status', { name: 'Loading files' })).toHaveClass('cu-gfs-loading')
    expect(screen.queryByRole('list', { name: 'Current folder resources' })).toBeNull()

    await act(async () => {
      resolveFolder?.({ items: [], nextCursor: null })
    })
    expect(await screen.findByText('No resources are visible in this folder.')).toBeTruthy()
  })

  it('shows operator CRUD controls and creates a folder in the current folder', async () => {
    mockApiGet.mockResolvedValueOnce({
      rootResourceId: '11111111-1111-1111-1111-111111111111',
      items: [],
      nextCursor: null,
    })
    mockApiGet.mockResolvedValueOnce({ items: [], nextCursor: null })
    mockApiGet.mockResolvedValueOnce({ items: [], nextCursor: null })
    mockApiSend.mockResolvedValueOnce({ ok: true })
    renderBrowser()
    await screen.findByText('No resources are visible in this folder.')
    const newFolder = await screen.findByRole('button', { name: /new folder/i })
    const newFile = screen.getByRole('button', { name: /upload file/i })
    expect(newFolder).not.toBeDisabled()
    expect(newFile).not.toBeDisabled()
    expect(newFolder).toHaveClass('cu-gfs-create-action', 'cu-btn--sm')
    expect(newFile).toHaveClass('cu-gfs-create-action', 'cu-btn--sm')
    expect(screen.queryByText(/files around 110 MB/i)).toBeNull()

    fireEvent.click(newFile)
    const uploadDialog = await screen.findByRole('dialog', { name: 'Upload file' })
    expect(within(uploadDialog).queryByText(/Upload v2 protocol ceiling/i)).toBeNull()
    expect(within(uploadDialog).getByText(/drag and drop, or click to browse/i)).toBeTruthy()
    fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Cancel' }))

    fireEvent.click(newFolder)
    const dialog = await screen.findByRole('dialog')
    fireEvent.change(within(dialog).getByLabelText('Folder name'), {
      target: { value: 'new-folder' },
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Create folder' }))
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'POST',
        '/api/v1/gfs/proxy/v1/resources/11111111111111111111111111111111/children',
        { name: 'new-folder', kind: 'directory' }
      )
    )
  })

  it('updates a second authenticated browser session from the coarse stream after a remote create', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const streamControllers: ReadableStreamDefaultController<Uint8Array>[] = []
    let created = false
    mockApiGet.mockImplementation(async (path: string) => {
      if (path === '/api/v1/gfs/tree') {
        return {
          rootResourceId: rootId,
          items: created ? [child('remote-folder', 'directory', 9)] : [],
          nextCursor: null,
        }
      }
      return { items: [], nextCursor: null }
    })
    vi.stubGlobal(
      'fetch',
      vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
        const body = new ReadableStream<Uint8Array>({
          start(controller) {
            streamControllers.push(controller)
            init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
          },
        })
        return new Response(body, {
          status: 200,
          headers: { 'content-type': 'application/x-ndjson' },
        })
      })
    )
    mockApiSend.mockImplementationOnce(async () => {
      created = true
      const frame = await controlApiProducerFrame()
      const encoded = new TextEncoder().encode(`${frame}\n`)
      for (const controller of streamControllers) controller.enqueue(encoded)
      return { ok: true }
    })

    render(
      <ToastProvider>
        <div data-testid="operator-session-a">
          <GfsBrowser />
        </div>
        <div data-testid="operator-session-b">
          <GfsBrowser />
        </div>
      </ToastProvider>
    )
    const sessionA = within(screen.getByTestId('operator-session-a'))
    const sessionB = within(screen.getByTestId('operator-session-b'))
    await waitFor(() => expect(streamControllers).toHaveLength(2))
    await sessionA.findAllByText('No resources are visible in this folder.')
    await sessionB.findAllByText('No resources are visible in this folder.')

    fireEvent.click(sessionA.getByRole('button', { name: 'New folder' }))
    const dialog = await sessionA.findByRole('dialog', { name: 'New folder' })
    fireEvent.change(within(dialog).getByLabelText('Folder name'), {
      target: { value: 'remote-folder' },
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Create folder' }))

    await waitFor(() => expect(mockApiSend).toHaveBeenCalledOnce())
    expect(await sessionA.findByText('remote-folder')).toBeTruthy()
    expect(await sessionB.findByText('remote-folder')).toBeTruthy()
    expect(fetch).toHaveBeenCalledTimes(2)
    expect(JSON.stringify(mockApiSend.mock.calls)).toContain('remote-folder')
  })

  it('routes producer-issued session expiry through the existing auth handler and stops the stream', async () => {
    mockApiGet.mockResolvedValue({ items: [], nextCursor: null })
    const frame = await controlApiSessionExpiredProducerFrame()
    const fetchMock = vi.fn(
      async () =>
        new Response(`${frame}\n`, {
          status: 200,
          headers: { 'content-type': 'application/x-ndjson' },
        })
    )
    vi.stubGlobal('fetch', fetchMock)

    renderBrowser()

    await waitFor(() => expect(mockHandleControlUIUnauthorized).toHaveBeenCalledOnce())
    expect(fetchMock).toHaveBeenCalledOnce()
  })

  it('routes an unauthenticated stream 401 through the existing auth handler without retrying', async () => {
    mockApiGet.mockResolvedValue({ items: [], nextCursor: null })
    const fetchMock = vi.fn(async () => new Response(null, { status: 401 }))
    vi.stubGlobal('fetch', fetchMock)

    renderBrowser()

    await waitFor(() => expect(mockHandleControlUIUnauthorized).toHaveBeenCalledOnce())
    expect(fetchMock).toHaveBeenCalledOnce()
  })

  it('keeps the loaded list and Rename dialog visible during a soft stream refresh', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const report = child('report.md', 'file', 1, 4)
    let resolvedReport = toResolveView({
      resourceId: report.resourceId,
      drive: 'main',
      name: report.name,
      kind: 'file',
      pathCache: report.path,
      bytes: report.bytes,
      version: report.version,
      updatedAt: '2026-09-28T00:00:00.000Z',
    })
    const streamControllers: ReadableStreamDefaultController<Uint8Array>[] = []
    let releaseRefresh!: (page: {
      rootResourceId: string
      items: Array<typeof report>
      nextCursor: null
    }) => void
    let treeReads = 0
    mockApiGet.mockImplementation(async (path: string, query?: Record<string, string>) => {
      if (path === '/api/v1/gfs/tree') {
        treeReads += 1
        if (treeReads === 2) {
          return new Promise(resolve => {
            releaseRefresh = resolve
          })
        }
        return { rootResourceId: rootId, items: [report], nextCursor: null }
      }
      if (path === '/api/v1/gfs/resolve' && query?.uri === report.gfsUri) return resolvedReport
      if (path === '/api/v1/gfs/resolve') {
        return resolvedFolderView(rootId, 'main', '/', 1)
      }
      return { items: [], nextCursor: null }
    })
    vi.stubGlobal(
      'fetch',
      vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
        const body = new ReadableStream<Uint8Array>({
          start(controller) {
            streamControllers.push(controller)
            init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
          },
        })
        return new Response(body, {
          status: 200,
          headers: { 'content-type': 'application/x-ndjson' },
        })
      })
    )

    renderBrowser()
    await waitFor(() => expect(streamControllers).toHaveLength(1))
    await screen.findByRole('button', { name: 'report.md' })
    await openResourceMenu('report.md')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }))
    const dialog = await screen.findByRole('dialog', { name: 'Rename file' })

    // The user's open dialog represents version 4. A stream revalidation may
    // learn that the resource is now version 5, but it must not silently change
    // the version the user is confirming.
    resolvedReport = { ...resolvedReport, version: 5 }
    const frame = await controlApiProducerFrame(['authorization'])
    await act(async () => {
      streamControllers[0]!.enqueue(new TextEncoder().encode(`${frame}\n`))
    })

    await waitFor(() => expect(treeReads).toBe(2))
    expect(screen.getByRole('button', { name: 'report.md' })).toBeVisible()
    expect(screen.getByRole('dialog', { name: 'Rename file' })).toBe(dialog)

    await act(async () => {
      releaseRefresh({ rootResourceId: rootId, items: [report], nextCursor: null })
    })
    expect(await screen.findByRole('button', { name: 'report.md' })).toBeVisible()
    expect(screen.getByRole('dialog', { name: 'Rename file' })).toBe(dialog)

    await waitFor(() =>
      expect(mockApiGet).toHaveBeenCalledWith(
        '/api/v1/gfs/resolve',
        { uri: report.gfsUri },
        expect.objectContaining({ signal: expect.any(AbortSignal) })
      )
    )
    mockApiSend.mockResolvedValue({ data: { resourceId: report.resourceId, version: 6 } })
    fireEvent.change(screen.getByRole('textbox', { name: 'New name' }), {
      target: { value: 'renamed.md' },
    })
    fireEvent.click(screen.getByRole('button', { name: 'Rename' }))
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        `/api/v1/gfs/resources/${encodeURIComponent(report.resourceId)}`,
        { drive: 'main', newName: 'renamed.md', ifMatch: 4 },
        { drive: 'main' }
      )
    )
  })

  it('purges the current folder after stream revalidation proves it is forbidden', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const report = child('report.md', 'file', 1, 4)
    const resolvedReport = toResolveView({
      resourceId: report.resourceId,
      drive: 'main',
      name: report.name,
      kind: 'file',
      pathCache: report.path,
      bytes: report.bytes,
      version: report.version,
      updatedAt: '2026-09-28T00:00:00.000Z',
    })
    const streamControllers: ReadableStreamDefaultController<Uint8Array>[] = []
    let rejectRefresh!: (error: Error) => void
    let treeReads = 0
    mockApiGet.mockImplementation(async (path: string, query?: Record<string, string>) => {
      if (path === '/api/v1/gfs/tree') {
        treeReads += 1
        if (treeReads === 2) {
          return new Promise((_resolve, reject) => {
            rejectRefresh = reject
          })
        }
        return { rootResourceId: rootId, items: [report], nextCursor: null }
      }
      if (path === '/api/v1/gfs/resolve' && query?.uri === report.gfsUri) {
        return resolvedReport
      }
      if (path === '/api/v1/gfs/resolve') {
        return resolvedFolderView(rootId, 'main', '/', 1)
      }
      return { items: [], nextCursor: null }
    })
    vi.stubGlobal(
      'fetch',
      vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
        const body = new ReadableStream<Uint8Array>({
          start(controller) {
            streamControllers.push(controller)
            init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
          },
        })
        return new Response(body, {
          status: 200,
          headers: { 'content-type': 'application/x-ndjson' },
        })
      })
    )

    renderBrowser()
    await waitFor(() => expect(streamControllers).toHaveLength(1))
    await screen.findByRole('button', { name: 'report.md' })
    await openResourceMenu('report.md')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }))
    await screen.findByRole('dialog', { name: 'Rename file' })

    const frame = await controlApiProducerFrame()
    await act(async () => {
      streamControllers[0]!.enqueue(new TextEncoder().encode(`${frame}\n`))
    })
    await waitFor(() => expect(treeReads).toBe(2))
    expect(screen.getByRole('button', { name: 'report.md' })).toBeVisible()
    expect(screen.getByRole('dialog', { name: 'Rename file' })).toBeVisible()

    await act(async () => {
      rejectRefresh(Object.assign(new Error('403 Forbidden'), { status: 403 }))
    })

    await waitFor(() => {
      expect(screen.queryByRole('button', { name: 'report.md' })).toBeNull()
      // The folder listing is no longer authorized, but the item-target
      // revalidation independently proved this file remains accessible.
      expect(screen.getByRole('dialog', { name: 'Rename file' })).toBeVisible()
    })
  })

  it('recovers the current list and open preview after one transient invalidation refetch failure', async () => {
    const streamControllers: ReadableStreamDefaultController<Uint8Array>[] = []
    let treeFailureUsed = false
    let previewFailureUsed = false
    mockApiGet.mockResolvedValueOnce({
      items: [child('avatar.PNG', 'file', 12)],
      nextCursor: null,
    })
    mockGfsFetchFileBlob.mockResolvedValue(new Blob(['image bytes']))
    vi.stubGlobal(
      'fetch',
      vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
        const body = new ReadableStream<Uint8Array>({
          start(controller) {
            streamControllers.push(controller)
            init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
          },
        })
        return new Response(body, {
          status: 200,
          headers: { 'content-type': 'application/x-ndjson' },
        })
      })
    )

    renderBrowser()
    await waitFor(() => expect(streamControllers).toHaveLength(1))
    fireEvent.click(await screen.findByRole('button', { name: 'avatar.PNG' }))
    const originalDialog = await screen.findByRole('dialog', { name: 'avatar.PNG' })
    await within(originalDialog).findByRole('img', { name: 'Preview of avatar.PNG' })

    mockApiGet.mockImplementation(async (path: string, query?: Record<string, string>) => {
      if (path === '/api/v1/gfs/tree') {
        if (!treeFailureUsed) {
          treeFailureUsed = true
          throw Object.assign(new Error('503 Service Unavailable'), { status: 503 })
        }
        return {
          items: [child('avatar.PNG', 'file', 12), child('remote-folder', 'directory', 99)],
          nextCursor: null,
        }
      }
      if (path === '/api/v1/gfs/resolve' && query?.uri === 'gfs://main/r12') {
        if (!previewFailureUsed) {
          previewFailureUsed = true
          throw Object.assign(new Error('503 Service Unavailable'), { status: 503 })
        }
        return {
          kind: 'file',
          resourceId: 'id-12',
          rid: 'r12',
          name: 'avatar.PNG',
          bytes: 0,
          version: 0,
        }
      }
      return { items: [], nextCursor: null }
    })
    const producerFrame = await controlApiProducerFrame()
    await act(async () => {
      streamControllers[0]!.enqueue(new TextEncoder().encode(`${producerFrame}\n`))
    })

    await waitFor(() => {
      expect(treeFailureUsed).toBe(true)
      expect(previewFailureUsed).toBe(true)
    })
    expect(screen.getByRole('dialog', { name: 'avatar.PNG' })).toBe(originalDialog)
    expect(
      await within(originalDialog).findByRole('img', { name: 'Preview of avatar.PNG' })
    ).toBeTruthy()
    expect(mockGfsFetchFileBlob).toHaveBeenCalledTimes(1)
    await screen.findByText('remote-folder')
    expect(mockGfsFetchFileBlob).toHaveBeenCalledTimes(1)
    expect(treeFailureUsed).toBe(true)
    expect(previewFailureUsed).toBe(true)
    expect(mockApiGet).toHaveBeenCalledWith(
      '/api/v1/gfs/resolve',
      { uri: 'gfs://main/r12' },
      expect.objectContaining({ signal: expect.any(AbortSignal) })
    )
  })

  it('keeps the visible error and browser state while a stream refresh retries', async () => {
    const streamControllers: ReadableStreamDefaultController<Uint8Array>[] = []
    const report = child('report.md', 'file', 1, 2)
    mockApiGet.mockResolvedValueOnce({ items: [report], nextCursor: null })
    vi.stubGlobal(
      'fetch',
      vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
        const body = new ReadableStream<Uint8Array>({
          start(controller) {
            streamControllers.push(controller)
            init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
          },
        })
        return new Response(body, {
          status: 200,
          headers: { 'content-type': 'application/x-ndjson' },
        })
      })
    )

    renderBrowser()
    await waitFor(() => expect(streamControllers).toHaveLength(1))
    await screen.findByRole('button', { name: 'report.md' })
    await openResourceMenu('report.md')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }))
    const dialog = await screen.findByRole('dialog', { name: 'Rename file' })
    const frame = await controlApiProducerFrame()

    let releaseRetry: ((page: { items: (typeof report)[]; nextCursor: null }) => void) | undefined
    let treeReads = 0
    mockApiGet.mockImplementation(async (path: string, query?: Record<string, string>) => {
      if (path === '/api/v1/gfs/tree') {
        treeReads += 1
        if (treeReads === 1) {
          throw Object.assign(new Error('503 Service Unavailable'), { status: 503 })
        }
        return new Promise(resolve => {
          releaseRetry = resolve
        })
      }
      if (path === '/api/v1/gfs/resolve' && query?.uri === report.gfsUri) {
        return {
          resourceId: report.resourceId,
          rid: report.rid,
          gfsUri: report.gfsUri,
          name: report.name,
          kind: report.kind,
          bytes: report.bytes,
          version: report.version,
        }
      }
      return { items: [], nextCursor: null }
    })

    await act(async () => {
      streamControllers[0]!.enqueue(new TextEncoder().encode(`${frame}\n`))
    })
    await waitFor(() => expect(treeReads).toBe(1))
    expect(screen.getByRole('button', { name: 'report.md' })).toBeVisible()
    expect(screen.getByRole('dialog', { name: 'Rename file' })).toBe(dialog)
    expect(screen.getByRole('alert')).toHaveTextContent('503 Service Unavailable')

    await waitFor(() => expect(releaseRetry).toBeDefined(), { timeout: 1500 })
    expect(treeReads).toBe(2)
    expect(screen.getByRole('button', { name: 'report.md' })).toBeVisible()
    expect(screen.getByRole('dialog', { name: 'Rename file' })).toBe(dialog)
    expect(screen.getByRole('alert')).toHaveTextContent('503 Service Unavailable')

    await act(async () => {
      releaseRetry?.({ items: [report], nextCursor: null })
    })
    expect(screen.getByRole('button', { name: 'report.md' })).toBeVisible()
    expect(screen.getByRole('dialog', { name: 'Rename file' })).toBe(dialog)
    expect(screen.queryByRole('alert')).toBeNull()
  })

  it('coalesces a stream burst without aborting the active refresh and applies the trailing state', async () => {
    const streamControllers: ReadableStreamDefaultController<Uint8Array>[] = []
    const report = child('report.md', 'file', 1, 2)
    const remote = child('remote.txt', 'file', 2, 3)
    let treeReads = 0
    let refreshSignal: AbortSignal | undefined
    let finishFirstRefresh!: (page: { items: (typeof report)[]; nextCursor: null }) => void
    mockApiGet.mockImplementation(
      async (
        path: string,
        _query?: Record<string, string>,
        options?: {
          signal?: AbortSignal
        }
      ) => {
        if (path === '/api/v1/gfs/tree') {
          treeReads += 1
          if (treeReads === 1) return { items: [report], nextCursor: null }
          if (treeReads === 2) {
            refreshSignal = options?.signal
            return new Promise(resolve => {
              finishFirstRefresh = resolve
            })
          }
          return { items: [report, remote], nextCursor: null }
        }
        return { items: [], nextCursor: null }
      }
    )
    vi.stubGlobal(
      'fetch',
      vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
        const body = new ReadableStream<Uint8Array>({
          start(controller) {
            streamControllers.push(controller)
            init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
          },
        })
        return new Response(body, {
          status: 200,
          headers: { 'content-type': 'application/x-ndjson' },
        })
      })
    )

    renderBrowser()
    await waitFor(() => expect(streamControllers).toHaveLength(1))
    await screen.findByRole('button', { name: 'report.md' })
    const firstFrame = await controlApiProducerFrame()
    await act(async () => {
      streamControllers[0]!.enqueue(new TextEncoder().encode(`${firstFrame}\n`))
    })
    await waitFor(() => expect(treeReads).toBe(2))
    const secondFrame = await controlApiProducerFrame()
    await act(async () => {
      streamControllers[0]!.enqueue(new TextEncoder().encode(`${secondFrame}\n`))
    })

    await new Promise(resolve => setTimeout(resolve, 150))
    expect(treeReads).toBe(2)
    expect(refreshSignal?.aborted).toBe(false)

    await act(async () => finishFirstRefresh({ items: [report], nextCursor: null }))
    await waitFor(() => expect(treeReads).toBe(3), { timeout: 1500 })
    expect(await screen.findByRole('button', { name: 'remote.txt' })).toBeVisible()
  })

  it.each(['avatar.PNG', 'notes.md', 'demo.mp4'])(
    'does not reload an unchanged open %s preview after a scope invalidation',
    async fileName => {
      const rootId = '11111111-1111-1111-1111-111111111111'
      const fileResourceId = '22222222-2222-2222-2222-222222222222'
      const fileRid = fileResourceId.replace(/-/g, '')
      const file = {
        ...child(fileName, 'file', 12, 2),
        resourceId: fileResourceId,
        rid: fileRid,
        gfsUri: `gfs://main/${fileRid}`,
      }
      let resolvedFile = toResolveView({
        resourceId: file.resourceId,
        drive: 'main',
        name: fileName,
        kind: 'file',
        pathCache: `/${fileName}`,
        bytes: file.bytes,
        version: file.version,
        updatedAt: '2026-09-28T00:00:00.000Z',
      })
      const streamControllers: ReadableStreamDefaultController<Uint8Array>[] = []
      mockApiGet.mockImplementation(async (path: string, query?: Record<string, string>) => {
        if (path === '/api/v1/gfs/tree') {
          return { rootResourceId: rootId, items: [file], nextCursor: null }
        }
        if (path === `/api/v1/gfs/resources/${rootId}/children`) {
          return { items: [file], nextCursor: null }
        }
        if (path === '/api/v1/gfs/resolve' && query?.uri === file.gfsUri) return resolvedFile
        if (path === '/api/v1/gfs/resolve') {
          return resolvedFolderView(rootId, 'main', '/', 1)
        }
        return { items: [], nextCursor: null }
      })
      mockGfsFetchFileBlob.mockResolvedValue(
        new Blob(['# unchanged preview\n\nbody'], { type: 'text/plain' })
      )
      vi.stubGlobal(
        'fetch',
        vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
          const body = new ReadableStream<Uint8Array>({
            start(controller) {
              streamControllers.push(controller)
              init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
            },
          })
          return new Response(body, {
            status: 200,
            headers: { 'content-type': 'application/x-ndjson' },
          })
        })
      )

      renderBrowser()
      await waitFor(() => expect(streamControllers).toHaveLength(1))
      fireEvent.click(await screen.findByRole('button', { name: fileName }))
      const dialog = await screen.findByRole('dialog', { name: fileName })
      if (fileName.endsWith('.PNG')) {
        await within(dialog).findByRole('img', { name: `Preview of ${fileName}` })
      } else if (fileName.endsWith('.md')) {
        await within(dialog).findByRole('heading', { name: 'unchanged preview' })
      } else {
        await within(dialog).findByLabelText(`Video preview of ${fileName}`)
      }
      expect(mockGfsFetchFileBlob).toHaveBeenCalledTimes(1)

      const frame = await controlApiProducerFrame(['authorization'])
      await act(async () => {
        streamControllers[0]!.enqueue(new TextEncoder().encode(`${frame}\n`))
      })
      await waitFor(() =>
        expect(mockApiGet).toHaveBeenCalledWith(
          '/api/v1/gfs/resolve',
          { uri: file.gfsUri },
          expect.objectContaining({ signal: expect.any(AbortSignal) })
        )
      )
      expect(screen.getByRole('dialog', { name: fileName })).toBe(dialog)
      expect(mockGfsFetchFileBlob).toHaveBeenCalledTimes(1)
      if (fileName.endsWith('.PNG')) {
        expect(within(dialog).getByRole('img', { name: `Preview of ${fileName}` })).toBeVisible()
      } else if (fileName.endsWith('.md')) {
        expect(within(dialog).getByRole('heading', { name: 'unchanged preview' })).toBeVisible()
      } else {
        expect(within(dialog).getByLabelText(`Video preview of ${fileName}`)).toBeVisible()
      }

      resolvedFile = toResolveView({
        resourceId: file.resourceId,
        drive: 'main',
        name: fileName,
        kind: 'file',
        pathCache: `/${fileName}`,
        bytes: file.bytes + 1,
        version: file.version + 1,
        updatedAt: '2026-09-28T00:00:01.000Z',
      })
      const changedFrame = await controlApiProducerFrame(['authorization'])
      await act(async () => {
        streamControllers.at(-1)!.enqueue(new TextEncoder().encode(`${changedFrame}\n`))
      })
      await waitFor(() => {
        expect(
          mockApiGet.mock.calls.filter(
            ([path, query]) => path === '/api/v1/gfs/resolve' && query?.uri === file.gfsUri
          )
        ).toHaveLength(2)
      })
      await waitFor(() => expect(mockGfsFetchFileBlob).toHaveBeenCalledTimes(2))
      const refreshedDialog = screen.getByRole('dialog', { name: fileName })
      expect(refreshedDialog).not.toBe(dialog)
      if (fileName.endsWith('.PNG')) {
        expect(
          within(refreshedDialog).getByRole('img', { name: `Preview of ${fileName}` })
        ).toBeVisible()
      } else if (fileName.endsWith('.md')) {
        expect(
          within(refreshedDialog).getByRole('heading', { name: 'unchanged preview' })
        ).toBeVisible()
      } else {
        expect(within(refreshedDialog).getByLabelText(`Video preview of ${fileName}`)).toBeVisible()
      }
    }
  )

  it('rebuilds the open directory breadcrumbs after a remote move', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const oldParent = listedFolder(
      '22222222-2222-2222-2222-222222222222',
      'old-parent',
      '/old-parent',
      1
    )
    const oldFolder = listedFolder(
      '33333333-3333-3333-3333-333333333333',
      'old-folder',
      '/old-parent/old-folder',
      2
    )
    const newParent = resolvedFolderView(
      '44444444-4444-4444-4444-444444444444',
      'new-parent',
      '/new-parent',
      11
    )
    const resolvedLocation = resolvedFolderView(
      oldFolder.resourceId,
      'renamed-folder',
      '/new-parent/renamed-folder',
      10
    )
    const refreshedFolder = resolvedFolderView(
      oldFolder.resourceId,
      'renamed-folder',
      '/new-parent/renamed-folder',
      12
    )
    const streamControllers: ReadableStreamDefaultController<Uint8Array>[] = []
    mockApiGet.mockImplementation(async (path: string, query?: Record<string, string>) => {
      if (path === '/api/v1/gfs/tree') {
        return {
          rootResourceId: rootId,
          items: [oldParent],
          nextCursor: null,
        }
      }
      if (path === '/api/v1/gfs/resolve') {
        return resolvedLocation
      }
      if (path === '/api/v1/gfs/by-path' && query?.path === '/new-parent') {
        return newParent
      }
      if (path === '/api/v1/gfs/by-path' && query?.path === '/new-parent/renamed-folder') {
        return refreshedFolder
      }
      if (path.endsWith('/children')) {
        if (path === `/api/v1/gfs/resources/${rootId}/children`) {
          return { items: [oldParent], nextCursor: null }
        }
        if (path.endsWith(`/${oldParent.resourceId}/children`)) {
          return { items: [oldFolder], nextCursor: null }
        }
        return { items: [], nextCursor: null }
      }
      return { items: [], nextCursor: null }
    })
    vi.stubGlobal(
      'fetch',
      vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
        const body = new ReadableStream<Uint8Array>({
          start(controller) {
            streamControllers.push(controller)
            init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
          },
        })
        return new Response(body, {
          status: 200,
          headers: { 'content-type': 'application/x-ndjson' },
        })
      })
    )

    renderBrowser()
    await waitFor(() => expect(streamControllers).toHaveLength(1))
    fireEvent.click(await screen.findByRole('button', { name: 'old-parent' }))
    fireEvent.click(await screen.findByRole('button', { name: 'old-folder' }))
    await screen.findByText('No resources are visible in this folder.')

    const frame = await controlApiProducerFrame()
    await act(async () => {
      streamControllers[0].enqueue(new TextEncoder().encode(`${frame}\n`))
    })

    const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })
    await within(breadcrumb).findByRole('button', { name: 'new-parent' })
    expect(within(breadcrumb).getByRole('button', { name: 'renamed-folder' })).toBeTruthy()
    expect(within(breadcrumb).queryByRole('button', { name: 'old-parent' })).toBeNull()
    expect(mockApiGet).toHaveBeenCalledWith(
      '/api/v1/gfs/by-path',
      { drive: 'main', path: '/new-parent/renamed-folder' },
      expect.objectContaining({ signal: expect.any(AbortSignal) })
    )

    mockApiSend.mockResolvedValueOnce({
      ok: true,
      data: { resourceId: oldFolder.resourceId, version: 13 },
    })
    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'Actions for renamed-folder' }))
    expect(screen.getAllByRole('menuitem').map(item => item.textContent)).toEqual([
      'Share',
      'Open EvenDrive link',
      'Rename',
      'Move to…',
      'Delete',
    ])
    fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }))
    const renameDialog = await screen.findByRole('dialog', { name: 'Rename folder' })
    fireEvent.change(within(renameDialog).getByLabelText('New name'), {
      target: { value: 'renamed-again' },
    })
    fireEvent.click(within(renameDialog).getByRole('button', { name: 'Rename' }))
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        `/api/v1/gfs/resources/${oldFolder.resourceId}`,
        { drive: 'main', newName: 'renamed-again', ifMatch: 12 },
        { drive: 'main' }
      )
    )
  })

  it('keeps a newer remote hierarchy when an older local move reconstruction completes late', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const work = child('work', 'directory', 1, 3)
    const org = child('org', 'directory', 2, 7)
    const archive = child('archive', 'directory', 3, 5)
    const dept = child('dept', 'directory', 4, 6)
    const streamControllers: ReadableStreamDefaultController<Uint8Array>[] = []
    const resolved = (resource: ReturnType<typeof child>, path: string) => ({
      resourceId: resource.resourceId,
      rid: resource.rid,
      name: resource.name,
      kind: 'directory',
      path,
    })
    let releaseLocalResolve: ((value: unknown) => void) | null = null
    let resolveCalls = 0
    mockApiGet.mockImplementation(async (path: string, query?: Record<string, string>) => {
      if (path === '/api/v1/gfs/tree' || path === `/api/v1/gfs/resources/${rootId}/children`) {
        return { rootResourceId: rootId, items: [work, archive, dept], nextCursor: null }
      }
      if (path === `/api/v1/gfs/resources/${work.resourceId}/children`) {
        return { items: [org], nextCursor: null }
      }
      if (path.endsWith('/children')) return { items: [], nextCursor: null }
      if (path === '/api/v1/gfs/resolve') {
        resolveCalls += 1
        if (resolveCalls === 1) {
          return new Promise<unknown>(resolve => {
            releaseLocalResolve = resolve
          })
        }
        return resolved(org, '/dept/org')
      }
      if (path === '/api/v1/gfs/by-path') {
        if (query?.path === '/dept') return resolved(dept, '/dept')
        if (query?.path === '/dept/org') return resolved(org, '/dept/org')
      }
      return { items: [], nextCursor: null }
    })
    mockGetGfsResourceByPath.mockImplementation(async () => resolved(archive, '/archive'))
    mockApiSend.mockResolvedValue({ ok: true, data: { resourceId: org.resourceId, version: 8 } })
    vi.stubGlobal(
      'fetch',
      vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
        const body = new ReadableStream<Uint8Array>({
          start(controller) {
            streamControllers.push(controller)
            init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
          },
        })
        return new Response(body, {
          status: 200,
          headers: { 'content-type': 'application/x-ndjson' },
        })
      })
    )

    renderBrowser()
    await waitFor(() => expect(streamControllers).toHaveLength(1))
    fireEvent.click(await screen.findByRole('button', { name: 'work' }))
    await waitFor(() =>
      expect(
        within(screen.getByRole('navigation', { name: 'Breadcrumb' }))
          .getAllByRole('button')
          .map(button => button.textContent)
      ).toContain('work')
    )
    fireEvent.click(await screen.findByRole('button', { name: 'org' }))
    await screen.findByText('No resources are visible in this folder.')
    const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })

    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'Actions for org' }))
    fireEvent.click(screen.getByRole('menuitem', { name: 'Move to…' }))
    const moveDialog = await screen.findByRole('dialog', { name: 'Move folder org' })
    fireEvent.click(await within(moveDialog).findByRole('button', { name: 'archive' }))
    fireEvent.click(within(moveDialog).getByRole('button', { name: 'Move here (archive)' }))
    await waitFor(() => expect(releaseLocalResolve).toBeTruthy())

    const frame = await controlApiProducerFrame()
    await act(async () => {
      streamControllers[0]!.enqueue(new TextEncoder().encode(`${frame}\n`))
    })
    await within(breadcrumb).findByRole('button', { name: 'dept' })

    await act(async () => {
      releaseLocalResolve!(resolved(org, '/archive/org'))
      await new Promise(resolve => setTimeout(resolve, 0))
    })
    expect(within(breadcrumb).getByRole('button', { name: 'dept' })).toBeTruthy()
    expect(within(breadcrumb).queryByRole('button', { name: 'archive' })).toBeNull()
  })

  it.each(['secret.png', 'secret.md', 'secret.mp4'])(
    'purges an open %s preview when the authoritative refetch denies access',
    async fileName => {
      const streamControllers: ReadableStreamDefaultController<Uint8Array>[] = []
      mockApiGet.mockImplementation(async (path: string) => {
        if (path === '/api/v1/gfs/tree') {
          return {
            rootResourceId: '11111111-1111-1111-1111-111111111111',
            items: [child(fileName, 'file', 12)],
            nextCursor: null,
          }
        }
        if (path === '/api/v1/gfs/resolve') {
          throw Object.assign(new Error('access revoked for sensitive subject'), { status: 403 })
        }
        return { items: [child(fileName, 'file', 12)], nextCursor: null }
      })
      mockGfsFetchFileBlob.mockResolvedValue(
        new Blob(['# Private title\n\nclassified content'], { type: 'text/plain' })
      )
      vi.stubGlobal(
        'fetch',
        vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
          const body = new ReadableStream<Uint8Array>({
            start(controller) {
              streamControllers.push(controller)
              init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
            },
          })
          return new Response(body, {
            status: 200,
            headers: { 'content-type': 'application/x-ndjson' },
          })
        })
      )

      renderBrowser()
      await waitFor(() => expect(streamControllers).toHaveLength(1))
      fireEvent.click(await screen.findByRole('button', { name: fileName }))
      const dialog = await screen.findByRole('dialog', { name: fileName })
      if (fileName.endsWith('.png')) {
        await within(dialog).findByRole('img', { name: `Preview of ${fileName}` })
      } else if (fileName.endsWith('.md')) {
        await within(dialog).findByRole('heading', { name: 'Private title' })
        expect(within(dialog).getByText('classified content')).toBeTruthy()
      } else {
        await within(dialog).findByLabelText(`Video preview of ${fileName}`)
      }

      const frame = await controlApiProducerFrame(['authorization'])
      await act(async () => {
        streamControllers[0]!.enqueue(new TextEncoder().encode(`${frame}\n`))
      })

      const unavailableDialog = await screen.findByRole('dialog', { name: 'File unavailable' })
      expect(unavailableDialog.textContent).not.toContain('access revoked for sensitive subject')
      expect(unavailableDialog.textContent).not.toContain('classified content')
      expect(within(unavailableDialog).queryByRole('img')).toBeNull()
      expect(within(unavailableDialog).queryByLabelText(/Video preview/)).toBeNull()
      if (!fileName.endsWith('.md')) {
        await waitFor(() =>
          expect(mockRevokeObjectUrl).toHaveBeenCalledWith('blob:gfs-image-preview')
        )
      }
      expect(mockGfsFetchFileBlob).toHaveBeenCalledTimes(1)
    }
  )

  it('shortens oversized folder and upload names before operator writes', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const rootRid = '11111111111111111111111111111111'
    const rawFolderName = `operator-folder-${'very-long-'.repeat(32)}child`
    const folderName = await normalizeGfsResourceName(rawFolderName)
    const rawFileName = `operator-upload-${'very-long-'.repeat(32)}report.txt`
    const fileName = await normalizeGfsResourceName(rawFileName)
    mockApiGet.mockResolvedValue({ rootResourceId: rootId, items: [], nextCursor: null })
    mockApiSend.mockResolvedValue({ ok: true })
    renderBrowser()
    await screen.findByText('No resources are visible in this folder.')

    fireEvent.click(await screen.findByRole('button', { name: /new folder/i }))
    const folderDialog = await screen.findByRole('dialog')
    fireEvent.change(within(folderDialog).getByLabelText('Folder name'), {
      target: { value: rawFolderName },
    })
    fireEvent.click(within(folderDialog).getByRole('button', { name: 'Create folder' }))
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'POST',
        `/api/v1/gfs/proxy/v1/resources/${rootRid}/children`,
        { name: folderName, kind: 'directory' }
      )
    )
    await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())

    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(['operator upload'], rawFileName, { type: 'text/plain' })],
      },
    })
    fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Upload' }))

    await waitFor(() =>
      expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(
        expect.objectContaining({
          name: fileName,
          target: { operation: 'create', parentRid: rootRid },
        })
      )
    )
  })

  it('uploads dropped files into the current folder', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const rootRid = '11111111111111111111111111111111'
    mockApiGet.mockResolvedValue({
      rootResourceId: rootId,
      items: [],
      nextCursor: null,
    })
    mockApiSend.mockResolvedValue({ ok: true })
    renderBrowser()
    await screen.findByText('No resources are visible in this folder.')

    const browser = screen.getByRole('region', { name: 'EvenDrive browser' })
    const image = new File(['operator image'], 'diagram.png', { type: 'image/png' })
    const markdown = new File(['# Operator notes'], 'notes.md', { type: 'text/markdown' })
    const pdf = new File(['%PDF operator report'], 'report.pdf', { type: 'application/pdf' })
    const dataTransfer = { dropEffect: 'none', files: [image, markdown, pdf], types: ['Files'] }

    fireEvent.dragEnter(browser.querySelector('.cu-gfs-card')!, { dataTransfer })
    const dropStatus = screen.getByRole('status')
    expect(dropStatus).toHaveTextContent('Drop files to upload to main')
    expect(dropStatus).toHaveClass('cu-gfs-drop-overlay')

    fireEvent.drop(browser.querySelector('.cu-gfs-card')!, { dataTransfer })

    await waitFor(() => {
      expect(mockCreateGfsUploadJob).toHaveBeenCalledTimes(3)
      expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(
        1,
        expect.objectContaining({
          name: 'diagram.png',
          target: { operation: 'create', parentRid: rootRid },
        })
      )
      expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(
        2,
        expect.objectContaining({
          name: 'notes.md',
          target: { operation: 'create', parentRid: rootRid },
        })
      )
      expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(
        3,
        expect.objectContaining({
          name: 'report.pdf',
          target: { operation: 'create', parentRid: rootRid },
        })
      )
    })
  })

  it('adds numbered suffixes for duplicate names in one dropped batch', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const rootRid = '11111111111111111111111111111111'
    mockApiGet.mockResolvedValue({
      rootResourceId: rootId,
      items: [child('report.txt', 'file', 2)],
      nextCursor: null,
    })
    renderBrowser()
    await screen.findByText('report.txt')

    const browser = screen.getByRole('region', { name: 'EvenDrive browser' })
    fireEvent.drop(browser.querySelector('.cu-gfs-card')!, {
      dataTransfer: {
        dropEffect: 'none',
        files: [
          new File(['first'], 'report.txt', { type: 'text/plain' }),
          new File(['second'], 'report.txt', { type: 'text/plain' }),
        ],
        types: ['Files'],
      },
    })

    await waitFor(() => {
      expect(mockCreateGfsUploadJob).toHaveBeenCalledTimes(2)
      expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(
        1,
        expect.objectContaining({
          name: 'report (1).txt',
          target: { operation: 'create', parentRid: rootRid },
        })
      )
      expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(
        2,
        expect.objectContaining({
          name: 'report (2).txt',
          target: { operation: 'create', parentRid: rootRid },
        })
      )
    })
  })

  it('retries the real Upload v2 409 producer error with the next available name', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const rootRid = '11111111111111111111111111111111'
    mockApiGet.mockResolvedValue({ rootResourceId: rootId, items: [], nextCursor: null })
    const actualUpload =
      await vi.importActual<typeof import('@lib/gfsFileUpload')>('@lib/gfsFileUpload')
    const producerErrors: unknown[] = []
    const uploadNames: string[] = []
    const session = {
      uploadId: 'producer-upload',
      drive: 'main',
      operation: 'create' as const,
      expectedBytes: 0,
      partBytes: 1,
      partCount: 0,
      state: 'initiated',
      committedBytes: 0,
      committedPartCount: 0,
      activePartCount: 0,
    }
    const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
      const url = String(input)
      const method = init?.method ?? 'GET'
      if (url.endsWith('/api/v1/gfs/proxy/v1/capabilities')) {
        return new Response(
          JSON.stringify({
            upload: {
              resumableV2: {
                enabled: true,
                maxFileBytes: GFS_FILE_UPLOAD_PROTOCOL_MAX_BYTES,
                preferredChunkBytes: 1,
                maxChunkBytes: 1,
              },
            },
          }),
          { status: 200 }
        )
      }
      if (method === 'POST' && url.endsWith('/api/v1/gfs/proxy/v1/uploads')) {
        const body = JSON.parse(String(init?.body)) as { name: string }
        uploadNames.push(body.name)
        if (uploadNames.length === 1) {
          return new Response(
            JSON.stringify({
              ok: false,
              error: { code: 'conflict', message: 'resource already exists' },
            }),
            { status: 409, statusText: 'Conflict' }
          )
        }
        return new Response(JSON.stringify({ ok: true, data: session }), { status: 201 })
      }
      if (
        method === 'POST' &&
        url.endsWith(`/api/v1/gfs/proxy/v1/uploads/${session.uploadId}/complete`)
      ) {
        return new Response(
          JSON.stringify({ ok: true, data: { ...session, state: 'completed' } }),
          { status: 200 }
        )
      }
      throw new Error(`Unexpected producer request: ${method} ${url}`)
    })
    vi.stubGlobal('fetch', fetchMock)
    mockCreateGfsUploadJob.mockImplementation(input => {
      const job = actualUpload.createGfsUploadJob(input)
      return {
        start: async () => {
          try {
            return await job.start()
          } catch (error) {
            producerErrors.push(error)
            throw error
          }
        },
        pause: job.pause.bind(job),
        resume: job.resume.bind(job),
        cancel: job.cancel.bind(job),
        snapshot: job.snapshot.bind(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([], 'report.txt', { type: 'text/plain' })] },
    })
    fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Upload' }))

    await waitFor(() => {
      expect(uploadNames).toEqual(['report.txt', 'report (1).txt'])
    })
    const conflict = producerErrors[0] as Error & { status?: number; code?: string }
    expect(conflict).toBeInstanceOf(Error)
    expect(conflict.message).toBe('409 resource already exists')
    expect(conflict.status).toBe(409)
    expect(conflict.code).toBe('conflict')
    expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(
      2,
      expect.objectContaining({
        name: 'report (1).txt',
        target: { operation: 'create', parentRid: rootRid },
      })
    )
    await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Upload file' })).toBeNull())
  })

  it('keeps the legacy Electron conflict string as a separate compatibility path', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    mockApiGet.mockResolvedValue({ rootResourceId: rootId, items: [], nextCursor: null })
    mockCreateGfsUploadJob.mockImplementationOnce(() => ({
      start: vi
        .fn()
        .mockRejectedValue(
          new Error(
            "Error invoking remote method 'gfs:createFileFromPath': Error: 409 Conflict: [object Object]"
          )
        ),
      pause: vi.fn(),
      resume: vi.fn(),
      cancel: vi.fn(),
      snapshot: vi.fn(() => ({ state: 'failed' })),
    }))
    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(['report'], 'report.txt', { type: 'text/plain' })] },
    })
    fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Upload' }))

    await waitFor(() => {
      expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(
        2,
        expect.objectContaining({ name: 'report (1).txt' })
      )
    })
  })

  it('moves a dragged file into a visible folder without treating it as an upload', async () => {
    const folder = child('archive', 'directory', 1)
    const file = child('report.md', 'file', 2)
    let moved = false
    mockApiGet.mockImplementation(async (path: string, query?: Record<string, string>) => {
      if (path === '/api/v1/gfs/resolve' && query?.uri === file.gfsUri) {
        // The pre-dispatch re-resolve answers with a FRESH source version —
        // the PATCH must carry it, not the stale row version.
        return {
          resourceId: file.resourceId,
          kind: 'file',
          path: '/report.md',
          version: 3,
        }
      }
      if (path === '/api/v1/gfs/resolve' && query?.uri === folder.gfsUri) {
        return {
          resourceId: folder.resourceId,
          kind: 'directory',
          path: '/archive',
          version: 0,
        }
      }
      if (path === '/api/v1/gfs/tree') {
        return { items: moved ? [folder] : [folder, file], nextCursor: null }
      }
      return { items: [], nextCursor: null }
    })
    mockApiSend.mockImplementationOnce(async () => {
      moved = true
      return { ok: true }
    })
    renderBrowser()

    const resources = await screen.findByRole('list', { name: 'Current folder resources' })
    const fileRow = within(resources).getByText('report.md').closest('li')
    const folderRow = within(resources).getByText('archive').closest('li')
    expect(fileRow).not.toBeNull()
    expect(folderRow).not.toBeNull()
    expect(fileRow).toHaveAttribute('draggable', 'true')
    // rev-2 D2: folders drag too (moves via the drop-target rows).
    expect(folderRow).toHaveAttribute('draggable', 'true')

    const dataTransfer = {
      dropEffect: 'none',
      effectAllowed: 'uninitialized',
      files: [],
      types: ['application/x-evenfire-gfs-resource'],
      setData: vi.fn(),
      getData: vi.fn(),
    }
    fireEvent.dragStart(fileRow!, { dataTransfer })
    fireEvent.dragEnter(folderRow!, { dataTransfer })
    expect(folderRow).toHaveAttribute('data-drop-target', 'true')
    fireEvent.dragOver(folderRow!, { dataTransfer })
    fireEvent.drop(folderRow!, { dataTransfer })

    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        '/api/v1/gfs/resources/id-2',
        { drive: 'main', newParentId: 'id-1', ifMatch: 3 },
        { drive: 'main' }
      )
    )
    expect(mockCreateGfsUploadJob).not.toHaveBeenCalled()
    expect(await screen.findByText('Moved "report.md" to "archive".')).toBeTruthy()
    await waitFor(() => expect(screen.queryByText('report.md')).toBeNull())
  })

  it('opens the compact move picker from the resource menu and moves to its selection', async () => {
    const folder = child('archive', 'directory', 1)
    const file = child('report.md', 'file', 2)
    mockApiGet.mockImplementation(async (path: string) => {
      if (
        path === '/api/v1/gfs/tree' ||
        path === '/api/v1/gfs/resources/11111111-1111-1111-1111-111111111111/children'
      ) {
        return {
          rootResourceId: '11111111-1111-1111-1111-111111111111',
          items: [folder, file],
          nextCursor: null,
        }
      }
      return { items: [], nextCursor: null }
    })
    mockApiSend.mockResolvedValueOnce({ ok: true })
    renderBrowser()

    await waitFor(() => expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull())
    await openResourceMenu('report.md')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Move to…' }))

    const dialog = await screen.findByRole('dialog', { name: 'Move file report.md' })
    const destination = await within(dialog).findByRole('button', { name: 'archive' })
    expect(destination.classList.contains('cu-gfs-move-dialog__tree-select')).toBe(true)
    fireEvent.click(destination)
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move here (archive)' }))

    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        '/api/v1/gfs/resources/id-2',
        { drive: 'main', newParentId: 'id-1', ifMatch: 0 },
        { drive: 'main' }
      )
    )
    await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
  })

  it('seeds the Move-dialog ladder with the names the destination already holds', async () => {
    // RP-003 residual: the destination is a NESTED folder, so the browser's
    // children cache never saw it — the Move dialog is the only surface that
    // knows the names it holds. Without that seed the ladder starts blind,
    // burns all three attempts on name, name (1) and name (2) and reports
    // "The destination changed" while name (3) is free.
    const projects = child('Projects', 'directory', 1)
    const source = child('name', 'file', 2)
    const archive = child('Archive', 'directory', 3)
    mockApiGet.mockImplementation(async (path: string) => {
      if (path === '/api/v1/gfs/tree') {
        return {
          rootResourceId: '11111111-1111-1111-1111-111111111111',
          items: [projects, source],
          nextCursor: null,
        }
      }
      if (path === '/api/v1/gfs/resources/id-1/children') {
        return { items: [archive], nextCursor: null }
      }
      if (path === '/api/v1/gfs/resources/id-3/children') {
        return {
          items: [
            child('name', 'file', 4),
            child('name (1)', 'file', 5),
            child('name (2)', 'file', 6),
          ],
          nextCursor: null,
        }
      }
      return { items: [], nextCursor: null }
    })
    const actualApi = await vi.importActual<typeof import('@lib/api')>('@lib/api')
    const conflict = () => {
      const text = JSON.stringify({
        error: { code: 'already_exists', message: 'a resource with this name already exists' },
      })
      return actualApi.formatApiError(
        new Response(text, { status: 409, statusText: 'Conflict' }),
        text
      )
    }
    // The destination holds name, name (1) and name (2); name (3) is free.
    mockApiSend.mockImplementation(async (_method: string, _path: string, body: unknown) => {
      const requested = (body as { newName?: string } | undefined)?.newName ?? 'name'
      if (requested !== 'name (3)') throw conflict()
      return { ok: true, data: { resourceId: 'id-2', version: 1 } }
    })
    renderBrowser()

    await waitFor(() => expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull())
    // The destination is NOT part of the visible listing: the browser's
    // children cache is cold for it.
    const list = screen.getByRole('list', { name: 'Current folder resources' })
    expect(within(list).queryByText('Archive')).toBeNull()

    await openResourceMenu('name')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Move to…' }))
    const dialog = await screen.findByRole('dialog', { name: 'Move file name' })
    // Walk the dialog tree down to the nested destination.
    fireEvent.click(await within(dialog).findByRole('button', { name: 'Projects' }))
    fireEvent.click(await within(dialog).findByRole('button', { name: 'Archive' }))
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move here (Archive)' }))

    await waitFor(() => expect(mockApiSend).toHaveBeenCalledTimes(2))
    expect(mockApiSend).toHaveBeenNthCalledWith(
      1,
      'PATCH',
      '/api/v1/gfs/resources/id-2',
      { drive: 'main', newParentId: 'id-3', ifMatch: 0 },
      { drive: 'main' }
    )
    expect(mockApiSend).toHaveBeenNthCalledWith(
      2,
      'PATCH',
      '/api/v1/gfs/resources/id-2',
      { drive: 'main', newParentId: 'id-3', ifMatch: 0, newName: 'name (3)' },
      { drive: 'main' }
    )
    expect(await screen.findByText('Moved "name" to "Archive" as "name (3)".')).toBeTruthy()
  })

  it('retries a conflicting move with numbered names until the destination accepts it', async () => {
    const actualApi = await vi.importActual<typeof import('@lib/api')>('@lib/api')
    const folder = child('archive', 'directory', 1)
    const file = child('report.md', 'file', 2)
    mockApiGet.mockImplementation(async (path: string) => {
      if (
        path === '/api/v1/gfs/tree' ||
        path === '/api/v1/gfs/resources/11111111-1111-1111-1111-111111111111/children'
      ) {
        return {
          rootResourceId: '11111111-1111-1111-1111-111111111111',
          items: [folder, file],
          nextCursor: null,
        }
      }
      return { items: [], nextCursor: null }
    })
    const conflict = () => {
      const text = JSON.stringify({
        error: { code: 'already_exists', message: 'a resource with this name already exists' },
      })
      return actualApi.formatApiError(
        new Response(text, { status: 409, statusText: 'Conflict' }),
        text
      )
    }
    mockApiSend
      .mockRejectedValueOnce(conflict())
      .mockRejectedValueOnce(conflict())
      .mockResolvedValueOnce({
        version: 1,
      })
    renderBrowser()

    await waitFor(() => expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull())
    await openResourceMenu('report.md')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Move to…' }))
    const dialog = await screen.findByRole('dialog', { name: 'Move file report.md' })
    fireEvent.click(await within(dialog).findByRole('button', { name: 'archive' }))
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move here (archive)' }))

    await waitFor(() => expect(mockApiSend).toHaveBeenCalledTimes(3))
    expect(mockApiSend).toHaveBeenNthCalledWith(
      1,
      'PATCH',
      '/api/v1/gfs/resources/id-2',
      { drive: 'main', newParentId: 'id-1', ifMatch: 0 },
      { drive: 'main' }
    )
    expect(mockApiSend).toHaveBeenNthCalledWith(
      2,
      'PATCH',
      '/api/v1/gfs/resources/id-2',
      { drive: 'main', newParentId: 'id-1', ifMatch: 0, newName: 'report (1).md' },
      { drive: 'main' }
    )
    expect(mockApiSend).toHaveBeenNthCalledWith(
      3,
      'PATCH',
      '/api/v1/gfs/resources/id-2',
      { drive: 'main', newParentId: 'id-1', ifMatch: 0, newName: 'report (2).md' },
      { drive: 'main' }
    )
    expect(
      await screen.findByText('Moved "report.md" to "archive" as "report (2).md".')
    ).toBeTruthy()
    await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
  })

  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: 'EvenDrive 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: 'EvenDrive 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({
      rootResourceId: rootId,
      items: [],
      nextCursor: null,
    })
    renderBrowser()
    await screen.findByText('No resources are visible in this folder.')
    const oversized = new File(['small fixture'], 'oversized.md', { type: 'text/markdown' })
    Object.defineProperty(oversized, 'size', { value: GFS_FILE_UPLOAD_PROTOCOL_MAX_BYTES + 1 })
    const arrayBuffer = vi.spyOn(oversized, 'arrayBuffer')

    const browser = screen.getByRole('region', { name: 'EvenDrive browser' })
    fireEvent.drop(browser.querySelector('.cu-gfs-card')!, {
      dataTransfer: { dropEffect: 'none', files: [oversized], types: ['Files'] },
    })

    expect(
      await screen.findByText('GFS uploads cannot exceed the 1 GiB Upload v2 protocol maximum.')
    ).toBeTruthy()
    expect(arrayBuffer).not.toHaveBeenCalled()
    expect(mockApiSend).not.toHaveBeenCalled()
  })

  it('shortens oversized rename names before operator patches a resource', async () => {
    const rawRename = `operator-rename-${'very-long-'.repeat(32)}report.txt`
    const renamed = await normalizeGfsResourceName(rawRename)
    mockApiGet.mockResolvedValueOnce({
      items: [child('report.txt', 'file', 2)],
      nextCursor: null,
    })
    mockApiGet.mockResolvedValueOnce({ items: [child(renamed, 'file', 2)], nextCursor: null })
    mockApiSend.mockResolvedValueOnce({ ok: true })
    renderBrowser()

    const currentResources = await screen.findByRole('list', { name: 'Current folder resources' })
    const reportRow = within(currentResources).getByText('report.txt').closest('li')
    expect(reportRow).toBeTruthy()
    await openResourceMenu('report.txt')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }))
    const renameDialog = await screen.findByRole('dialog', { name: 'Rename file' })
    expect(within(renameDialog).getByLabelText('New name')).toHaveValue('report.txt')
    expect(within(reportRow!).queryByRole('form', { name: 'Rename resource' })).toBeNull()
    fireEvent.change(within(renameDialog).getByLabelText('New name'), {
      target: { value: rawRename },
    })
    fireEvent.click(within(renameDialog).getByRole('button', { name: 'Rename' }))

    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        '/api/v1/gfs/resources/id-2',
        { drive: 'main', newName: renamed, ifMatch: 0 },
        { drive: 'main' }
      )
    )
  })

  it('keeps a directory rename draft open on failure and discards it on cancel', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('archive', 'directory', 1)],
      nextCursor: null,
    })
    mockApiSend.mockRejectedValueOnce(new Error('stale resource version'))
    renderBrowser()

    await openResourceMenu('archive')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }))
    const renameDialog = await screen.findByRole('dialog', { name: 'Rename folder' })
    fireEvent.change(within(renameDialog).getByLabelText('New name'), {
      target: { value: 'renamed-archive' },
    })
    fireEvent.click(within(renameDialog).getByRole('button', { name: 'Rename' }))

    expect(await within(renameDialog).findByRole('alert')).toHaveTextContent(
      'stale resource version'
    )
    expect(within(renameDialog).getByLabelText('New name')).toHaveValue('renamed-archive')
    fireEvent.click(within(renameDialog).getByRole('button', { name: 'Cancel' }))
    expect(screen.queryByRole('dialog', { name: 'Rename folder' })).toBeNull()

    await openResourceMenu('archive')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }))
    expect(await screen.findByLabelText('New name')).toHaveValue('archive')
  })

  it('carries the server version through consecutive renames', async () => {
    const first = child('report.txt', 'file', 1, 7)
    const second = { ...first, name: 'report-renamed.txt', version: 8 }
    const third = { ...second, name: 'report-final.txt', version: 9 }
    mockApiGet
      .mockResolvedValueOnce({ items: [first], nextCursor: null })
      .mockResolvedValueOnce({ items: [second], nextCursor: null })
      .mockResolvedValueOnce({ items: [third], nextCursor: null })
    mockApiSend
      .mockResolvedValueOnce({ ok: true, data: { resourceId: 'id-1', version: 8 } })
      .mockResolvedValueOnce({ ok: true, data: { resourceId: 'id-1', version: 9 } })
    renderBrowser()

    await screen.findByText('report.txt')
    await openResourceMenu('report.txt')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }))
    let renameDialog = await screen.findByRole('dialog', { name: 'Rename file' })
    fireEvent.change(within(renameDialog).getByLabelText('New name'), {
      target: { value: 'report-renamed.txt' },
    })
    fireEvent.click(within(renameDialog).getByRole('button', { name: 'Rename' }))

    await screen.findByText('report-renamed.txt')
    expect(mockApiSend).toHaveBeenNthCalledWith(
      1,
      'PATCH',
      '/api/v1/gfs/resources/id-1',
      { drive: 'main', newName: 'report-renamed.txt', ifMatch: 7 },
      { drive: 'main' }
    )
    await openResourceMenu('report-renamed.txt')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }))
    renameDialog = await screen.findByRole('dialog', { name: 'Rename file' })
    fireEvent.change(within(renameDialog).getByLabelText('New name'), {
      target: { value: 'report-final.txt' },
    })
    fireEvent.click(within(renameDialog).getByRole('button', { name: 'Rename' }))

    await waitFor(() => expect(screen.getByText('report-final.txt')).toBeTruthy())
    expect(mockApiSend).toHaveBeenNthCalledWith(
      2,
      'PATCH',
      '/api/v1/gfs/resources/id-1',
      { drive: 'main', newName: 'report-final.txt', ifMatch: 8 },
      { drive: 'main' }
    )
  })

  it('keeps the share dialog focused on sharing without resource actions', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('report.txt', 'file', 2)],
      nextCursor: null,
    })
    renderBrowser()

    await openManage('report.txt')
    const manageDialog = await screen.findByRole('dialog', { name: 'Share file report.txt' })
    expect(within(manageDialog).getByRole('heading', { name: 'Share “report.txt”' })).toBeTruthy()
    expect(
      within(manageDialog).queryByRole('button', { name: 'Actions for report.txt' })
    ).toBeNull()
    expect(within(manageDialog).queryByRole('menu')).toBeNull()
  })

  it('downloads a file through the operator content proxy using rid + name', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('report.md', 'file', 2)],
      nextCursor: null,
    })
    mockGfsDownload.mockResolvedValueOnce(undefined)
    renderBrowser()

    const currentResources = await screen.findByRole('list', { name: 'Current folder resources' })
    const reportRow = within(currentResources).getByText('report.md').closest('li')
    expect(reportRow).toBeTruthy()
    await openResourceMenu('report.md')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Download' }))

    await waitFor(() => expect(mockGfsDownload).toHaveBeenCalledWith('r2', 'report.md'))
  })

  it('converges every resource action into one row menu trigger', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('report.md', 'file', 2)],
      nextCursor: null,
    })
    renderBrowser()

    const currentResources = await screen.findByRole('list', { name: 'Current folder resources' })
    const reportRow = within(currentResources).getByText('report.md').closest('li')
    expect(reportRow).toBeTruthy()
    expect(
      Array.from(reportRow!.querySelectorAll('.cu-gfs-list__actions button')).map(button =>
        button.getAttribute('aria-label')
      )
    ).toEqual(['Actions for report.md'])
    const actionsCell = reportRow!.querySelector('.cu-gfs-list__actions')
    expect(actionsCell).not.toBeNull()
    expect(actionsCell).not.toHaveAttribute('tabindex')
    fireEvent.click(actionsCell!)
    expect(screen.getByRole('menuitem', { name: 'Share' })).toBeVisible()
    expect(screen.getByRole('menuitem', { name: 'Download' })).toBeVisible()
    expect(screen.getByRole('menuitem', { name: 'Rename' })).toBeVisible()
    expect(screen.getByRole('menuitem', { name: 'Move to…' })).toBeVisible()
    expect(screen.getByRole('menuitem', { name: 'Delete' })).toBeVisible()
  })

  it('uses one action trigger on both folder and file rows', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('archive', 'directory', 1), child('report.md', 'file', 2)],
      nextCursor: null,
    })
    renderBrowser()

    const currentResources = await screen.findByRole('list', { name: 'Current folder resources' })
    const folderRow = within(currentResources).getByText('archive').closest('li')
    const fileRow = within(currentResources).getByText('report.md').closest('li')
    expect(folderRow).not.toBeNull()
    expect(fileRow).not.toBeNull()

    expect(within(folderRow!).getAllByRole('button')).toHaveLength(2)
    expect(within(folderRow!).getByRole('button', { name: 'Actions for archive' })).toBeTruthy()
    expect(within(folderRow!).queryByRole('button', { name: 'Download archive' })).toBeNull()

    expect(within(fileRow!).getByRole('button', { name: 'Actions for report.md' })).toBeTruthy()
    expect(within(fileRow!).queryByRole('button', { name: 'Share report.md' })).toBeNull()
  })

  it('surfaces download failures through the toast stack', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('report.md', 'file', 2)],
      nextCursor: null,
    })
    mockGfsDownload.mockRejectedValueOnce(new Error('download unavailable'))
    renderBrowser()

    await openResourceMenu('report.md')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Download' }))

    expect(await screen.findByRole('status')).toHaveTextContent('download unavailable')
  })

  it('previews supported image files from the file name and resource menu', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('avatar.PNG', 'file', 2), child('notes.bin', 'file', 3)],
      nextCursor: null,
    })
    mockGfsFetchFileBlob.mockResolvedValue(new Blob(['image bytes']))
    renderBrowser()

    const previewTrigger = await screen.findByRole('button', { name: 'avatar.PNG' })
    expect(screen.getByText('notes.bin').closest('button')).toBeNull()
    expect(mockGfsFetchFileBlob).not.toHaveBeenCalled()
    fireEvent.click(previewTrigger)

    const dialog = await screen.findByRole('dialog', { name: 'avatar.PNG' })
    const copyButton = within(dialog).getByRole('button', { name: /Copy image to clipboard/i })
    expect(copyButton.querySelector('svg')?.getAttribute('viewBox')).toBe('0 0 24 24')
    expect(copyButton.querySelector('path')?.getAttribute('d')).toBe('M0 0h24v24H0z')
    expect(
      await within(dialog).findByRole('img', { name: 'Preview of avatar.PNG' })
    ).toHaveAttribute('src', 'blob:gfs-image-preview')
    expect(mockGfsFetchFileBlob).toHaveBeenCalledWith('r2')
    // Preview modal wraps the fetched blob with the original MIME type so
    // the dialog <img> loads as that media type.
    const previewCall = mockCreateObjectUrl.mock.calls.find(
      call => (call[0] as Blob).type === 'image/png'
    )
    expect(previewCall?.[0]).toBeDefined()

    const closeButton = within(dialog).getByRole('button', { name: /close image preview/i })
    fireEvent.click(closeButton)
    await waitFor(() => expect(screen.queryByRole('dialog', { name: 'avatar.PNG' })).toBeNull())
    expect(mockRevokeObjectUrl).toHaveBeenCalledWith('blob:gfs-image-preview')

    await openResourceMenu('avatar.PNG')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Preview' }))
    expect(await screen.findByRole('dialog', { name: 'avatar.PNG' })).toBeTruthy()
    fireEvent.keyDown(window, { key: 'Escape' })
    await waitFor(() => expect(screen.queryByRole('dialog', { name: 'avatar.PNG' })).toBeNull())

    await openResourceMenu('notes.bin')
    expect(screen.queryByRole('menuitem', { name: 'Preview' })).toBeNull()
  })

  it('surfaces image preview loading failures inside the modal', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('diagram.svg', 'file', 4)],
      nextCursor: null,
    })
    // Both the row thumbnail and the preview modal hit gfsFetchFileBlob
    // for the same file; reject both so the preview can show its error.
    mockGfsFetchFileBlob.mockRejectedValue(new Error('preview unavailable'))
    renderBrowser()

    fireEvent.click(await screen.findByRole('button', { name: 'diagram.svg' }))
    const dialog = await screen.findByRole('dialog', { name: 'diagram.svg' })
    expect(await within(dialog).findByRole('alert')).toHaveTextContent('preview unavailable')
  })

  it('rejects oversized image previews before downloading them', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [{ ...child('oversized.png', 'file', 4), bytes: GFS_IMAGE_PREVIEW_MAX_BYTES + 1 }],
      nextCursor: null,
    })
    renderBrowser()

    fireEvent.click(await screen.findByRole('button', { name: 'oversized.png' }))
    const dialog = await screen.findByRole('dialog', { name: 'oversized.png' })
    expect(await within(dialog).findByRole('alert')).toHaveTextContent(
      'Image previews are limited to 10 MB.'
    )
    expect(mockGfsFetchFileBlob).not.toHaveBeenCalled()
  })

  it('copies markdown source to the clipboard via the preview header button', async () => {
    const writeText = vi.fn(async () => undefined)
    Object.defineProperty(navigator, 'clipboard', {
      configurable: true,
      value: { ...navigator.clipboard, writeText },
    })

    mockApiGet.mockResolvedValueOnce({
      items: [child('README.md', 'file', 9)],
      nextCursor: null,
    })
    mockGfsFetchFileBlob.mockResolvedValueOnce(
      new Blob(['# Hello\n\nGreetings.'], { type: 'text/markdown' })
    )

    renderBrowser()
    fireEvent.click(await screen.findByRole('button', { name: 'README.md' }))
    const dialog = await screen.findByRole('dialog', { name: 'README.md' })

    const copyButton = within(dialog).getByRole('button', {
      name: /Copy preview contents to clipboard/i,
    })
    expect(copyButton.querySelector('svg')?.getAttribute('viewBox')).toBe('0 0 24 24')
    expect(copyButton.querySelector('path')?.getAttribute('d')).toBe('M0 0h24v24H0z')
    fireEvent.click(copyButton)

    await waitFor(() => expect(writeText).toHaveBeenCalledWith('# Hello\n\nGreetings.'))
  })

  it('renders a .txt file as plain text inside the preview dialog', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('notes.txt', 'file', 11)],
      nextCursor: null,
    })
    mockGfsFetchFileBlob.mockResolvedValueOnce(
      new Blob(['line one\nline two\twith tab'], { type: 'text/plain' })
    )

    renderBrowser()
    fireEvent.click(await screen.findByRole('button', { name: 'notes.txt' }))

    const dialog = await screen.findByRole('dialog', { name: 'notes.txt' })
    const pre = await within(dialog).findByText(/line one/)
    expect(pre.tagName).toBe('PRE')
    expect(pre.textContent).toContain('line two\twith tab')
  })

  it('previews supported video files in a closable HTML5 video dialog', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('demo.mp4', 'file', 7)],
      nextCursor: null,
    })
    mockGfsFetchFileBlob.mockResolvedValueOnce(new Blob(['fake-video-bytes']))
    renderBrowser()

    const previewTrigger = await screen.findByRole('button', { name: 'demo.mp4' })
    fireEvent.click(previewTrigger)

    const dialog = await screen.findByRole('dialog', { name: 'demo.mp4' })
    const video = await within(dialog).findByLabelText('Video preview of demo.mp4')
    expect(video.tagName).toBe('VIDEO')
    expect(video).toHaveAttribute('controls', '')
    expect(video).toHaveAttribute('src', 'blob:gfs-image-preview')
    expect((mockCreateObjectUrl.mock.calls[0]?.[0] as Blob).type).toBe('video/mp4')

    fireEvent.click(within(dialog).getByRole('button', { name: 'Close video preview' }))
    await waitFor(() => expect(screen.queryByRole('dialog', { name: 'demo.mp4' })).toBeNull())
    expect(mockRevokeObjectUrl).toHaveBeenCalledWith('blob:gfs-image-preview')

    await openResourceMenu('demo.mp4')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Preview' }))
    expect(await screen.findByRole('dialog', { name: 'demo.mp4' })).toBeTruthy()
  })

  it('previews Markdown files with safe vanilla rendering', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('README.md', 'file', 5)],
      nextCursor: null,
    })
    mockGfsFetchFileBlob.mockResolvedValueOnce(
      new Blob([
        '# Project guide\n\nUse **safe rendering**.\n\n- First\n- Second\n\n[Unsafe](javascript:alert)\n\n<script>alert("no")</script>',
      ])
    )
    renderBrowser()

    fireEvent.click(await screen.findByRole('button', { name: 'README.md' }))

    const dialog = await screen.findByRole('dialog', { name: 'README.md' })
    expect(
      await within(dialog).findByRole('heading', { name: 'Project guide', level: 1 })
    ).toBeTruthy()
    expect(within(dialog).getByText('safe rendering').tagName).toBe('STRONG')
    expect(within(dialog).getAllByRole('listitem')).toHaveLength(2)
    expect(within(dialog).getByText('Unsafe').closest('a')).toBeNull()
    expect(dialog.querySelector('script')).toBeNull()
    expect(mockGfsFetchFileBlob).toHaveBeenCalledWith('r5')

    fireEvent.click(within(dialog).getByRole('button', { name: /^close preview$/i }))
    await waitFor(() => expect(screen.queryByRole('dialog', { name: 'README.md' })).toBeNull())

    await openResourceMenu('README.md')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Preview' }))
    expect(await screen.findByRole('dialog', { name: 'README.md' })).toBeTruthy()
  })

  it('rejects oversized Markdown previews before downloading them', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [{ ...child('oversized.md', 'file', 5), bytes: GFS_MARKDOWN_PREVIEW_MAX_BYTES + 1 }],
      nextCursor: null,
    })
    renderBrowser()

    fireEvent.click(await screen.findByRole('button', { name: 'oversized.md' }))
    const dialog = await screen.findByRole('dialog', { name: 'oversized.md' })
    expect(await within(dialog).findByRole('alert')).toHaveTextContent(
      'Markdown previews are limited to 2 MB.'
    )
    expect(mockGfsFetchFileBlob).not.toHaveBeenCalled()
  })

  it('opens folders from their name and replaces files from the resource menu', async () => {
    mockApiGet
      .mockResolvedValueOnce({
        items: [child('org', 'directory', 1), child('report.md', 'file', 2)],
        nextCursor: null,
      })
      // The 'org' folder prefetch resolves with an empty children page
      // so the cache holds something realistic.
      .mockResolvedValueOnce({ items: [], nextCursor: null })
      // Entering org serves that cache and revalidates in the background.
      .mockResolvedValueOnce({ items: [], nextCursor: null })
      // Navigate back: re-fetch the root listing.
      .mockResolvedValueOnce({
        items: [child('org', 'directory', 1), child('report.md', 'file', 2)],
        nextCursor: null,
      })
    mockApiSend.mockResolvedValueOnce({ ok: true })
    renderBrowser()

    await openResourceMenu('org')
    expect(screen.queryByRole('menuitem', { name: 'Open folder' })).toBeNull()
    fireEvent.click(screen.getByRole('button', { name: 'org' }))
    await waitFor(() =>
      expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resources/id-1/children', {
        drive: 'main',
      })
    )

    const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })
    fireEvent.click(within(breadcrumb).getAllByRole('button')[0])
    await screen.findByText('report.md')
    await openResourceMenu('report.md')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Replace file' }))
    fireEvent.change(screen.getByLabelText('Replace report.md'), {
      target: { files: [new File(['replacement'], 'report.md', { type: 'text/markdown' })] },
    })

    await waitFor(() =>
      expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(
        expect.objectContaining({
          name: 'report.md',
          target: { operation: 'replace', resourceRid: 'r2', ifMatch: 0 },
        })
      )
    )
  })

  it('shows the ⋯ menu only on the active breadcrumb folder and opens pasted EvenDrive links', async () => {
    const orgFolder = child('org', 'directory', 1)
    const nestedFolder = child('nested', 'directory', 3)
    const linkedView = resolvedFolderView(
      '99999999-9999-9999-9999-999999999999',
      'nested',
      '/nested',
      4
    )
    mockApiGet.mockImplementation(async (path: string) => {
      if (path === '/api/v1/gfs/tree') {
        return { items: [orgFolder], nextCursor: null }
      }
      if (path === '/api/v1/gfs/resources/id-1/children') {
        return { items: [nestedFolder], nextCursor: null }
      }
      if (path === '/api/v1/gfs/resolve') {
        return linkedView
      }
      return { items: [], nextCursor: null }
    })
    renderBrowser()

    fireEvent.click(await screen.findByRole('button', { name: 'org' }))
    await screen.findByText('nested')

    const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })
    // Only the ACTIVE folder (org) carries a menu. The synthetic drive root
    // and non-active segments — and the nested ROW, which lives in the listing
    // rather than the breadcrumb — do not render breadcrumb menus.
    expect(within(breadcrumb).queryByRole('button', { name: 'Actions for main' })).toBeNull()
    expect(within(breadcrumb).queryByRole('button', { name: 'Actions for nested' })).toBeNull()
    const activeTrigger = within(breadcrumb).getByRole('button', { name: 'Actions for org' })
    // The menu sits to the RIGHT of the active folder's name: its wrapper is
    // the breadcrumb label button's next sibling within the segment.
    const activeWrapper = activeTrigger.closest('.cu-gfs-resource-menu')
    expect(activeWrapper?.previousElementSibling).toBe(
      within(breadcrumb).getByRole('button', { name: 'org' })
    )

    // The active folder menu lists the same options as that folder's row menu
    // in its parent view.
    await openResourceMenu('nested')
    const rowOptions = screen.getAllByRole('menuitem').map(item => item.textContent)
    fireEvent.keyDown(document, { key: 'Escape' })
    await openResourceMenu('org')
    expect(screen.getAllByRole('menuitem').map(item => item.textContent)).toEqual(rowOptions)
    expect(rowOptions).toEqual(['Share', 'Open EvenDrive link', 'Rename', 'Move to…', 'Delete'])

    // "Open EvenDrive link" resolves the pasted URI through the real producer
    // contract and preserves its authoritative mutation version.
    fireEvent.click(screen.getByRole('menuitem', { name: 'Open EvenDrive link' }))
    const dialog = await screen.findByRole('dialog', { name: 'Open EvenDrive link' })
    fireEvent.change(within(dialog).getByLabelText('EvenDrive link'), {
      target: { value: linkedView.gfsUri },
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Open' }))

    await waitFor(() =>
      expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resolve', { uri: linkedView.gfsUri })
    )
    await waitFor(() =>
      expect(within(breadcrumb).getByRole('button', { name: 'nested' })).toBeTruthy()
    )
    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'Actions for nested' }))
    fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }))
    const renameDialog = await screen.findByRole('dialog', { name: 'Rename folder' })
    fireEvent.change(within(renameDialog).getByLabelText('New name'), {
      target: { value: 'linked-renamed' },
    })
    mockApiSend.mockResolvedValueOnce({
      ok: true,
      data: { resourceId: linkedView.resourceId, version: 5 },
    })
    fireEvent.click(within(renameDialog).getByRole('button', { name: 'Rename' }))
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        `/api/v1/gfs/resources/${linkedView.resourceId}`,
        { drive: 'main', newName: 'linked-renamed', ifMatch: 4 },
        { drive: 'main' }
      )
    )
    expect(within(breadcrumb).queryByRole('button', { name: 'Actions for org' })).toBeNull()
    expect(screen.queryByRole('dialog', { name: 'Open EvenDrive link' })).toBeNull()
  })

  it('keeps the current list visible when an EvenDrive link resolves to the same folder', async () => {
    const folder = listedFolder('11111111-1111-1111-1111-111111111111', 'org', '/org', 4)
    const childFile = child('nested.txt', 'file', 2)
    mockApiGet.mockImplementation(async (path: string) => {
      if (path === '/api/v1/gfs/tree') return { items: [folder], nextCursor: null }
      if (path === `/api/v1/gfs/resources/${folder.resourceId}/children`) {
        return { items: [childFile], nextCursor: null }
      }
      if (path === '/api/v1/gfs/resolve') {
        return resolvedFolderView(folder.resourceId, folder.name, folder.path!, folder.version)
      }
      return { items: [], nextCursor: null }
    })

    renderBrowser()
    fireEvent.click(await screen.findByRole('button', { name: 'org' }))
    await screen.findByText('nested.txt')
    const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })
    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'Actions for org' }))
    fireEvent.click(screen.getByRole('menuitem', { name: 'Open EvenDrive link' }))
    const dialog = await screen.findByRole('dialog', { name: 'Open EvenDrive link' })
    fireEvent.change(within(dialog).getByLabelText('EvenDrive link'), {
      target: { value: folder.gfsUri },
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Open' }))

    await waitFor(() =>
      expect(
        mockApiGet.mock.calls.filter(
          ([path]) => path === `/api/v1/gfs/resources/${folder.resourceId}/children`
        ).length
      ).toBeGreaterThan(1)
    )
    await waitFor(() => expect(screen.getByText('nested.txt')).toBeVisible())
    expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull()
  })

  // R5-M1: moving the folder the breadcrumb is INSIDE changes its ancestry, so
  // patching the moved crumb in place would leave the trail pointing at the
  // old location. The trail must be rebuilt from the folder's new location.
  it('rebuilds the breadcrumb trail after moving the open folder to another parent', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const folder = listedFolder('55555555-5555-5555-5555-555555555555', 'org', '/org', 7)
    const archive = listedFolder('66666666-6666-6666-6666-666666666666', 'archive', '/archive', 5)
    const resolveView = (resourceId: string, name: string, path: string, version: number) =>
      resolvedFolderView(resourceId, name, path, version)
    mockApiGet.mockImplementation(async (path: string) => {
      if (path === '/api/v1/gfs/tree' || path === `/api/v1/gfs/resources/${rootId}/children`) {
        return { rootResourceId: rootId, items: [folder, archive], nextCursor: null }
      }
      if (path === '/api/v1/gfs/resolve') {
        return resolveView(folder.resourceId, folder.name, '/archive/org', 8)
      }
      if (path === '/api/v1/gfs/by-path') {
        return resolveView(archive.resourceId, archive.name, '/archive', 10)
      }
      return { items: [], nextCursor: null }
    })
    mockGetGfsResourceByPath.mockReset()
    mockGetGfsResourceByPath.mockImplementation(async (_drive: string, path: string) =>
      resolveView(archive.resourceId, archive.name, path, 10)
    )
    mockApiSend
      .mockResolvedValueOnce({
        ok: true,
        data: { resourceId: folder.resourceId, version: 8 },
      })
      .mockResolvedValueOnce({
        ok: true,
        data: { resourceId: folder.resourceId, version: 9 },
      })
      .mockResolvedValueOnce({
        ok: true,
        data: { resourceId: archive.resourceId, version: 11 },
      })
    renderBrowser()

    await waitFor(() =>
      expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/tree', { drive: 'main' })
    )
    // Open /org by navigation, so its crumb carries the listed version (7).
    fireEvent.click(await screen.findByRole('button', { name: 'org' }))
    await screen.findByText('No resources are visible in this folder.')

    const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })
    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'Actions for org' }))
    fireEvent.click(screen.getByRole('menuitem', { name: 'Move to…' }))
    const moveDialog = await screen.findByRole('dialog', { name: 'Move folder org' })
    fireEvent.click(await within(moveDialog).findByRole('button', { name: 'archive' }))
    fireEvent.click(within(moveDialog).getByRole('button', { name: 'Move here (archive)' }))

    // The move runs with the pre-move version from the listing.
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenNthCalledWith(
        1,
        'PATCH',
        `/api/v1/gfs/resources/${folder.resourceId}`,
        { drive: 'main', newParentId: archive.resourceId, ifMatch: 7 },
        { drive: 'main' }
      )
    )
    // The trail is rebuilt from the folder's new location: the moved folder
    // resolves at /archive/org, and each ancestor prefix resolves by-path.
    await waitFor(() =>
      expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resolve', { uri: folder.gfsUri })
    )
    await waitFor(() => expect(mockGetGfsResourceByPath).toHaveBeenCalledWith('main', '/archive'))
    await waitFor(() => {
      const labels = within(breadcrumb)
        .getAllByRole('button')
        .map(button => button.getAttribute('aria-label') ?? button.textContent)
      expect(labels).toEqual(['main', 'archive', 'org', 'Actions for org'])
    })

    // The rebuilt active crumb kept the move receipt's version: a follow-up
    // breadcrumb rename runs with the post-move version, not the pre-move one.
    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'Actions for org' }))
    fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }))
    const renameDialog = await screen.findByRole('dialog', { name: 'Rename folder' })
    fireEvent.change(within(renameDialog).getByLabelText('New name'), {
      target: { value: 'org-renamed' },
    })
    fireEvent.click(within(renameDialog).getByRole('button', { name: 'Rename' }))

    await waitFor(() =>
      expect(mockApiSend).toHaveBeenNthCalledWith(
        2,
        'PATCH',
        `/api/v1/gfs/resources/${folder.resourceId}`,
        { drive: 'main', newName: 'org-renamed', ifMatch: 8 },
        { drive: 'main' }
      )
    )
    await waitFor(() =>
      expect(within(breadcrumb).getByRole('button', { name: 'org-renamed' })).toBeTruthy()
    )

    // The by-path ancestor also retained its producer version and remains
    // actionable when navigated into after move reconstruction.
    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'archive' }))
    await screen.findByText('No resources are visible in this folder.')
    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'Actions for archive' }))
    fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }))
    const archiveRenameDialog = await screen.findByRole('dialog', { name: 'Rename folder' })
    fireEvent.change(within(archiveRenameDialog).getByLabelText('New name'), {
      target: { value: 'archive-renamed' },
    })
    fireEvent.click(within(archiveRenameDialog).getByRole('button', { name: 'Rename' }))
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenNthCalledWith(
        3,
        'PATCH',
        `/api/v1/gfs/resources/${archive.resourceId}`,
        { drive: 'main', newName: 'archive-renamed', ifMatch: 10 },
        { drive: 'main' }
      )
    )
  })

  // Defensive fallback: an incomplete runtime response remains browseable but
  // cannot enable mutation actions with a fabricated version.
  it('keeps breadcrumb mutations disabled when a link resolve omits its version', async () => {
    const orgFolder = child('org', 'directory', 1)
    // Deliberately incomplete response to preserve the fail-closed boundary.
    const linkedView = {
      resourceId: 'id-9',
      rid: 'r9',
      gfsUri: 'gfs://main/r9',
      drive: 'main',
      name: 'nested',
      kind: 'directory',
      path: '/nested',
      updatedAt: '2026-09-24T00:00:00.000Z',
    }
    mockApiGet.mockImplementation(async (path: string) => {
      if (path === '/api/v1/gfs/tree') {
        return { items: [orgFolder], nextCursor: null }
      }
      if (path === '/api/v1/gfs/resolve') {
        return linkedView
      }
      return { items: [], nextCursor: null }
    })
    renderBrowser()

    await openResourceMenu('org')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Open EvenDrive link' }))
    const dialog = await screen.findByRole('dialog', { name: 'Open EvenDrive link' })
    fireEvent.change(within(dialog).getByLabelText('EvenDrive link'), {
      target: { value: 'gfs://main/r9' },
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Open' }))

    await waitFor(() =>
      expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resolve', { uri: 'gfs://main/r9' })
    )
    const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })
    await waitFor(() =>
      expect(within(breadcrumb).getByRole('button', { name: 'nested' })).toBeTruthy()
    )
    // Browsing the linked folder still works…
    await waitFor(() =>
      expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resources/id-9/children', {
        drive: 'main',
      })
    )
    // …but without a response version, the active crumb has no mutating menu
    // and no request is issued against an invented ifMatch.
    expect(within(breadcrumb).queryByRole('button', { name: 'Actions for nested' })).toBeNull()
    expect(within(breadcrumb).queryByRole('button', { name: 'Actions for org' })).toBeNull()
    expect(mockApiSend).not.toHaveBeenCalled()
  })

  // R5-M1 failure path (leaf resolve fails): after a successful Move PATCH,
  // the breadcrumb must NOT be replaced by a shortened trail presented as
  // authoritative. The stale trail stays on screen, a visible notice says
  // the path could not be refreshed, and Retry rebuilds the trail once
  // resolve recovers.
  it('keeps the stale trail with a retry notice when the post-move resolve fails', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const work = child('work', 'directory', 1, 3)
    const org = child('org', 'directory', 2, 7)
    const archive = child('archive', 'directory', 3, 5)
    const resolveView = (resourceId: string, rid: string, name: string, path: string) => ({
      resourceId,
      rid,
      gfsUri: `gfs://main/${rid}`,
      drive: 'main',
      name,
      kind: 'directory',
      path,
      updatedAt: '2026-09-24T00:00:00.000Z',
    })
    let resolveCalls = 0
    mockApiGet.mockImplementation(async (path: string) => {
      if (path === '/api/v1/gfs/tree' || path === `/api/v1/gfs/resources/${rootId}/children`) {
        return { rootResourceId: rootId, items: [work, archive], nextCursor: null }
      }
      if (path === `/api/v1/gfs/resources/${work.resourceId}/children`) {
        return { items: [org], nextCursor: null }
      }
      if (path === '/api/v1/gfs/resolve') {
        resolveCalls += 1
        if (resolveCalls === 1) throw new Error('resolve unavailable')
        return resolveView(org.resourceId, org.rid, 'org', '/archive/org')
      }
      return { items: [], nextCursor: null }
    })
    mockGetGfsResourceByPath.mockReset()
    mockGetGfsResourceByPath.mockImplementation(async (_drive: string, path: string) =>
      resolveView(archive.resourceId, archive.rid, archive.name, path)
    )
    mockApiSend.mockResolvedValueOnce({
      ok: true,
      data: { resourceId: org.resourceId, version: 8 },
    })
    renderBrowser()

    // Open /work/org so the pre-move trail is deep enough to prove the
    // stale trail is PRESERVED (work stays in it), not truncated.
    fireEvent.click(await screen.findByRole('button', { name: 'work' }))
    fireEvent.click(await screen.findByRole('button', { name: 'org' }))
    await screen.findByText('No resources are visible in this folder.')

    const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })
    const labels = () =>
      within(breadcrumb)
        .getAllByRole('button')
        .map(button => button.getAttribute('aria-label') ?? button.textContent)
    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'Actions for org' }))
    fireEvent.click(screen.getByRole('menuitem', { name: 'Move to…' }))
    const moveDialog = await screen.findByRole('dialog', { name: 'Move folder org' })
    fireEvent.click(await within(moveDialog).findByRole('button', { name: 'archive' }))
    fireEvent.click(within(moveDialog).getByRole('button', { name: 'Move here (archive)' }))

    // The Move PATCH succeeded with the pre-move version.
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        `/api/v1/gfs/resources/${org.resourceId}`,
        { drive: 'main', newParentId: archive.resourceId, ifMatch: 7 },
        { drive: 'main' }
      )
    )

    // Reconstruction failed: the OLD trail is preserved and explicitly
    // labeled — never shortened to main / org as if reconstruction
    // succeeded.
    const notice = await screen.findByRole('alert')
    expect(notice.textContent).toMatch(/folder path could not be refreshed/)
    expect(within(notice).getByRole('button', { name: 'Retry' })).toBeTruthy()
    expect(labels()).toEqual(['main', 'work', 'org', 'Actions for org'])

    // Retry: resolve now answers, the trail rebuilds from the new location,
    // and the notice clears.
    fireEvent.click(within(notice).getByRole('button', { name: 'Retry' }))
    await waitFor(() => expect(labels()).toEqual(['main', 'archive', 'org', 'Actions for org']))
    await waitFor(() => expect(screen.queryByRole('alert')).toBeNull())
  })

  // R5-M1 failure path (ancestor by-path fails): resolve names the new
  // location, but an ancestor by-path lookup fails. Same contract — the
  // stale trail is preserved and labeled, never partially applied, and
  // Retry rebuilds it once by-path recovers.
  it('keeps the stale trail with a retry notice when a post-move ancestor by-path lookup fails', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const work = child('work', 'directory', 1, 3)
    const org = child('org', 'directory', 2, 7)
    const archive = child('archive', 'directory', 3, 5)
    const resolveView = (resourceId: string, rid: string, name: string, path: string) => ({
      resourceId,
      rid,
      gfsUri: `gfs://main/${rid}`,
      drive: 'main',
      name,
      kind: 'directory',
      path,
      updatedAt: '2026-09-24T00:00:00.000Z',
    })
    mockApiGet.mockImplementation(async (path: string) => {
      if (path === '/api/v1/gfs/tree' || path === `/api/v1/gfs/resources/${rootId}/children`) {
        return { rootResourceId: rootId, items: [work, archive], nextCursor: null }
      }
      if (path === `/api/v1/gfs/resources/${work.resourceId}/children`) {
        return { items: [org], nextCursor: null }
      }
      if (path === '/api/v1/gfs/resolve') {
        return resolveView(org.resourceId, org.rid, 'org', '/archive/org')
      }
      return { items: [], nextCursor: null }
    })
    let byPathCalls = 0
    mockGetGfsResourceByPath.mockReset()
    mockGetGfsResourceByPath.mockImplementation(async (_drive: string, path: string) => {
      byPathCalls += 1
      if (byPathCalls === 1) throw new Error('by-path unavailable')
      return resolveView(archive.resourceId, archive.rid, archive.name, path)
    })
    mockApiSend.mockResolvedValueOnce({
      ok: true,
      data: { resourceId: org.resourceId, version: 8 },
    })
    renderBrowser()

    fireEvent.click(await screen.findByRole('button', { name: 'work' }))
    fireEvent.click(await screen.findByRole('button', { name: 'org' }))
    await screen.findByText('No resources are visible in this folder.')

    const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })
    const labels = () =>
      within(breadcrumb)
        .getAllByRole('button')
        .map(button => button.getAttribute('aria-label') ?? button.textContent)
    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'Actions for org' }))
    fireEvent.click(screen.getByRole('menuitem', { name: 'Move to…' }))
    const moveDialog = await screen.findByRole('dialog', { name: 'Move folder org' })
    fireEvent.click(await within(moveDialog).findByRole('button', { name: 'archive' }))
    fireEvent.click(within(moveDialog).getByRole('button', { name: 'Move here (archive)' }))

    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        `/api/v1/gfs/resources/${org.resourceId}`,
        { drive: 'main', newParentId: archive.resourceId, ifMatch: 7 },
        { drive: 'main' }
      )
    )
    // Resolve DID name the new location; only the ancestor lookup failed —
    // still no partial trail.
    await waitFor(() =>
      expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resolve', { uri: org.gfsUri })
    )
    expect(byPathCalls).toBe(1)
    const notice = await screen.findByRole('alert')
    expect(notice.textContent).toMatch(/folder path could not be refreshed/)
    expect(within(notice).getByRole('button', { name: 'Retry' })).toBeTruthy()
    expect(labels()).toEqual(['main', 'work', 'org', 'Actions for org'])

    fireEvent.click(within(notice).getByRole('button', { name: 'Retry' }))
    await waitFor(() => expect(labels()).toEqual(['main', 'archive', 'org', 'Actions for org']))
    await waitFor(() => expect(screen.queryByRole('alert')).toBeNull())
  })

  // R7-M1: the recovery snapshot must carry IDENTITY only. A rename that
  // lands between the failed post-move reconstruction and Retry keeps its
  // newer name/version — Retry rebuilds the ancestry from the server and the
  // crumb metadata from LIVE state, never replaying the move-time snapshot.
  it('retry preserves a rename that landed while move recovery was pending', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const work = child('work', 'directory', 1, 3)
    const org = child('org', 'directory', 2, 7)
    const archive = child('archive', 'directory', 3, 5)
    const resolveView = (resourceId: string, rid: string, name: string, path: string) => ({
      resourceId,
      rid,
      gfsUri: `gfs://main/${rid}`,
      drive: 'main',
      name,
      kind: 'directory',
      path,
      updatedAt: '2026-09-24T00:00:00.000Z',
    })
    let resolveCalls = 0
    mockApiGet.mockImplementation(async (path: string) => {
      if (path === '/api/v1/gfs/tree' || path === `/api/v1/gfs/resources/${rootId}/children`) {
        return { rootResourceId: rootId, items: [work, archive], nextCursor: null }
      }
      if (path === `/api/v1/gfs/resources/${work.resourceId}/children`) {
        return { items: [org], nextCursor: null }
      }
      if (path === '/api/v1/gfs/resolve') {
        resolveCalls += 1
        if (resolveCalls === 1) throw new Error('resolve unavailable')
        // Retry resolves the RENAMED folder at its real new location.
        return resolveView(org.resourceId, org.rid, 'org-renamed', '/archive/org-renamed')
      }
      return { items: [], nextCursor: null }
    })
    mockGetGfsResourceByPath.mockReset()
    mockGetGfsResourceByPath.mockImplementation(async (_drive: string, path: string) =>
      resolveView(archive.resourceId, archive.rid, archive.name, path)
    )
    mockApiSend
      .mockResolvedValueOnce({
        ok: true,
        data: { resourceId: org.resourceId, version: 8 },
      })
      .mockResolvedValueOnce({
        ok: true,
        data: { resourceId: org.resourceId, version: 9 },
      })
      .mockResolvedValueOnce({
        ok: true,
        data: { resourceId: org.resourceId, version: 10 },
      })
    renderBrowser()

    fireEvent.click(await screen.findByRole('button', { name: 'work' }))
    fireEvent.click(await screen.findByRole('button', { name: 'org' }))
    await screen.findByText('No resources are visible in this folder.')

    const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })
    const labels = () =>
      within(breadcrumb)
        .getAllByRole('button')
        .map(button => button.getAttribute('aria-label') ?? button.textContent)
    // Move /work/org under /archive — the PATCH succeeds (version 7 → 8)…
    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'Actions for org' }))
    fireEvent.click(screen.getByRole('menuitem', { name: 'Move to…' }))
    const moveDialog = await screen.findByRole('dialog', { name: 'Move folder org' })
    fireEvent.click(await within(moveDialog).findByRole('button', { name: 'archive' }))
    fireEvent.click(within(moveDialog).getByRole('button', { name: 'Move here (archive)' }))
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenNthCalledWith(
        1,
        'PATCH',
        `/api/v1/gfs/resources/${org.resourceId}`,
        { drive: 'main', newParentId: archive.resourceId, ifMatch: 7 },
        { drive: 'main' }
      )
    )
    // …but reconstruction fails: stale trail kept, warning + Retry shown.
    const notice = await screen.findByRole('alert')
    expect(within(notice).getByRole('button', { name: 'Retry' })).toBeTruthy()
    expect(labels()).toEqual(['main', 'work', 'org', 'Actions for org'])

    // BEFORE Retry: rename the active crumb. It succeeds and advances the
    // name/version (8 → 9, 'org' → 'org-renamed').
    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'Actions for org' }))
    fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }))
    const renameForm = await screen.findByRole('dialog', { name: 'Rename folder' })
    fireEvent.change(within(renameForm).getByLabelText('New name'), {
      target: { value: 'org-renamed' },
    })
    fireEvent.click(within(renameForm).getByRole('button', { name: 'Rename' }))
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenNthCalledWith(
        2,
        'PATCH',
        `/api/v1/gfs/resources/${org.resourceId}`,
        { drive: 'main', newName: 'org-renamed', ifMatch: 8 },
        { drive: 'main' }
      )
    )
    await waitFor(() =>
      expect(within(breadcrumb).getByRole('button', { name: 'org-renamed' })).toBeTruthy()
    )
    // The notice reads the LIVE crumb name, not a move-time snapshot.
    expect(screen.getByRole('alert').textContent).toContain('org-renamed')

    // Retry now succeeds: the ancestry rebuilds from the server while the
    // crumb keeps the renamed identity and version 9.
    fireEvent.click(within(screen.getByRole('alert')).getByRole('button', { name: 'Retry' }))
    await waitFor(() =>
      expect(labels()).toEqual(['main', 'archive', 'org-renamed', 'Actions for org-renamed'])
    )
    await waitFor(() => expect(screen.queryByRole('alert')).toBeNull())

    // The next breadcrumb mutation uses the LATEST version (9), not the
    // earlier Move version (8) — a stale ifMatch here would 409.
    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'Actions for org-renamed' }))
    fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }))
    const finalRenameForm = await screen.findByRole('dialog', { name: 'Rename folder' })
    fireEvent.change(within(finalRenameForm).getByLabelText('New name'), {
      target: { value: 'org-final' },
    })
    fireEvent.click(within(finalRenameForm).getByRole('button', { name: 'Rename' }))
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenNthCalledWith(
        3,
        'PATCH',
        `/api/v1/gfs/resources/${org.resourceId}`,
        { drive: 'main', newName: 'org-final', ifMatch: 9 },
        { drive: 'main' }
      )
    )
    await waitFor(() =>
      expect(within(breadcrumb).getByRole('button', { name: 'org-final' })).toBeTruthy()
    )
  })

  // R7-M1 (in-flight race): a Retry whose resolve/by-path responses land
  // AFTER a newer Move completed must be discarded whole — the stale response
  // can neither overwrite the newer ancestry nor clear the newer operation's
  // recovery state.
  it('discards a superseded Retry response that lands after a newer Move', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const work = child('work', 'directory', 1, 3)
    const org = child('org', 'directory', 2, 7)
    const archive = child('archive', 'directory', 3, 5)
    const dept = child('dept', 'directory', 4, 6)
    const resolveView = (resourceId: string, rid: string, name: string, path: string) => ({
      resourceId,
      rid,
      gfsUri: `gfs://main/${rid}`,
      drive: 'main',
      name,
      kind: 'directory',
      path,
      updatedAt: '2026-09-24T00:00:00.000Z',
    })
    // resolve call order: 1 = Move A reconstruction (fails), 2 = Retry A
    // (HELD pending), 3 = Move B reconstruction (succeeds → /dept/org).
    let resolveCalls = 0
    let releaseRetryResolve: ((view: unknown) => void) | null = null
    mockApiGet.mockImplementation(async (path: string) => {
      if (path === '/api/v1/gfs/tree' || path === `/api/v1/gfs/resources/${rootId}/children`) {
        return { rootResourceId: rootId, items: [work, archive, dept], nextCursor: null }
      }
      if (path === `/api/v1/gfs/resources/${work.resourceId}/children`) {
        return { items: [org], nextCursor: null }
      }
      if (path === '/api/v1/gfs/resolve') {
        resolveCalls += 1
        if (resolveCalls === 1) throw new Error('resolve unavailable')
        if (resolveCalls === 2) {
          return new Promise<unknown>(resolve => {
            releaseRetryResolve = resolve
          })
        }
        return resolveView(org.resourceId, org.rid, 'org', '/dept/org')
      }
      return { items: [], nextCursor: null }
    })
    mockGetGfsResourceByPath.mockReset()
    mockGetGfsResourceByPath.mockImplementation(async (_drive: string, path: string) => {
      if (path === '/dept') {
        return resolveView(dept.resourceId, dept.rid, dept.name, '/dept')
      }
      // Retry A's ancestor lookup (after its release) answers with the OLD
      // Move A ancestry — exactly the stale data that must be discarded.
      return resolveView(archive.resourceId, archive.rid, archive.name, path)
    })
    mockApiSend
      .mockResolvedValueOnce({
        ok: true,
        data: { resourceId: org.resourceId, version: 8 },
      })
      .mockResolvedValueOnce({
        ok: true,
        data: { resourceId: org.resourceId, version: 9 },
      })
    renderBrowser()

    fireEvent.click(await screen.findByRole('button', { name: 'work' }))
    fireEvent.click(await screen.findByRole('button', { name: 'org' }))
    await screen.findByText('No resources are visible in this folder.')

    const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })
    const labels = () =>
      within(breadcrumb)
        .getAllByRole('button')
        .map(button => button.getAttribute('aria-label') ?? button.textContent)

    // Move A: /work/org → /archive. Succeeds, reconstruction FAILS.
    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'Actions for org' }))
    fireEvent.click(screen.getByRole('menuitem', { name: 'Move to…' }))
    let moveDialog = await screen.findByRole('dialog', { name: 'Move folder org' })
    fireEvent.click(await within(moveDialog).findByRole('button', { name: 'archive' }))
    fireEvent.click(within(moveDialog).getByRole('button', { name: 'Move here (archive)' }))
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenNthCalledWith(
        1,
        'PATCH',
        `/api/v1/gfs/resources/${org.resourceId}`,
        { drive: 'main', newParentId: archive.resourceId, ifMatch: 7 },
        { drive: 'main' }
      )
    )
    const notice = await screen.findByRole('alert')
    expect(within(notice).getByRole('button', { name: 'Retry' })).toBeTruthy()
    expect(labels()).toEqual(['main', 'work', 'org', 'Actions for org'])

    // Start Retry A and HOLD its resolve response pending.
    fireEvent.click(within(notice).getByRole('button', { name: 'Retry' }))
    await waitFor(() => expect(resolveCalls).toBe(2))
    expect(releaseRetryResolve).toBeTruthy()

    // While Retry A is held: Move B moves the same folder under /dept and
    // completes — its reconstruction succeeds and refreshes the trail.
    fireEvent.click(within(breadcrumb).getByRole('button', { name: 'Actions for org' }))
    fireEvent.click(screen.getByRole('menuitem', { name: 'Move to…' }))
    moveDialog = await screen.findByRole('dialog', { name: 'Move folder org' })
    fireEvent.click(await within(moveDialog).findByRole('button', { name: 'dept' }))
    fireEvent.click(within(moveDialog).getByRole('button', { name: 'Move here (dept)' }))
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenNthCalledWith(
        2,
        'PATCH',
        `/api/v1/gfs/resources/${org.resourceId}`,
        { drive: 'main', newParentId: dept.resourceId, ifMatch: 8 },
        { drive: 'main' }
      )
    )
    await waitFor(() => expect(labels()).toEqual(['main', 'dept', 'org', 'Actions for org']))
    // Move B's successful reconstruction retires Move A's stale notice.
    await waitFor(() => expect(screen.queryByRole('alert')).toBeNull())

    // Release Retry A's OLD response (Move A-era /archive ancestry) and let
    // its full walk settle.
    await act(async () => {
      releaseRetryResolve!(resolveView(org.resourceId, org.rid, 'org', '/archive/org'))
      await new Promise(resolve => setTimeout(resolve, 0))
    })

    // The superseded response was discarded: the breadcrumb still reflects
    // Move B's ancestry, and no recovery state was resurrected or cleared.
    expect(labels()).toEqual(['main', 'dept', 'org', 'Actions for org'])
    expect(screen.queryByRole('alert')).toBeNull()
  })

  it('does not fall back to legacy when replacing a persisted resumable session', async () => {
    const lastModified = 1_725_000_000_000
    const uploadId = '66666666-6666-4666-8666-666666666666'
    window.localStorage.setItem(
      'evenfire:gfs-upload-v2:pending',
      JSON.stringify({
        uploadId,
        fileName: 'report.md',
        fileSize: 11,
        lastModified,
        target: { operation: 'replace', resourceRid: 'r2', ifMatch: 0 },
        name: 'report.md',
      })
    )
    mockApiGet.mockResolvedValueOnce({
      items: [child('report.md', 'file', 2)],
      nextCursor: null,
    })
    const capabilityError = new GfsUploadCapabilityError('writer unavailable', {
      allowLegacyFallback: true,
    })
    mockCreateGfsUploadJob.mockImplementationOnce(() => ({
      start: vi.fn().mockRejectedValue(capabilityError),
      snapshot: vi.fn(() => ({ state: 'failed' })),
      pause: vi.fn(),
      resume: vi.fn(),
      cancel: vi.fn(),
    }))
    renderBrowser()

    await openResourceMenu('report.md')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Replace file' }))
    fireEvent.change(screen.getByLabelText('Replace report.md'), {
      target: {
        files: [new File(['resume data'], 'report.md', { lastModified })],
      },
    })

    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('supports roving keyboard focus and Escape in the resource menu', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('report.md', 'file', 2)],
      nextCursor: null,
    })
    renderBrowser()

    await openResourceMenu('report.md')
    const shareItem = screen.getByRole('menuitem', { name: 'Share' })
    await waitFor(() => expect(document.activeElement).toBe(shareItem))
    fireEvent.keyDown(shareItem, { key: 'ArrowDown' })
    expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Preview' }))
    fireEvent.keyDown(document.activeElement!, { key: 'End' })
    expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Delete' }))
    fireEvent.keyDown(document.activeElement!, { key: 'Escape' })
    expect(screen.queryByRole('menu')).toBeNull()
    expect(document.activeElement).toBe(
      screen.getByRole('button', { name: 'Actions for report.md' })
    )
  })

  it('does not render a download button for directories', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('org', 'directory', 1)],
      nextCursor: null,
    })
    renderBrowser()
    await screen.findAllByText(/org/)
    expect(screen.queryByRole('button', { name: /^Download / })).toBeNull()
  })

  it('navigates into a directory and lists its children', async () => {
    mockApiGet
      .mockResolvedValueOnce({ items: [child('org', 'directory', 1)], nextCursor: null })
      // Prefetch returns org's children so the cache is populated.
      .mockResolvedValueOnce({ items: [child('eng', 'directory', 3)], nextCursor: null })
      // Entering org serves the cache and revalidates in the background.
      .mockResolvedValueOnce({ items: [child('eng', 'directory', 3)], nextCursor: null })
      // After the revalidated view renders, the prefetcher reaches for eng's
      // children. Empty page is fine — eng has no folders.
      .mockResolvedValueOnce({ items: [], nextCursor: null })
      // Navigate back: re-fetch the root listing.
      .mockResolvedValueOnce({ items: [child('org', 'directory', 1)], nextCursor: null })
    renderBrowser()
    const orgButton = (await screen.findAllByRole('button', { name: 'org' }))[0]
    fireEvent.click(orgButton)
    await screen.findAllByText(/eng/)
    // The click handler is served from the prefetch cache; the recorded
    // apiGet covers the org children fetch that primed the cache.
    expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resources/id-1/children', {
      drive: 'main',
    })
    // Navigate back to the drive root via the breadcrumb root crumb (Back/Forward were removed).
    const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })
    fireEvent.click(within(breadcrumb).getAllByRole('button')[0])
    await screen.findAllByRole('button', { name: 'org' })
  })

  it('revalidates a prefetched folder in the background when navigating into it', async () => {
    mockApiGet
      .mockResolvedValueOnce({ items: [child('org', 'directory', 1)], nextCursor: null }) // root listing
      .mockResolvedValueOnce({ items: [child('stale.md', 'file', 3)], nextCursor: null }) // prefetch org
      .mockResolvedValueOnce({ items: [child('fresh.md', 'file', 4)], nextCursor: null }) // background revalidation
    renderBrowser()

    fireEvent.click((await screen.findAllByRole('button', { name: 'org' }))[0])
    // The cached page renders instantly — no spinner, stale rows visible…
    await screen.findByText('stale.md')
    expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull()
    // …then the background revalidation replaces them with the server state.
    await waitFor(() => expect(screen.getByText('fresh.md')).toBeTruthy())
    await waitFor(() => expect(screen.queryByText('stale.md')).toBeNull())
    expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resources/id-1/children', {
      drive: 'main',
    })
  })

  it('reflects mutations in the folder cache when returning to a folder', async () => {
    const rootPage = { items: [child('org', 'directory', 1)], nextCursor: null }
    mockApiGet
      .mockResolvedValueOnce(rootPage) // initial root listing
      .mockResolvedValueOnce({ items: [], nextCursor: null }) // prefetch org (empty)
      .mockResolvedValueOnce({ items: [], nextCursor: null }) // background revalidation on entering org
      .mockResolvedValueOnce({ items: [child('report.md', 'file', 3)], nextCursor: null }) // refresh after upload
      .mockResolvedValueOnce(rootPage) // navigate back to the root
      // Re-entering org revalidates in the background against fresh rows.
      .mockResolvedValue({ items: [child('report.md', 'file', 3)], nextCursor: null })
    renderBrowser()

    fireEvent.click((await screen.findAllByRole('button', { name: 'org' }))[0])
    await screen.findByText('No resources are visible in this folder.')

    // Upload into org: the resumable job mock completes → refreshCurrent().
    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(['report'], 'report.md', { type: 'text/markdown' })] },
    })
    fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Upload' }))
    await waitFor(() => expect(screen.getByText('report.md')).toBeTruthy())

    // Navigate back to the root, then into org again: the served cache must
    // hold the post-mutation rows, not the prefetched empty page.
    const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })
    fireEvent.click(within(breadcrumb).getAllByRole('button')[0])
    await screen.findAllByRole('button', { name: 'org' })
    fireEvent.click(screen.getByRole('button', { name: 'org' }))
    await waitFor(() => expect(screen.getByText('report.md')).toBeTruthy())
  })

  it('routes files above the legacy limit through the resumable transport, not contentBase64', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    const rootRid = '11111111111111111111111111111111'
    mockApiGet.mockResolvedValue({ rootResourceId: rootId, items: [], nextCursor: null })
    renderBrowser()
    await screen.findByText('No resources are visible in this folder.')

    // One byte above the legacy raw ceiling: legacy transport must be
    // impossible; the resumable job is the only path. The transport decision
    // reads only `size`, so the fixture overrides it instead of allocating
    // 16 MiB through jsdom's fireEvent serialization.
    const bigFile = new File(['x'], 'big-report.bin')
    Object.defineProperty(bigFile, 'size', { value: 16 * 1024 * 1024 + 1 })
    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: [bigFile] },
    })
    fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Upload' }))

    await waitFor(() =>
      expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(
        expect.objectContaining({
          name: 'big-report.bin',
          target: { operation: 'create', parentRid: rootRid },
        })
      )
    )
    expect(mockApiSend).not.toHaveBeenCalled()
  })

  it('keeps the new-folder modal open after an error and allows a retry', async () => {
    const rootId = '11111111-1111-1111-1111-111111111111'
    mockApiGet.mockResolvedValue({ rootResourceId: rootId, items: [], nextCursor: null })
    mockApiSend
      .mockRejectedValueOnce(new Error('folder already exists'))
      .mockResolvedValueOnce({ ok: true })
    renderBrowser()
    await screen.findByText('No resources are visible in this folder.')

    fireEvent.click(await screen.findByRole('button', { name: 'New folder' }))
    const dialog = await screen.findByRole('dialog', { name: 'New folder' })
    fireEvent.change(within(dialog).getByLabelText('Folder name'), {
      target: { value: 'research' },
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Create folder' }))
    expect(await within(dialog).findByRole('alert')).toHaveTextContent('folder already exists')
    fireEvent.click(within(dialog).getByRole('button', { name: 'Create folder' }))

    await waitFor(() => expect(mockApiSend).toHaveBeenCalledTimes(2))
    await waitFor(() => expect(screen.queryByRole('dialog', { name: 'New folder' })).toBeNull())
  })

  it('deletes a resource from the menu-backed manage dialog', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('obsolete.md', 'file', 4)],
      nextCursor: null,
    })
    mockApiGet.mockResolvedValueOnce({ items: [], nextCursor: null })
    mockApiSend.mockResolvedValueOnce({ ok: true })
    renderBrowser()

    await openResourceMenu('obsolete.md')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Delete' }))
    const confirmation = await screen.findByRole('alertdialog', { name: 'Delete resource' })
    expect(within(confirmation).getByText('Delete obsolete.md?')).toBeTruthy()
    expect(within(confirmation).getByText('This action cannot be undone.')).toBeTruthy()
    expect(screen.queryByText('Access')).toBeNull()
    expect(screen.queryByRole('button', { name: 'Replace file' })).toBeNull()
    fireEvent.click(within(confirmation).getByRole('button', { name: 'Cancel' }))
    await waitFor(() =>
      expect(screen.queryByRole('alertdialog', { name: 'Delete resource' })).toBeNull()
    )
    expect(screen.queryByRole('dialog', { name: 'Manage file obsolete.md' })).toBeNull()

    await openResourceMenu('obsolete.md')
    fireEvent.click(screen.getByRole('menuitem', { name: 'Delete' }))
    fireEvent.click(
      within(await screen.findByRole('alertdialog', { name: 'Delete resource' })).getByRole(
        'button',
        { name: 'Delete' }
      )
    )

    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith('DELETE', '/api/v1/gfs/proxy/v1/resources/r4', {
        ifMatch: 0,
      })
    )
  })

  it('surfaces a load error (fail-loud, not a silent empty tree)', async () => {
    mockApiGet.mockRejectedValueOnce(new Error('boom'))
    renderBrowser()
    const alert = await screen.findByRole('alert')
    expect(alert.textContent).toContain('boom')
  })

  it('grants access to a selected bulk subject with the correct body', async () => {
    mockApiGet.mockResolvedValueOnce({ items: [child('report.md', 'file', 2)], nextCursor: null })
    mockPutGfsGrant.mockResolvedValueOnce({ ok: true })
    renderBrowser()

    await openManage('report.md')
    await waitFor(() => expect(mockGetAdminUsers).toHaveBeenCalledWith(''))
    await waitFor(() => expect(mockGetAdminTeams).toHaveBeenCalled())
    const manageDialog = screen.getByRole('dialog', { name: 'Share file report.md' })
    expect(within(manageDialog).queryByRole('button', { name: 'Actions for report.md' })).toBeNull()
    await openSubjectPicker()
    fireEvent.click(await screen.findByRole('option', { name: 'Ada Lovelace' }))
    selectPermission('Read')
    fireEvent.click(screen.getByRole('button', { name: 'Share' }))

    await waitFor(() =>
      expect(mockPutGfsGrant).toHaveBeenCalledWith({
        drive: 'main',
        resourceId: 'id-2',
        subjects: [{ type: 'user', id: '11111111-1111-1111-1111-111111111111' }],
        permissions: ['read', 'share'],
        inherit: false,
      })
    )
  })

  it('keeps user grants available when agent or workflow directories fail', async () => {
    mockApiGet.mockResolvedValueOnce({ items: [child('report.md', 'file', 2)], nextCursor: null })
    mockGetHosts.mockRejectedValueOnce(new Error('host directory unavailable'))
    mockGetRecipes.mockRejectedValueOnce(new Error('recipe directory unavailable'))
    renderBrowser()

    await openManage('report.md')
    await screen.findByText('Some grant subjects could not be loaded: agents, workflows')
    await openSubjectPicker()
    fireEvent.click(await screen.findByRole('option', { name: 'Ada Lovelace' }))
    selectPermission('Read')

    expect(screen.getByRole('button', { name: 'Share' })).not.toBeDisabled()
  })

  it('does not expose share creation from a directory resource menu', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('team-folder', 'directory', 2)],
      nextCursor: null,
    })
    renderBrowser()

    await openResourceMenu('team-folder')
    const rowMenu = screen.getByRole('menu')
    expect(within(rowMenu).queryByRole('menuitem', { name: 'Create share' })).toBeNull()
    fireEvent.click(within(rowMenu).getByRole('menuitem', { name: 'Share' }))
    fireEvent.click(
      within(screen.getByRole('menu', { name: 'Share options for team-folder' })).getByRole(
        'menuitem',
        { name: 'Share' }
      )
    )
    expect(screen.queryByText('Manage folder')).toBeNull()
    await waitFor(() => expect(mockGetAdminUsers).toHaveBeenCalledWith(''))
    expect(screen.queryByRole('checkbox', { name: /Include contents of this folder/ })).toBeNull()
    const manageDialog = screen.getByRole('dialog', { name: 'Share folder team-folder' })
    expect(
      within(manageDialog).queryByRole('button', { name: 'Actions for team-folder' })
    ).toBeNull()
    expect(within(manageDialog).queryByRole('button', { name: 'Upload file' })).toBeNull()
    await openSubjectPicker()
    fireEvent.click(await screen.findByRole('option', { name: 'Ada Lovelace' }))
    selectPermission('Read')
    expect(screen.getByRole('checkbox', { name: /Include contents of this folder/ })).toBeChecked()
    expect(screen.getByRole('button', { name: 'Share' })).toBeEnabled()
  })

  it('lets an operator select team and operator subjects without typing UUIDs', async () => {
    mockApiGet.mockResolvedValueOnce({ items: [child('report.md', 'file', 2)], nextCursor: null })
    mockPutGfsGrant.mockResolvedValue({ ok: true })
    renderBrowser()

    await openManage('report.md')
    await waitFor(() => expect(mockGetAdminUsers).toHaveBeenCalledWith(''))
    await waitFor(() => expect(mockGetAdminTeams).toHaveBeenCalled())
    expect(screen.queryByLabelText('Subject ID')).toBeNull()

    await openSubjectPicker()
    expect(within(screen.getByRole('listbox')).getByRole('option', { name: 'Ada Lovelace' }))
    fireEvent.click(await screen.findByRole('option', { name: 'Research' }))
    selectPermission('Read')
    fireEvent.click(screen.getByRole('button', { name: 'Share' }))

    await waitFor(() =>
      expect(mockPutGfsGrant).toHaveBeenCalledWith(
        expect.objectContaining({
          subjects: [{ type: 'team', id: '22222222-2222-2222-2222-222222222222' }],
        })
      )
    )

    await openSubjectPicker()
    fireEvent.click(await screen.findByRole('option', { name: 'Operator' }))
    selectPermission('Read')
    fireEvent.click(screen.getByRole('button', { name: 'Share' }))

    await waitFor(() =>
      expect(mockPutGfsGrant).toHaveBeenLastCalledWith(
        expect.objectContaining({
          subject: { type: 'operator' },
        })
      )
    )
  })

  it('surfaces the machine error code on a no-escalation rejection', async () => {
    mockApiGet.mockResolvedValueOnce({ items: [child('report.md', 'file', 2)], nextCursor: null })
    mockPutGfsGrant.mockRejectedValueOnce(
      Object.assign(new Error('403 escalation_rejected'), { code: 'escalation_rejected' })
    )
    renderBrowser()

    await openManage('report.md')
    await waitFor(() => expect(mockGetAdminUsers).toHaveBeenCalledWith(''))
    await waitFor(() => expect(mockGetAdminTeams).toHaveBeenCalled())
    await openSubjectPicker()
    fireEvent.click(await screen.findByRole('option', { name: 'Ada Lovelace' }))
    selectPermission('Write')
    fireEvent.click(screen.getByRole('button', { name: 'Share' }))

    expect((await screen.findByText('escalation_rejected')).getAttribute('role')).toBe('alert')
  })

  it('shows the loaded count and the truncation notice while a page cap holds more rows', async () => {
    mockApiGet.mockResolvedValueOnce({
      items: [child('a.md', 'file', 1), child('b.md', 'file', 2)],
      nextCursor: 'cursor-1',
    })
    renderBrowser()

    const count = await screen.findByText('Showing the first 2 items.')
    // WCAG 4.1.3: the count changes after Load more, so updates must be
    // announced politely.
    expect(count).toHaveAttribute('aria-live', 'polite')
    expect(
      screen.getByText(
        'The listing is truncated at the page cap — Load more fetches the next page.'
      )
    ).toBeTruthy()
    expect(screen.getByRole('button', { name: 'Load more' })).toBeTruthy()
  })

  it('announces the complete count and drops the notice after the last page loads', async () => {
    mockApiGet.mockImplementation((_path: string, query?: Record<string, string>) => {
      if (query?.cursor === 'cursor-1') {
        return Promise.resolve({ items: [child('c.md', 'file', 3)], nextCursor: null })
      }
      return Promise.resolve({
        items: [child('a.md', 'file', 1), child('b.md', 'file', 2)],
        nextCursor: 'cursor-1',
      })
    })
    renderBrowser()

    expect(await screen.findByText('Showing the first 2 items.')).toBeTruthy()
    fireEvent.click(screen.getByRole('button', { name: 'Load more' }))

    expect(await screen.findByText('Showing all 3 items.')).toBeTruthy()
    expect(
      screen.queryByText(
        'The listing is truncated at the page cap — Load more fetches the next page.'
      )
    ).toBeNull()
    expect(screen.queryByRole('button', { name: 'Load more' })).toBeNull()
    expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/tree', {
      drive: 'main',
      cursor: 'cursor-1',
    })
  })

  it('states the complete count without a truncation notice on a short listing', async () => {
    mockApiGet.mockResolvedValueOnce({ items: [child('a.md', 'file', 1)], nextCursor: null })
    renderBrowser()

    expect(await screen.findByText('Showing all 1 item.')).toBeTruthy()
    expect(screen.queryByText(/truncated at the page cap/)).toBeNull()
    expect(screen.queryByRole('button', { name: 'Load more' })).toBeNull()
  })

  it('uses the singular item wording for a one-row truncated page', async () => {
    mockApiGet.mockResolvedValueOnce({ items: [child('a.md', 'file', 1)], nextCursor: 'cursor-1' })
    renderBrowser()

    expect(await screen.findByText('Showing the first 1 item.')).toBeTruthy()
    expect(screen.getByRole('button', { name: 'Load more' })).toBeTruthy()
  })
})

// ── folder drag moves (rev-2 D2) ─────────────────────────────────────────────

describe('GfsBrowser — folder drag-and-drop', () => {
  // The file's shared mock reset lives inside the sibling describe('GfsBrowser')
  // block; this block resets the same API mocks for itself.
  beforeEach(() => {
    mockApiGet.mockReset()
    mockApiSend.mockReset()
  })

  function folderPage(archiveChildren: ReturnType<typeof child>[] = []) {
    const archive = child('archive', 'directory', 1)
    const projects = child('projects', 'directory', 2)
    const resolveViewFor = (uri: string) => {
      if (uri === archive.gfsUri) {
        return {
          resourceId: archive.resourceId,
          kind: 'directory',
          path: '/archive',
          version: 0,
        }
      }
      if (uri === projects.gfsUri) {
        return {
          resourceId: projects.resourceId,
          kind: 'directory',
          path: '/projects',
          version: 0,
        }
      }
      return null
    }
    mockApiGet.mockImplementation(async (path: string, query?: Record<string, string>) => {
      if (path === '/api/v1/gfs/resolve' && query?.uri) {
        const view = resolveViewFor(query.uri)
        if (view) return view
        throw Object.assign(new Error('404 Not Found'), { status: 404 })
      }
      if (
        path === '/api/v1/gfs/tree' ||
        path === '/api/v1/gfs/resources/11111111-1111-1111-1111-111111111111/children'
      ) {
        return {
          rootResourceId: '11111111-1111-1111-1111-111111111111',
          items: [archive, projects],
          nextCursor: null,
        }
      }
      if (path === '/api/v1/gfs/resources/id-1/children') {
        return { items: archiveChildren, nextCursor: null }
      }
      return { items: [], nextCursor: null }
    })
    return { archive, projects, resolveViewFor }
  }

  function dragAndDrop(sourceRow: HTMLElement, destinationRow: HTMLElement) {
    const dataTransfer = {
      dropEffect: 'none',
      effectAllowed: 'uninitialized',
      files: [],
      types: ['application/x-evenfire-gfs-resource'],
      setData: vi.fn(),
      getData: vi.fn(),
    }
    fireEvent.dragStart(sourceRow, { dataTransfer })
    fireEvent.dragEnter(destinationRow, { dataTransfer })
    fireEvent.dragOver(destinationRow, { dataTransfer })
    fireEvent.drop(destinationRow, { dataTransfer })
    fireEvent.dragEnd(sourceRow, { dataTransfer })
  }

  it('stops a folder drop at the one confirmation and commits on Move', async () => {
    const { projects } = folderPage()
    mockApiSend.mockResolvedValueOnce({ ok: true, data: { resourceId: 'id-2', version: 1 } })
    renderBrowser()

    await waitFor(() => expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull())
    const projectsRow = within(screen.getByRole('list', { name: 'Current folder resources' }))
      .getByText('projects')
      .closest('li')!
    const archiveRow = within(screen.getByRole('list', { name: 'Current folder resources' }))
      .getByText('archive')
      .closest('li')!

    dragAndDrop(projectsRow, archiveRow)

    const dialog = await screen.findByRole('dialog', {
      name: 'Move folder projects to archive',
    })
    expect(
      within(dialog).getByText(
        /Inherited access to this folder and its contents follows the new location/
      )
    ).toBeTruthy()
    // The structure guard passed on fresh canonical paths (both rows carry
    // paths; sibling folders are structurally safe) — no request yet.
    expect(mockApiSend).not.toHaveBeenCalled()

    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        '/api/v1/gfs/resources/id-2',
        { drive: 'main', newParentId: 'id-1', ifMatch: 0 },
        { drive: 'main' }
      )
    )
    expect(await screen.findByText('Moved "projects" to "archive".')).toBeTruthy()
    expect(await screen.findByText(/access now follows the new location/)).toBeTruthy()
    expect(screen.queryByRole('dialog')).toBeNull()
    void projects
  })

  it('cancelling the folder confirmation sends no PATCH and claims no move', async () => {
    folderPage()
    renderBrowser()

    await waitFor(() => expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull())
    const list = screen.getByRole('list', { name: 'Current folder resources' })
    const projectsRow = within(list).getByText('projects').closest('li')!
    const archiveRow = within(list).getByText('archive').closest('li')!

    dragAndDrop(projectsRow, archiveRow)
    const dialog = await screen.findByRole('dialog', {
      name: 'Move folder projects to archive',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))

    expect(mockApiSend).not.toHaveBeenCalled()
    expect(screen.queryByText(/Moved/)).toBeNull()
    expect(screen.queryByRole('dialog')).toBeNull()
  })

  it('refuses a folder drop into its own descendant using canonical paths', async () => {
    // projects lives at /projects; archive lives at /projects/archive — a
    // child of the source. The listing rows carry those paths and the
    // admission re-resolves both endpoints by immutable URI.
    const projects = child('projects', 'directory', 2)
    const nestedArchive = child('archive', 'directory', 1)
    nestedArchive.path = '/projects/archive'
    mockApiGet.mockImplementation(async (path: string, query?: Record<string, string>) => {
      if (path === '/api/v1/gfs/resolve' && query?.uri === projects.gfsUri) {
        return {
          resourceId: projects.resourceId,
          kind: 'directory',
          path: '/projects',
          version: 0,
        }
      }
      if (path === '/api/v1/gfs/resolve' && query?.uri === nestedArchive.gfsUri) {
        return {
          resourceId: nestedArchive.resourceId,
          kind: 'directory',
          path: '/projects/archive',
          version: 0,
        }
      }
      if (
        path === '/api/v1/gfs/tree' ||
        path === '/api/v1/gfs/resources/11111111-1111-1111-1111-111111111111/children'
      ) {
        return {
          rootResourceId: '11111111-1111-1111-1111-111111111111',
          items: [projects, nestedArchive],
          nextCursor: null,
        }
      }
      return { items: [], nextCursor: null }
    })
    renderBrowser()

    await waitFor(() => expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull())
    const list = screen.getByRole('list', { name: 'Current folder resources' })
    const projectsRow = within(list).getByText('projects').closest('li')!
    const archiveRow = within(list).getByText('archive').closest('li')!

    dragAndDrop(projectsRow, archiveRow)

    expect(
      await screen.findByText(/You can't move projects into a folder inside itself/)
    ).toBeTruthy()
    expect(mockApiSend).not.toHaveBeenCalled()
    expect(screen.queryByRole('dialog')).toBeNull()
  })

  it('a folder conflict without the numbered-name opt-in stops after one attempt', async () => {
    folderPage()
    const actualApi = await vi.importActual<typeof import('@lib/api')>('@lib/api')
    const conflict = () => {
      const text = JSON.stringify({
        error: { code: 'already_exists', message: 'a resource with this name already exists' },
      })
      return actualApi.formatApiError(
        new Response(text, { status: 409, statusText: 'Conflict' }),
        text
      )
    }
    mockApiSend.mockRejectedValueOnce(conflict())
    renderBrowser()

    await waitFor(() => expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull())
    const list = screen.getByRole('list', { name: 'Current folder resources' })
    const projectsRow = within(list).getByText('projects').closest('li')!
    const archiveRow = within(list).getByText('archive').closest('li')!

    dragAndDrop(projectsRow, archiveRow)
    const dialog = await screen.findByRole('dialog', {
      name: 'Move folder projects to archive',
    })
    // The numbered-name policy is an explicit opt-in (unchecked by default).
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    expect(await screen.findByText(/An item with this name already exists/)).toBeTruthy()
    expect(mockApiSend).toHaveBeenCalledTimes(1)
  })

  it('a folder conflict with the numbered-name opt-in renames the whole folder within 3 attempts', async () => {
    folderPage()
    const actualApi = await vi.importActual<typeof import('@lib/api')>('@lib/api')
    const conflict = () => {
      const text = JSON.stringify({
        error: { code: 'already_exists', message: 'a resource with this name already exists' },
      })
      return actualApi.formatApiError(
        new Response(text, { status: 409, statusText: 'Conflict' }),
        text
      )
    }
    mockApiSend
      .mockRejectedValueOnce(conflict())
      .mockRejectedValueOnce(conflict())
      .mockResolvedValueOnce({ ok: true, data: { resourceId: 'id-2', version: 1 } })
    renderBrowser()

    await waitFor(() => expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull())
    const list = screen.getByRole('list', { name: 'Current folder resources' })
    const projectsRow = within(list).getByText('projects').closest('li')!
    const archiveRow = within(list).getByText('archive').closest('li')!

    dragAndDrop(projectsRow, archiveRow)
    const dialog = await screen.findByRole('dialog', {
      name: 'Move folder projects to archive',
    })
    fireEvent.click(within(dialog).getByRole('checkbox'))
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    await waitFor(() => expect(mockApiSend).toHaveBeenCalledTimes(3))
    expect(mockApiSend).toHaveBeenNthCalledWith(
      3,
      'PATCH',
      '/api/v1/gfs/resources/id-2',
      { drive: 'main', newParentId: 'id-1', ifMatch: 0, newName: 'projects (2)' },
      { drive: 'main' }
    )
    expect(await screen.findByText('Moved "projects" to "archive" as "projects (2)".')).toBeTruthy()
  })

  it('a cached destination seeds the ladder so the first 409 jumps to the first free numbered name', async () => {
    // RP-003: archive is prefetched holding projects, projects (1) and
    // projects (2). The blind ladder burned all three attempts on taken
    // names and ended on "The destination changed". Seeded from the same
    // cache the suggestion came from, attempt two lands on projects (3).
    folderPage([
      child('projects', 'directory', 3),
      child('projects (1)', 'directory', 4),
      child('projects (2)', 'directory', 5),
    ])
    const actualApi = await vi.importActual<typeof import('@lib/api')>('@lib/api')
    const conflict = () => {
      const text = JSON.stringify({
        error: { code: 'already_exists', message: 'a resource with this name already exists' },
      })
      return actualApi.formatApiError(
        new Response(text, { status: 409, statusText: 'Conflict' }),
        text
      )
    }
    mockApiSend.mockRejectedValueOnce(conflict()).mockResolvedValueOnce({
      ok: true,
      data: { resourceId: 'id-2', version: 1 },
    })
    renderBrowser()

    await waitFor(() => expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull())
    // Wait until the archive prefetch has landed in the children cache.
    await waitFor(() =>
      expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resources/id-1/children', {
        drive: 'main',
      })
    )
    const list = screen.getByRole('list', { name: 'Current folder resources' })
    const projectsRow = within(list).getByText('projects').closest('li')!
    const archiveRow = within(list).getByText('archive').closest('li')!

    dragAndDrop(projectsRow, archiveRow)
    const dialog = await screen.findByRole('dialog', {
      name: 'Move folder projects to archive',
    })
    // The suggestion is derived from the same cached names.
    expect(within(dialog).getByText(/projects \(3\)/)).toBeTruthy()
    fireEvent.click(within(dialog).getByRole('checkbox'))
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    await waitFor(() => expect(mockApiSend).toHaveBeenCalledTimes(2))
    expect(mockApiSend).toHaveBeenNthCalledWith(
      2,
      'PATCH',
      '/api/v1/gfs/resources/id-2',
      { drive: 'main', newParentId: 'id-1', ifMatch: 0, newName: 'projects (3)' },
      { drive: 'main' }
    )
    expect(await screen.findByText('Moved "projects" to "archive" as "projects (3)".')).toBeTruthy()
  })
})

describe('GfsBrowser — breadcrumb drop moves', () => {
  // The file's shared mock reset lives inside the sibling describe('GfsBrowser')
  // block; this block resets the same API mocks for itself.
  beforeEach(() => {
    mockApiGet.mockReset()
    mockApiSend.mockReset()
  })

  // Drive fixture: main › Product › live tests, browsing `live tests` with
  // the file abac.md and the folder specs. Resolve answers carry FRESH
  // versions so the pre-dispatch re-resolve is observable in ifMatch.
  const rootId = '11111111-1111-1111-1111-111111111111'
  const rootRid = '11111111111111111111111111111111'

  interface EndpointView {
    resourceId: string
    kind: string
    path: string
    version: number
  }

  function breadcrumbTrailFixture(options?: { hydrateRoot?: boolean }) {
    const product = child('Product', 'directory', 1)
    product.path = '/Product'
    const liveTests = child('live tests', 'directory', 3)
    liveTests.path = '/Product/live tests'
    const abac = child('abac.md', 'file', 2)
    abac.path = '/Product/live tests/abac.md'
    const specs = child('specs', 'directory', 4)
    specs.path = '/Product/live tests/specs'
    const views: Record<string, EndpointView> = {
      // The root is keyed by its RID (dashes stripped): that is the form
      // gfs:// URIs resolve with.
      [rootRid]: { resourceId: rootId, kind: 'directory', path: '/', version: 1 },
      r1: { resourceId: 'id-1', kind: 'directory', path: '/Product', version: 2 },
      r2: { resourceId: 'id-2', kind: 'file', path: '/Product/live tests/abac.md', version: 5 },
      r3: {
        resourceId: 'id-3',
        kind: 'directory',
        path: '/Product/live tests',
        version: 3,
      },
      r4: {
        resourceId: 'id-4',
        kind: 'directory',
        path: '/Product/live tests/specs',
        version: 7,
      },
    }
    let moved = false
    let treeReads = 0
    let sourceResolveReads = 0
    const parkedSourceReads: Array<(view: EndpointView) => void> = []
    const parkedTreeReads: Array<(page: unknown) => void> = []
    const hydrateRoot = options?.hydrateRoot !== false
    // Test-side knobs that do not clobber the base listing mocks.
    const policy = {
      /** Tree reads (1-based) at and after this index throw transport errors. */
      treeErrorFromRead: 0,
      /** One exact tree read (1-based) that answers 401 (session lost). */
      treeUnauthorizedAt: 0,
      /** Tree reads (1-based) at/after this index park until released. */
      parkTreeReadsFrom: 0,
      /** Per-read (1-based) overrides for the SOURCE resolve: a view, 'failed', or 'unauthorized'. */
      sourceReadResults: new Map<number, EndpointView | 'failed' | 'unauthorized'>(),
      /** Park source reads at/after this index until released. */
      parkSourceReadFrom: 0,
    }
    const resolveOverride: {
      uri?: string
      result?: 'missing' | 'failed' | 'unauthorized' | EndpointView
    } = {}
    const treePageFor = (includeRoot: boolean) => ({
      ...(includeRoot ? { rootResourceId: rootId } : {}),
      items: [product],
      nextCursor: null,
    })
    mockApiGet.mockImplementation(async (path: string, query?: Record<string, string>) => {
      if (path === '/api/v1/gfs/resolve' && query?.uri) {
        if (resolveOverride.uri === query.uri) {
          if (resolveOverride.result === 'missing') {
            throw Object.assign(new Error('404 Not Found'), { status: 404 })
          }
          if (resolveOverride.result === 'failed') {
            throw new TypeError('fetch failed')
          }
          if (resolveOverride.result === 'unauthorized') {
            throw Object.assign(new Error('401 Unauthorized'), { status: 401 })
          }
          if (resolveOverride.result) return resolveOverride.result
        }
        if (query.uri === 'gfs://main/r2') {
          sourceResolveReads += 1
          const readResult = policy.sourceReadResults.get(sourceResolveReads)
          if (readResult === 'failed') throw new TypeError('fetch failed')
          if (readResult === 'unauthorized') {
            throw Object.assign(new Error('401 Unauthorized'), { status: 401 })
          }
          if (readResult) return readResult
          if (policy.parkSourceReadFrom > 0 && sourceResolveReads >= policy.parkSourceReadFrom) {
            return new Promise<EndpointView>(resolve => {
              parkedSourceReads.push(resolve)
            })
          }
        }
        const rid = query.uri.replace('gfs://main/', '')
        const view = views[rid]
        if (!view) throw Object.assign(new Error('404 Not Found'), { status: 404 })
        return view
      }
      if (path === '/api/v1/gfs/tree') {
        treeReads += 1
        if (policy.treeUnauthorizedAt === treeReads) {
          throw Object.assign(new Error('401 Unauthorized'), { status: 401 })
        }
        if (policy.treeErrorFromRead > 0 && treeReads >= policy.treeErrorFromRead) {
          throw new TypeError('fetch failed')
        }
        if (policy.parkTreeReadsFrom > 0 && treeReads >= policy.parkTreeReadsFrom) {
          return new Promise(resolve => {
            parkedTreeReads.push(resolve)
          })
        }
        // First load leaves the root synthetic when hydration is disabled;
        // the drop-time retry then hydrates on the next tree read.
        return treePageFor(hydrateRoot || treeReads > 1)
      }
      if (path === '/api/v1/gfs/by-path' && query?.path === '/live tests') {
        return { ...views['r3']!, path: '/live tests' }
      }
      if (path === `/api/v1/gfs/resources/${rootId}/children`) {
        return { items: [product], nextCursor: null }
      }
      if (path === '/api/v1/gfs/resources/id-1/children') {
        return { items: moved ? [liveTests, abac] : [liveTests], nextCursor: null }
      }
      if (path === '/api/v1/gfs/resources/id-3/children') {
        return { items: moved ? [specs] : [abac, specs], nextCursor: null }
      }
      return { items: [], nextCursor: null }
    })
    mockApiSend.mockImplementation(async () => {
      moved = true
      return { ok: true, data: { resourceId: 'id-2', version: 6 } }
    })
    return {
      product,
      liveTests,
      abac,
      specs,
      views,
      resolveOverride,
      policy,
      releaseParkedSourceReads(view: EndpointView) {
        for (const release of parkedSourceReads.splice(0)) release(view)
      },
      releaseParkedTreeReads() {
        for (const release of parkedTreeReads.splice(0)) release(treePageFor(true))
      },
    }
  }

  function dataTransfer() {
    return {
      dropEffect: 'none',
      effectAllowed: 'uninitialized',
      files: [],
      types: ['application/x-evenfire-gfs-resource'],
      setData: vi.fn(),
      getData: vi.fn(),
    }
  }

  function breadcrumbNav() {
    return screen.getByRole('navigation', { name: 'Breadcrumb' })
  }

  function crumbButton(name: string) {
    return within(breadcrumbNav()).getByRole('button', { name, exact: true })
  }

  async function browseToLiveTests(productName = 'Product') {
    renderBrowser()
    await waitFor(() => expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull())
    fireEvent.click((await screen.findAllByRole('button', { name: productName }))[0]!)
    let list = screen.getByRole('list', { name: 'Current folder resources' })
    fireEvent.click(await within(list).findByRole('button', { name: 'live tests', exact: true }))
    await waitFor(() => expect(crumbButton('live tests')).toHaveAttribute('aria-current', 'page'))
    list = screen.getByRole('list', { name: 'Current folder resources' })
    await within(list).findByText('abac.md')
    return list
  }

  function rowOf(list: HTMLElement, name: string) {
    return within(list).getByText(name).closest('li')!
  }

  function dragRowOverCrumb(row: HTMLElement, crumb: HTMLElement) {
    const transfer = dataTransfer()
    fireEvent.dragStart(row, { dataTransfer: transfer })
    fireEvent.dragEnter(crumb, { dataTransfer: transfer })
    fireEvent.dragOver(crumb, { dataTransfer: transfer })
    return transfer
  }

  it('moves a dropped file onto an ancestor crumb after one file-kind confirmation', async () => {
    breadcrumbTrailFixture()
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')
    const productCrumb = crumbButton('Product')

    const transfer = dragRowOverCrumb(abacRow, productCrumb)
    expect(productCrumb).toHaveAttribute('data-drop-state', 'allowed')
    expect(screen.getByTestId('gfs-drop-announce')).toHaveTextContent('You can move into Product.')
    fireEvent.drop(productCrumb, { dataTransfer: transfer })
    fireEvent.dragEnd(abacRow, { dataTransfer: transfer })

    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    expect(within(dialog).getByRole('heading', { level: 3 })).toHaveTextContent(
      'Move “abac.md” to “Product”?'
    )
    expect(
      within(dialog).getByText(/Inherited access to this file follows the new location/)
    ).toBeTruthy()
    expect(
      within(dialog).queryByText(/Inherited access to this folder and its contents/)
    ).toBeNull()
    expect(mockApiSend).not.toHaveBeenCalled()

    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    // The commit re-resolved BOTH endpoints and used the FRESH source
    // version (5), not the stale row version (0).
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        '/api/v1/gfs/resources/id-2',
        { drive: 'main', newParentId: 'id-1', ifMatch: 5 },
        { drive: 'main' }
      )
    )
    expect(await screen.findByText('Moved "abac.md" to "Product".')).toBeTruthy()
    await waitFor(() => expect(screen.queryByText('abac.md')).toBeNull())
  })

  it('moves a dropped folder onto an ancestor crumb after one folder confirmation', async () => {
    breadcrumbTrailFixture()
    const list = await browseToLiveTests()
    const specsRow = rowOf(list, 'specs')
    const productCrumb = crumbButton('Product')

    const transfer = dragRowOverCrumb(specsRow, productCrumb)
    expect(productCrumb).toHaveAttribute('data-drop-state', 'allowed')
    fireEvent.drop(productCrumb, { dataTransfer: transfer })
    fireEvent.dragEnd(specsRow, { dataTransfer: transfer })

    const dialog = await screen.findByRole('dialog', {
      name: 'Move folder specs to Product',
    })
    expect(
      within(dialog).getByText(/Inherited access to this folder and its contents/)
    ).toBeTruthy()
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        '/api/v1/gfs/resources/id-4',
        { drive: 'main', newParentId: 'id-1', ifMatch: 7 },
        { drive: 'main' }
      )
    )
    expect(await screen.findByText('Moved "specs" to "Product".')).toBeTruthy()
    expect(await screen.findByText(/access now follows the new location/)).toBeTruthy()
  })

  it('admits a drop onto the hydrated drive-root crumb as an intrinsic-authority move', async () => {
    breadcrumbTrailFixture()
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')
    const rootCrumb = crumbButton('main')

    const transfer = dragRowOverCrumb(abacRow, rootCrumb)
    expect(rootCrumb).toHaveAttribute('data-drop-state', 'allowed')
    fireEvent.drop(rootCrumb, { dataTransfer: transfer })
    fireEvent.dragEnd(abacRow, { dataTransfer: transfer })

    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to main',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        '/api/v1/gfs/resources/id-2',
        { drive: 'main', newParentId: rootId, ifMatch: 5 },
        { drive: 'main' }
      )
    )
    expect(await screen.findByText('Moved "abac.md" to "main".')).toBeTruthy()
  })

  it('hydrates an unhydrated root on drop and completes the move', async () => {
    const { resolveOverride } = breadcrumbTrailFixture({ hydrateRoot: false })
    void resolveOverride
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')
    const rootCrumb = crumbButton('main')

    const transfer = dragRowOverCrumb(abacRow, rootCrumb)
    // Identity not available yet: warning paint, never a fake denial, with
    // the reason carried on the dedicated attribute.
    expect(rootCrumb).toHaveAttribute('data-drop-state', 'unavailable')
    expect(rootCrumb).toHaveAttribute('data-drop-reason', 'target-unavailable')
    expect(screen.getByTestId('gfs-drop-announce')).toHaveTextContent(
      'EvenDrive could not confirm whether you can move into main.'
    )
    fireEvent.drop(rootCrumb, { dataTransfer: transfer })
    fireEvent.dragEnd(abacRow, { dataTransfer: transfer })

    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to main',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        '/api/v1/gfs/resources/id-2',
        { drive: 'main', newParentId: rootId, ifMatch: 5 },
        { drive: 'main' }
      )
    )
  })

  it('warns honestly when the drop-time root hydration read fails, without any PATCH', async () => {
    // The first load stays rootless and every later tree read fails, so the
    // drop-time hydration retry cannot answer.
    const fixture = breadcrumbTrailFixture({ hydrateRoot: false })
    fixture.policy.treeErrorFromRead = 2
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')
    const rootCrumb = crumbButton('main')

    const transfer = dragRowOverCrumb(abacRow, rootCrumb)
    fireEvent.drop(rootCrumb, { dataTransfer: transfer })
    fireEvent.dragEnd(abacRow, { dataTransfer: transfer })

    expect(
      await screen.findByText(
        'EvenDrive couldn’t verify this move. Check your connection and try again.'
      )
    ).toBeTruthy()
    expect(
      screen.getByText(/EvenDrive couldn’t verify this move/).closest('.cu-toast')
    ).toHaveClass('cu-toast--warning')
    expect(mockApiSend).not.toHaveBeenCalled()
    expect(screen.queryByRole('dialog')).toBeNull()
  })

  it('reports the active crumb as already-here info without a dialog or PATCH', async () => {
    breadcrumbTrailFixture()
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')
    const activeCrumb = crumbButton('live tests')

    const transfer = dragRowOverCrumb(abacRow, activeCrumb)
    expect(activeCrumb).toHaveAttribute('data-drop-state', 'same-parent')
    expect(activeCrumb).toHaveAttribute('data-drop-reason', 'same-parent')
    expect(screen.getByTestId('gfs-drop-announce')).toHaveTextContent(
      'abac.md is already in live tests.'
    )
    fireEvent.drop(activeCrumb, { dataTransfer: transfer })
    fireEvent.dragEnd(abacRow, { dataTransfer: transfer })

    expect(await screen.findByText('abac.md is already in live tests.')).toBeTruthy()
    expect(screen.getByText('abac.md is already in live tests.').closest('.cu-toast')).toHaveClass(
      'cu-toast--info'
    )
    expect(mockApiSend).not.toHaveBeenCalled()
    expect(screen.queryByRole('dialog')).toBeNull()
    expect(within(list).getByText('abac.md')).toBeTruthy()
  })

  it('cancelling the crumb confirmation sends no PATCH and claims no move', async () => {
    breadcrumbTrailFixture()
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')
    const productCrumb = crumbButton('Product')

    const transfer = dragRowOverCrumb(abacRow, productCrumb)
    fireEvent.drop(productCrumb, { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))

    expect(mockApiSend).not.toHaveBeenCalled()
    expect(screen.queryByText(/Moved/)).toBeNull()
    expect(screen.queryByRole('dialog')).toBeNull()
    expect(within(list).getByText('abac.md')).toBeTruthy()
  })

  it('refuses admission when the destination crumb vanished (404), without a PATCH', async () => {
    const { resolveOverride } = breadcrumbTrailFixture()
    resolveOverride.uri = 'gfs://main/r1'
    resolveOverride.result = 'missing'
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')
    const productCrumb = crumbButton('Product')

    const transfer = dragRowOverCrumb(abacRow, productCrumb)
    fireEvent.drop(productCrumb, { dataTransfer: transfer })
    fireEvent.dragEnd(abacRow, { dataTransfer: transfer })

    expect(await screen.findByText('This folder is no longer available.')).toBeTruthy()
    expect(mockApiSend).not.toHaveBeenCalled()
    expect(screen.queryByRole('dialog')).toBeNull()
  })

  it('refuses admission when the source can no longer be located (404)', async () => {
    const { resolveOverride } = breadcrumbTrailFixture()
    resolveOverride.uri = 'gfs://main/r2'
    resolveOverride.result = 'missing'
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })

    expect(
      await screen.findByText(
        'EvenDrive cannot verify this item’s current location. Refresh and try again.'
      )
    ).toBeTruthy()
    expect(mockApiSend).not.toHaveBeenCalled()
    expect(screen.queryByRole('dialog')).toBeNull()
  })

  it('refuses admission with a warning when endpoint resolution itself fails', async () => {
    const { resolveOverride } = breadcrumbTrailFixture()
    resolveOverride.uri = 'gfs://main/r1'
    resolveOverride.result = 'failed'
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })

    expect(
      await screen.findByText(
        'EvenDrive couldn’t verify this move. Check your connection and try again.'
      )
    ).toBeTruthy()
    expect(mockApiSend).not.toHaveBeenCalled()
    expect(screen.queryByRole('dialog')).toBeNull()
  })

  it('re-checks the destination at commit: vanished target refuses without a PATCH', async () => {
    const { resolveOverride } = breadcrumbTrailFixture()
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    // The destination disappears between the confirmation and the commit.
    resolveOverride.uri = 'gfs://main/r1'
    resolveOverride.result = 'missing'
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    expect(await screen.findByText('This folder is no longer available.')).toBeTruthy()
    expect(mockApiSend).not.toHaveBeenCalled()
  })

  it('re-checks the destination at commit: a target that is no longer a folder refuses', async () => {
    const { resolveOverride, views } = breadcrumbTrailFixture()
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    resolveOverride.uri = 'gfs://main/r1'
    resolveOverride.result = { ...views['r1']!, kind: 'file' }
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    expect(await screen.findByText('This folder is no longer available.')).toBeTruthy()
    expect(mockApiSend).not.toHaveBeenCalled()
  })

  it('re-checks structure at commit: a remote same-parent move becomes info, not a PATCH', async () => {
    const { resolveOverride, views } = breadcrumbTrailFixture()
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    // The source was moved into Product by someone else while the dialog
    // was open: the fresh commit read sees the new parent.
    resolveOverride.uri = 'gfs://main/r2'
    resolveOverride.result = { ...views['r2']!, path: '/Product/abac.md' }
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    expect(await screen.findByText('abac.md is already in Product.')).toBeTruthy()
    expect(screen.getByText('abac.md is already in Product.').closest('.cu-toast')).toHaveClass(
      'cu-toast--info'
    )
    expect(mockApiSend).not.toHaveBeenCalled()
  })

  it('keeps the commit anchored to the captured crumb identity when the trail rebuilds mid-gesture', async () => {
    const streamControllers: ReadableStreamDefaultController<Uint8Array>[] = []
    const { views, resolveOverride } = breadcrumbTrailFixture()
    // `live tests` was moved to the drive root by the remote change the
    // frame announces: the rebuilt trail drops the Product crumb while the
    // confirmation is still open.
    resolveOverride.uri = 'gfs://main/r3'
    resolveOverride.result = { ...views['r3']!, path: '/live tests' }
    vi.stubGlobal(
      'fetch',
      vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
        const body = new ReadableStream<Uint8Array>({
          start(controller) {
            streamControllers.push(controller)
            init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
          },
        })
        return new Response(body, {
          status: 200,
          headers: { 'content-type': 'application/x-ndjson' },
        })
      })
    )
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })

    const frame = await controlApiProducerFrame()
    await act(async () => {
      streamControllers[0]!.enqueue(new TextEncoder().encode(`${frame}\n`))
    })
    await waitFor(() =>
      expect(within(breadcrumbNav()).queryByRole('button', { name: 'Product' })).toBeNull()
    )
    expect(dialog).toBeVisible()

    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    // The commit still targets the CAPTURED immutable destination identity,
    // never a crumb re-read from the rebuilt trail (R7-M1).
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        '/api/v1/gfs/resources/id-2',
        { drive: 'main', newParentId: 'id-1', ifMatch: 5 },
        { drive: 'main' }
      )
    )
  })

  it('a newer drag gesture supersedes the open confirmation', async () => {
    breadcrumbTrailFixture()
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')
    const specsRow = rowOf(list, 'specs')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    await screen.findByRole('dialog', { name: 'Move file abac.md to Product' })

    // Starting a new drag invalidates the pending confirmation.
    const secondTransfer = dataTransfer()
    fireEvent.dragStart(specsRow, { dataTransfer: secondTransfer })

    await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
    expect(mockApiSend).not.toHaveBeenCalled()
  })

  it('dragend after an accepted drop does not cancel its admission', async () => {
    breadcrumbTrailFixture()
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dataTransfer()
    fireEvent.dragStart(abacRow, { dataTransfer: transfer })
    fireEvent.dragEnter(crumbButton('Product'), { dataTransfer: transfer })
    fireEvent.dragOver(crumbButton('Product'), { dataTransfer: transfer })
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    // The drop was accepted; dragend only clears presentation.
    fireEvent.dragEnd(abacRow, { dataTransfer: transfer })

    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))
    await waitFor(() => expect(mockApiSend).toHaveBeenCalledTimes(1))
  })

  it('unmount supersedes a commit that has not dispatched yet', async () => {
    const fixture = breadcrumbTrailFixture()
    // Park the commit-time SOURCE read (read #2) until the surface is gone.
    fixture.policy.parkSourceReadFrom = 2
    const { unmount } = renderBrowser()
    await waitFor(() => expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull())
    fireEvent.click((await screen.findAllByRole('button', { name: 'Product' }))[0]!)
    let list = screen.getByRole('list', { name: 'Current folder resources' })
    fireEvent.click(await within(list).findByRole('button', { name: 'live tests', exact: true }))
    await waitFor(() => expect(crumbButton('live tests')).toHaveAttribute('aria-current', 'page'))
    list = screen.getByRole('list', { name: 'Current folder resources' })
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    // The surface unmounts while the commit read is still in flight: the
    // epoch is superseded, so the PATCH must never dispatch.
    unmount()
    fixture.releaseParkedSourceReads(fixture.views['r2']!)
    await act(async () => {
      await Promise.resolve()
    })
    expect(mockApiSend).not.toHaveBeenCalled()
  })

  it('verifies a transport-lost PATCH by identity once and reports the move it proved', async () => {
    const fixture = breadcrumbTrailFixture()
    // Source resolve read #3 is the post-transport verification: the move
    // actually landed in Product.
    fixture.policy.sourceReadResults.set(3, {
      ...fixture.views['r2']!,
      path: '/Product/abac.md',
    })
    let patched = false
    mockApiSend.mockImplementation(async () => {
      if (patched) throw new Error('PATCH repeated after an unknown transport outcome')
      patched = true
      // Transport loss AFTER dispatch: no HTTP status, outcome unknown.
      throw new TypeError('fetch failed')
    })
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    expect(await screen.findByText('Moved "abac.md" to "Product".')).toBeTruthy()
    // Exactly one PATCH — the ambiguous outcome was resolved by reading,
    // never by repeating the dispatch.
    await waitFor(() => expect(mockApiSend).toHaveBeenCalledTimes(1))
    expect(mockApiSend).toHaveBeenCalledTimes(1)
  })

  it('keeps a transport-lost PATCH unknown when the source lands under a third folder', async () => {
    // A differing parent does NOT prove the PATCH failed: it may still be
    // executing, or another actor may have moved the source. The single
    // verification read must report unknown — with refresh guidance, never a
    // failure verdict and never a repeat PATCH.
    const fixture = breadcrumbTrailFixture()
    fixture.policy.sourceReadResults.set(3, {
      ...fixture.views['r2']!,
      path: '/Elsewhere/abac.md',
    })
    mockApiSend.mockImplementation(async () => {
      throw new TypeError('fetch failed')
    })
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    expect(
      await screen.findByText(/Couldn.t confirm the move\. Refresh before trying again\./)
    ).toBeTruthy()
    expect(screen.getByText(/confirm the move/).closest('.cu-toast')).toHaveClass(
      'cu-toast--warning'
    )
    expect(mockApiSend).toHaveBeenCalledTimes(1)
  })

  it('keeps a transport-lost PATCH unknown when the destination cannot be established', async () => {
    const fixture = breadcrumbTrailFixture()
    // The PATCH "transport-fails" while the source read would prove the
    // move — but the destination itself is no longer resolvable, so the
    // positive proof is incomplete and the outcome stays unknown.
    mockApiSend.mockImplementation(async () => {
      fixture.resolveOverride.uri = 'gfs://main/r1'
      fixture.resolveOverride.result = 'missing'
      throw new TypeError('fetch failed')
    })
    fixture.policy.sourceReadResults.set(3, {
      ...fixture.views['r2']!,
      path: '/Product/abac.md',
    })
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    expect(
      await screen.findByText(/Couldn.t confirm the move\. Refresh before trying again\./)
    ).toBeTruthy()
    expect(screen.queryByText(/Moved "abac\.md"/)).toBeNull()
    expect(mockApiSend).toHaveBeenCalledTimes(1)
  })

  it('never reads a source resolved at the drive root as a completed move to root', async () => {
    const fixture = breadcrumbTrailFixture()
    // The verification read resolves the source AT '/' (the drive root
    // itself). A completed move lands at '/<name>', so '/' can never prove
    // this move — the outcome stays unknown.
    fixture.policy.sourceReadResults.set(3, { ...fixture.views['r2']!, path: '/' })
    mockApiSend.mockImplementation(async () => {
      throw new TypeError('fetch failed')
    })
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    expect(
      await screen.findByText(/Couldn.t confirm the move\. Refresh before trying again\./)
    ).toBeTruthy()
    expect(screen.queryByText(/Moved "abac\.md"/)).toBeNull()
    expect(mockApiSend).toHaveBeenCalledTimes(1)
  })

  it('keeps a transport-lost PATCH honestly unknown when verification cannot answer', async () => {
    const fixture = breadcrumbTrailFixture()
    // Source resolve read #3 is the post-transport verification and fails.
    fixture.policy.sourceReadResults.set(3, 'failed')
    mockApiSend.mockImplementation(async () => {
      throw new TypeError('fetch failed')
    })
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    expect(
      await screen.findByText(/Couldn.t confirm the move\. Refresh before trying again\./)
    ).toBeTruthy()
    expect(screen.getByText(/confirm the move/).closest('.cu-toast')).toHaveClass(
      'cu-toast--warning'
    )
    expect(mockApiSend).toHaveBeenCalledTimes(1)
  })

  it('explains a row dropped onto itself instead of silently ignoring it', async () => {
    breadcrumbTrailFixture()
    const list = await browseToLiveTests()
    const specsRow = rowOf(list, 'specs')

    const transfer = dataTransfer()
    fireEvent.dragStart(specsRow, { dataTransfer: transfer })
    fireEvent.dragEnter(specsRow, { dataTransfer: transfer })
    fireEvent.dragOver(specsRow, { dataTransfer: transfer })
    expect(specsRow).toHaveAttribute('data-drop-state', 'denied')
    expect(specsRow).toHaveAttribute('data-drop-reason', 'self')
    expect(screen.getByTestId('gfs-drop-announce')).toHaveTextContent(
      'You dropped specs onto itself. Pick a destination folder.'
    )
    fireEvent.drop(specsRow, { dataTransfer: transfer })
    fireEvent.dragEnd(specsRow, { dataTransfer: transfer })

    expect(
      await screen.findByText('You dropped specs onto itself. Pick a destination folder.')
    ).toBeTruthy()
    expect(mockApiSend).not.toHaveBeenCalled()
    expect(within(list).getByText('specs')).toBeTruthy()
  })

  it('refuses without a PATCH when the fresh source version is missing', async () => {
    const fixture = breadcrumbTrailFixture()
    // Commit-time source read succeeds but carries NO version: the fresh
    // precondition contract forbids downgrading to the stale row version.
    fixture.policy.sourceReadResults.set(2, {
      resourceId: 'id-2',
      kind: 'file',
      path: '/Product/live tests/abac.md',
    })
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    expect(
      await screen.findByText(
        /EvenDrive couldn.t confirm this item.s current version\. Refresh the folder and try again\./
      )
    ).toBeTruthy()
    expect(mockApiSend).not.toHaveBeenCalled()
    expect(screen.queryByText(/Moved "abac\.md"/)).toBeNull()
  })

  it('refuses without a PATCH when the fresh source version is negative', async () => {
    const fixture = breadcrumbTrailFixture()
    fixture.policy.sourceReadResults.set(2, { ...fixture.views['r2']!, version: -1 })
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    expect(await screen.findByText(/couldn.t confirm this item.s current version/)).toBeTruthy()
    expect(mockApiSend).not.toHaveBeenCalled()
  })

  it('refuses without a PATCH when the fresh source kind no longer matches the captured one', async () => {
    const fixture = breadcrumbTrailFixture()
    // The immutable URI now resolves to a directory while the captured
    // source is a file: the read no longer names the captured item.
    fixture.policy.sourceReadResults.set(2, {
      ...fixture.views['r2']!,
      kind: 'directory',
    })
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    expect(
      await screen.findByText(
        'EvenDrive cannot verify this item’s current location. Refresh and try again.'
      )
    ).toBeTruthy()
    expect(mockApiSend).not.toHaveBeenCalled()
  })

  it('keeps same-parent facts captured at drop when a reconstruction lands during root hydration (R7)', async () => {
    const streamControllers: ReadableStreamDefaultController<Uint8Array>[] = []
    const fixture = breadcrumbTrailFixture({ hydrateRoot: false })
    // Park the drop-time root hydration read so the trail can change while
    // the admission awaits.
    fixture.policy.parkTreeReadsFrom = 2
    vi.stubGlobal(
      'fetch',
      vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
        const body = new ReadableStream<Uint8Array>({
          start(controller) {
            streamControllers.push(controller)
            init?.signal?.addEventListener('abort', () => controller.close(), { once: true })
          },
        })
        return new Response(body, {
          status: 200,
          headers: { 'content-type': 'application/x-ndjson' },
        })
      })
    )
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    // Drop onto the (synthetic, unhydrated) root crumb at index 0 of a
    // three-crumb trail: a real upward move, NOT the active crumb.
    const transfer = dragRowOverCrumb(abacRow, crumbButton('main'))
    fireEvent.drop(crumbButton('main'), { dataTransfer: transfer })
    fireEvent.dragEnd(abacRow, { dataTransfer: transfer })

    // While hydration is pending, a remote change removes the current
    // folder's ancestry: the hierarchy refresh collapses the trail to the
    // root alone. Comparing the CAPTURED index (0) against the LIVE active
    // index would now falsely read as same-parent.
    fixture.resolveOverride.uri = 'gfs://main/r3'
    fixture.resolveOverride.result = 'missing'
    const frame = await controlApiProducerFrame()
    await act(async () => {
      streamControllers[0]!.enqueue(new TextEncoder().encode(`${frame}\n`))
    })
    await waitFor(() =>
      expect(within(breadcrumbNav()).queryByRole('button', { name: 'live tests' })).toBeNull()
    )

    fixture.releaseParkedTreeReads()

    // The admission continues from the drop-boundary facts: no false
    // "already in" refusal — the confirmation for the root move appears.
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to main',
    })
    expect(screen.queryByText(/is already in/)).toBeNull()
    void dialog
  })

  it('refreshes the live folder and captured old parent when the operator navigates mid-commit', async () => {
    const fixture = breadcrumbTrailFixture()
    // Park the commit-time SOURCE read so the operator can navigate while
    // the commit is in flight.
    fixture.policy.parkSourceReadFrom = 2
    const { unmount } = renderBrowser()
    void unmount
    await waitFor(() => expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull())
    fireEvent.click((await screen.findAllByRole('button', { name: 'Product' }))[0]!)
    let list = screen.getByRole('list', { name: 'Current folder resources' })
    fireEvent.click(await within(list).findByRole('button', { name: 'live tests', exact: true }))
    await waitFor(() => expect(crumbButton('live tests')).toHaveAttribute('aria-current', 'page'))
    list = screen.getByRole('list', { name: 'Current folder resources' })
    await within(list).findByText('abac.md')
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    const childrenOfOldParentBefore = mockApiGet.mock.calls.filter(
      ([path]) => path === '/api/v1/gfs/resources/id-3/children'
    ).length
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))
    // The commit is parked on its source read; navigate to the drive root.
    fireEvent.click(crumbButton('main'))
    await waitFor(() => expect(crumbButton('main')).toHaveAttribute('aria-current', 'page'))

    fixture.releaseParkedSourceReads(fixture.views['r2']!)

    // The commit completes against the captured destination and the LIVE
    // location refreshes: the operator stays at the root with its rows on
    // screen — never navigated away, never stuck loading.
    await waitFor(() =>
      expect(mockApiSend).toHaveBeenCalledWith(
        'PATCH',
        '/api/v1/gfs/resources/id-2',
        { drive: 'main', newParentId: 'id-1', ifMatch: 5 },
        { drive: 'main' }
      )
    )
    expect(await screen.findByText('Moved "abac.md" to "Product".')).toBeTruthy()
    await waitFor(() => {
      expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull()
      expect(
        within(screen.getByRole('list', { name: 'Current folder resources' })).getByText('Product')
      ).toBeTruthy()
    })
    expect(crumbButton('main')).toHaveAttribute('aria-current', 'page')
    // The OLD source parent's listing was invalidated through the captured
    // drop-boundary parent: re-entering it must re-fetch, not serve cache.
    const childrenOfOldParentAfter = mockApiGet.mock.calls.filter(
      ([path]) => path === '/api/v1/gfs/resources/id-3/children'
    ).length
    expect(childrenOfOldParentAfter).toBeGreaterThanOrEqual(childrenOfOldParentBefore)
    await act(async () => {
      fireEvent.click(
        within(screen.getByRole('list', { name: 'Current folder resources' })).getByRole('button', {
          name: 'Product',
          exact: true,
        })
      )
    })
    await waitFor(() =>
      expect(
        mockApiGet.mock.calls.filter(([path]) => path === '/api/v1/gfs/resources/id-3/children')
          .length
      ).toBeGreaterThan(childrenOfOldParentAfter)
    )
  })

  it('raises the persistent sign-in alert when an admission read comes back 401 (A11)', async () => {
    const fixture = breadcrumbTrailFixture()
    fixture.resolveOverride.uri = 'gfs://main/r1'
    fixture.resolveOverride.result = 'unauthorized'
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    fireEvent.dragEnd(abacRow, { dataTransfer: transfer })

    const alert = await screen.findByRole('alert')
    expect(alert).toHaveTextContent('Your session ended. Sign in again to continue moving files.')
    // Session loss is NOT a connection hiccup: no generic warning toast and
    // no move admission.
    expect(screen.queryByText(/couldn.t verify this move/)).toBeNull()
    expect(mockApiSend).not.toHaveBeenCalled()
    expect(screen.queryByRole('dialog')).toBeNull()
  })

  it('raises the persistent sign-in alert when a commit read comes back 401 (A11)', async () => {
    const fixture = breadcrumbTrailFixture()
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    fixture.resolveOverride.uri = 'gfs://main/r2'
    fixture.resolveOverride.result = 'unauthorized'
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    const alert = await screen.findByRole('alert')
    expect(alert).toHaveTextContent('Your session ended. Sign in again to continue moving files.')
    expect(screen.queryByText(/couldn.t verify this move/)).toBeNull()
    expect(mockApiSend).not.toHaveBeenCalled()
  })

  it('raises the persistent sign-in alert when root hydration comes back 401 (A11)', async () => {
    const fixture = breadcrumbTrailFixture({ hydrateRoot: false })
    fixture.policy.treeUnauthorizedAt = 2
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('main'))
    fireEvent.drop(crumbButton('main'), { dataTransfer: transfer })
    fireEvent.dragEnd(abacRow, { dataTransfer: transfer })

    const alert = await screen.findByRole('alert')
    expect(alert).toHaveTextContent('Your session ended. Sign in again to continue moving files.')
    expect(screen.queryByText(/couldn.t verify this move/)).toBeNull()
    expect(mockApiSend).not.toHaveBeenCalled()
    expect(screen.queryByRole('dialog')).toBeNull()
  })

  it('raises the persistent sign-in alert when the dispatched PATCH itself comes back 401 (A11)', async () => {
    breadcrumbTrailFixture()
    // The API layer already routes PATCH 401s through the global
    // unauthorized handler (throwing AuthExpiredError); a raw 401 status
    // exercises the same classification. Either way: persistent sign-in
    // alert, no transient error toast, no ladder retry.
    mockApiSend.mockImplementation(async () => {
      throw Object.assign(new Error('401 Unauthorized'), { status: 401 })
    })
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    const alert = await screen.findByRole('alert')
    expect(alert).toHaveTextContent('Your session ended. Sign in again to continue moving files.')
    // No generic transient toast for the 401, no unknown-outcome claim, no
    // success claim — and exactly one PATCH (a dead session never retries).
    expect(screen.queryByText(/401/)).toBeNull()
    expect(screen.queryByText(/couldn.t (verify this move|confirm the move)/)).toBeNull()
    expect(screen.queryByText(/Moved "abac\.md"/)).toBeNull()
    await waitFor(() => expect(mockApiSend).toHaveBeenCalledTimes(1))
    await act(async () => {
      await Promise.resolve()
    })
    expect(mockApiSend).toHaveBeenCalledTimes(1)
  })

  it('surfaces session loss alongside an honestly unknown outcome when verification reads 401', async () => {
    const fixture = breadcrumbTrailFixture()
    // The PATCH transport-fails after dispatch, and the session expires
    // before the verification read can answer: the move outcome stays
    // unknown (the PATCH may have landed) while the session loss surfaces
    // through the persistent alert next to the warning toast.
    fixture.policy.sourceReadResults.set(3, 'unauthorized')
    mockApiSend.mockImplementation(async () => {
      throw new TypeError('fetch failed')
    })
    const list = await browseToLiveTests()
    const abacRow = rowOf(list, 'abac.md')

    const transfer = dragRowOverCrumb(abacRow, crumbButton('Product'))
    fireEvent.drop(crumbButton('Product'), { dataTransfer: transfer })
    const dialog = await screen.findByRole('dialog', {
      name: 'Move file abac.md to Product',
    })
    fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))

    const alert = await screen.findByRole('alert')
    expect(alert).toHaveTextContent('Your session ended. Sign in again to continue moving files.')
    expect(
      await screen.findByText(/Couldn.t confirm the move\. Refresh before trying again\./)
    ).toBeTruthy()
    expect(screen.getByText(/confirm the move/).closest('.cu-toast')).toHaveClass(
      'cu-toast--warning'
    )
    // No connection-flavored warning and no repeat PATCH.
    expect(screen.queryByText(/couldn.t verify this move/)).toBeNull()
    expect(mockApiSend).toHaveBeenCalledTimes(1)
  })
})