Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

346 KB
Raw Blame
import type { KnowledgeFsProductPermission } from '@dify/contracts/api/console/knowledge-fs/types.gen'
import type { ComponentProps, ReactElement } from 'react'
import type { Source } from '../../sources/source-models'
import type { DocumentMetadataField } from '../metadata/editor-model'
import type { BackgroundTask, DocumentProcessingTask, LogicalDocument } from '../models'
import {
  zKnowledgeFsBackgroundTaskListResponse,
  zKnowledgeFsLogicalDocumentListResponse,
  zKnowledgeFsSourceListResponse,
} from '@dify/contracts/api/console/knowledge-fs/zod.gen'
import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { consoleQuery } from '@/service/console'
import { createHttpError } from '@/service/http-error'
import { consoleQueryKey } from '@/test/console/operation-hooks'
import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
import { createKnowledgeSpaceFixture, KnowledgeSpaceTestProvider } from '@/test/knowledge-space'
import { QueryTestingAdapter } from '@/test/query-state-testing-adapter'
import { DocumentsPage } from '../page'
import {
  documentSourcesInfiniteOptions,
  documentTasksInfiniteOptions,
  logicalDocumentsInfiniteOptions,
} from '../queries'

vi.mock('../../components/knowledge-model-readiness-banner', () => ({
  KnowledgeModelReadinessBanner: () => null,
}))

// pdf.js needs a real canvas and worker; the documents page owns only the preview URL.
vi.mock('@/app/components/base/file-uploader/pdf-preview', () => ({
  PdfPreview: ({ url }: { url: string }) => (
    <div role="img" aria-label="PDF preview" data-url={url}>
      PDF preview
    </div>
  ),
}))

// Server-side state behind the real Query observers. A repeated first-page read is a refetch and a
// cursor read is the next page, so the refetch/fetchNextPage spies keep their meaning.
const documentsQuery = vi.hoisted(() => ({
  data: undefined as
    | { pages: Array<{ items: LogicalDocument[]; nextCursor?: string }> }
    | undefined,
  error: null as unknown,
  fetchNextPage: vi.fn(),
  hasNextPage: false,
  isFetchNextPageError: false,
  isPending: false,
  refetch: vi.fn(),
}))

const tasksQuery = vi.hoisted(() => ({
  data: undefined as { pages: Array<{ items: BackgroundTask[]; nextCursor?: string }> } | undefined,
  error: null as unknown,
  fetchNextPage: vi.fn(),
  hasNextPage: false,
  isFetchNextPageError: false,
  isPending: false,
  refetch: vi.fn(),
}))

const sourcesQuery = vi.hoisted(() => ({
  data: undefined as { pages: Array<{ items: Source[]; nextCursor?: string }> } | undefined,
  error: null as unknown,
  fetchNextPage: vi.fn(),
  hasNextPage: false,
  isFetchNextPageError: false,
  isPending: false,
  refetch: vi.fn(),
}))

const cancelMutation = vi.hoisted(() => ({ mutateAsync: vi.fn() }))
const retryMutation = vi.hoisted(() => ({ mutateAsync: vi.fn() }))
const reindexMutation = vi.hoisted(() => ({ mutateAsync: vi.fn() }))
const removeDocumentMutation = vi.hoisted(() => vi.fn())
const bulkRemoveDocumentsMutation = vi.hoisted(() => vi.fn())
const renameDocumentMutation = vi.hoisted(() => vi.fn())
const updateLogicalDocumentMutation = vi.hoisted(() => vi.fn())
const bulkUpdateLogicalDocumentsMutation = vi.hoisted(() => vi.fn())
const downloadDocumentMutation = vi.hoisted(() => vi.fn())
const downloadDocumentsMutation = vi.hoisted(() => vi.fn())
const downloadBlobMock = vi.hoisted(() => vi.fn())
const listLogicalDocuments = vi.hoisted(() => vi.fn())
const createMetadataField = vi.hoisted(() => vi.fn())
const renameMetadataField = vi.hoisted(() => vi.fn())
const deleteMetadataField = vi.hoisted(() => vi.fn())
const metadataFieldsQuery = vi.hoisted(() => ({
  data: undefined as DocumentMetadataField[] | undefined,
  error: null as unknown,
  isPending: false,
  refetch: vi.fn(),
}))
const updateSourceMutation = vi.hoisted(() => vi.fn())
const uploadMutation = vi.hoisted(() => ({ mutateAsync: vi.fn() }))
const stageUploadMutation = vi.hoisted(() => vi.fn())
const getUploadQuotaFailure = vi.hoisted(() => vi.fn())
const discardStagedUploadMutation = vi.hoisted(() => vi.fn())
const bulkUploadMutation = vi.hoisted(() => ({ mutateAsync: vi.fn() }))
const streamProcessingTaskEvents = vi.hoisted(() => vi.fn())
const getTaskSnapshot = vi.hoisted(() => vi.fn())
const permissionStateMock = vi.hoisted(() => ({
  datasetKeys: ['dataset.acl.edit'],
  error: null as unknown,
  loading: false,
  refreshAfterDenial: vi.fn(),
  spaceKeys: ['knowledge_space_document_write'] as KnowledgeFsProductPermission[],
}))
const systemFeaturesStateMock = vi.hoisted(() => ({
  deploymentEdition: 'ENTERPRISE' as 'CLOUD' | 'ENTERPRISE',
  uploadEnabled: true,
}))
const uploadPlanMock = vi.hoisted(() => ({ plan: 'professional' as string | undefined }))
const toastMock = vi.hoisted(() => ({
  error: vi.fn(),
  info: vi.fn(),
  success: vi.fn(),
  warning: vi.fn(),
}))
const routerMock = vi.hoisted(() => ({ push: vi.fn() }))
const settingsState = vi.hoisted(() => ({
  configurationState: 'active' as 'active' | 'setup-required',
  refetch: vi.fn(),
}))
const workspacePermissions = vi.hoisted(() => (datasetKeys: string[]) => ({
  agent: { default_permission_keys: [], overrides: [] },
  app: { default_permission_keys: [], overrides: [] },
  dataset: { default_permission_keys: datasetKeys, overrides: [] },
  workspace: { permission_keys: [] },
}))
const server = vi.hoisted(() => ({
  inflight: 0,
  inputs: new Map<string, unknown[]>(),
  reads: new Map<string, number>(),
  // What each resource last answered with, so rerenders refetch only what a test changed.
  served: new Map<string, { data: unknown; error: unknown }>(),
  // Refreshes the test harness issues itself; they are not the page's refetches.
  harnessRefetches: new Set<string>(),
  // Resources whose described pages are already in the cache when the page mounts.
  preloaded: new Set<'documents' | 'sources' | 'tasks'>(),
}))
const revisionApiResponse = vi.hoisted(
  () => (revision: NonNullable<LogicalDocument['active']>) => ({
    activated_at: revision.activatedAt ?? null,
    content_hash: revision.contentHash,
    created_at: revision.createdAt,
    document_asset_id: revision.documentAssetId,
    document_asset_version: revision.documentAssetVersion,
    document_id: revision.documentId,
    knowledge_space_id: revision.knowledgeSpaceId,
    mime_type: revision.mimeType,
    revision: revision.revision,
    size_bytes: revision.sizeBytes,
    state: revision.state,
  }),
)
const taskApiResponse = vi.hoisted(() => (item: BackgroundTask) => ({
  semantic_enrichment: item.semanticEnrichment ?? null,
  can_cancel: item.canCancel ?? true,
  can_retry: item.canRetry ?? item.state === 'failed',
  completed_at: item.completedAt ?? null,
  created_at: item.createdAt,
  document_id: item.documentId ?? null,
  document_title: item.documentTitle ?? null,
  document_revision: item.documentRevision ?? null,
  error_code: item.errorCode ?? null,
  error_message: item.errorMessage ?? null,
  failure: item.failure ?? null,
  id: item.id,
  knowledge_space_id: item.knowledgeSpaceId,
  operation: item.operation ?? 'document_processing',
  progress_completed:
    item.progressCompleted ?? (item.state === 'succeeded' ? (item.progressTotal ?? 1) : 0),
  progress_failed: item.progressFailed ?? 0,
  progress_percent: item.progressPercent,
  progress_total: item.progressTotal ?? 1,
  source_id: item.sourceId ?? null,
  source_title: item.sourceTitle ?? null,
  state:
    item.state === 'succeeded'
      ? 'completed'
      : item.state === 'dispatch_pending'
        ? 'queued'
        : item.state === 'superseded'
          ? 'canceled'
          : item.state,
  task_kind: item.taskKind ?? 'document',
  updated_at: item.updatedAt,
}))
const documentApiResponse = vi.hoisted(() => (item: LogicalDocument) => ({
  active: item.active ? revisionApiResponse(item.active) : null,
  active_revision: item.activeRevision ?? null,
  latest_task: item.latestTask ? taskApiResponse(item.latestTask) : null,
  created_at: item.createdAt,
  disabled_at: item.enabled ? null : item.updatedAt,
  disabled_by_subject_id: item.enabled ? null : 'account-1',
  enabled: item.enabled,
  id: item.id,
  knowledge_space_id: item.knowledgeSpaceId,
  provider_item_id: item.providerItemId ?? null,
  row_version: item.rowVersion,
  source_id: item.sourceId ?? null,
  status: item.status,
  title: item.title,
  updated_at: item.updatedAt,
  user_metadata: item.userMetadata,
}))
const sourceApiResponse = vi.hoisted(() => (item: Source) => ({
  connection_id: item.connectionId ?? null,
  created_at: item.createdAt,
  credential_configured: item.credentialConfigured ?? null,
  id: item.id,
  knowledge_space_id: item.knowledgeSpaceId,
  metadata: item.metadata,
  name: item.name,
  permission_scope: item.permissionScope ?? [],
  status: item.status,
  type: item.type,
  updated_at: item.updatedAt,
  uri: item.uri,
  version: item.version ?? 1,
}))

const metadataFieldApiResponse = vi.hoisted(() => (field: DocumentMetadataField) => ({
  count: field.count,
  created_at: field.createdAt,
  id: field.id,
  name: field.name,
  row_version: field.rowVersion,
  type: field.type,
  updated_at: field.updatedAt,
}))

vi.mock('@/app/components/billing/upgrade-btn', () => ({
  default: ({ labelKey }: { labelKey: string }) => (
    <button type="button">{`billing.${labelKey}`}</button>
  ),
}))
vi.mock('@/app/notifications', () => ({ toast: toastMock }))
vi.mock('@/next/navigation', () => ({
  usePathname: () => '/datasets/new/space-1/documents',
  useRouter: () => routerMock,
}))
// Saving a Blob is a browser download boundary.
vi.mock('@/utils/download', () => ({ downloadBlob: downloadBlobMock }))

vi.mock('@/service/console', async (importOriginal) => {
  const actual = await importOriginal<typeof import('@/service/console')>()
  const { withConsoleClientResponses, withConsoleResponses } =
    await import('@/test/console/service-responses')
  const { documentDisplayStatus } = await import('../model')
  const forever = () => new Promise<never>(() => {})
  const track = async <T,>(read: () => Promise<T> | T) => {
    server.inflight += 1
    try {
      return await read()
    } finally {
      server.inflight -= 1
    }
  }
  const record = (resource: string, input: unknown) =>
    server.inputs.set(resource, [...(server.inputs.get(resource) ?? []), input])
  const repeatRead = (resource: string) => {
    const reads = server.reads.get(resource) ?? 0
    server.reads.set(resource, reads + 1)
    return reads > 0
  }
  type PagedState<Item> = {
    data: { pages: Array<{ items: Item[]; nextCursor?: string }> } | undefined
    error: unknown
    fetchNextPage: (...args: never[]) => unknown
    hasNextPage: boolean
    isFetchNextPageError: boolean
    isPending: boolean
    refetch?: () => unknown
  }
  const paged =
    <Item,>(resource: string, state: PagedState<Item>, toApi: (item: Item) => unknown) =>
    (input: { query?: { cursor?: string; query?: string; status?: string } }) => {
      record(resource, input)
      if (state.isPending || (!state.data && !state.error)) return forever()
      return track(async () => {
        const cursor = input.query?.cursor
        if (cursor) {
          await state.fetchNextPage()
          if (state.isFetchNextPageError) throw new Error(`${resource} next page unavailable`)
        } else {
          const refetch = repeatRead(resource)
          if (refetch && !server.harnessRefetches.delete(resource)) {
            // A refresh the test describes as failed fails this read without changing the state.
            const refreshed: unknown = await state.refetch?.()
            if (
              refreshed &&
              typeof refreshed === 'object' &&
              'error' in refreshed &&
              refreshed.error
            )
              throw refreshed.error
          }
          // Data with an error means cached rows whose latest refresh failed: answer the first
          // read with the rows, and let the follow-up refresh after render fail.
          const failing = state.error && (refetch || !state.data)
          server.served.set(resource, { data: state.data, error: failing ? state.error : null })
          if (failing) throw state.error
        }
        const pages = state.data?.pages ?? []
        const cursorIndex = pages.findIndex((_, i) => i > 0 && pages[i - 1]?.nextCursor === cursor)
        const index = !cursor
          ? 0
          : cursorIndex >= 0
            ? cursorIndex
            : cursor.startsWith('page-')
              ? Number(cursor.slice('page-'.length))
              : pages.length
        // The service filters the collection before applying its cursor. Fixtures describe the
        // available collection; hasNextPage can also model a still-unavailable matching page.
        if (resource === 'documents' && (input.query?.query || input.query?.status)) {
          const names = new Map(
            sourcesQuery.data?.pages.flatMap((page) =>
              page.items.map((item) => [item.id, item.name] as const),
            ) ?? [],
          )
          const matches = (pages.flatMap((page) => page.items) as LogicalDocument[]).filter(
            (item) => {
              if (
                input.query?.status &&
                documentDisplayStatus(item, item.latestTask) !== input.query.status
              )
                return false
              const name = item.sourceId ? names.get(item.sourceId) : undefined
              return `${item.title} ${name ?? item.userMetadata.sourceName ?? ''}`
                .toLowerCase()
                .includes(input.query?.query?.toLowerCase() ?? '')
            },
          )
          const offset = cursor?.startsWith('match-')
            ? Number(cursor.slice(6))
            : cursor
              ? matches.length
              : 0
          return {
            data: matches.slice(offset, offset + 50).map((item) => toApi(item as Item)),
            next_cursor:
              offset + 50 < matches.length
                ? `match-${offset + 50}`
                : state.hasNextPage
                  ? 'unavailable-matches'
                  : null,
          }
        }
        const page = pages[index]
        // A page the test has not described yet is the end of the list.
        if (!page) return { data: [], next_cursor: null }
        // A failing next page implies there is one after the last described page.
        const hasMore =
          index + 1 < pages.length ||
          ((state.hasNextPage || state.isFetchNextPageError) && index === pages.length - 1)
        return {
          data: page.items.map(toApi),
          next_cursor: page.nextCursor ?? (hasMore ? `page-${index + 1}` : null),
        }
      })
    }
  const space = 'knowledgeFs.spaces.byControlSpaceId'
  const settingsResponse = () => {
    const active = settingsState.configurationState === 'active'
    return {
      active_profile_available: active,
      active_profile_revisions: active ? { embedding: 1, retrieval: 1 } : {},
      capabilities: {
        deep: active,
        index: active,
        ingest: active,
        query: active,
        research: active,
        source_sync: active,
      },
      configuration_state: settingsState.configurationState,
      embedding: null,
      issues: [],
      retrieval: null,
      revision: 1,
    }
  }
  return {
    ...actual,
    consoleClient: withConsoleClientResponses(actual.consoleClient, {
      [`${space}.backgroundTasks.byTaskKind.byTaskId.cancel.post`]: async (input: never) =>
        taskApiResponse(await cancelMutation.mutateAsync(input)),
      [`${space}.backgroundTasks.byTaskKind.byTaskId.retry.post`]: async (input: never) =>
        taskApiResponse(await retryMutation.mutateAsync(input)),
      // Exact task lookups: one task is looked up by its identity, a batch with one request.
      [`${space}.backgroundTasks.get`]: async (
        input: { query?: { task_ids?: string } },
        options?: unknown,
      ) => {
        const tasks = tasksQuery.data?.pages.flatMap((page) => page.items) ?? []
        const ids = input.query?.task_ids?.split(',') ?? []
        const snapshots = []
        if (ids.length > 1) {
          const batch = await getTaskSnapshot(input, options)
          snapshots.push(...(Array.isArray(batch) ? batch : batch ? [batch] : []))
        }
        for (const id of ids.length > 1 ? [] : ids) {
          const listed = tasks.find((task) => task.id === id)
          const snapshot = await getTaskSnapshot(
            listed
              ? {
                  params: {
                    documentId: listed.documentId,
                    id: listed.knowledgeSpaceId,
                    taskId: listed.id,
                  },
                }
              : input,
            options,
          )
          snapshots.push(...(Array.isArray(snapshot) ? snapshot : snapshot ? [snapshot] : []))
        }
        return { data: snapshots.map(taskApiResponse), next_cursor: null }
      },
      [`${space}.documents.byDocumentId.patch`]: renameDocumentMutation,
      [`${space}.documents.post`]: (input: never) => uploadMutation.mutateAsync(input),
      [`${space}.logicalDocuments.bulk.delete`]: bulkRemoveDocumentsMutation,
      [`${space}.logicalDocuments.byDocumentId.delete`]: removeDocumentMutation,
      [`${space}.logicalDocuments.byDocumentId.download.get`]: downloadDocumentMutation,
      [`${space}.logicalDocuments.byDocumentId.patch`]: updateLogicalDocumentMutation,
      [`${space}.logicalDocuments.downloadZip.post`]: downloadDocumentsMutation,
      [`${space}.logicalDocuments.get`]: listLogicalDocuments,
      [`${space}.logicalDocuments.patch`]: bulkUpdateLogicalDocumentsMutation,
      [`${space}.metadata.byFieldId.delete`]: deleteMetadataField,
      [`${space}.metadata.byFieldId.patch`]: renameMetadataField,
      [`${space}.metadata.get`]: () =>
        metadataFieldsQuery.isPending
          ? forever()
          : track(async () => {
              if (repeatRead('metadata-fields')) await metadataFieldsQuery.refetch()
              server.served.set('metadata-fields', {
                data: metadataFieldsQuery.data,
                error: metadataFieldsQuery.error,
              })
              if (metadataFieldsQuery.error) throw metadataFieldsQuery.error
              return {
                data: (metadataFieldsQuery.data ?? []).map(metadataFieldApiResponse),
                next_cursor: null,
              }
            }),
      [`${space}.metadata.post`]: createMetadataField,
      [`${space}.sources.bySourceId.patch`]: updateSourceMutation,
    }),
    consoleQuery: withConsoleResponses(actual.consoleQuery, {
      'features.get': () =>
        track(() => ({ billing: { subscription: { plan: uploadPlanMock.plan } } })),
      [`${space}.backgroundTasks.get`]: paged('tasks', tasksQuery, taskApiResponse),
      [`${space}.documents.reindex.post`]: async (input: never) => {
        const result = await reindexMutation.mutateAsync(input)
        return {
          ...result,
          items: result.items.map((item: { documentId?: string; document_id?: string }) => ({
            ...item,
            document_id: item.document_id ?? item.documentId ?? null,
          })),
        }
      },
      [`${space}.logicalDocuments.get`]: paged('documents', documentsQuery, documentApiResponse),
      [`${space}.settings.get`]: () =>
        track(async () => {
          if (repeatRead('settings')) {
            const refreshed = await settingsState.refetch()
            if (refreshed?.isError) throw new Error('settings refresh failed')
          }
          server.served.set('settings', { data: settingsState.configurationState, error: null })
          return settingsResponse()
        }),
      [`${space}.sources.get`]: paged('sources', sourcesQuery, sourceApiResponse),
      'workspaces.current.rbac.myPermissions.get': () =>
        permissionStateMock.loading
          ? forever()
          : track(async () => {
              const refreshed = repeatRead('permissions')
                ? await permissionStateMock.refreshAfterDenial()
                : undefined
              server.served.set('permissions', {
                data: permissionStateMock.datasetKeys,
                error: permissionStateMock.error,
              })
              if (permissionStateMock.error) throw permissionStateMock.error
              return workspacePermissions(
                refreshed?.data?.dataset?.default_permission_keys ??
                  permissionStateMock.datasetKeys,
              )
            }),
    }),
  }
})

// The SSE stream is the browser transport boundary for task progress; it has its own suite.
vi.mock('../tasks/events', () => ({ streamProcessingTaskEvents }))
vi.mock('../../upload/quota', () => ({
  getKnowledgeFsUploadQuotaFailure: getUploadQuotaFailure,
}))
vi.mock('../../upload/knowledge-fs-upload', async (importOriginal) => ({
  ...(await importOriginal<typeof import('../../upload/knowledge-fs-upload')>()),
  discardKnowledgeFsStagedUpload: discardStagedUploadMutation,
  stageKnowledgeFsDocument: async (file: File, signal?: AbortSignal) => {
    const result = await stageUploadMutation({ body: { file } }, { signal })
    return result.id
  },
}))

let queryClient = createConsoleQueryClient()

/** Waits until no request is in flight, including requests that depend on earlier responses. */
async function settle() {
  // Under fake timers only zero-delay work runs, so scenarios keep full control of their clock.
  for (let turns = 0, quiet = 0; turns < 400 && quiet < 2; turns += 1) {
    if (vi.isFakeTimers()) await act(() => vi.advanceTimersByTimeAsync(0))
    else await act(() => new Promise((resolve) => setTimeout(resolve, 0)))
    quiet = server.inflight === 0 ? quiet + 1 : 0
  }
}

/** Lets mounted queries observe the current server state, as a background refetch would. */
async function refetchAll() {
  // Requests the test deliberately leaves pending never settle, so do not await the refetch itself.
  // Refetch rather than invalidate so tests can still assert the page's own invalidations.
  act(() => {
    void queryClient.refetchQueries({
      queryKey: consoleQuery.knowledgeFs.spaces.key(),
      type: 'active',
    })
  })
  await settle()
}

/** Refetches only the resources whose server state a test changed since they were last read. */
async function refetchChanged() {
  const space = consoleQuery.knowledgeFs.spaces.byControlSpaceId
  const resources = [
    ['documents', documentsQuery.data, documentsQuery.error, space.logicalDocuments.get.key()],
    ['tasks', tasksQuery.data, tasksQuery.error, space.backgroundTasks.get.key()],
    ['sources', sourcesQuery.data, sourcesQuery.error, space.sources.get.key()],
    [
      'metadata-fields',
      metadataFieldsQuery.data,
      metadataFieldsQuery.error,
      space.metadata.get.key(),
    ],
    ['settings', settingsState.configurationState, null, space.settings.get.key()],
    [
      'permissions',
      permissionStateMock.datasetKeys,
      permissionStateMock.error,
      consoleQueryKey('workspaces.current.rbac.myPermissions.get'),
    ],
  ] as const
  act(() => {
    for (const [resource, data, error, queryKey] of resources) {
      const served = server.served.get(resource)
      if (served && served.data === data && served.error === error) continue
      server.harnessRefetches.add(resource)
      void queryClient.refetchQueries({ queryKey, type: 'active' })
    }
  })
  await settle()
}

/** A background refresh of the task list, as task polling would issue. */
async function notifyTaskQuerySuccess() {
  server.harnessRefetches.add('tasks')
  act(() => {
    void queryClient.refetchQueries({
      queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.backgroundTasks.get.key(),
      type: 'active',
    })
  })
  await settle()
}

const lastInput = (resource: string) => server.inputs.get(resource)?.at(-1)

const goldenQuestionsKey = (spaceId: string) =>
  consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.get.queryKey({
    input: { params: { control_space_id: spaceId } },
  })

/** Seeds Quality's golden questions for this and another space; document edits affect only this one. */
function seedGoldenQuestions() {
  for (const spaceId of ['space-1', 'space-2'])
    queryClient.setQueryData(goldenQuestionsKey(spaceId), { data: [], next_cursor: null })
}

/** Caches every described page of a list, as if the user had already paged through them. */
function preload(...resources: Array<'documents' | 'sources' | 'tasks'>) {
  for (const resource of resources) server.preloaded.add(resource)
}

function seedPreloadedPages() {
  const cursorPages = <Item, Page>(
    state: {
      data: { pages: Array<{ items: Item[] }> } | undefined
      hasNextPage: boolean
      isFetchNextPageError: boolean
    },
    toPage: (page: { data: Item[]; next_cursor: string | null }) => Page,
  ) => {
    const pages = state.data?.pages ?? []
    const hasMore = state.hasNextPage || state.isFetchNextPageError
    return {
      // Generated cursors keep each loaded page distinct; the next cursor is past the described pages.
      pageParams: pages.map((_, index) => (index ? `page-${index}` : null)),
      pages: pages.map((page, index) =>
        toPage({
          data: page.items,
          next_cursor: index + 1 < pages.length || hasMore ? `page-${index + 1}` : null,
        }),
      ),
    }
  }
  if (server.preloaded.has('documents')) {
    queryClient.setQueryData(
      logicalDocumentsInfiniteOptions('space-1').queryKey,
      cursorPages(documentsQuery, (page) =>
        zKnowledgeFsLogicalDocumentListResponse.parse({
          ...page,
          data: page.data.map(documentApiResponse),
        }),
      ),
    )
    server.served.set('documents', { data: documentsQuery.data, error: null })
  }
  if (server.preloaded.has('tasks')) {
    queryClient.setQueryData(
      documentTasksInfiniteOptions('space-1', { enabled: true }).queryKey,
      cursorPages(tasksQuery, (page) =>
        zKnowledgeFsBackgroundTaskListResponse.parse({
          ...page,
          data: page.data.map(taskApiResponse),
        }),
      ),
    )
    server.served.set('tasks', { data: tasksQuery.data, error: null })
  }
  if (server.preloaded.has('sources')) {
    queryClient.setQueryData(
      documentSourcesInfiniteOptions('space-1', { enabled: true }).queryKey,
      cursorPages(sourcesQuery, (page) =>
        zKnowledgeFsSourceListResponse.parse({ ...page, data: page.data.map(sourceApiResponse) }),
      ),
    )
    server.served.set('sources', { data: sourcesQuery.data, error: null })
  }
}

type RenderOptions = {
  onUrlUpdate?: ComponentProps<typeof QueryTestingAdapter>['onUrlUpdate']
  searchParams?: string
  settle?: boolean
}

async function render(ui: ReactElement, options: RenderOptions = {}) {
  const onUrlUpdate = vi.fn<NonNullable<RenderOptions['onUrlUpdate']>>(options.onUrlUpdate)
  queryClient = createConsoleQueryClient()
  queryClient.setDefaultOptions({
    ...queryClient.getDefaultOptions(),
    queries: { ...queryClient.getDefaultOptions().queries, retryDelay: 0 },
  })
  queryClient.setQueryData(
    consoleQueryKey('workspaces.current.rbac.myPermissions.get'),
    permissionStateMock.loading || permissionStateMock.error
      ? undefined
      : workspacePermissions(permissionStateMock.datasetKeys),
  )
  if (!permissionStateMock.loading && !permissionStateMock.error)
    server.served.set('permissions', { data: permissionStateMock.datasetKeys, error: null })
  seedPreloadedPages()
  // Mutation flows await these invalidations, so keep the real behavior and observe the calls.
  vi.spyOn(queryClient, 'invalidateQueries')
  const refetchSpace = async () => {
    const result = await permissionStateMock.refreshAfterDenial()
    const legacyKeys = result?.data?.dataset?.default_permission_keys
    return createKnowledgeSpaceFixture({
      permission_keys: legacyKeys
        ? legacyKeys.includes('dataset.acl.edit')
          ? ['knowledge_space_document_write']
          : []
        : permissionStateMock.spaceKeys,
    })
  }
  const withProviders = (content: ReactElement) => (
    <QueryTestingAdapter searchParams={options.searchParams} onUrlUpdate={onUrlUpdate}>
      <KnowledgeSpaceTestProvider
        refetch={refetchSpace}
        space={createKnowledgeSpaceFixture({ permission_keys: permissionStateMock.spaceKeys })}
      >
        {content}
      </KnowledgeSpaceTestProvider>
    </QueryTestingAdapter>
  )
  const rendered = renderWithConsoleQuery(withProviders(ui), {
    knowledgeFsFeatures: { upload_enabled: systemFeaturesStateMock.uploadEnabled },
    queryClient,
    systemFeatures: { deployment_edition: systemFeaturesStateMock.deploymentEdition },
  })
  if (options.settle !== false) {
    await settle()
    await refetchChanged()
  }
  return {
    ...rendered,
    onUrlUpdate,
    async rerender(nextUi: ReactElement) {
      rendered.rerender(withProviders(nextUi))
      await refetchChanged()
    },
  }
}

const document = (overrides: Partial<LogicalDocument> = {}): LogicalDocument => ({
  active: {
    activatedAt: '2026-07-20T10:01:00Z',
    contentHash: 'hash',
    createdAt: '2026-07-20T10:00:00Z',
    documentAssetId: 'asset-1',
    documentAssetVersion: 1,
    documentId: 'document-1',
    knowledgeSpaceId: 'space-1',
    mimeType: 'application/pdf',
    revision: 2,
    sizeBytes: 1024,
    state: 'active',
  },
  activeRevision: 2,
  createdAt: '2026-07-20T10:00:00Z',
  enabled: true,
  id: 'document-1',
  knowledgeSpaceId: 'space-1',
  rowVersion: 1,
  sourceId: 'source-1',
  status: 'ready',
  title: 'sso-enterprise.pdf',
  updatedAt: '2026-07-20T10:01:00Z',
  userMetadata: { sourceName: 'Notion support SOP' },
  ...overrides,
})

const metadataField = (overrides: Partial<DocumentMetadataField> = {}): DocumentMetadataField => ({
  count: 1,
  createdAt: '2026-08-10T10:00:00Z',
  id: 'metadata-field-1',
  name: 'category',
  rowVersion: 0,
  type: 'string',
  updatedAt: '2026-08-10T10:00:00Z',
  ...overrides,
})

const task = (overrides: Partial<DocumentProcessingTask> = {}): DocumentProcessingTask => ({
  createdAt: '2026-07-20T10:00:00Z',
  documentId: 'document-1',
  documentRevision: 2,
  id: 'task-1',
  knowledgeSpaceId: 'space-1',
  operation: 'document_processing',
  progressPercent: 45,
  stage: 'parsed',
  state: 'running',
  taskKind: 'document',
  updatedAt: '2026-07-20T10:01:00Z',
  ...overrides,
})

const backgroundTask = (overrides: Partial<BackgroundTask> = {}): BackgroundTask => ({
  createdAt: '2026-07-20T10:00:00Z',
  id: 'background-task-1',
  knowledgeSpaceId: 'space-1',
  operation: 'document_reindex',
  progressPercent: 100,
  stage: 'published',
  state: 'succeeded',
  taskKind: 'document_bulk',
  updatedAt: '2026-07-20T10:01:00Z',
  ...overrides,
})

function streamFailedTaskThenWait(taskId: string) {
  let streamCount = 0
  streamProcessingTaskEvents.mockImplementation(async function* () {
    streamCount += 1
    if (streamCount === 1) {
      yield {
        data: {
          progressPercent: 80,
          stage: 'parsed' as const,
          state: 'failed' as const,
          updatedAt: '2026-07-20T10:03:00Z',
        },
        event: 'progress' as const,
        id: `${taskId}:2026-07-20T10:03:00Z`,
      }
      yield {
        data: { errorCode: 'PARSER_FAILED', state: 'failed' as const },
        event: 'terminal' as const,
        id: `${taskId}:terminal`,
      }
      return
    }
    await new Promise<void>(() => {})
  })
}

const source = (overrides: Partial<Source> = {}): Source => ({
  createdAt: '2026-07-20T10:00:00Z',
  id: 'source-1',
  knowledgeSpaceId: 'space-1',
  metadata: {},
  name: 'Notion support SOP',
  status: 'active',
  type: 'connector',
  updatedAt: '2026-07-20T10:00:00Z',
  uri: 'notion://support',
  ...overrides,
})

function openTasksDrawer() {
  fireEvent.click(
    screen.getByRole('button', {
      name: /knowledgeDocuments\.tasksWithAttention/,
    }),
  )
}

async function waitForDocumentFilesStaged() {
  await waitFor(() =>
    expect(screen.queryByText('knowledgeCreate.uploadingFiles')).not.toBeInTheDocument(),
  )
}

describe('DocumentsPage', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    server.inflight = 0
    server.inputs.clear()
    server.reads.clear()
    server.served.clear()
    server.harnessRefetches.clear()
    server.preloaded.clear()
    documentsQuery.refetch.mockReset()
    documentsQuery.fetchNextPage.mockReset()
    tasksQuery.refetch.mockReset()
    tasksQuery.fetchNextPage.mockReset()
    sourcesQuery.refetch.mockReset()
    sourcesQuery.fetchNextPage.mockReset()
    getTaskSnapshot.mockReset()
    uploadPlanMock.plan = 'professional'
    systemFeaturesStateMock.uploadEnabled = true
    systemFeaturesStateMock.deploymentEdition = 'ENTERPRISE'
    getUploadQuotaFailure.mockReset().mockResolvedValue(undefined)
    settingsState.configurationState = 'active'
    settingsState.refetch.mockImplementation(async () => ({
      data: {
        active_profile_available: settingsState.configurationState === 'active',
        active_profile_revisions:
          settingsState.configurationState === 'active' ? { embedding: 1, retrieval: 1 } : {},
        capabilities: {
          deep: settingsState.configurationState === 'active',
          index: settingsState.configurationState === 'active',
          ingest: settingsState.configurationState === 'active',
          query: settingsState.configurationState === 'active',
          research: settingsState.configurationState === 'active',
          source_sync: settingsState.configurationState === 'active',
        },
        configuration_state: settingsState.configurationState,
        embedding: null,
        issues: [],
        retrieval: null,
        revision: 1,
      },
      isError: false,
    }))
    documentsQuery.data = { pages: [{ items: [] }] }
    documentsQuery.error = null
    documentsQuery.hasNextPage = false
    documentsQuery.isFetchNextPageError = false
    documentsQuery.isPending = false
    documentsQuery.refetch.mockResolvedValue({ error: null })
    metadataFieldsQuery.data = []
    metadataFieldsQuery.error = null
    metadataFieldsQuery.isPending = false
    metadataFieldsQuery.refetch.mockResolvedValue({ data: [], error: null })
    tasksQuery.data = { pages: [{ items: [] }] }
    tasksQuery.error = null
    tasksQuery.hasNextPage = false
    tasksQuery.isFetchNextPageError = false
    tasksQuery.isPending = false
    tasksQuery.refetch.mockResolvedValue({ error: null })
    sourcesQuery.data = { pages: [{ items: [source()] }] }
    sourcesQuery.error = null
    sourcesQuery.hasNextPage = false
    sourcesQuery.isFetchNextPageError = false
    sourcesQuery.isPending = false
    sourcesQuery.refetch.mockResolvedValue({ error: null })
    permissionStateMock.datasetKeys = ['dataset.acl.edit', 'dataset.acl.document_download']
    permissionStateMock.spaceKeys = ['knowledge_space_document_write']
    permissionStateMock.error = null
    permissionStateMock.loading = false
    permissionStateMock.refreshAfterDenial.mockResolvedValue({
      data: {
        dataset: {
          default_permission_keys: ['dataset.acl.edit', 'dataset.acl.document_download'],
        },
      },
      error: null,
    })
    downloadDocumentMutation.mockResolvedValue(new Blob(['document']))
    downloadDocumentsMutation.mockResolvedValue(
      new Blob(['documents'], { type: 'application/zip' }),
    )
    getTaskSnapshot.mockResolvedValue(task({ state: 'succeeded' }))
    cancelMutation.mutateAsync.mockResolvedValue(task({ state: 'canceled' }))
    retryMutation.mutateAsync.mockResolvedValue(task({ state: 'queued' }))
    reindexMutation.mutateAsync.mockResolvedValue({
      bulkJobId: 'reindex-1',
      items: [
        {
          asset: {
            createdAt: '2026-07-20T10:00:00Z',
            filename: 'one.pdf',
            id: 'asset-1',
            knowledgeSpaceId: 'space-1',
            mimeType: 'application/pdf',
            objectKey: 'documents/one.pdf',
            parserStatus: 'pending',
            sha256: 'sha',
            sizeBytes: 1024,
            version: 1,
          },
          compilationJob: { id: 'job-1', stage: 'queued' },
          status: 'queued',
          statusUrl: '/tasks/job-1',
        },
      ],
      total: 1,
    })
    removeDocumentMutation.mockResolvedValue({
      job: { id: 'delete-1', state: 'accepted' },
      status_url: '/delete-1',
    })
    bulkRemoveDocumentsMutation.mockResolvedValue({ items: [], total: 2 })
    listLogicalDocuments.mockImplementation(async () => ({
      data: (documentsQuery.data?.pages.flatMap((page) => page.items) ?? []).map(
        documentApiResponse,
      ),
      next_cursor: null,
    }))
    createMetadataField.mockResolvedValue({
      count: 0,
      created_at: '2026-08-10T10:00:00Z',
      id: 'metadata-field-1',
      name: 'category',
      row_version: 0,
      type: 'string',
      updated_at: '2026-08-10T10:00:00Z',
    })
    renameMetadataField.mockResolvedValue({
      count: 1,
      created_at: '2026-08-10T10:00:00Z',
      id: 'metadata-field-1',
      name: 'topic',
      row_version: 1,
      type: 'string',
      updated_at: '2026-08-10T10:01:00Z',
    })
    deleteMetadataField.mockResolvedValue({ deleted: true })
    renameDocumentMutation.mockImplementation(
      async ({ body }: { body: { patch: Record<string, unknown> } }) => {
        const userMetadata = { ...document().userMetadata }
        for (const [name, value] of Object.entries(body.patch)) {
          if (value === null) delete userMetadata[name]
          else userMetadata[name] = value
        }
        return documentApiResponse(document({ rowVersion: 2, userMetadata }))
      },
    )
    updateLogicalDocumentMutation.mockImplementation(
      async ({ body }: { body: { enabled: boolean } }) =>
        documentApiResponse(document({ enabled: body.enabled, rowVersion: 2 })),
    )
    bulkUpdateLogicalDocumentsMutation.mockImplementation(
      async ({
        body,
      }: {
        body: { documents: Array<{ documentId: string }>; enabled: boolean }
      }) => ({
        items: body.documents.map(({ documentId }) =>
          documentApiResponse(document({ enabled: body.enabled, id: documentId, rowVersion: 2 })),
        ),
        total: body.documents.length,
      }),
    )
    updateSourceMutation.mockImplementation(
      async ({ body }: { body: { status: Source['status'] } }) =>
        sourceApiResponse(source({ status: body.status, version: 2 })),
    )
    uploadMutation.mutateAsync.mockResolvedValue({
      asset: {
        createdAt: '2026-07-20T10:00:00Z',
        filename: 'one.md',
        id: 'asset-1',
        knowledgeSpaceId: 'space-1',
        mimeType: 'text/markdown',
        objectKey: 'documents/one.md',
        parserStatus: 'pending',
        sha256: 'sha',
        sizeBytes: 3,
        version: 1,
      },
      compilationJob: { id: 'job-1', stage: 'queued' },
      documentRevision: 1,
      logicalDocument: { id: 'document-1', revision: 1 },
      logicalDocumentId: 'document-1',
      statusUrl: '/tasks/job-1',
    })
    stageUploadMutation.mockImplementation(({ body }: { body: { file: File } }) =>
      Promise.resolve({ id: `staged-${body.file.name}` }),
    )
    discardStagedUploadMutation.mockResolvedValue(undefined)
    bulkUploadMutation.mutateAsync.mockResolvedValue({
      accepted: 2,
      bulkJobId: 'upload-1',
      excluded: 0,
      items: [],
      total: 2,
    })
    streamProcessingTaskEvents.mockImplementation(async function* () {})
  })

  it('loads logical documents for the routed knowledge space', async () => {
    documentsQuery.isPending = true

    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { settle: false })

    expect(await screen.findByRole('progressbar', { name: 'common.loading' })).toBeInTheDocument()
    expect(lastInput('documents')).toEqual({ params: { control_space_id: 'space-1' }, query: {} })
  })

  it('restores document search and status filters from the URL', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({ id: 'ready-document', title: 'Ready handbook.pdf' }),
            document({
              id: 'failed-document',
              title: 'Failed report.pdf',
              latestTask: task({
                documentId: 'failed-document',
                id: 'failed-task',
                state: 'failed',
              }),
            }),
          ],
        },
      ],
    }
    tasksQuery.data = {
      pages: [
        {
          items: [task({ documentId: 'failed-document', id: 'failed-task', state: 'failed' })],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />, {
      searchParams: '?query=report&status=failed',
    })

    const metadata = screen.getByRole('button', { name: 'knowledgeSpace.metadata' })
    expect(metadata).toBeEnabled()
    await user.click(metadata)
    expect(
      await screen.findByRole('heading', { name: 'dataset.metadata.metadata' }),
    ).toBeInTheDocument()
    expect(
      screen.getByRole('button', {
        name: 'dataset.metadata.datasetMetadata.addMetaData',
      }),
    ).toBeEnabled()
    expect(screen.queryByText('sourceName')).not.toBeInTheDocument()
    expect(screen.queryByText('document_name')).not.toBeInTheDocument()
    expect(screen.queryByText('uploader')).not.toBeInTheDocument()
    expect(screen.queryByText('upload_date')).not.toBeInTheDocument()
    expect(screen.queryByText('last_update_date')).not.toBeInTheDocument()
    expect(screen.queryByText('source')).not.toBeInTheDocument()
    await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
    await waitFor(() => {
      expect(
        screen.queryByRole('heading', { name: 'dataset.metadata.metadata' }),
      ).not.toBeInTheDocument()
    })
    const rowActions = screen.getByRole('button', {
      name: /knowledgeDocuments\.documentActions/,
    })
    expect(rowActions).toBeEnabled()
    await user.click(rowActions)
    const rowMenuItems = await screen.findAllByRole('menuitem')
    expect(rowMenuItems).toHaveLength(4)
    expect(rowMenuItems.map((item) => item.textContent)).toEqual([
      'common.operation.rename',
      'knowledgeSpace.retryTask',
      'knowledgeDocuments.downloadDocuments',
      'common.operation.delete',
    ])
    expect(rowMenuItems[2]).not.toHaveAttribute('aria-disabled', 'true')

    expect(screen.getByRole('searchbox')).toHaveValue('report')
    expect(screen.getByRole('combobox')).toHaveTextContent('knowledgeSpace.documentStatus.failed')
    expect(screen.getByText('Failed report.pdf')).toBeInTheDocument()
    expect(screen.queryByText('Ready handbook.pdf')).not.toBeInTheDocument()
  })

  it('keeps published text ready and retries only its failed graph task', async () => {
    const user = userEvent.setup()
    const latestTask = task({
      state: 'succeeded',
      canCancel: false,
      canRetry: true,
      semanticEnrichment: { state: 'failed', nodes_completed: 0 },
    })
    documentsQuery.data = { pages: [{ items: [document({ latestTask })] }] }
    tasksQuery.data = { pages: [{ items: [latestTask] }] }
    retryMutation.mutateAsync.mockResolvedValue({
      ...latestTask,
      canRetry: false,
      semanticEnrichment: { state: 'pending', nodes_completed: 0 },
    })
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(screen.getByText('knowledgeSpace.documentStatus.ready')).toBeInTheDocument()
    expect(screen.getByText('knowledgeTasks.graphRepairFailed')).toBeInTheDocument()
    await user.click(
      screen.getByRole('button', { name: 'knowledgeDocuments.tasksWithAttention:{"count":1}' }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeTasks.graphRepairRetry' }))
    expect(retryMutation.mutateAsync).toHaveBeenCalled()
    expect(await screen.findAllByText('knowledgeTasks.graphRepairPending')).not.toHaveLength(0)
    expect(
      screen.queryByRole('button', { name: 'knowledgeTasks.graphRepairRetry' }),
    ).not.toBeInTheDocument()
    expect(
      screen.queryByRole('button', { name: 'knowledgeTasks.interruptTask' }),
    ).not.toBeInTheDocument()
    expect(screen.getByText('knowledgeSpace.documentStatus.ready')).toBeInTheDocument()
  })

  it('reveals the latest document task failure reason from the failed status', async () => {
    const user = userEvent.setup()
    const latestTask = task({
      documentId: 'failed-document',
      failure: {
        action: 'configure_model',
        category: 'configuration',
        code: 'MODEL_SELECTION_NOT_FOUND',
        message: 'Select another model.',
        retryPolicy: 'after_configuration',
      },
      id: 'failed-task',
      state: 'failed',
    })
    documentsQuery.data = {
      pages: [
        { items: [document({ id: 'failed-document', title: 'Failed report.pdf', latestTask })] },
      ],
    }
    tasksQuery.data = {
      pages: [
        {
          items: [latestTask],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    const failedStatus = screen.getByRole('button', {
      name: 'knowledgeSpace.documentStatus.failed: knowledgeErrors.taskFailure.modelConfiguration',
    })
    expect(screen.queryByText('knowledgeErrors.taskFailure.modelConfiguration')).toBeNull()

    await user.hover(failedStatus)

    expect(
      await screen.findByText('knowledgeErrors.taskFailure.modelConfiguration'),
    ).toBeInTheDocument()
  })

  it('shows actionable task failures without technical identifiers', async () => {
    const user = userEvent.setup()
    const latestTask = task({
      documentId: 'failed-document',
      failure: {
        action: 'contact_admin',
        category: 'internal',
        code: 'DOCUMENT_COMPILATION_FAILED',
        message: 'Safe server fallback',
        retryPolicy: 'manual',
        traceId: 'cef52296-3aa7-41ec-9953-2bbe030fdf6c',
      },
      id: 'failed-task',
      state: 'failed',
    })
    documentsQuery.data = {
      pages: [
        { items: [document({ id: 'failed-document', title: 'Failed report.pdf', latestTask })] },
      ],
    }
    tasksQuery.data = {
      pages: [
        {
          items: [latestTask],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    const failedStatus = screen.getByRole('button', {
      name: 'knowledgeSpace.documentStatus.failed: knowledgeErrors.taskFailure.documentProcessing',
    })
    await user.hover(failedStatus)
    expect(
      await screen.findByText('knowledgeErrors.taskFailure.documentProcessing'),
    ).toBeInTheDocument()
    expect(screen.queryByText('cef52296-3aa7-41ec-9953-2bbe030fdf6c')).not.toBeInTheDocument()

    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )

    const panel = screen.getByRole('dialog', { name: 'knowledgeSpace.backgroundTasks' })
    expect(
      within(panel).getByText('knowledgeErrors.taskFailure.documentProcessing'),
    ).toBeInTheDocument()
    expect(within(panel).queryByText('DOCUMENT_COMPILATION_FAILED')).not.toBeInTheDocument()
    expect(
      within(panel).queryByRole('button', {
        name: 'knowledgeErrors.taskFailure.technicalDetails',
      }),
    ).not.toBeInTheDocument()
    expect(
      within(panel).queryByText('cef52296-3aa7-41ec-9953-2bbe030fdf6c'),
    ).not.toBeInTheDocument()
  })

  it('downloads the active revision from the document action menu', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [{ items: [document({ id: 'report', title: 'Report.pdf' })] }],
    }
    const file = new File(['report'], 'source-report.md', { type: 'text/markdown' })
    downloadDocumentMutation.mockResolvedValue(file)

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
    await user.click(screen.getByRole('menuitem', { name: 'knowledgeDocuments.downloadDocuments' }))

    expect(downloadDocumentMutation).toHaveBeenCalledWith(
      {
        params: { control_space_id: 'space-1', document_id: 'report' },
      },
      { context: { silent: true } },
    )
    expect(downloadBlobMock).toHaveBeenCalledWith({ data: file, fileName: 'source-report.md' })
  })

  it('downloads a failed document without an active revision from the document action menu', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({
              active: null,
              activeRevision: undefined,
              id: 'failed-report',
              status: 'failed',
              title: 'Failed report.pdf',
            }),
          ],
        },
      ],
    }
    tasksQuery.data = {
      pages: [
        {
          items: [task({ documentId: 'failed-report', documentRevision: 1, state: 'failed' })],
        },
      ],
    }
    const file = new File(['failed report'], 'failed-report.pdf', { type: 'application/pdf' })
    downloadDocumentMutation.mockResolvedValue(file)

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
    const download = await screen.findByRole('menuitem', {
      name: 'knowledgeDocuments.downloadDocuments',
    })
    expect(download).toBeEnabled()
    await user.click(download)

    expect(downloadDocumentMutation).toHaveBeenCalledWith(
      {
        params: { control_space_id: 'space-1', document_id: 'failed-report' },
      },
      { context: { silent: true } },
    )
    expect(downloadBlobMock).toHaveBeenCalledWith({ data: file, fileName: 'failed-report.pdf' })
  })

  it('keeps downloads disabled when a pending document is displayed as failed by a canceled task', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({
              active: null,
              activeRevision: undefined,
              id: 'canceled-report',
              status: 'pending',
              title: 'Canceled report.pdf',
            }),
          ],
        },
      ],
    }
    tasksQuery.data = {
      pages: [
        {
          items: [task({ documentId: 'canceled-report', documentRevision: 1, state: 'canceled' })],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'Canceled report.pdf' }))
    const bulkActions = screen.getByRole('group', {
      name: 'knowledgeDocuments.bulkDocumentActions',
    })
    expect(
      within(bulkActions).getByRole('button', {
        name: 'knowledgeDocuments.downloadDocuments',
      }),
    ).toBeDisabled()

    await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
    expect(
      await screen.findByRole('menuitem', {
        name: 'knowledgeDocuments.downloadDocuments',
      }),
    ).toHaveAttribute('aria-disabled', 'true')
    expect(downloadDocumentMutation).not.toHaveBeenCalled()
    expect(downloadDocumentsMutation).not.toHaveBeenCalled()
  })

  it('keeps downloads available from the document snapshot while task history loads', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [{ items: [document({ latestTask: task({ state: 'succeeded' }) })] }],
    }
    tasksQuery.data = undefined
    tasksQuery.isPending = true
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' }))
    expect(
      screen.getByRole('button', { name: 'knowledgeDocuments.downloadDocuments' }),
    ).toBeEnabled()
    await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
    expect(
      await screen.findByRole('menuitem', { name: 'knowledgeDocuments.downloadDocuments' }),
    ).not.toHaveAttribute('aria-disabled', 'true')
  })

  it('creates a metadata field without scanning or rewriting documents', async () => {
    const user = userEvent.setup()

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.metadata' }))
    await user.click(
      await screen.findByRole('button', {
        name: 'dataset.metadata.datasetMetadata.addMetaData',
      }),
    )
    await user.type(
      screen.getByRole('textbox', { name: 'dataset.metadata.createMetadata.name' }),
      'category',
    )
    await user.click(screen.getByRole('button', { name: 'common.operation.save' }))

    expect(createMetadataField).toHaveBeenCalledOnce()
    expect(createMetadataField).toHaveBeenCalledWith(
      { body: { name: 'category', type: 'string' }, params: { control_space_id: 'space-1' } },
      { context: { silent: true } },
    )
    expect(listLogicalDocuments).not.toHaveBeenCalled()
    expect(renameDocumentMutation).not.toHaveBeenCalled()
    await waitFor(() =>
      expect(
        screen.queryByRole('textbox', { name: 'dataset.metadata.createMetadata.name' }),
      ).not.toBeInTheDocument(),
    )
  })

  it('keeps metadata creation open when the field request fails', async () => {
    const user = userEvent.setup()
    createMetadataField.mockRejectedValueOnce(new Error('conflict'))

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.metadata' }))
    await user.click(
      await screen.findByRole('button', {
        name: 'dataset.metadata.datasetMetadata.addMetaData',
      }),
    )
    const nameInput = screen.getByRole('textbox', {
      name: 'dataset.metadata.createMetadata.name',
    })
    await user.type(nameInput, 'category')
    await user.keyboard('{Enter}')

    await waitFor(() => expect(toastMock.error).toHaveBeenCalled())
    expect(nameInput).toBeInTheDocument()
    expect(createMetadataField).toHaveBeenCalledOnce()
    expect(renameDocumentMutation).not.toHaveBeenCalled()
  })

  it('disables metadata creation until the field catalog query completes', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [{ items: [document({ id: 'one', title: 'One.pdf' })] }],
    }
    metadataFieldsQuery.isPending = true

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.metadata' }))

    expect(
      await screen.findByRole('button', {
        name: 'dataset.metadata.datasetMetadata.addMetaData',
      }),
    ).toBeDisabled()
  })

  it('lets users retry when the metadata field query fails', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [{ items: [document({ id: 'one', title: 'One.pdf' })] }],
    }
    metadataFieldsQuery.error = new Error('metadata query failed')

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.metadata' }))
    expect(
      await screen.findByText('knowledgeCitation.documentLoadErrorDescription'),
    ).toBeInTheDocument()

    await user.click(screen.getByRole('button', { name: 'common.operation.retry' }))

    expect(metadataFieldsQuery.refetch).toHaveBeenCalledOnce()
  })

  it('validates a metadata name in the metadata drawer before submitting it', async () => {
    const user = userEvent.setup()
    metadataFieldsQuery.data = [metadataField({ name: 'existing_field' })]
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({
              id: 'one',
              title: 'One.pdf',
              userMetadata: { existing_field: 'support' },
            }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.metadata' }))
    await user.click(
      await screen.findByRole('button', {
        name: 'dataset.metadata.datasetMetadata.addMetaData',
      }),
    )
    const nameInput = screen.getByRole('textbox', {
      name: 'dataset.metadata.createMetadata.name',
    })
    const createDialog = nameInput.closest<HTMLElement>('[role="dialog"]')!
    const save = within(createDialog).getByRole('button', { name: 'common.operation.save' })
    expect(nameInput).toHaveFocus()

    await user.click(save)
    expect(createMetadataField).not.toHaveBeenCalled()
    expect(nameInput).toHaveAttribute('aria-invalid', 'true')
    expect(nameInput).toHaveAccessibleDescription(/dataset.metadata.checkName.empty/)
    expect(nameInput).toHaveFocus()

    const cases = [
      ['11', 'invalid'],
      ['existing_field', 'duplicate'],
      ['a'.repeat(256), 'tooLong'],
      ['displayName', 'invalid'],
    ] as const
    for (const [name, error] of cases) {
      await user.clear(nameInput)
      await user.type(nameInput, name)
      expect(nameInput).toHaveAccessibleDescription(
        new RegExp(`dataset.metadata.checkName.${error}`),
      )
    }

    await user.clear(nameInput)
    await user.type(nameInput, 'priority_1{Enter}')
    expect(nameInput).not.toHaveAttribute('aria-invalid')
    expect(createMetadataField).toHaveBeenCalledWith(
      { body: { name: 'priority_1', type: 'string' }, params: { control_space_id: 'space-1' } },
      { context: { silent: true } },
    )
  })

  it('renames metadata through the field catalog endpoint', async () => {
    const user = userEvent.setup()
    metadataFieldsQuery.data = [metadataField()]
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({
              id: 'one',
              title: 'One.pdf',
              userMetadata: { category: 'support', sourceName: 'Notion support SOP' },
            }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.metadata' }))
    await user.click(await screen.findByRole('button', { name: 'common.operation.edit' }))
    const nameInput = screen.getByRole('textbox', {
      name: 'dataset.metadata.datasetMetadata.name',
    })
    await user.clear(nameInput)
    await user.type(nameInput, 'topic')
    await user.keyboard('{Enter}')

    expect(renameMetadataField).toHaveBeenCalledWith(
      {
        body: { expectedRowVersion: 0, name: 'topic' },
        params: { control_space_id: 'space-1', field_id: 'metadata-field-1' },
      },
      { context: { silent: true } },
    )
    expect(renameDocumentMutation).not.toHaveBeenCalled()
  })

  it('keeps the metadata rename dialog open when the catalog request fails', async () => {
    const user = userEvent.setup()
    metadataFieldsQuery.data = [metadataField()]
    renameMetadataField.mockRejectedValueOnce(new Error('conflict'))

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.metadata' }))
    await user.click(await screen.findByRole('button', { name: 'common.operation.edit' }))
    const nameInput = screen.getByRole('textbox', {
      name: 'dataset.metadata.datasetMetadata.name',
    })
    await user.clear(nameInput)
    await user.type(nameInput, 'topic')
    await user.keyboard('{Enter}')

    await waitFor(() => expect(toastMock.error).toHaveBeenCalled())
    expect(nameInput).toBeInTheDocument()
    expect(renameMetadataField).toHaveBeenCalledOnce()
    expect(renameDocumentMutation).not.toHaveBeenCalled()
  })

  it('deletes metadata through the field catalog endpoint', async () => {
    const user = userEvent.setup()
    metadataFieldsQuery.data = [metadataField({ count: 1 })]
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({
              id: 'one',
              title: 'One.pdf',
              userMetadata: { category: 'support', sourceName: 'Notion support SOP' },
            }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.metadata' }))
    await user.click(await screen.findByRole('button', { name: 'common.operation.remove' }))
    await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))

    expect(deleteMetadataField).toHaveBeenCalledWith(
      {
        params: { control_space_id: 'space-1', field_id: 'metadata-field-1' },
        query: { expectedRowVersion: 0 },
      },
      { context: { silent: true } },
    )
    expect(renameDocumentMutation).not.toHaveBeenCalled()
  })

  it('starts re-indexing from a document row action', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [{ items: [document({ id: 'one', title: 'One.pdf' })] }],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: /knowledgeDocuments\.documentActions/,
      }),
    )
    await user.click(
      await screen.findByRole('menuitem', {
        name: 'knowledgeDocuments.reindexDocument',
      }),
    )

    expect(reindexMutation.mutateAsync).toHaveBeenCalledWith({
      body: { documentIds: ['one'] },
      params: { control_space_id: 'space-1' },
    })
    await waitFor(() =>
      expect(toastMock.success).toHaveBeenCalledWith('knowledgeDocuments.documentsReindexStarted'),
    )
  })

  it.each(['response', 'item'] as const)(
    'shows the vector quota failure returned by a row re-index %s',
    async (failureSource) => {
      const user = userEvent.setup()
      documentsQuery.data = { pages: [{ items: [document({ id: 'one', title: 'One.pdf' })] }] }
      if (failureSource === 'response') {
        reindexMutation.mutateAsync.mockRejectedValueOnce(
          Response.json(
            {
              failure: {
                action: 'retry',
                category: 'configuration',
                code: 'VECTOR_SPACE_QUOTA_EXCEEDED',
                message: 'Upstream quota details',
                retryPolicy: 'manual',
              },
            },
            { status: 413 },
          ),
        )
      } else {
        reindexMutation.mutateAsync.mockResolvedValueOnce({
          bulkJobId: 'quota-reindex',
          items: [{ documentId: 'one', status: 'failed', code: 'VECTOR_SPACE_QUOTA_EXCEEDED' }],
          total: 1,
        })
      }

      await render(<DocumentsPage knowledgeSpaceId="space-1" />)
      await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
      await user.click(
        await screen.findByRole('menuitem', { name: 'knowledgeDocuments.reindexDocument' }),
      )

      await waitFor(() =>
        expect(toastMock.error).toHaveBeenCalledWith(
          'knowledgeErrors.taskFailure.vectorSpaceQuotaExceeded',
        ),
      )
      expect(toastMock.success).not.toHaveBeenCalled()
    },
  )

  it.each([
    ['queued', 'queued'],
    ['processing', 'running'],
  ] as const)(
    'locks re-index, download, and availability actions while a document is %s',
    async (_status, taskState) => {
      const user = userEvent.setup()
      documentsQuery.data = {
        pages: [
          {
            items: [
              document({
                id: 'one',
                title: 'One.pdf',
                latestTask: task({ documentId: 'one', state: taskState }),
              }),
            ],
          },
        ],
      }
      tasksQuery.data = {
        pages: [{ items: [task({ documentId: 'one', state: taskState })] }],
      }

      await render(<DocumentsPage knowledgeSpaceId="space-1" />)
      await user.click(
        screen.getByRole('button', {
          name: /knowledgeDocuments\.documentActions/,
        }),
      )

      expect(
        await screen.findByRole('menuitem', {
          name: 'knowledgeDocuments.reindexDocument',
        }),
      ).toHaveAttribute('aria-disabled', 'true')
      expect(
        screen.getByRole('menuitem', { name: 'knowledgeDocuments.downloadDocuments' }),
      ).toHaveAttribute('aria-disabled', 'true')
      expect(
        screen.getByRole('menuitem', { name: 'knowledgeSpace.disableSource' }),
      ).toHaveAttribute('aria-disabled', 'true')
      expect(reindexMutation.mutateAsync).not.toHaveBeenCalled()
      expect(downloadDocumentMutation).not.toHaveBeenCalled()
      expect(updateLogicalDocumentMutation).not.toHaveBeenCalled()
    },
  )

  it.each(['disabled', 'failed'] as const)(
    'reports a %s row re-index without success feedback',
    async (status) => {
      const user = userEvent.setup()
      documentsQuery.data = {
        pages: [{ items: [document({ id: 'one', title: 'One.pdf' })] }],
      }
      reindexMutation.mutateAsync.mockResolvedValue({
        bulkJobId: 'reindex-disabled',
        items: [{ documentId: 'one', status }],
        total: 1,
      })

      await render(<DocumentsPage knowledgeSpaceId="space-1" />)
      await user.click(
        screen.getByRole('button', {
          name: /knowledgeDocuments\.documentActions/,
        }),
      )
      await user.click(
        await screen.findByRole('menuitem', {
          name: 'knowledgeDocuments.reindexDocument',
        }),
      )

      expect(toastMock.success).not.toHaveBeenCalled()
      expect(toastMock.error).toHaveBeenCalledWith('knowledgeDocuments.documentsReindexFailed')
    },
  )

  it('retries a failed document from its row action', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({
              id: 'one',
              status: 'failed',
              title: 'One.pdf',
              latestTask: task({ documentId: 'one', id: 'failed-task', state: 'failed' }),
            }),
          ],
        },
      ],
    }
    tasksQuery.data = {
      pages: [
        {
          items: [task({ documentId: 'one', id: 'failed-task', state: 'failed' })],
        },
      ],
    }
    retryMutation.mutateAsync.mockResolvedValueOnce(
      task({ documentId: 'one', id: 'failed-task', state: 'queued' }),
    )

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: /knowledgeDocuments\.documentActions/,
      }),
    )
    expect(
      screen.queryByRole('menuitem', { name: 'knowledgeDocuments.reindexDocument' }),
    ).not.toBeInTheDocument()
    const retry = await screen.findByRole('menuitem', {
      name: 'knowledgeSpace.retryTask',
    })
    expect(
      screen.queryByRole('menuitem', { name: 'knowledgeSpace.disableSource' }),
    ).not.toBeInTheDocument()
    expect(retry).toBeEnabled()
    expect(retry).not.toHaveAttribute('aria-disabled', 'true')
    await user.click(retry)

    await waitFor(() =>
      expect(retryMutation.mutateAsync).toHaveBeenCalledWith({
        params: {
          control_space_id: 'space-1',
          task_id: 'failed-task',
          task_kind: 'document',
        },
      }),
    )
    expect(await screen.findByText('knowledgeSpace.documentStatus.queued')).toBeInTheDocument()
  })

  it('shows the quota verification error when retrying a document row', async () => {
    const user = userEvent.setup()
    systemFeaturesStateMock.deploymentEdition = 'CLOUD'
    getUploadQuotaFailure.mockResolvedValue('taskFailure.documentCountQuotaExceeded')
    const failedTask = task({ documentId: 'one', id: 'failed-task', state: 'failed' })
    documentsQuery.data = {
      pages: [{ items: [document({ id: 'one', status: 'failed', latestTask: failedTask })] }],
    }
    tasksQuery.data = { pages: [{ items: [failedTask] }] }
    retryMutation.mutateAsync.mockRejectedValueOnce(
      Response.json(
        {
          failure: {
            action: 'retry',
            category: 'dependency',
            code: 'VECTOR_SPACE_QUOTA_UNAVAILABLE',
            message: 'Upstream billing diagnostics',
            retryPolicy: 'manual',
          },
        },
        { status: 503 },
      ),
    )

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
    await user.click(await screen.findByRole('menuitem', { name: 'knowledgeSpace.retryTask' }))

    await waitFor(() =>
      expect(toastMock.error).toHaveBeenCalledWith(
        'knowledgeErrors.taskFailure.vectorSpaceQuotaUnavailable',
      ),
    )
    expect(
      screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }),
    ).toBeEnabled()
    expect(getUploadQuotaFailure).not.toHaveBeenCalled()
  })

  it.each(['document', 'document_bulk'] as const)(
    'keeps a historical %s failure in the drawer without changing the document row',
    async (taskKind) => {
      const user = userEvent.setup()
      documentsQuery.data = {
        pages: [
          { items: [document({ latestTask: task({ id: 'current-task', state: 'succeeded' }) })] },
        ],
      }
      tasksQuery.data = {
        pages: [
          {
            items: [
              task({
                id: 'history-task',
                taskKind,
                state: 'failed',
                documentRevision: 1,
                updatedAt: '2026-07-21T10:00:00Z',
              }),
            ],
          },
        ],
      }
      await render(<DocumentsPage knowledgeSpaceId="space-1" />)

      const row = within(screen.getByRole('row', { name: /sso-enterprise\.pdf/ }))
      expect(row.getByText('knowledgeSpace.documentStatus.ready')).toBeInTheDocument()
      await user.click(row.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
      expect(
        await screen.findByRole('menuitem', { name: 'knowledgeDocuments.reindexDocument' }),
      ).not.toHaveAttribute('aria-disabled', 'true')
      expect(
        screen.queryByRole('menuitem', { name: 'knowledgeSpace.retryTask' }),
      ).not.toBeInTheDocument()
      await user.keyboard('{Escape}')

      await user.click(
        screen.getByRole('button', { name: 'knowledgeDocuments.tasksWithAttention:{"count":1}' }),
      )
      expect(
        within(screen.getByRole('dialog', { name: 'knowledgeSpace.backgroundTasks' })).getByRole(
          'button',
          { name: 'knowledgeSpace.retryTask' },
        ),
      ).toBeInTheDocument()
    },
  )

  it('does not infer a document task from history when its snapshot has no task', async () => {
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ state: 'failed' })] }] }
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(
      within(screen.getByRole('row', { name: /sso-enterprise\.pdf/ })).getByText(
        'knowledgeSpace.documentStatus.ready',
      ),
    ).toBeInTheDocument()
  })

  it('keeps a ready document selectable and editable while another document is processing and history is incomplete', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document(),
            document({
              id: 'document-b',
              title: 'Pending.pdf',
              latestTask: task({ documentId: 'document-b', id: 'task-b', state: 'running' }),
            }),
          ],
        },
      ],
    }
    tasksQuery.data = { pages: [{ items: [task({ state: 'succeeded' })], nextCursor: 'next' }] }
    tasksQuery.hasNextPage = true
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const readyRow = within(screen.getByRole('row', { name: /sso-enterprise\.pdf/ }))
    expect(readyRow.getByText('knowledgeSpace.documentStatus.ready')).toBeInTheDocument()
    expect(readyRow.getByRole('checkbox')).not.toHaveAttribute('aria-disabled')
    expect(screen.getByRole('checkbox', { name: 'Pending.pdf' })).not.toHaveAttribute(
      'aria-disabled',
      'true',
    )
    expect(
      screen.getByRole('checkbox', { name: 'knowledgeDocuments.selectAllDocuments' }),
    ).not.toHaveAttribute('aria-disabled', 'true')
    await user.click(readyRow.getByRole('checkbox'))
    expect(readyRow.getByRole('checkbox')).toBeChecked()
    expect(screen.getByRole('button', { name: 'knowledgeSpace.reindexDocuments' })).toBeEnabled()
    await user.click(readyRow.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
    await user.click(await screen.findByRole('menuitem', { name: 'common.operation.rename' }))
    const input = screen.getByRole('textbox', { name: 'knowledgeSpace.documentColumn' })
    await user.clear(input)
    await user.type(input, 'Renamed.pdf')
    await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
    expect(renameDocumentMutation).toHaveBeenCalledWith(
      expect.objectContaining({
        params: { control_space_id: 'space-1', document_id: 'document-1' },
      }),
      { context: { silent: true } },
    )
  })

  it('discards a cancelled rename draft before reopening', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const open = async () => {
      await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
      await user.click(await screen.findByRole('menuitem', { name: 'common.operation.rename' }))
    }
    await open()
    const name = screen.getByRole('textbox', { name: 'knowledgeSpace.documentColumn' })
    const original = (name as HTMLInputElement).value
    await user.clear(name)
    await user.type(name, 'Unsaved draft')
    await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
    await waitFor(() =>
      expect(
        screen.queryByRole('dialog', { name: 'common.operation.rename' }),
      ).not.toBeInTheDocument(),
    )
    await open()
    expect(screen.getByRole('textbox', { name: 'knowledgeSpace.documentColumn' })).toHaveValue(
      original,
    )
    expect(renameDocumentMutation).not.toHaveBeenCalled()
  })

  it('renames a document through its user-facing display metadata', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
    await user.click(await screen.findByRole('menuitem', { name: 'common.operation.rename' }))
    const input = screen.getByRole('textbox', { name: 'knowledgeSpace.documentColumn' })
    await user.clear(input)
    await user.type(input, 'Renamed handbook.pdf')
    await user.click(screen.getByRole('button', { name: 'common.operation.save' }))

    expect(renameDocumentMutation).toHaveBeenCalledWith(
      {
        body: {
          expectedRowVersion: 1,
          patch: { displayName: 'Renamed handbook.pdf' },
        },
        params: { control_space_id: 'space-1', document_id: 'document-1' },
      },
      { context: { silent: true } },
    )
    await waitFor(() =>
      expect(
        screen.queryByRole('dialog', { name: 'common.operation.rename' }),
      ).not.toBeInTheDocument(),
    )
  })

  it('disables the document from the row action', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    seedGoldenQuestions()
    await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
    await user.click(await screen.findByRole('menuitem', { name: 'knowledgeSpace.disableSource' }))

    expect(updateLogicalDocumentMutation).toHaveBeenCalledWith(
      {
        body: { enabled: false, expectedRowVersion: 1 },
        params: { control_space_id: 'space-1', document_id: 'document-1' },
      },
      { context: { silent: true } },
    )
    await waitFor(() =>
      expect(queryClient.getQueryState(goldenQuestionsKey('space-1'))?.isInvalidated).toBe(true),
    )
    expect(queryClient.getQueryState(goldenQuestionsKey('space-2'))?.isInvalidated).toBe(false)
  })

  it('re-enables a disabled document from the same row action', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({ enabled: false })] }] }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(screen.getByText('knowledgeSpace.documentStatus.disabled')).toBeInTheDocument()
    await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
    await user.click(await screen.findByRole('menuitem', { name: 'dataset.enable' }))

    expect(updateLogicalDocumentMutation).toHaveBeenCalledWith(
      {
        body: { enabled: true, expectedRowVersion: 1 },
        params: { control_space_id: 'space-1', document_id: 'document-1' },
      },
      { context: { silent: true } },
    )
    expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
      expect.objectContaining({
        queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.get.key(),
      }),
    )
  })

  it('confirms permanent document removal from the row action', async () => {
    const user = userEvent.setup()
    systemFeaturesStateMock.deploymentEdition = 'CLOUD'
    documentsQuery.data = { pages: [{ items: [document()] }] }

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
    await user.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
    expect(removeDocumentMutation).not.toHaveBeenCalled()
    await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))

    expect(removeDocumentMutation).toHaveBeenCalledWith(
      {
        body: { expectedRevision: 1 },
        headers: { 'Idempotency-Key': expect.any(String) },
        params: { control_space_id: 'space-1', document_id: 'document-1' },
      },
      { context: { silent: true } },
    )
    expect(queryClient.invalidateQueries).not.toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.get.key() },
      { cancelRefetch: false },
    )
    expect(queryClient.invalidateQueries).not.toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.vectorSpace.get.key() },
      { cancelRefetch: false },
    )

    tasksQuery.data = { pages: [{ items: [backgroundTask({ operation: 'document_delete' })] }] }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() =>
      expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
        { queryKey: consoleQuery.features.get.key() },
        { cancelRefetch: false },
      ),
    )
    expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.vectorSpace.get.key() },
      { cancelRefetch: false },
    )

    vi.mocked(queryClient.invalidateQueries).mockClear()
    tasksQuery.data = { pages: [{ items: [backgroundTask({ operation: 'document_delete' })] }] }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(queryClient.invalidateQueries).not.toHaveBeenCalled()
  })

  it('opens the upload form and consumes the one-shot URL request', async () => {
    const user = userEvent.setup()
    const { onUrlUpdate } = await render(<DocumentsPage knowledgeSpaceId="space-1" />, {
      searchParams: '?upload=1',
    })

    expect(
      await screen.findByRole('heading', { name: 'knowledgeSpace.addDocument' }),
    ).toBeInTheDocument()
    await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
    await waitFor(() => {
      const urlUpdate = onUrlUpdate.mock.calls.at(-1)?.[0]
      expect(urlUpdate?.searchParams.get('upload')).toBeNull()
      expect(urlUpdate?.options.history).toBe('replace')
    })
    expect(
      screen.queryByRole('heading', { name: 'knowledgeSpace.addDocument' }),
    ).not.toBeInTheDocument()
  })

  it('keeps the upload form opened from the document page in the URL', async () => {
    const user = userEvent.setup()
    const { onUrlUpdate } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))

    await waitFor(() => {
      const urlUpdate = onUrlUpdate.mock.calls.at(-1)?.[0]
      expect(urlUpdate?.searchParams.get('upload')).toBe('1')
      expect(urlUpdate?.options.history).toBe('replace')
    })
    expect(screen.getByRole('heading', { name: 'knowledgeSpace.addDocument' })).toBeInTheDocument()
  })

  it('consumes an upload URL request without opening the form for a read-only user', async () => {
    permissionStateMock.datasetKeys = ['dataset.acl.readonly']
    permissionStateMock.spaceKeys = []
    const { onUrlUpdate } = await render(<DocumentsPage knowledgeSpaceId="space-1" />, {
      searchParams: '?upload=1',
    })

    expect(
      screen.queryByRole('heading', { name: 'knowledgeSpace.addDocument' }),
    ).not.toBeInTheDocument()
    await waitFor(() => {
      const urlUpdate = onUrlUpdate.mock.calls.at(-1)?.[0]
      expect(urlUpdate?.searchParams.get('upload')).toBeNull()
      expect(urlUpdate?.options.history).toBe('replace')
    })
  })

  it('renders revisions, sources, stable cursor-ordered rows, and every designed status', async () => {
    documentsQuery.data = {
      pages: [
        {
          items: [document({ id: 'ready', title: 'Ready.pdf', userMetadata: {} })],
        },
        {
          items: [
            document({
              active: null,
              activeRevision: undefined,
              id: 'queued',
              status: 'pending',
              title: 'Queued.docx',
              updatedAt: '2026-07-20T10:05:00Z',
            }),
            document({ id: 'failed', status: 'failed', title: 'Failed.html' }),
            document({
              enabled: false,
              id: 'disabled',
              sourceId: 'disabled-source',
              title: 'Disabled.xlsx',
              userMetadata: { sourceName: 'Archive' },
            }),
            document({
              id: 'processing',
              status: 'pending',
              title: 'Processing.md',
              latestTask: task({ documentId: 'processing', id: 'processing-task' }),
            }),
          ],
        },
      ],
    }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({ documentId: 'processing', id: 'processing-task' }),
            task({ documentId: 'queued', id: 'queued-task', state: 'queued' }),
          ],
        },
      ],
    }
    sourcesQuery.data = {
      pages: [
        {
          items: [source(), source({ id: 'disabled-source', name: 'Archive', status: 'disabled' })],
        },
      ],
    }
    preload('documents')

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    const rows = screen.getAllByRole('row').slice(1)
    expect(within(rows[0]!).getByText('Ready.pdf')).toBeInTheDocument()
    expect(screen.getByRole('link', { name: 'Ready.pdf' })).toHaveAttribute(
      'href',
      '/datasets/new/space-1/documents/ready',
    )
    expect(screen.getAllByText('Notion support SOP').length).toBeGreaterThan(0)
    expect(screen.getAllByText('v2').length).toBeGreaterThan(0)
    for (const status of ['ready', 'queued', 'processing', 'failed', 'disabled'])
      expect(screen.getAllByText(`knowledgeSpace.documentStatus.${status}`).length).toBeGreaterThan(
        0,
      )
    expect(screen.getByText('knowledgeDocuments.lastReadyRevisionHint')).toBeInTheDocument()
  })

  it('does not derive document availability from disabled or unresolved sources', async () => {
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({ id: 'archived', sourceId: 'disabled-source', title: 'Archived.pdf' }),
            document({ id: 'orphaned', sourceId: 'missing-source', title: 'Orphaned.pdf' }),
          ],
        },
      ],
    }
    sourcesQuery.data = {
      pages: [{ items: [source({ id: 'disabled-source', name: 'Archive', status: 'disabled' })] }],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.getAllByText('knowledgeSpace.documentStatus.ready')).toHaveLength(2)
    expect(screen.getByRole('checkbox', { name: 'Archived.pdf' })).toBeEnabled()
    expect(screen.getByRole('checkbox', { name: 'Orphaned.pdf' })).toBeEnabled()
  })

  it('renders the designed empty state with an available upload action', async () => {
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({ id: 'failed-1', state: 'failed' }),
            task({ id: 'failed-2', state: 'failed' }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    const emptyState = screen.getByText('knowledgeSpace.documentsEmptyTitle').parentElement
    expect(emptyState).not.toBeNull()
    expect(screen.getByText('knowledgeSpace.documentsEmptyDescription')).toBeInTheDocument()
    expect(screen.getByText('knowledgeDocuments.documentsDropHint')).toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' })).toBeEnabled()
    expect(
      screen.queryByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":2}',
      }),
    ).not.toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'knowledgeSpace.metadata' })).toBeEnabled()
    const dataTransfer = { dropEffect: 'none' }
    const dragOver = new Event('dragover', { bubbles: true, cancelable: true })
    Object.defineProperty(dragOver, 'dataTransfer', { value: dataTransfer })
    expect(fireEvent(emptyState!, dragOver)).toBe(false)
    expect(dataTransfer.dropEffect).toBe('copy')
  })

  it('keeps the standard document toolbar free of an empty task shortcut', async () => {
    documentsQuery.data = { pages: [{ items: [document()] }] }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.getByRole('button', { name: 'knowledgeSpace.metadata' })).toBeEnabled()
    expect(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' })).toBeEnabled()
    expect(
      screen.queryByRole('button', { name: 'knowledgeDocuments.tasks' }),
    ).not.toBeInTheDocument()
  })

  it('shows the drop target while dragging and previews dropped files in the upload form', async () => {
    documentsQuery.data = { pages: [{ items: [document()] }] }
    const droppedFile = new File(['# handbook'], 'handbook.md', { type: 'text/markdown' })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    const documentSurface = screen
      .getByRole('heading', { name: 'knowledgeSpace.documents' })
      .closest('section')
    expect(documentSurface).not.toBeNull()
    fireEvent.dragEnter(documentSurface!, {
      dataTransfer: { files: [droppedFile], types: ['Files'] },
    })

    expect(screen.getByText('knowledgeDocuments.dropFilesHere')).toBeInTheDocument()

    fireEvent.dragLeave(documentSurface!, {
      dataTransfer: { files: [droppedFile], types: ['Files'] },
    })

    expect(screen.queryByText('knowledgeDocuments.dropFilesHere')).not.toBeInTheDocument()

    fireEvent.dragEnter(documentSurface!, {
      dataTransfer: { files: [droppedFile], types: ['Files'] },
    })
    fireEvent.drop(documentSurface!, {
      dataTransfer: {
        dropEffect: 'copy',
        files: [droppedFile],
        types: ['Files'],
      },
    })

    expect(screen.getByRole('heading', { name: 'knowledgeSpace.addDocument' })).toBeInTheDocument()
    expect(screen.queryByText('knowledgeDocuments.dropFilesHere')).not.toBeInTheDocument()
    expect(screen.getByText('handbook.md')).toBeInTheDocument()
  })

  it('keeps the designed drop target active over the open upload form', async () => {
    const droppedFile = new File(['# handbook'], 'handbook.md', { type: 'text/markdown' })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })

    const documentSurface = screen
      .getByRole('heading', { name: 'knowledgeSpace.addDocument' })
      .closest('section')
    expect(documentSurface).not.toBeNull()

    fireEvent.dragEnter(documentSurface!, {
      dataTransfer: { files: [droppedFile], types: ['Files'] },
    })

    expect(screen.getByText('knowledgeDocuments.dropFilesHere')).toBeInTheDocument()

    fireEvent.drop(documentSurface!, {
      dataTransfer: {
        dropEffect: 'copy',
        files: [droppedFile],
        types: ['Files'],
      },
    })

    expect(screen.queryByText('knowledgeDocuments.dropFilesHere')).not.toBeInTheDocument()
    expect(await screen.findByText('handbook.md')).toBeInTheDocument()
  })

  it('keeps direct-upload actions unavailable until the deployment is verified', async () => {
    systemFeaturesStateMock.uploadEnabled = false

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.queryByLabelText('knowledgeCreate.uploadDocuments')).not.toBeInTheDocument()
    const addDocument = screen.getByRole('button', {
      name: 'knowledgeSpace.addDocument',
    })
    expect(addDocument).toBeDisabled()
    expect(addDocument).toHaveAccessibleDescription('dataset.cornerLabel.unavailable')
  })

  it('removes the empty-state drop affordance when uploads are unavailable', async () => {
    permissionStateMock.datasetKeys = ['dataset.acl.readonly']
    permissionStateMock.spaceKeys = []

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    const emptyState = screen.getByText('knowledgeSpace.documentsEmptyTitle').parentElement
    expect(emptyState).not.toBeNull()
    expect(screen.queryByText('knowledgeDocuments.documentsDropHint')).not.toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' })).toHaveAttribute(
      'aria-describedby',
      'documents-readonly-reason',
    )
    const dataTransfer = {
      dropEffect: 'copy',
      files: [new File(['one'], 'one.md', { type: 'text/markdown' })],
    }
    const dragOver = new Event('dragover', { bubbles: true, cancelable: true })
    Object.defineProperty(dragOver, 'dataTransfer', { value: dataTransfer })
    expect(fireEvent(emptyState!, dragOver)).toBe(false)
    expect(dataTransfer.dropEffect).toBe('none')
    expect(
      fireEvent.drop(emptyState!, {
        dataTransfer,
      }),
    ).toBe(false)
    expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()
  })

  it('does not expose processing tasks while the document list is empty', async () => {
    tasksQuery.data = { pages: [{ items: [task({ id: 'orphaned-running-task' })] }] }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(
      screen.queryByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    ).not.toBeInTheDocument()
  })

  it('keeps every write action unavailable for read-only users', async () => {
    const user = userEvent.setup()
    permissionStateMock.datasetKeys = ['dataset.acl.readonly']
    permissionStateMock.spaceKeys = []
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task()] }] }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.getByText('knowledgeSpace.documentPermissionRestricted')).toBeVisible()
    expect(screen.queryByLabelText('knowledgeCreate.uploadDocuments')).not.toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' })).toBeDisabled()
    expect(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' })).toHaveAttribute(
      'aria-disabled',
      'true',
    )
    expect(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' })).toHaveAttribute(
      'aria-describedby',
      'documents-readonly-reason',
    )
    await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
    for (const item of await screen.findAllByRole('menuitem'))
      expect(item).toHaveAttribute('aria-disabled', 'true')
    await user.keyboard('{Escape}')
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    expect(
      screen.queryByRole('button', { name: 'knowledgeTasks.interruptTask' }),
    ).not.toBeInTheDocument()
    expect(
      within(screen.getByRole('dialog')).getByText('knowledgeSpace.documentPermissionRestricted'),
    ).toBeInTheDocument()
  })

  it('does not confuse legacy download-permission failures with KnowledgeFS write access', async () => {
    permissionStateMock.error = new Error('permission service unavailable')
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task()] }] }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    const addDocument = screen.getByRole('button', { name: 'knowledgeSpace.addDocument' })
    expect(addDocument).toBeEnabled()
    expect(screen.queryByRole('alert')).not.toBeInTheDocument()
  })

  it('does not block task actions while legacy download permission is loading', async () => {
    const user = userEvent.setup()
    permissionStateMock.loading = true
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task()] }] }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' })).toBeEnabled()
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )

    expect(screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' })).toBeInTheDocument()
  })

  it('stages one or multiple files before uploading them through the Dify API contract', async () => {
    const user = userEvent.setup()
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const otherSpaceDocuments = logicalDocumentsInfiniteOptions('space-2').queryKey
    queryClient.setQueryData(otherSpaceDocuments, { pageParams: [], pages: [] })
    const documentReadsBeforeUpload = server.reads.get('documents') ?? 0
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    const input = screen.getByLabelText('knowledgeCreate.uploadDocuments')
    expect(input).toHaveAttribute('hidden')
    expect(input).toHaveAttribute('tabindex', '-1')
    expect(input).toHaveAttribute(
      'accept',
      '.csv,.doc,.docx,.eml,.epub,.htm,.html,.json,.jsonl,.markdown,.md,.mdx,.msg,.odt,.pdf,.ppt,.pptx,.properties,.rtf,.text,.txt,.vtt,.xls,.xlsx,.xml',
    )

    await user.upload(input, new File(['one'], 'one.md', { type: 'text/markdown' }))
    await waitFor(() =>
      expect(stageUploadMutation).toHaveBeenCalledWith(
        {
          body: { file: expect.objectContaining({ name: 'one.md' }) },
        },
        { signal: expect.any(AbortSignal) },
      ),
    )
    await waitForDocumentFilesStaged()
    expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()
    expect(
      screen.getByRole('region', { name: 'knowledgeSpace.modelCost.title' }),
    ).toHaveTextContent('knowledgeSpace.modelCost.uploadDescription')
    expect(screen.getByText(/knowledgeSpace\.modelCost\.uploadSummary/)).toBeVisible()
    expect(
      screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }),
    ).toHaveAccessibleDescription(
      expect.stringContaining('knowledgeSpace.modelCost.uploadDescription'),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))
    expect(uploadMutation.mutateAsync).toHaveBeenCalledWith({
      body: { upload_id: 'staged-one.md' },
      params: { control_space_id: 'space-1' },
    })

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    const multipleInput = screen.getByLabelText('knowledgeCreate.uploadDocuments')
    await user.upload(multipleInput, [
      new File(['two'], 'two.md', { type: 'text/markdown' }),
      new File(['three'], 'three.txt', { type: 'text/plain' }),
    ])
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))
    expect(uploadMutation.mutateAsync).toHaveBeenCalledTimes(3)
    expect(getUploadQuotaFailure).not.toHaveBeenCalled()
    expect(queryClient.invalidateQueries).not.toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.get.key() },
      { cancelRefetch: false },
    )
    expect(queryClient.invalidateQueries).not.toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.vectorSpace.get.key() },
      { cancelRefetch: false },
    )
    await settle()
    // Only this space's document list refreshes after the uploads.
    expect(server.reads.get('documents')).toBeGreaterThan(documentReadsBeforeUpload)
    expect(queryClient.getQueryState(otherSpaceDocuments)?.isInvalidated).toBe(false)
  })

  it('refreshes Cloud plan usage only after a staged file becomes a document', async () => {
    const user = userEvent.setup()
    systemFeaturesStateMock.deploymentEdition = 'CLOUD'
    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })
    await user.upload(
      screen.getByLabelText('knowledgeCreate.uploadDocuments'),
      new File(['draft'], 'draft.md', { type: 'text/markdown' }),
    )
    await waitForDocumentFilesStaged()

    expect(queryClient.invalidateQueries).not.toHaveBeenCalled()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))

    expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.get.key() },
      { cancelRefetch: false },
    )
    expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.vectorSpace.get.key() },
      { cancelRefetch: false },
    )
  })

  it.each([
    'taskFailure.documentCountQuotaExceeded',
    'taskFailure.vectorSpaceQuotaExceeded',
    'taskFailure.documentCountQuotaUnavailable',
    'taskFailure.vectorSpaceQuotaUnavailable',
  ])('blocks file transfer and submission for Cloud uploads with %s', async (failureKey) => {
    const user = userEvent.setup()
    systemFeaturesStateMock.deploymentEdition = 'CLOUD'
    getUploadQuotaFailure.mockResolvedValue(failureKey)
    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })

    await user.upload(
      screen.getByLabelText('knowledgeCreate.uploadDocuments'),
      new File(['draft'], 'draft.md', { type: 'text/markdown' }),
    )
    await waitForDocumentFilesStaged()

    expect(toastMock.error).toHaveBeenCalledWith(`knowledgeErrors.${failureKey}`)
    expect(stageUploadMutation).not.toHaveBeenCalled()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))

    expect(getUploadQuotaFailure).toHaveBeenCalledTimes(2)
    expect(stageUploadMutation).not.toHaveBeenCalled()
    expect(settingsState.refetch).not.toHaveBeenCalled()
    expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()
    expect(screen.getByText('draft.md')).toBeVisible()
    expect(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' })).toBeEnabled()
  })

  it('rechecks Cloud quotas before claiming already staged files', async () => {
    const user = userEvent.setup()
    systemFeaturesStateMock.deploymentEdition = 'CLOUD'
    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })
    await user.upload(screen.getByLabelText('knowledgeCreate.uploadDocuments'), [
      new File(['one'], 'one.md', { type: 'text/markdown' }),
      new File(['two'], 'two.md', { type: 'text/markdown' }),
    ])
    await waitForDocumentFilesStaged()
    expect(getUploadQuotaFailure).toHaveBeenCalledOnce()
    expect(stageUploadMutation).toHaveBeenCalledTimes(2)

    getUploadQuotaFailure.mockResolvedValue('taskFailure.documentCountQuotaExceeded')
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))

    expect(toastMock.error).toHaveBeenCalledWith(
      'knowledgeErrors.taskFailure.documentCountQuotaExceeded',
    )
    expect(settingsState.refetch).not.toHaveBeenCalled()
    expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()
    expect(stageUploadMutation).toHaveBeenCalledTimes(2)
  })

  it.each(['remove', 'cancel'])(
    'does not transfer files after %s while a Cloud quota check is pending',
    async (action) => {
      const user = userEvent.setup()
      systemFeaturesStateMock.deploymentEdition = 'CLOUD'
      let resolveQuota!: (value: string) => void
      getUploadQuotaFailure.mockImplementationOnce(
        () =>
          new Promise((resolve) => {
            resolveQuota = resolve
          }),
      )
      await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })
      await user.upload(
        screen.getByLabelText('knowledgeCreate.uploadDocuments'),
        new File(['draft'], 'draft.md', { type: 'text/markdown' }),
      )
      expect(getUploadQuotaFailure).toHaveBeenCalledOnce()
      expect(stageUploadMutation).not.toHaveBeenCalled()
      await user.click(
        screen.getByRole('button', {
          name:
            action === 'remove' ? 'common.operation.remove · draft.md' : 'common.operation.cancel',
        }),
      )

      await act(async () => {
        resolveQuota('taskFailure.vectorSpaceQuotaExceeded')
      })

      expect(stageUploadMutation).not.toHaveBeenCalled()
      expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()
      expect(toastMock.error).not.toHaveBeenCalled()
    },
  )

  it('shows progress on only the staged file currently being uploaded', async () => {
    const user = userEvent.setup()
    let resolveFirstUpload!: (value: unknown) => void
    let resolveSecondUpload!: (value: unknown) => void
    uploadMutation.mutateAsync
      .mockImplementationOnce(
        () =>
          new Promise((resolve) => {
            resolveFirstUpload = resolve
          }),
      )
      .mockImplementationOnce(
        () =>
          new Promise((resolve) => {
            resolveSecondUpload = resolve
          }),
      )

    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })
    await user.upload(screen.getByLabelText('knowledgeCreate.uploadDocuments'), [
      new File(['one'], 'one.pdf', { type: 'application/pdf' }),
      new File(['two'], 'two.pdf', { type: 'application/pdf' }),
    ])
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))

    const uploadRegion = screen.getByRole('region', {
      name: 'knowledgeCreate.uploadDocuments',
    })
    const [firstRow, secondRow] = within(uploadRegion).getAllByRole('listitem')
    if (!firstRow || !secondRow) throw new Error('Expected two staged upload rows')
    await waitFor(() => expect(firstRow).toHaveAttribute('aria-busy', 'true'))
    expect(within(firstRow).getByText('knowledgeCreate.uploadingFiles')).toBeVisible()
    expect(secondRow).not.toHaveAttribute('aria-busy')

    await act(async () => resolveFirstUpload({}))
    await waitFor(() => expect(secondRow).toHaveAttribute('aria-busy', 'true'))
    expect(firstRow).not.toHaveAttribute('aria-busy')
    expect(within(secondRow).getByText('knowledgeCreate.uploadingFiles')).toBeVisible()

    await act(async () => resolveSecondUpload({}))
  })

  it('previews a browser-supported staged document from its local file', async () => {
    const user = userEvent.setup()
    const file = new File(['local content'], 'handbook.pdf', { type: 'application/pdf' })
    const createObjectUrl = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:handbook')
    const revokeObjectUrl = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})
    const open = vi.spyOn(globalThis, 'open').mockReturnValue(null)

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    await user.upload(screen.getByLabelText('knowledgeCreate.uploadDocuments'), file)
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.preview' }))

    const preview = await screen.findByRole('img', { name: 'PDF preview' })
    expect(preview).toHaveAttribute('data-url', 'blob:handbook')
    expect(createObjectUrl).toHaveBeenCalledWith(expect.any(Blob))
    expect((createObjectUrl.mock.calls[0]?.[0] as Blob).size).toBe(file.size)
    expect(open).not.toHaveBeenCalled()
    expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()

    await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
    await waitFor(() => expect(revokeObjectUrl).toHaveBeenCalledWith('blob:handbook'))
  })

  it('does not offer a local preview for an Office document', async () => {
    const file = new File(['local content'], 'handbook.docx', {
      type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    fireEvent.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    fireEvent.change(screen.getByLabelText('knowledgeCreate.uploadDocuments'), {
      target: { files: [file] },
    })

    expect(screen.queryByRole('button', { name: 'knowledgeSpace.preview' })).toBeNull()
  })

  it('prompts for model setup before uploading staged documents', async () => {
    const user = userEvent.setup()
    settingsState.configurationState = 'setup-required'
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    await user.upload(
      screen.getByLabelText('knowledgeCreate.uploadDocuments'),
      new File(['one'], 'one.md', { type: 'text/markdown' }),
    )
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))

    expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()
    const dialog = screen.getByRole('dialog', {
      name: 'knowledgeSpace.overview.attention.modelReadiness.title',
    })
    await user.click(
      within(dialog).getByRole('button', {
        name: 'modelProvider.modelProvider.selector.configure',
      }),
    )
    expect(routerMock.push).toHaveBeenCalledWith(
      '/datasets/new/space-1/settings?returnTo=%2Fdatasets%2Fnew%2Fspace-1%2Fdocuments&capability=ingest',
    )
  })

  it('waits for an authoritative model setup check before uploading', async () => {
    const user = userEvent.setup()
    let resolveSettingsCheck!: (result: {
      data: {
        active_profile_available: true
        active_profile_revisions: { embedding: 1; retrieval: 1 }
        capabilities: {
          deep: true
          index: true
          ingest: true
          query: true
          research: true
          source_sync: true
        }
        configuration_state: 'active'
        embedding: null
        issues: []
        retrieval: null
        revision: number
      }
      isError: false
    }) => void
    settingsState.refetch.mockReturnValueOnce(
      new Promise((resolve) => {
        resolveSettingsCheck = resolve
      }),
    )
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    await user.upload(
      screen.getByLabelText('knowledgeCreate.uploadDocuments'),
      new File(['one'], 'one.md', { type: 'text/markdown' }),
    )
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))

    await waitFor(() => expect(settingsState.refetch).toHaveBeenCalled())
    expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()

    await act(async () =>
      resolveSettingsCheck({
        data: {
          active_profile_available: true,
          active_profile_revisions: { embedding: 1, retrieval: 1 },
          capabilities: {
            deep: true,
            index: true,
            ingest: true,
            query: true,
            research: true,
            source_sync: true,
          },
          configuration_state: 'active',
          embedding: null,
          issues: [],
          retrieval: null,
          revision: 1,
        },
        isError: false,
      }),
    )
    await waitFor(() => expect(uploadMutation.mutateAsync).toHaveBeenCalledOnce())
  })

  it('fails closed when the model setup check cannot be refreshed', async () => {
    const user = userEvent.setup()
    settingsState.refetch.mockResolvedValueOnce({ data: undefined, isError: true })
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    await user.upload(
      screen.getByLabelText('knowledgeCreate.uploadDocuments'),
      new File(['one'], 'one.md', { type: 'text/markdown' }),
    )
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))

    expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()
    expect(toastMock.error).toHaveBeenCalledWith('settings refresh failed')
  })

  it('discards a staged upload without claiming it', async () => {
    const user = userEvent.setup()
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    await user.upload(
      screen.getByLabelText('knowledgeCreate.uploadDocuments'),
      new File(['draft'], 'draft.md', { type: 'text/markdown' }),
    )
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))

    expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()
    expect(discardStagedUploadMutation).toHaveBeenCalledWith('staged-draft.md')
    expect(screen.getByRole('heading', { name: 'knowledgeSpace.documents' })).toBeInTheDocument()
    expect(screen.queryByLabelText('knowledgeCreate.uploadDocuments')).not.toBeInTheDocument()
  })

  it('keeps a slow exact 15 MiB staging request alive until it settles', async () => {
    vi.useFakeTimers()
    let resolveStaging!: (value: { id: string }) => void
    let stagingSignal: AbortSignal | undefined
    stageUploadMutation.mockImplementationOnce(
      (_input: unknown, options: { signal?: AbortSignal }) =>
        new Promise((resolve) => {
          stagingSignal = options.signal
          resolveStaging = resolve
        }),
    )
    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />, {
      searchParams: '?upload=1',
    })

    try {
      const maxSizeFile = new File(['boundary'], 'boundary.txt', { type: 'text/plain' })
      Object.defineProperty(maxSizeFile, 'size', { value: 15 * 1024 * 1024 })
      fireEvent.change(screen.getByLabelText('knowledgeCreate.uploadDocuments'), {
        target: { files: [maxSizeFile] },
      })

      expect(stageUploadMutation).toHaveBeenCalledOnce()

      await act(async () => {
        vi.advanceTimersByTime(5 * 60_000)
        await Promise.resolve()
        await Promise.resolve()
      })

      expect(stagingSignal?.aborted).toBe(false)
      expect(toastMock.error).not.toHaveBeenCalled()

      await act(async () => {
        resolveStaging({ id: 'slow-boundary-upload' })
        await Promise.resolve()
        await Promise.resolve()
      })

      expect(discardStagedUploadMutation).not.toHaveBeenCalled()
      expect(toastMock.error).not.toHaveBeenCalled()
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('cancels exact 15 MiB staging and ignores a late failure', async () => {
    const user = userEvent.setup()
    let rejectStaging!: (reason: unknown) => void
    let stagingSignal: AbortSignal | undefined
    stageUploadMutation.mockImplementationOnce(
      (_input: unknown, options: { signal?: AbortSignal }) =>
        new Promise((_resolve, reject) => {
          stagingSignal = options.signal
          rejectStaging = reject
        }),
    )
    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })
    const maxSizeFile = new File(['draft'], 'draft.txt', { type: 'text/plain' })
    Object.defineProperty(maxSizeFile, 'size', { value: 15 * 1024 * 1024 })
    fireEvent.change(screen.getByLabelText('knowledgeCreate.uploadDocuments'), {
      target: { files: [maxSizeFile] },
    })

    expect(stageUploadMutation).toHaveBeenCalledOnce()
    await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))

    expect(stagingSignal?.aborted).toBe(true)
    expect(toastMock.error).not.toHaveBeenCalled()
    expect(screen.getByRole('heading', { name: 'knowledgeSpace.documents' })).toBeInTheDocument()

    await act(async () => {
      rejectStaging(new Error('late staging failure'))
      await Promise.resolve()
      await Promise.resolve()
    })

    expect(discardStagedUploadMutation).not.toHaveBeenCalled()
    expect(toastMock.error).not.toHaveBeenCalled()
    expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()
  })

  it('reports a real staging failure when another file in the batch is canceled', async () => {
    const user = userEvent.setup()
    const canceledFile = new File(['cancel'], 'cancel.txt', { type: 'text/plain' })
    const failedFile = new File(['fail'], 'fail.txt', { type: 'text/plain' })
    let canceledSignal: AbortSignal | undefined
    let rejectFailedStaging!: (reason: unknown) => void
    stageUploadMutation.mockImplementation(
      ({ body }: { body: { file: File } }, options: { signal?: AbortSignal }) =>
        new Promise((_resolve, reject) => {
          if (body.file === canceledFile) canceledSignal = options.signal
          if (body.file === failedFile) rejectFailedStaging = reject
        }),
    )
    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })
    fireEvent.change(screen.getByLabelText('knowledgeCreate.uploadDocuments'), {
      target: { files: [canceledFile, failedFile] },
    })

    expect(stageUploadMutation).toHaveBeenCalledTimes(2)
    await user.click(screen.getByRole('button', { name: 'common.operation.remove · cancel.txt' }))
    expect(canceledSignal?.aborted).toBe(true)

    await act(async () => {
      rejectFailedStaging(new Error('staging service unavailable'))
      await Promise.resolve()
      await Promise.resolve()
    })

    expect(toastMock.error).toHaveBeenCalledOnce()
    expect(toastMock.error).toHaveBeenCalledWith('knowledgeSpace.documentUploadFailed')
    expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()
  })

  it('excludes unsupported files locally while uploading valid files', async () => {
    const user = userEvent.setup()
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const validFile = new File(['one'], 'one.md', { type: 'text/markdown' })
    const unsupportedFile = new File(['two'], 'two.exe', {
      type: 'application/octet-stream',
    })

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    fireEvent.change(screen.getByLabelText('knowledgeCreate.uploadDocuments'), {
      target: { files: [validFile, unsupportedFile] },
    })
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))

    await waitFor(() =>
      expect(uploadMutation.mutateAsync).toHaveBeenCalledWith({
        body: { upload_id: 'staged-one.md' },
        params: { control_space_id: 'space-1' },
      }),
    )
  })

  it('rejects empty files locally while staging a one-byte file from a mixed selection', async () => {
    const user = userEvent.setup()
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const emptyFile = new File([], 'empty.txt', { type: 'text/plain' })
    const oneByteFile = new File(['x'], 'one-byte.txt', { type: 'text/plain' })

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    await user.upload(screen.getByLabelText('knowledgeCreate.uploadDocuments'), [
      emptyFile,
      oneByteFile,
    ])

    expect(screen.getByText(/knowledgeCreate\.selectedFiles:.*"total":2.*"valid":1/)).toBeVisible()
    expect(screen.getByText('knowledgeSpace.documentUploadExclusion.fileEmpty')).toBeVisible()
    await waitFor(() =>
      expect(stageUploadMutation).toHaveBeenCalledWith(
        {
          body: { file: expect.objectContaining({ name: 'one-byte.txt', size: 1 }) },
        },
        { signal: expect.any(AbortSignal) },
      ),
    )
    expect(stageUploadMutation).toHaveBeenCalledTimes(1)
    expect(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' })).toBeEnabled()
  })

  it('rejects oversized files before invoking an upload contract', async () => {
    const user = userEvent.setup()
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const oversizedFile = new File(['one'], 'oversized.pdf', { type: 'application/pdf' })
    Object.defineProperty(oversizedFile, 'size', { value: 16 * 1024 * 1024 })

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    fireEvent.change(screen.getByLabelText('knowledgeCreate.uploadDocuments'), {
      target: { files: [oversizedFile] },
    })

    expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()
    expect(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' })).toBeDisabled()
    expect(
      screen.getByText(/knowledgeSpace\.documentUploadExclusion\.fileSize:.*"size":15/),
    ).toBeVisible()
  })

  it.each(['sandbox', 'professional', 'team'])(
    'shows the append rules before file selection for the %s plan',
    async (plan) => {
      const user = userEvent.setup()
      systemFeaturesStateMock.deploymentEdition = 'CLOUD'
      uploadPlanMock.plan = plan
      await render(<DocumentsPage knowledgeSpaceId="space-1" />)
      await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
      expect(stageUploadMutation).not.toHaveBeenCalled()
      expect(screen.getByText(/knowledgeSpace\.documentUploadFormats:.*"size":15/)).toBeVisible()
      const title = screen.queryByText('billing.upgrade.uploadMultiplePages.title')
      if (plan === 'sandbox') {
        expect(title).toBeVisible()
        const notice = title!.parentElement!.parentElement!
        expect(
          within(notice).getByText(
            /datasetCreation\.stepOne\.uploader\.tip:.*"size":15.*"batchCount":1/,
          ),
        ).toBeVisible()
        expect(
          within(notice).getByRole('button', { name: 'billing.triggerLimitModal.upgrade' }),
        ).toBeVisible()
        expect(notice).not.toHaveTextContent('50')
      } else expect(title).not.toBeInTheDocument()
    },
  )

  it.each(['single-file', 'multiple-files'] as const)(
    'clears the drag overlay and handles a Sandbox inner drop once for %s',
    async (selection) => {
      systemFeaturesStateMock.deploymentEdition = 'CLOUD'
      uploadPlanMock.plan = 'sandbox'
      await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })
      const surface = screen
        .getByRole('heading', { name: 'knowledgeSpace.addDocument' })
        .closest('section')!
      const dropZone = screen.getByText('knowledgeCreate.uploadDropZoneTitle').closest('button')!
      const files = [new File(['one'], 'one.md')]
      if (selection === 'multiple-files') files.push(new File(['two'], 'two.md'))
      const dataTransfer = { files, types: ['Files'] }

      fireEvent.dragEnter(surface, { dataTransfer })
      fireEvent.dragEnter(dropZone, { dataTransfer })
      expect(screen.getByText('knowledgeDocuments.dropFilesHere')).toBeVisible()
      fireEvent.drop(dropZone, { dataTransfer })

      expect(screen.queryByText('knowledgeDocuments.dropFilesHere')).not.toBeInTheDocument()
      if (selection === 'single-file') {
        await waitForDocumentFilesStaged()
        expect(stageUploadMutation).toHaveBeenCalledTimes(1)
        expect(screen.getByText('one.md')).toBeVisible()
        expect(toastMock.error).not.toHaveBeenCalled()
      } else {
        expect(stageUploadMutation).not.toHaveBeenCalled()
        expect(screen.queryByText('one.md')).not.toBeInTheDocument()
        expect(toastMock.error).toHaveBeenCalledTimes(1)
        expect(toastMock.error).toHaveBeenCalledWith(
          expect.stringContaining('datasetCreation.stepOne.uploader.validation.filesNumber'),
        )
      }
      expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()

      // A fresh gesture must not inherit the nested drag depth from the completed drop.
      fireEvent.dragEnter(surface, { dataTransfer })
      expect(screen.getByText('knowledgeDocuments.dropFilesHere')).toBeVisible()
      fireEvent.dragLeave(surface, { dataTransfer })
      expect(screen.queryByText('knowledgeDocuments.dropFilesHere')).not.toBeInTheDocument()
    },
  )

  it.each(['picker', 'page-drop', 'form-drop'])(
    'blocks Sandbox multi-file append through %s',
    async (entry) => {
      systemFeaturesStateMock.deploymentEdition = 'CLOUD'
      uploadPlanMock.plan = 'sandbox'
      await render(
        <DocumentsPage knowledgeSpaceId="space-1" />,
        entry === 'page-drop' ? undefined : { searchParams: '?upload=1' },
      )
      const files = [new File(['one'], 'one.md'), new File(['two'], 'two.md')]
      if (entry === 'picker') {
        const input = screen.getByLabelText('knowledgeCreate.uploadDocuments')
        expect(input).not.toHaveAttribute('multiple')
        fireEvent.change(input, { target: { files } })
      } else {
        const target =
          entry === 'page-drop'
            ? screen.getByRole('heading', { name: 'knowledgeSpace.documents' }).closest('section')!
            : screen.getByText('knowledgeCreate.uploadDropZoneTitle').closest('button')!
        fireEvent.drop(target, { dataTransfer: { files, types: ['Files'] } })
      }
      expect(toastMock.error).toHaveBeenCalledTimes(1)
      expect(toastMock.error).toHaveBeenCalledWith(
        expect.stringContaining('datasetCreation.stepOne.uploader.validation.filesNumber'),
      )
      expect(stageUploadMutation).not.toHaveBeenCalled()
      expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()
      expect(screen.queryByText('one.md')).not.toBeInTheDocument()
    },
  )

  it('blocks accumulated Sandbox append selections and permits another upload after completion', async () => {
    const user = userEvent.setup()
    systemFeaturesStateMock.deploymentEdition = 'CLOUD'
    uploadPlanMock.plan = 'sandbox'
    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })
    const first = new File(['one'], 'one.md')
    const second = new File(['two'], 'two.md')
    await user.upload(
      screen.getByLabelText('knowledgeCreate.uploadDocuments', { selector: 'input[type="file"]' }),
      first,
    )
    await waitForDocumentFilesStaged()
    await user.upload(
      screen.getByLabelText('knowledgeCreate.uploadDocuments', { selector: 'input[type="file"]' }),
      second,
    )
    const surface = screen
      .getByRole('heading', { name: 'knowledgeSpace.addDocument' })
      .closest('section')!
    fireEvent.drop(surface, { dataTransfer: { files: [second], types: ['Files'] } })
    expect(screen.queryByText('two.md')).not.toBeInTheDocument()
    expect(stageUploadMutation).toHaveBeenCalledTimes(1)
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))
    await waitFor(() => expect(uploadMutation.mutateAsync).toHaveBeenCalledTimes(1))
    await waitFor(() =>
      expect(
        screen.queryByLabelText('knowledgeCreate.uploadDocuments', {
          selector: 'input[type="file"]',
        }),
      ).not.toBeInTheDocument(),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    await user.upload(
      screen.getByLabelText('knowledgeCreate.uploadDocuments', { selector: 'input[type="file"]' }),
      second,
    )
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))
    await waitFor(() => expect(uploadMutation.mutateAsync).toHaveBeenCalledTimes(2))
  })

  it.each(['professional', 'team'])('allows multi-file append for the %s plan', async (plan) => {
    const user = userEvent.setup()
    systemFeaturesStateMock.deploymentEdition = 'CLOUD'
    uploadPlanMock.plan = plan
    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })
    const input = screen.getByLabelText('knowledgeCreate.uploadDocuments')
    expect(input).toHaveAttribute('multiple')
    await user.upload(input, [new File(['one'], 'one.md'), new File(['two'], 'two.md')])
    await waitForDocumentFilesStaged()
    expect(stageUploadMutation).toHaveBeenCalledTimes(2)
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))
    await waitFor(() => expect(uploadMutation.mutateAsync).toHaveBeenCalledTimes(2))
  })

  it.each([
    ['sandbox', 0],
    ['sandbox', 1],
    ['professional', 0],
    ['professional', 1],
  ] as const)(
    'enforces the %s 15MB append boundary despite legacy 50MB configuration with %s extra bytes',
    async (plan, extraBytes) => {
      const user = userEvent.setup()
      systemFeaturesStateMock.deploymentEdition = 'CLOUD'
      uploadPlanMock.plan = plan
      await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })
      const file = new File(['content'], 'boundary.pdf', { type: 'application/pdf' })
      Object.defineProperty(file, 'size', { value: 15 * 1024 * 1024 + extraBytes })
      await user.upload(screen.getByLabelText('knowledgeCreate.uploadDocuments'), file)
      if (extraBytes) {
        expect(stageUploadMutation).not.toHaveBeenCalled()
        expect(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' })).toBeDisabled()
        expect(screen.getByText(/knowledgeSpace\.documentUploadExclusion\.fileSize/)).toBeVisible()
      } else {
        await waitForDocumentFilesStaged()
        expect(stageUploadMutation).toHaveBeenCalledTimes(1)
        expect(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' })).toBeEnabled()
      }
    },
  )

  it('rejects new RAG files above 15MB even when the legacy workspace limit is 50MB', async () => {
    const user = userEvent.setup()
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const file = new File(['one'], 'handbook.pdf', { type: 'application/pdf' })
    Object.defineProperty(file, 'size', { value: 16 * 1024 * 1024 })
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    fireEvent.change(screen.getByLabelText('knowledgeCreate.uploadDocuments'), {
      target: { files: [file] },
    })
    expect(stageUploadMutation).not.toHaveBeenCalled()
    expect(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' })).toBeDisabled()
    expect(
      screen.getByText(/knowledgeSpace\.documentUploadExclusion\.fileSize:.*"size":15/),
    ).toBeVisible()
  })

  it('rejects empty files locally with a field-level reason', async () => {
    const user = userEvent.setup()
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const emptyFile = new File([], 'empty.txt', { type: 'text/plain' })

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    fireEvent.change(screen.getByLabelText('knowledgeCreate.uploadDocuments'), {
      target: { files: [emptyFile] },
    })

    expect(stageUploadMutation).not.toHaveBeenCalled()
    expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()
    expect(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' })).toBeDisabled()
    expect(screen.getByText('knowledgeSpace.documentUploadExclusion.fileEmpty')).toBeVisible()
  })

  it.each([
    ['DOCUMENT_COUNT_QUOTA_EXCEEDED', 'configuration', 413, 'documentCountQuotaExceeded'],
    ['VECTOR_SPACE_QUOTA_UNAVAILABLE', 'dependency', 503, 'vectorSpaceQuotaUnavailable'],
  ])(
    'shows %s without losing the staged file or write access',
    async (code, category, status, key) => {
      const user = userEvent.setup()
      systemFeaturesStateMock.deploymentEdition = 'CLOUD'
      uploadMutation.mutateAsync.mockRejectedValueOnce(
        new Response(
          JSON.stringify({
            failure: {
              action: 'retry',
              category,
              code,
              message: 'private billing diagnostic',
              retryPolicy: 'manual',
            },
          }),
          { status },
        ),
      )
      await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })
      await user.upload(
        screen.getByLabelText('knowledgeCreate.uploadDocuments'),
        new File(['one'], 'one.md', { type: 'text/markdown' }),
      )
      await waitForDocumentFilesStaged()
      await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))

      await waitFor(() =>
        expect(toastMock.error).toHaveBeenCalledWith(`knowledgeErrors.taskFailure.${key}`),
      )
      expect(screen.getByText('one.md')).toBeVisible()
      expect(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' })).toBeEnabled()
      expect(permissionStateMock.refreshAfterDenial).not.toHaveBeenCalled()
      expect(queryClient.invalidateQueries).not.toHaveBeenCalled()
    },
  )

  it('reports a partial quota failure and only retries files that were not added', async () => {
    const user = userEvent.setup()
    systemFeaturesStateMock.deploymentEdition = 'CLOUD'
    uploadMutation.mutateAsync.mockResolvedValueOnce({}).mockRejectedValueOnce(
      new Response(
        JSON.stringify({
          failure: {
            action: 'retry',
            category: 'configuration',
            code: 'DOCUMENT_COUNT_QUOTA_EXCEEDED',
            message: 'private billing diagnostic',
            retryPolicy: 'manual',
          },
        }),
        { status: 413 },
      ),
    )
    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })
    await user.upload(screen.getByLabelText('knowledgeCreate.uploadDocuments'), [
      new File(['one'], 'one.md', { type: 'text/markdown' }),
      new File(['two'], 'two.md', { type: 'text/markdown' }),
      new File(['three'], 'three.md', { type: 'text/markdown' }),
    ])
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))

    await waitFor(() =>
      expect(toastMock.error).toHaveBeenCalledWith(
        'knowledgeDocuments.documentUploadIncomplete:{"completed":1,"remaining":2,"reason":"knowledgeErrors.taskFailure.documentCountQuotaExceeded"}',
      ),
    )
    const uploadRegion = screen.getByRole('region', { name: 'knowledgeCreate.uploadDocuments' })
    expect(within(uploadRegion).getByText('knowledgeCreate.uploadCompleted')).toBeVisible()
    expect(
      within(uploadRegion).queryByText('knowledgeCreate.uploadingFiles'),
    ).not.toBeInTheDocument()
    expect(queryClient.invalidateQueries).toHaveBeenCalled()

    expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.get.key() },
      { cancelRefetch: false },
    )
    expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.vectorSpace.get.key() },
      { cancelRefetch: false },
    )

    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.retryRemainingFiles' }))

    await waitFor(() =>
      expect(screen.getByRole('heading', { name: 'knowledgeSpace.documents' })).toBeVisible(),
    )
    expect(uploadMutation.mutateAsync.mock.calls.map(([input]) => input.body.upload_id)).toEqual([
      'staged-one.md',
      'staged-two.md',
      'staged-two.md',
      'staged-three.md',
    ])
    expect(stageUploadMutation).toHaveBeenCalledTimes(3)
  })

  it('reports local exclusions and API upload failures', async () => {
    const user = userEvent.setup()
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const oversizedFile = new File(['large'], 'too-large.pdf', { type: 'application/pdf' })
    Object.defineProperty(oversizedFile, 'size', { value: 16 * 1024 * 1024 })

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    const input = screen.getByLabelText('knowledgeCreate.uploadDocuments')
    await user.upload(input, [
      new File(['one'], 'one.md', { type: 'text/markdown' }),
      oversizedFile,
    ])
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))

    vi.mocked(queryClient.invalidateQueries).mockClear()
    uploadMutation.mutateAsync.mockRejectedValueOnce(new Error('quota exceeded'))
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    await user.upload(screen.getByLabelText('knowledgeCreate.uploadDocuments'), [
      new File(['one'], 'one.md', { type: 'text/markdown' }),
      new File(['two'], 'two.md', { type: 'text/markdown' }),
    ])
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))
    expect(toastMock.error).toHaveBeenCalledWith('knowledgeSpace.documentUploadFailed')
    expect(queryClient.invalidateQueries).not.toHaveBeenCalled()
  })

  it('distinguishes a permission failure and exposes retry for other load errors', async () => {
    const user = userEvent.setup()
    documentsQuery.data = undefined
    documentsQuery.error = createHttpError(new Response(null, { status: 403 }))

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(screen.getByRole('alert')).toHaveTextContent(
      'knowledgeSpace.documentsPermissionDescription',
    )
    expect(screen.queryByRole('button', { name: 'common.operation.retry' })).not.toBeInTheDocument()

    documentsQuery.error = new Error('temporary')
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.documentsErrorDescription',
      }),
    )
    expect(documentsQuery.refetch).toHaveBeenCalledOnce()
  })

  it('reports a failed background document refresh while preserving cached rows', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' }))

    documentsQuery.error = new Error('background refresh failed')
    await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.getByText('sso-enterprise.pdf')).toBeInTheDocument()
    expect(screen.getByRole('alert')).toHaveTextContent('knowledgeSpace.documentsErrorDescription')
    expect(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' })).toHaveAttribute(
      'aria-disabled',
      'true',
    )
    const actions = screen.getByRole('group', {
      name: 'knowledgeDocuments.bulkDocumentActions',
    })
    expect(
      within(actions).getByRole('button', {
        name: 'knowledgeSpace.reindexDocuments',
      }),
    ).toHaveAttribute('aria-describedby', 'document-reindex-unavailable')
    expect(
      within(actions).getByText(
        'knowledgeSpace.reindexDocuments · knowledgeSpace.documentsErrorDescription',
      ),
    ).toBeVisible()
    await user.click(
      screen.getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.documentsErrorDescription',
      }),
    )
    expect(documentsQuery.refetch).toHaveBeenCalledOnce()
  })

  it('blocks cached document content when a background refresh loses permission', async () => {
    documentsQuery.data = { pages: [{ items: [document()] }] }
    documentsQuery.error = createHttpError(new Response(null, { status: 403 }))

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.getByRole('alert')).toHaveTextContent(
      'knowledgeSpace.documentsPermissionDescription',
    )
    expect(screen.queryByText('sso-enterprise.pdf')).not.toBeInTheDocument()
    expect(screen.queryByLabelText('knowledgeCreate.uploadDocuments')).not.toBeInTheDocument()
    expect(
      screen.queryByRole('button', { name: 'knowledgeDocuments.tasks' }),
    ).not.toBeInTheDocument()
  })

  it('keeps cached refresh retries busy while their queries are fetching', async () => {
    documentsQuery.data = { pages: [{ items: [document()] }] }
    documentsQuery.error = new Error('document refresh failed')
    tasksQuery.error = new Error('task refresh failed')

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    // Both failed refreshes are retried and their responses have not arrived yet.
    const refreshing = new Promise<never>(() => {})
    documentsQuery.refetch.mockReturnValue(refreshing)
    tasksQuery.refetch.mockReturnValue(refreshing)
    await refetchAll()

    expect(
      screen.getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.documentsErrorDescription',
      }),
    ).toHaveAttribute('aria-disabled', 'true')
    expect(
      screen.getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.tasksErrorDescription',
      }),
    ).toHaveAttribute('aria-disabled', 'true')
  })

  it('does not expose a KnowledgeFS permission retry for legacy download refreshes', async () => {
    permissionStateMock.error = new Error('permission refresh failed')

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.queryByRole('alert')).not.toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' })).toBeEnabled()
  })

  it('does not disable a failed dependency retry for an unrelated background refresh', async () => {
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.error = new Error('task refresh failed')

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    // A background refresh of the source list stays in flight.
    sourcesQuery.refetch.mockReturnValueOnce(new Promise(() => {}))
    act(() => {
      void queryClient.invalidateQueries({
        queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.sources.get.key(),
      })
    })

    expect(
      screen.getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.tasksErrorDescription',
      }),
    ).not.toHaveAttribute('aria-disabled')
  })

  it('keeps a blocking dependency retry stable while its first page refetches', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    sourcesQuery.data = undefined
    sourcesQuery.error = new Error('task first page failed')

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const retry = screen.getByRole('button', {
      name: 'common.operation.retry · knowledgeSpace.sourcesErrorDescription',
    })

    const firstPage = createDeferred<void>()
    sourcesQuery.refetch.mockReturnValueOnce(firstPage.promise)
    await user.click(retry)
    await waitFor(() => expect(sourcesQuery.refetch).toHaveBeenCalledOnce())

    expect(retry).toBeInTheDocument()
    expect(retry).toHaveFocus()
    expect(retry).toHaveAttribute('aria-disabled', 'true')

    sourcesQuery.data = { pages: [{ items: [] }] }
    sourcesQuery.error = null
    await act(async () => firstPage.resolve())
    await settle()
    expect(screen.getByText('sso-enterprise.pdf')).toBeInTheDocument()
    await waitFor(() =>
      expect(screen.getByRole('heading', { name: 'knowledgeSpace.documents' })).toHaveFocus(),
    )
  })

  it('closes a task drawer permanently and restores focus when document permission is revoked', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task()] }] }
    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    expect(screen.getByRole('dialog')).toBeInTheDocument()

    documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
    const permissionAlert = screen.getByRole('alert')
    expect(permissionAlert).toHaveFocus()
    // Task and source reads stop for the revoked space.
    const reads = { sources: server.reads.get('sources'), tasks: server.reads.get('tasks') }
    await refetchAll()
    expect(server.reads.get('tasks')).toBe(reads.tasks)
    expect(server.reads.get('sources')).toBe(reads.sources)

    documentsQuery.error = null
    tasksQuery.refetch.mockClear()
    sourcesQuery.refetch.mockClear()
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
    await waitFor(() => expect(tasksQuery.refetch).toHaveBeenCalled())
    await waitFor(() => expect(sourcesQuery.refetch).toHaveBeenCalled())
  })

  it('does not repeat the child query that already recovered from permission denial', async () => {
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [] }] }
    tasksQuery.error = createHttpError(new Response(null, { status: 403 }))
    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    tasksQuery.error = null
    tasksQuery.refetch.mockClear()
    sourcesQuery.refetch.mockClear()
    await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(tasksQuery.refetch).not.toHaveBeenCalled()
    await waitFor(() => expect(sourcesQuery.refetch).toHaveBeenCalled())
  })

  it('moves focus from document controls to the permission alert after dynamic revocation', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const searchbox = screen.getByRole('searchbox', {
      name: 'knowledgeDocuments.searchDocuments',
    })
    await user.click(searchbox)
    expect(searchbox).toHaveFocus()

    documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() => expect(screen.getByRole('alert')).toHaveFocus())

    documentsQuery.error = null
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() =>
      expect(screen.getByRole('heading', { name: 'knowledgeSpace.documents' })).toHaveFocus(),
    )
  })

  it('moves focus from bulk actions to the permission alert after dynamic revocation', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' }))
    const reindex = within(
      screen.getByRole('group', { name: 'knowledgeDocuments.bulkDocumentActions' }),
    ).getByRole('button', { name: 'knowledgeSpace.reindexDocuments' })
    act(() => reindex.focus())

    documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() => expect(screen.getByRole('alert')).toHaveFocus())
  })

  it('stops background pagination and failed-task polling while document permission is denied', async () => {
    documentsQuery.data = {
      pages: [{ items: [document({ sourceId: 'unresolved-source' })], nextCursor: 'next' }],
    }
    documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
    documentsQuery.hasNextPage = true
    tasksQuery.data = {
      pages: [{ items: [task({ state: 'failed' })], nextCursor: 'task-next' }],
    }
    tasksQuery.hasNextPage = true
    sourcesQuery.data = { pages: [{ items: [], nextCursor: 'source-next' }] }
    sourcesQuery.hasNextPage = true

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />, {
      searchParams: '?query=sso',
    })
    // The list paged normally until its refresh was denied; only later work matters here.
    for (const spy of [
      documentsQuery.fetchNextPage,
      tasksQuery.fetchNextPage,
      sourcesQuery.fetchNextPage,
      getTaskSnapshot,
      streamProcessingTaskEvents,
    ])
      spy.mockClear()
    // Start the clock only once the denial is shown, so the initial responses arrive in order.
    vi.useFakeTimers()
    try {
      await act(async () => vi.advanceTimersByTime(10_000))

      expect(documentsQuery.fetchNextPage).not.toHaveBeenCalled()
      expect(tasksQuery.fetchNextPage).not.toHaveBeenCalled()
      expect(sourcesQuery.fetchNextPage).not.toHaveBeenCalled()
      expect(getTaskSnapshot).not.toHaveBeenCalled()
      expect(streamProcessingTaskEvents).not.toHaveBeenCalled()
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('debounces server searches while keeping the input responsive', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({ title: 'Report.pdf' })] }] }
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    server.inputs.set('documents', [])

    await user.type(screen.getByRole('searchbox'), 'report')
    expect(screen.getByRole('searchbox')).toHaveValue('report')
    expect(server.inputs.get('documents')).toEqual([])
    await waitFor(() =>
      expect(server.inputs.get('documents')).toEqual([
        { params: { control_space_id: 'space-1' }, query: { query: 'report' } },
      ]),
    )
    expect(await screen.findByRole('link', { name: 'Report.pdf' })).toBeInTheDocument()
  })

  it('clears search immediately and cancels the pending server search', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?query=sso' })
    expect(server.inputs.get('documents')).toEqual([
      { params: { control_space_id: 'space-1' }, query: { query: 'sso' } },
    ])
    server.inputs.set('documents', [])

    await user.type(screen.getByRole('searchbox'), ' pending')
    await user.clear(screen.getByRole('searchbox'))
    await settle()
    expect(screen.getByRole('searchbox')).toHaveValue('')
    expect(screen.getByRole('searchbox')).toHaveFocus()
    expect(server.inputs.get('documents')).toEqual([
      { params: { control_space_id: 'space-1' }, query: {} },
    ])
    await user.type(screen.getByRole('searchbox'), 'missing')
    expect(await screen.findByText('knowledgeDocuments.noMatchingDocuments')).toBeInTheDocument()
    expect(server.inputs.get('documents')).toEqual([
      { params: { control_space_id: 'space-1' }, query: {} },
      { params: { control_space_id: 'space-1' }, query: { query: 'missing' } },
    ])
  })

  it('searches the server and only fetches another matching page on request', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({ title: 'Product handbook.pdf' })] }] }
    documentsQuery.hasNextPage = true
    documentsQuery.fetchNextPage.mockReturnValue(new Promise(() => {}))
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.type(screen.getByRole('searchbox'), 'later page')
    await settle()
    await waitFor(() =>
      expect(lastInput('documents')).toMatchObject({ query: { query: 'later page' } }),
    )
    expect(documentsQuery.fetchNextPage).not.toHaveBeenCalled()
    expect(screen.queryByText('knowledgeDocuments.noMatchingDocuments')).not.toBeInTheDocument()
    await user.click(await screen.findByRole('button', { name: 'knowledgeSpace.loadMore' }))
    expect(documentsQuery.fetchNextPage).toHaveBeenCalledOnce()
    expect(screen.getByRole('progressbar', { name: 'common.loading' })).toBeInTheDocument()
  })

  it('keeps search focused when clearing a direct-link filter while the full list loads', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?query=sso' })
    expect(screen.getByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()

    const fullList = createDeferred<{ error: null }>()
    documentsQuery.refetch.mockReturnValueOnce(fullList.promise)
    await user.clear(screen.getByRole('searchbox'))
    expect(screen.getByRole('searchbox')).toHaveFocus()
    await user.type(screen.getByRole('searchbox'), 'missing')
    expect(await screen.findByText('knowledgeDocuments.noMatchingDocuments')).toBeInTheDocument()
    await act(async () => fullList.resolve({ error: null }))
    expect(screen.getByRole('searchbox')).toHaveValue('missing')
    expect(screen.getByRole('searchbox')).toHaveFocus()
  })

  it('can clear a failed status request without retrying the broken filter', async () => {
    const user = userEvent.setup()
    documentsQuery.data = undefined
    documentsQuery.error = createHttpError(new Response(null, { status: 500 }))
    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?status=failed' })
    expect(
      await screen.findByRole('button', { name: /common.operation.retry/ }),
    ).toBeInTheDocument()

    documentsQuery.error = null
    documentsQuery.data = { pages: [{ items: [document()] }] }
    await user.click(screen.getByRole('combobox'))
    await user.click(screen.getByRole('option', { name: 'knowledgeDocuments.allDocumentStatuses' }))
    expect(await screen.findByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()
    expect(lastInput('documents')).toMatchObject({ query: {} })
  })

  it.each([
    { filter: 'queued', from: 'queued', to: 'running', matches: false },
    { filter: 'processing', from: 'queued', to: 'running', matches: true },
    { filter: 'queued', from: 'running', to: 'retry_wait', matches: true },
    { filter: 'processing', from: 'running', to: 'retry_wait', matches: false },
  ] as const)(
    'refreshes $filter matches when live progress changes $from to $to',
    async ({ filter, from, to, matches }) => {
      const progress = createDeferred<void>()
      const moreProgress = createDeferred<void>()
      const initialTask = task({ state: from })
      documentsQuery.data = { pages: [{ items: [document({ latestTask: initialTask })] }] }
      tasksQuery.data = { pages: [{ items: [initialTask] }] }
      streamProcessingTaskEvents.mockImplementation(async function* () {
        await progress.promise
        yield {
          data: {
            progressPercent: 50,
            stage: 'parsed' as const,
            state: to,
            updatedAt: '2026-07-20T10:02:00Z',
          },
          event: 'progress' as const,
          id: 'task-1:changed',
        }
        await moreProgress.promise
        yield {
          data: {
            progressPercent: 60,
            stage: 'parsed' as const,
            state: to,
            updatedAt: '2026-07-20T10:03:00Z',
          },
          event: 'progress' as const,
          id: 'task-1:more-progress',
        }
        await new Promise<void>(() => {})
      })
      await render(<DocumentsPage knowledgeSpaceId="space-1" />, {
        searchParams: `?status=${filter}`,
      })
      if (!matches)
        expect(screen.getByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()
      else expect(screen.getByText('knowledgeDocuments.noMatchingDocuments')).toBeInTheDocument()

      const inactiveFilter = filter === 'queued' ? 'processing' : 'queued'
      const inactiveKey = logicalDocumentsInfiniteOptions('space-1', {
        filter: inactiveFilter,
      }).queryKey
      const otherSpaceKey = logicalDocumentsInfiniteOptions('space-2', { filter }).queryKey
      for (const key of [inactiveKey, otherSpaceKey])
        queryClient.setQueryData(key, { pages: [], pageParams: [] })
      documentsQuery.refetch.mockClear()
      documentsQuery.data = {
        pages: [
          {
            items: [
              document({ latestTask: task({ state: to, updatedAt: '2026-07-20T10:02:00Z' }) }),
            ],
          },
        ],
      }
      await act(async () => progress.resolve())
      if (matches)
        expect(await screen.findByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()
      else
        expect(
          await screen.findByText('knowledgeDocuments.noMatchingDocuments'),
        ).toBeInTheDocument()
      expect(documentsQuery.refetch).toHaveBeenCalledOnce()
      expect(lastInput('documents')).toMatchObject({ query: { status: filter } })
      expect(queryClient.getQueryState(inactiveKey)?.isInvalidated).toBe(true)
      expect(queryClient.getQueryState(otherSpaceKey)?.isInvalidated).toBe(false)

      await act(async () => moreProgress.resolve())
      await settle()
      expect(documentsQuery.refetch).toHaveBeenCalledOnce()
    },
  )

  it.each(['retry_wait', 'succeeded'] as const)(
    'tracks a filtered-out document outside loaded task history through %s',
    async (nextState) => {
      const running = createDeferred<void>()
      const nextUpdate = createDeferred<void>()
      const initialTask = task({ state: 'queued' })
      const updatedTask = task({ state: nextState, updatedAt: '2026-07-20T10:03:00Z' })
      documentsQuery.data = { pages: [{ items: [document({ latestTask: initialTask })] }] }
      tasksQuery.data = {
        pages: [
          {
            items: Array.from({ length: 100 }, (_, index) =>
              backgroundTask({ id: `other-${index}` }),
            ),
          },
          { items: [initialTask] },
        ],
      }
      tasksQuery.hasNextPage = true
      getTaskSnapshot.mockResolvedValue(updatedTask)
      streamProcessingTaskEvents.mockImplementation(async function* () {
        await running.promise
        yield {
          data: {
            progressPercent: 50,
            stage: 'parsed' as const,
            state: 'running' as const,
            updatedAt: '2026-07-20T10:02:00Z',
          },
          event: 'progress' as const,
          id: 'task-1:running',
        }
        await nextUpdate.promise
        yield {
          data: {
            progressPercent: 50,
            stage: 'parsed' as const,
            state: nextState,
            updatedAt: updatedTask.updatedAt,
          },
          event: 'progress' as const,
          id: 'task-1:next',
        }
        if (nextState === 'succeeded')
          yield { data: { state: nextState }, event: 'terminal' as const, id: 'task-1:terminal' }
        await new Promise<void>(() => {})
      })
      await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?status=queued' })
      expect(screen.getByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()
      documentsQuery.data = {
        pages: [
          {
            items: [
              document({
                latestTask: task({ state: 'running', updatedAt: '2026-07-20T10:02:00Z' }),
              }),
            ],
          },
        ],
      }
      await act(async () => running.resolve())
      expect(await screen.findByText('knowledgeDocuments.noMatchingDocuments')).toBeInTheDocument()
      documentsQuery.refetch.mockClear()
      documentsQuery.data = { pages: [{ items: [document({ latestTask: updatedTask })] }] }
      await act(async () => nextUpdate.resolve())
      await waitFor(() => expect(documentsQuery.refetch).toHaveBeenCalledOnce())
      if (nextState === 'retry_wait')
        expect(await screen.findByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()
      else {
        await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledOnce())
        const user = userEvent.setup()
        await user.click(screen.getByRole('combobox'))
        await user.click(
          screen.getByRole('option', { name: 'knowledgeSpace.documentStatus.ready' }),
        )
        expect(await screen.findByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()
      }
      expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()
    },
  )

  it('finds a document beyond twenty unfiltered pages and clears an exhausted search', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: Array.from({ length: 21 }, (_, pageIndex) => ({
        items: Array.from({ length: 50 }, (_, itemIndex) =>
          document({
            id: `doc-${pageIndex}-${itemIndex}`,
            title:
              pageIndex === 20 && itemIndex === 49
                ? 'Unique late document.pdf'
                : `Other ${pageIndex}-${itemIndex}`,
          }),
        ),
      })),
    }
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(screen.queryByText('Unique late document.pdf')).not.toBeInTheDocument()
    await user.type(screen.getByRole('searchbox'), 'Unique late')
    expect(await screen.findByText('Unique late document.pdf')).toBeInTheDocument()
    expect(documentsQuery.fetchNextPage).not.toHaveBeenCalled()
    expect(lastInput('documents')).toMatchObject({ query: { query: 'Unique late' } })
    await user.clear(screen.getByRole('searchbox'))
    await user.type(screen.getByRole('searchbox'), 'no such document')
    expect(await screen.findByText('knowledgeDocuments.noMatchingDocuments')).toBeInTheDocument()
    expect(screen.getByRole('searchbox')).toHaveFocus()
    await user.clear(screen.getByRole('searchbox'))
    expect(await screen.findByText('Other 0-0')).toBeInTheDocument()
  })

  it('blocks selection until filtered cursor pages are complete', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [{ items: [document({ title: 'Product handbook.pdf' })], nextCursor: 'next' }],
    }
    documentsQuery.hasNextPage = true
    // The next page is still loading when the user filters.
    documentsQuery.fetchNextPage.mockReturnValue(new Promise(() => {}))

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.type(
      screen.getByRole('searchbox', { name: 'knowledgeDocuments.searchDocuments' }),
      'product',
    )
    await waitFor(() =>
      expect(lastInput('documents')).toMatchObject({ query: { query: 'product' } }),
    )
    await settle()

    expect(screen.getByRole('checkbox', { name: 'Product handbook.pdf' })).toHaveAttribute(
      'aria-disabled',
      'true',
    )
    expect(
      screen.getByRole('checkbox', { name: 'knowledgeDocuments.selectAllDocuments' }),
    ).toHaveAttribute('aria-disabled', 'true')
  })

  it('surfaces dependent source pagination failures and retries the failed page', async () => {
    const user = userEvent.setup()
    // The document's source is past the first source page, so the page must load the next one.
    documentsQuery.data = { pages: [{ items: [document({ sourceId: 'source-on-later-page' })] }] }
    sourcesQuery.isFetchNextPageError = true

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.getByRole('alert')).toHaveTextContent('knowledgeSpace.sourcesErrorDescription')
    expect(sourcesQuery.fetchNextPage).toHaveBeenCalledOnce()
    await user.click(
      screen.getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.sourcesErrorDescription',
      }),
    )
    await settle()
    expect(sourcesQuery.fetchNextPage).toHaveBeenCalledTimes(2)
    // The document stays identifiable while its source cannot be resolved.
    expect(screen.getByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()
    expect(screen.getByRole('alert')).toHaveTextContent('knowledgeSpace.sourcesErrorDescription')
  })

  it('retries a failed task cursor page from the task drawer', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.isFetchNextPageError = true

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', { name: /knowledgeDocuments\.taskHistoryIncomplete/ }),
    )
    await user.click(
      within(screen.getByRole('dialog')).getByRole('button', { name: 'knowledgeSpace.loadMore' }),
    )
    await settle()
    expect(tasksQuery.fetchNextPage).toHaveBeenCalledOnce()
    await user.click(
      within(screen.getByRole('dialog')).getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.tasksErrorDescription',
      }),
    )
    await settle()

    expect(tasksQuery.fetchNextPage).toHaveBeenCalledTimes(2)
    expect(tasksQuery.refetch).not.toHaveBeenCalled()
  })

  it('returns focus to the drawer close button after a query retry succeeds', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.error = new Error('task refresh failed')
    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('button', { name: 'knowledgeDocuments.tasks' }))
    const panel = screen.getByRole('dialog')
    await user.click(
      within(panel).getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.tasksErrorDescription',
      }),
    )

    tasksQuery.error = null
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() =>
      expect(within(panel).getByRole('button', { name: 'common.operation.close' })).toHaveFocus(),
    )
  })

  it('moves focus between drawer query retries as each error recovers', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [{ items: [document()], nextCursor: 'document-next' }],
    }
    documentsQuery.hasNextPage = true
    documentsQuery.isFetchNextPageError = true
    tasksQuery.data = {
      pages: [{ items: [task({ documentId: 'missing-document' })] }],
    }
    tasksQuery.error = new Error('task refresh failed')
    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    const panel = screen.getByRole('dialog')
    await user.click(
      within(panel).getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.tasksErrorDescription',
      }),
    )

    tasksQuery.error = null
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    const documentRetry = within(panel).getByRole('button', {
      name: 'common.operation.retry · knowledgeSpace.documentsErrorDescription',
    })
    await waitFor(() => expect(documentRetry).toHaveFocus())
    documentsQuery.isFetchNextPageError = false
    await user.click(documentRetry)
    await settle()
    await waitFor(() =>
      expect(within(panel).getByRole('button', { name: 'common.operation.close' })).toHaveFocus(),
    )
  })

  it('does not scan history when a document has no task', async () => {
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [], nextCursor: 'history' }] }
    tasksQuery.hasNextPage = true
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(tasksQuery.fetchNextPage).not.toHaveBeenCalled()
    expect(screen.getByText('knowledgeSpace.documentStatus.ready')).toBeInTheDocument()
  })

  it('loads document titles for tasks whose documents are on a later cursor page', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: Array.from({ length: 20 }, (_, index) => ({
        items: index === 0 ? [document()] : [],
        nextCursor: 'next',
      })),
    }
    documentsQuery.hasNextPage = true
    tasksQuery.data = {
      pages: [
        {
          items: [task({ documentId: 'later-document', id: 'later-task', state: 'succeeded' })],
        },
      ],
    }
    preload('documents')

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('button', { name: 'knowledgeDocuments.tasks' }))

    const panel = screen.getByRole('dialog')
    expect(within(panel).queryByText('later-document')).not.toBeInTheDocument()
    expect(
      within(panel).getByText('knowledgeSpace.addDocument · knowledgeSpace.documentColumn'),
    ).toBeInTheDocument()
    await user.click(within(panel).getByRole('button', { name: 'knowledgeSpace.loadMore' }))
    expect(documentsQuery.fetchNextPage).toHaveBeenCalledOnce()
  })

  it('defers task title pagination until the task drawer is opened', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [{ items: [document()], nextCursor: 'next' }],
    }
    documentsQuery.hasNextPage = true
    tasksQuery.data = {
      pages: [
        {
          items: [task({ documentId: 'later-document', id: 'later-task', state: 'succeeded' })],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(documentsQuery.fetchNextPage).not.toHaveBeenCalled()

    await user.click(screen.getByRole('button', { name: 'knowledgeDocuments.tasks' }))
    await waitFor(() => expect(documentsQuery.fetchNextPage).toHaveBeenCalledOnce())
  })

  it('reports and retries task title pagination failures inside the drawer', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [{ items: [document()], nextCursor: 'next' }],
    }
    documentsQuery.hasNextPage = true
    documentsQuery.isFetchNextPageError = true
    tasksQuery.data = {
      pages: [
        {
          items: [task({ documentId: 'later-document', id: 'later-task', state: 'succeeded' })],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('button', { name: 'knowledgeDocuments.tasks' }))

    const panel = screen.getByRole('dialog')
    await settle()
    // Opening the drawer looks for the task's document on the next page, which fails.
    expect(documentsQuery.fetchNextPage).toHaveBeenCalledOnce()
    expect(within(panel).getByRole('alert')).toHaveTextContent(
      'knowledgeSpace.documentsErrorDescription',
    )
    await user.click(
      within(panel).getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.documentsErrorDescription',
      }),
    )
    await settle()
    expect(documentsQuery.fetchNextPage).toHaveBeenCalledTimes(2)
  })

  it('keeps an unresolved source pending when a background source refresh fails', async () => {
    documentsQuery.data = {
      pages: [{ items: [document({ sourceId: 'unresolved-source' })] }],
    }
    sourcesQuery.error = new Error('source refresh failed')

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    const documentRow = screen.getByRole('row', { name: /sso-enterprise\.pdf/ })
    expect(
      within(documentRow).queryByText('knowledgeSpace.documentStatus.disabled'),
    ).not.toBeInTheDocument()
    expect(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' })).toHaveAttribute(
      'aria-disabled',
      'true',
    )
  })

  it('keeps loaded task actions available when background task pagination fails', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task()] }] }
    tasksQuery.error = new Error('poll failed')

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.getByText('sso-enterprise.pdf')).toBeInTheDocument()
    expect(screen.getByRole('alert')).toHaveTextContent('knowledgeSpace.tasksErrorDescription')
    expect(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' })).not.toHaveAttribute(
      'aria-disabled',
      'true',
    )
    await user.click(
      screen.getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.tasksErrorDescription',
      }),
    )
    expect(tasksQuery.refetch).toHaveBeenCalledOnce()
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    expect(screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' })).toBeInTheDocument()
  })

  it('reports and retries cached task refresh failures from the document empty state', async () => {
    const user = userEvent.setup()
    tasksQuery.error = new Error('task refresh failed')

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.getByRole('alert')).toHaveTextContent('knowledgeSpace.tasksErrorDescription')
    await user.click(
      screen.getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.tasksErrorDescription',
      }),
    )
    expect(tasksQuery.refetch).toHaveBeenCalledOnce()
  })

  it('renders document identity while dependency cursor pages continue loading', async () => {
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [], nextCursor: 'task-next' }] }
    tasksQuery.hasNextPage = true
    sourcesQuery.data = { pages: [{ items: [], nextCursor: 'source-next' }] }
    sourcesQuery.hasNextPage = true
    sourcesQuery.fetchNextPage.mockReturnValue(new Promise(() => {}))

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.getByText('sso-enterprise.pdf')).toBeInTheDocument()
    expect(screen.getByRole('combobox')).not.toBeDisabled()
    expect(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' })).toHaveAttribute(
      'aria-disabled',
      'true',
    )
    expect(tasksQuery.fetchNextPage).not.toHaveBeenCalled()
    expect(sourcesQuery.fetchNextPage).toHaveBeenCalledOnce()
  })

  it('shows the embedded document task before the first history page arrives', async () => {
    documentsQuery.data = {
      pages: [{ items: [document({ latestTask: task({ state: 'running' }) })] }],
    }
    tasksQuery.data = undefined
    tasksQuery.isPending = true
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(screen.getByText('knowledgeSpace.documentStatus.processing')).toBeInTheDocument()
    expect(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' })).not.toHaveAttribute(
      'aria-disabled',
      'true',
    )
  })

  it('keeps document state actionable while an older task page is loading', async () => {
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ state: 'succeeded' })], nextCursor: 'next' }] }
    tasksQuery.hasNextPage = true

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    const documentRow = screen.getByRole('row', { name: /sso-enterprise\.pdf/ })
    expect(within(documentRow).getByText('knowledgeSpace.documentStatus.ready')).toBeInTheDocument()
    expect(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' })).not.toHaveAttribute(
      'aria-disabled',
    )
  })

  it('keeps selection disabled after a filtered document page fails', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [{ items: [document({ title: 'Product handbook.pdf' })], nextCursor: 'next' }],
    }
    documentsQuery.hasNextPage = true
    documentsQuery.isFetchNextPageError = true

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.type(
      screen.getByRole('searchbox', { name: 'knowledgeDocuments.searchDocuments' }),
      'product',
    )
    await waitFor(() =>
      expect(lastInput('documents')).toMatchObject({ query: { query: 'product' } }),
    )
    await settle()
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.loadMore' }))
    await settle()
    expect(documentsQuery.fetchNextPage).toHaveBeenCalledOnce()

    expect(screen.getByRole('checkbox', { name: 'Product handbook.pdf' })).toHaveAttribute(
      'aria-disabled',
      'true',
    )
    expect(
      screen.getByRole('checkbox', { name: 'knowledgeDocuments.selectAllDocuments' }),
    ).toHaveAttribute('aria-disabled', 'true')
    await user.click(
      screen.getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.documentsErrorDescription',
      }),
    )
    await settle()
    expect(documentsQuery.fetchNextPage).toHaveBeenCalledTimes(2)
  })

  it('keeps a failed document page retry busy while the next page is fetching', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [{ items: [document()], nextCursor: 'next' }],
    }
    documentsQuery.hasNextPage = true
    documentsQuery.isFetchNextPageError = true

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.type(
      screen.getByRole('searchbox', { name: 'knowledgeDocuments.searchDocuments' }),
      'sso',
    )
    await waitFor(() => expect(lastInput('documents')).toMatchObject({ query: { query: 'sso' } }))
    await settle()
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.loadMore' }))
    await settle()
    const retry = screen.getByRole('button', {
      name: 'common.operation.retry · knowledgeSpace.documentsErrorDescription',
    })
    documentsQuery.fetchNextPage.mockReturnValue(new Promise(() => {}))
    await user.click(retry)

    expect(retry).toHaveAttribute('aria-disabled', 'true')
  })

  it('does not disable a document page retry for unrelated dependency pagination', async () => {
    documentsQuery.data = { pages: [{ items: [document()], nextCursor: 'next' }] }
    documentsQuery.hasNextPage = true
    tasksQuery.data = {
      pages: Array.from({ length: 20 }, () => ({ items: [] })),
    }
    tasksQuery.hasNextPage = true
    preload('tasks')

    const user = userEvent.setup()
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    documentsQuery.isFetchNextPageError = true
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.loadMore' }))
    await settle()

    expect(
      screen.getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.documentsErrorDescription',
      }),
    ).not.toHaveAttribute('aria-disabled')
  })

  it('moves pagination focus from load more to retry and then to final results', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()], nextCursor: 'next' }] }
    documentsQuery.hasNextPage = true
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    documentsQuery.isFetchNextPageError = true
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.loadMore' }))
    await settle()
    const retry = screen.getByRole('button', {
      name: 'common.operation.retry · knowledgeSpace.documentsErrorDescription',
    })
    await waitFor(() => expect(retry).toHaveFocus())

    documentsQuery.data = {
      pages: [
        { items: [document()], nextCursor: 'next' },
        { items: [document({ id: 'last-document', title: 'Last.pdf' })] },
      ],
    }
    documentsQuery.hasNextPage = false
    documentsQuery.isFetchNextPageError = false
    await user.click(retry)
    await settle()

    await waitFor(() => expect(screen.getByRole('table').parentElement).toHaveFocus())
  })

  it('re-indexes selected documents and keeps the designed bulk action order', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [{ items: [document({ id: 'one', title: 'One.pdf' }), document({ id: 'two' })] }],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'One.pdf' }))

    const actions = screen.getByRole('group', {
      name: 'knowledgeDocuments.bulkDocumentActions',
    })
    expect(
      screen.getByRole('heading', { name: 'knowledgeSpace.documents' }).closest('section'),
    ).toHaveClass('pb-[calc(7rem+env(safe-area-inset-bottom,0px))]')
    expect(
      within(actions).getByText('knowledgeSpace.documentsSelected:{"count":1}'),
    ).toBeInTheDocument()
    const reindex = within(actions).getByRole('button', {
      name: 'knowledgeSpace.reindexDocuments',
    })
    expect(reindex).toBeEnabled()
    const orderedActions = within(actions).getAllByRole('button')
    expect(orderedActions[0]).toHaveAccessibleName('knowledgeSpace.reindexDocuments')
    expect(orderedActions[1]).toHaveAccessibleName('knowledgeDocuments.downloadDocuments')
    expect(orderedActions[1]).toBeEnabled()
    expect(orderedActions[2]).toHaveAccessibleName('knowledgeSpace.disableSource')
    expect(orderedActions[2]).toBeEnabled()
    expect(orderedActions[3]).toHaveAccessibleName('common.operation.remove')
    expect(orderedActions[3]).toBeEnabled()
    expect(orderedActions[4]).toHaveAccessibleName('knowledgeDocuments.clearDocumentSelection')
    expect(actions.firstElementChild).toHaveTextContent(
      'knowledgeSpace.documentsSelected:{"count":1}',
    )
    await user.dblClick(reindex)
    expect(reindexMutation.mutateAsync).toHaveBeenCalledOnce()
    expect(reindexMutation.mutateAsync).toHaveBeenCalledWith({
      body: { documentIds: ['one'] },
      params: { control_space_id: 'space-1' },
    })
    await waitFor(() =>
      expect(screen.getByRole('heading', { name: 'knowledgeSpace.documents' })).toHaveFocus(),
    )
  })

  it.each([
    ['queued', 'queued'],
    ['processing', 'running'],
  ] as const)(
    'locks bulk re-index, download, and availability actions for a %s document',
    async (_status, taskState) => {
      const user = userEvent.setup()
      documentsQuery.data = {
        pages: [
          {
            items: [
              document({
                id: 'one',
                title: 'One.pdf',
                latestTask: task({ documentId: 'one', state: taskState }),
              }),
            ],
          },
        ],
      }
      tasksQuery.data = {
        pages: [{ items: [task({ documentId: 'one', state: taskState })] }],
      }

      await render(<DocumentsPage knowledgeSpaceId="space-1" />)
      await user.click(screen.getByRole('checkbox', { name: 'One.pdf' }))
      const actions = screen.getByRole('group', {
        name: 'knowledgeDocuments.bulkDocumentActions',
      })

      expect(
        within(actions).getByRole('button', { name: 'knowledgeSpace.reindexDocuments' }),
      ).toBeDisabled()
      expect(
        within(actions).getByRole('button', { name: 'knowledgeDocuments.downloadDocuments' }),
      ).toBeDisabled()
      expect(
        within(actions).getByRole('button', { name: 'knowledgeSpace.disableSource' }),
      ).toBeDisabled()
      expect(within(actions).getByRole('button', { name: 'common.operation.remove' })).toBeEnabled()
    },
  )

  it('does not offer a bulk availability action for failed documents', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [{ items: [document({ id: 'failed', status: 'failed', title: 'Failed.pdf' })] }],
    }
    tasksQuery.data = {
      pages: [{ items: [task({ documentId: 'failed', state: 'failed' })] }],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'Failed.pdf' }))
    const actions = screen.getByRole('group', {
      name: 'knowledgeDocuments.bulkDocumentActions',
    })

    expect(
      within(actions).queryByRole('button', { name: 'knowledgeSpace.disableSource' }),
    ).not.toBeInTheDocument()
    expect(within(actions).getByRole('button', { name: 'common.operation.remove' })).toBeEnabled()
  })

  it('disables selected documents through the bulk availability API', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({ id: 'one', rowVersion: 2, title: 'One.pdf' }),
            document({ id: 'two', rowVersion: 4, title: 'Two.pdf' }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'One.pdf' }))
    await user.click(screen.getByRole('checkbox', { name: 'Two.pdf' }))

    const actions = screen.getByRole('group', {
      name: 'knowledgeDocuments.bulkDocumentActions',
    })
    expect(
      within(actions).getByRole('button', { name: 'knowledgeDocuments.downloadDocuments' }),
    ).toBeEnabled()
    await user.click(within(actions).getByRole('button', { name: 'knowledgeSpace.disableSource' }))

    expect(bulkUpdateLogicalDocumentsMutation).toHaveBeenCalledWith(
      {
        body: {
          documents: [
            { documentId: 'one', expectedRowVersion: 2 },
            { documentId: 'two', expectedRowVersion: 4 },
          ],
          enabled: false,
        },
        params: { control_space_id: 'space-1' },
      },
      { context: { silent: true } },
    )
    expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
      expect.objectContaining({
        queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.get.key(),
      }),
    )
    await waitFor(() =>
      expect(
        screen.queryByRole('group', { name: 'knowledgeDocuments.bulkDocumentActions' }),
      ).not.toBeInTheDocument(),
    )
  })

  it('re-enables selected disabled documents through the bulk availability API', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({ enabled: false, id: 'one', rowVersion: 3, title: 'One.pdf' }),
            document({ enabled: false, id: 'two', rowVersion: 7, title: 'Two.pdf' }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'One.pdf' }))
    await user.click(screen.getByRole('checkbox', { name: 'Two.pdf' }))
    const actions = screen.getByRole('group', {
      name: 'knowledgeDocuments.bulkDocumentActions',
    })
    await user.click(within(actions).getByRole('button', { name: 'dataset.enable' }))

    expect(bulkUpdateLogicalDocumentsMutation).toHaveBeenCalledWith(
      {
        body: {
          documents: [
            { documentId: 'one', expectedRowVersion: 3 },
            { documentId: 'two', expectedRowVersion: 7 },
          ],
          enabled: true,
        },
        params: { control_space_id: 'space-1' },
      },
      { context: { silent: true } },
    )
    expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
      expect.objectContaining({
        queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.get.key(),
      }),
    )
  })

  it('does not submit availability updates for more than 100 selected documents', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: Array.from({ length: 101 }, (_, index) =>
            document({ id: `document-${index}`, title: `Document ${index}.pdf` }),
          ),
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('checkbox', { name: 'knowledgeDocuments.selectAllDocuments' }),
    )
    const actions = screen.getByRole('group', {
      name: 'knowledgeDocuments.bulkDocumentActions',
    })

    expect(
      within(actions).getByRole('button', { name: 'knowledgeSpace.disableSource' }),
    ).toBeDisabled()
    expect(bulkUpdateLogicalDocumentsMutation).not.toHaveBeenCalled()
  })

  it('refreshes documents after an availability row-version conflict', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    updateLogicalDocumentMutation.mockRejectedValueOnce(
      createHttpError(new Response(null, { status: 409 })),
    )

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
    await user.click(await screen.findByRole('menuitem', { name: 'knowledgeSpace.disableSource' }))

    expect(queryClient.invalidateQueries).toHaveBeenCalled()
    expect(toastMock.warning).toHaveBeenCalledWith('knowledgeSpace.taskActionFailed')
  })

  it('downloads selected active revisions as a ZIP archive', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({ id: 'one', title: 'One.pdf' }),
            document({ id: 'two', title: 'Two.pdf' }),
          ],
        },
      ],
    }
    const archive = new File(['documents'], 'space-1-documents.zip', {
      type: 'application/zip',
    })
    downloadDocumentsMutation.mockResolvedValue(archive)

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'One.pdf' }))
    await user.click(screen.getByRole('checkbox', { name: 'Two.pdf' }))
    const actions = screen.getByRole('group', {
      name: 'knowledgeDocuments.bulkDocumentActions',
    })
    await user.click(
      within(actions).getByRole('button', { name: 'knowledgeDocuments.downloadDocuments' }),
    )

    expect(downloadDocumentsMutation).toHaveBeenCalledWith(
      {
        body: { document_ids: ['one', 'two'] },
        params: { control_space_id: 'space-1' },
      },
      { context: { silent: true } },
    )
    expect(downloadBlobMock).toHaveBeenCalledWith({
      data: archive,
      fileName: 'space-1-documents.zip',
    })
  })

  it('allows bulk download without document-write permission', async () => {
    const user = userEvent.setup()
    permissionStateMock.datasetKeys = ['dataset.acl.readonly', 'dataset.acl.document_download']
    permissionStateMock.spaceKeys = ['knowledge_space_read']
    documentsQuery.data = {
      pages: [{ items: [document({ id: 'download-only', title: 'Download only.pdf' })] }],
    }
    const archive = new File(['documents'], 'download-only.zip', {
      type: 'application/zip',
    })
    downloadDocumentsMutation.mockResolvedValue(archive)

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const selection = screen.getByRole('checkbox', { name: 'Download only.pdf' })
    expect(selection).toBeEnabled()
    await user.click(selection)
    const actions = screen.getByRole('group', {
      name: 'knowledgeDocuments.bulkDocumentActions',
    })
    expect(
      within(actions).queryByRole('button', { name: 'knowledgeSpace.reindexDocuments' }),
    ).not.toBeInTheDocument()
    expect(
      within(actions).queryByRole('button', { name: 'common.operation.remove' }),
    ).not.toBeInTheDocument()
    await user.click(
      within(actions).getByRole('button', { name: 'knowledgeDocuments.downloadDocuments' }),
    )

    expect(downloadDocumentsMutation).toHaveBeenCalledWith(
      {
        body: { document_ids: ['download-only'] },
        params: { control_space_id: 'space-1' },
      },
      { context: { silent: true } },
    )
  })

  it('downloads selected failed documents without active revisions as a ZIP archive', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({
              active: null,
              activeRevision: undefined,
              id: 'failed',
              status: 'failed',
              title: 'Failed.pdf',
            }),
          ],
        },
      ],
    }
    tasksQuery.data = {
      pages: [
        {
          items: [task({ documentId: 'failed', documentRevision: 1, state: 'failed' })],
        },
      ],
    }
    const archive = new File(['documents'], 'failed-documents.zip', {
      type: 'application/zip',
    })
    downloadDocumentsMutation.mockResolvedValue(archive)

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'Failed.pdf' }))
    const actions = screen.getByRole('group', {
      name: 'knowledgeDocuments.bulkDocumentActions',
    })
    const download = within(actions).getByRole('button', {
      name: 'knowledgeDocuments.downloadDocuments',
    })
    expect(download).toBeEnabled()
    await user.click(download)

    expect(downloadDocumentsMutation).toHaveBeenCalledWith(
      {
        body: { document_ids: ['failed'] },
        params: { control_space_id: 'space-1' },
      },
      { context: { silent: true } },
    )
    expect(downloadBlobMock).toHaveBeenCalledWith({
      data: archive,
      fileName: 'failed-documents.zip',
    })
  })

  it('disables bulk download when any selected document is pending', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({ id: 'ready', title: 'Ready.pdf' }),
            document({
              active: null,
              activeRevision: undefined,
              id: 'pending',
              status: 'pending',
              title: 'Pending.pdf',
            }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'Ready.pdf' }))
    await user.click(screen.getByRole('checkbox', { name: 'Pending.pdf' }))

    const actions = screen.getByRole('group', {
      name: 'knowledgeDocuments.bulkDocumentActions',
    })
    expect(
      within(actions).getByRole('button', { name: 'knowledgeDocuments.downloadDocuments' }),
    ).toBeDisabled()
    expect(downloadDocumentsMutation).not.toHaveBeenCalled()
  })

  it('disables bulk download when more than 100 documents are selected', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: Array.from({ length: 101 }, (_, index) =>
            document({ id: `document-${index}`, title: `Document ${index}.pdf` }),
          ),
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('checkbox', { name: 'knowledgeDocuments.selectAllDocuments' }),
    )

    const actions = screen.getByRole('group', {
      name: 'knowledgeDocuments.bulkDocumentActions',
    })
    expect(
      within(actions).getByRole('button', { name: 'knowledgeDocuments.downloadDocuments' }),
    ).toBeDisabled()
    expect(downloadDocumentsMutation).not.toHaveBeenCalled()
  })

  it('removes selected documents through one bulk deletion request', async () => {
    const user = userEvent.setup()
    systemFeaturesStateMock.deploymentEdition = 'CLOUD'
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({ id: 'one', rowVersion: 2, title: 'One.pdf' }),
            document({ id: 'two', rowVersion: 4, title: 'Two.pdf' }),
          ],
        },
      ],
    }

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'One.pdf' }))
    await user.click(screen.getByRole('checkbox', { name: 'Two.pdf' }))
    await user.click(screen.getByRole('button', { name: 'common.operation.remove' }))

    expect(bulkRemoveDocumentsMutation).not.toHaveBeenCalled()
    await user.click(screen.getByRole('button', { name: 'common.operation.remove' }))
    expect(bulkRemoveDocumentsMutation).toHaveBeenCalledOnce()
    expect(bulkRemoveDocumentsMutation).toHaveBeenCalledWith(
      {
        body: {
          documents: [
            { documentId: 'one', expectedRevision: 2 },
            { documentId: 'two', expectedRevision: 4 },
          ],
        },
        headers: { 'Idempotency-Key': expect.any(String) },
        params: { control_space_id: 'space-1' },
      },
      { context: { silent: true } },
    )
    expect(removeDocumentMutation).not.toHaveBeenCalled()
    expect(queryClient.invalidateQueries).not.toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.get.key() },
      { cancelRefetch: false },
    )
    expect(queryClient.invalidateQueries).not.toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.vectorSpace.get.key() },
      { cancelRefetch: false },
    )

    tasksQuery.data = {
      pages: [
        {
          items: [
            backgroundTask({
              operation: 'document_delete',
              progressCompleted: 2,
              progressTotal: 2,
            }),
          ],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() =>
      expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
        { queryKey: consoleQuery.features.get.key() },
        { cancelRefetch: false },
      ),
    )
    expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.vectorSpace.get.key() },
      { cancelRefetch: false },
    )

    vi.mocked(queryClient.invalidateQueries).mockClear()
    tasksQuery.data = {
      pages: [
        {
          items: [
            backgroundTask({
              operation: 'document_delete',
              progressCompleted: 2,
              progressTotal: 2,
            }),
          ],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(queryClient.invalidateQueries).not.toHaveBeenCalled()
  })

  it('keeps rejected documents selected after a partial bulk deletion', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({ id: 'one', rowVersion: 2, title: 'One.pdf' }),
            document({ id: 'two', rowVersion: 4, title: 'Two.pdf' }),
          ],
        },
      ],
    }
    bulkRemoveDocumentsMutation.mockResolvedValue({
      items: [],
      results: [
        { document_id: 'one', status: 'accepted' },
        { document_id: 'two', status: 'rejected' },
      ],
      total: 2,
    })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'One.pdf' }))
    await user.click(screen.getByRole('checkbox', { name: 'Two.pdf' }))
    await user.click(screen.getByRole('button', { name: 'common.operation.remove' }))
    await user.click(
      within(screen.getByRole('alertdialog')).getByRole('button', {
        name: 'common.operation.remove',
      }),
    )

    await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
    expect(screen.getByRole('checkbox', { name: 'One.pdf' })).not.toBeChecked()
    expect(screen.getByRole('checkbox', { name: 'Two.pdf' })).toBeChecked()
    expect(toastMock.warning).toHaveBeenCalledWith(
      'knowledgeDocuments.documentsRemovePartial:{"rejected":1,"removed":1}',
    )
  })

  it('explains the selection limit instead of sending oversized re-index or delete requests', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: Array.from({ length: 101 }, (_, index) =>
            document({ id: `document-${index}`, title: `Document ${index}.pdf` }),
          ),
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('checkbox', { name: 'knowledgeDocuments.selectAllDocuments' }),
    )

    const actions = screen.getByRole('group', {
      name: 'knowledgeDocuments.bulkDocumentActions',
    })
    const reindex = within(actions).getByRole('button', {
      name: 'knowledgeSpace.reindexDocuments',
    })
    const remove = within(actions).getByRole('button', { name: 'common.operation.remove' })
    const limit = 'knowledgeDocuments.documentSelectionLimit:{"max":100}'
    expect(within(actions).getByText(limit)).toBeVisible()
    expect(reindex).toBeDisabled()
    expect(reindex).toHaveAccessibleDescription(limit)
    expect(remove).toBeDisabled()
    expect(remove).toHaveAccessibleDescription(limit)

    await user.click(reindex)
    await user.click(remove)
    expect(reindexMutation.mutateAsync).not.toHaveBeenCalled()
    expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
    expect(bulkRemoveDocumentsMutation).not.toHaveBeenCalled()
  })

  it('prompts for model setup before re-indexing selected documents', async () => {
    const user = userEvent.setup()
    settingsState.configurationState = 'setup-required'
    documentsQuery.data = {
      pages: [{ items: [document({ id: 'one', title: 'One.pdf' })] }],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'One.pdf' }))
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.reindexDocuments' }))

    expect(reindexMutation.mutateAsync).not.toHaveBeenCalled()
    expect(
      screen.getByRole('dialog', {
        name: 'knowledgeSpace.overview.attention.modelReadiness.title',
      }),
    ).toBeInTheDocument()
  })

  it('explains why re-indexing becomes unavailable while results refresh', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    // The document's source is not among the loaded sources.
    sourcesQuery.data = { pages: [{ items: [] }] }
    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' }))

    documentsQuery.error = new Error('document refresh failed')
    await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    const actions = screen.getByRole('group', {
      name: 'knowledgeDocuments.bulkDocumentActions',
    })
    expect(
      within(actions).getByRole('button', { name: 'knowledgeSpace.reindexDocuments' }),
    ).toHaveAttribute('aria-describedby', 'document-reindex-unavailable')
    expect(
      within(actions).getByText(
        'knowledgeSpace.reindexDocuments · knowledgeSpace.documentsErrorDescription',
      ),
    ).toBeVisible()

    documentsQuery.error = null
    sourcesQuery.error = new Error('source refresh failed')
    await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(
      within(actions).getByText(
        'knowledgeSpace.reindexDocuments · knowledgeSpace.sourcesErrorDescription',
      ),
    ).toBeVisible()
  })

  it('keeps missing documents selected after a partial bulk re-index result', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({ id: 'one', title: 'One.pdf' }),
            document({ id: 'missing', title: 'Missing.pdf' }),
          ],
        },
      ],
    }
    reindexMutation.mutateAsync.mockResolvedValue({
      bulkJobId: 'reindex-partial',
      items: [
        {
          asset: {
            createdAt: '2026-07-20T10:00:00Z',
            filename: 'one.pdf',
            id: 'asset-1',
            knowledgeSpaceId: 'space-1',
            mimeType: 'application/pdf',
            objectKey: 'documents/one.pdf',
            parserStatus: 'pending',
            sha256: 'sha',
            sizeBytes: 1024,
            version: 1,
          },
          compilationJob: { id: 'job-1', stage: 'queued' },
          status: 'queued',
          statusUrl: '/tasks/job-1',
        },
        { documentId: 'missing', status: 'not_found' },
      ],
      total: 2,
    })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'One.pdf' }))
    await user.click(screen.getByRole('checkbox', { name: 'Missing.pdf' }))
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.reindexDocuments' }))

    expect(screen.getByRole('checkbox', { name: 'One.pdf' })).not.toBeChecked()
    expect(screen.getByRole('checkbox', { name: 'Missing.pdf' })).toBeChecked()
    expect(toastMock.warning).toHaveBeenCalledWith(
      'knowledgeSpace.documentsReindexPartial:{"missing":1,"queued":1}',
    )
  })

  it.each(['disabled', 'failed'] as const)(
    'keeps %s documents selected after a partial bulk re-index result',
    async (status) => {
      const user = userEvent.setup()
      documentsQuery.data = {
        pages: [
          {
            items: [
              document({ id: 'one', title: 'One.pdf' }),
              document({ id: 'disabled', title: 'Disabled.pdf' }),
            ],
          },
        ],
      }
      reindexMutation.mutateAsync.mockResolvedValue({
        bulkJobId: 'reindex-partial-disabled',
        items: [
          {
            asset: {
              createdAt: '2026-07-20T10:00:00Z',
              filename: 'one.pdf',
              id: 'asset-1',
              knowledgeSpaceId: 'space-1',
              mimeType: 'application/pdf',
              objectKey: 'documents/one.pdf',
              parserStatus: 'pending',
              sha256: 'sha',
              sizeBytes: 1024,
              version: 1,
            },
            compilationJob: { id: 'job-1', stage: 'queued' },
            status: 'queued',
            statusUrl: '/tasks/job-1',
          },
          { documentId: 'disabled', status },
        ],
        total: 2,
      })

      await render(<DocumentsPage knowledgeSpaceId="space-1" />)
      await user.click(screen.getByRole('checkbox', { name: 'One.pdf' }))
      await user.click(screen.getByRole('checkbox', { name: 'Disabled.pdf' }))
      await user.click(screen.getByRole('button', { name: 'knowledgeSpace.reindexDocuments' }))

      expect(screen.getByRole('checkbox', { name: 'One.pdf' })).not.toBeChecked()
      expect(screen.getByRole('checkbox', { name: 'Disabled.pdf' })).toBeChecked()
      expect(toastMock.warning).toHaveBeenCalledWith('knowledgeDocuments.documentsReindexFailed')
    },
  )

  it('keeps quota-blocked documents selected after a partial bulk re-index', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({ id: 'one', title: 'One.pdf' }),
            document({ id: 'blocked', title: 'Blocked.pdf' }),
          ],
        },
      ],
    }
    reindexMutation.mutateAsync.mockResolvedValueOnce({
      bulkJobId: 'quota-partial',
      items: [
        { documentId: 'one', status: 'queued' },
        { documentId: 'blocked', status: 'failed', code: 'VECTOR_SPACE_QUOTA_EXCEEDED' },
      ],
      total: 2,
    })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'One.pdf' }))
    await user.click(screen.getByRole('checkbox', { name: 'Blocked.pdf' }))
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.reindexDocuments' }))

    expect(screen.getByRole('checkbox', { name: 'One.pdf' })).not.toBeChecked()
    expect(screen.getByRole('checkbox', { name: 'Blocked.pdf' })).toBeChecked()
    expect(toastMock.warning).toHaveBeenCalledWith(
      'knowledgeErrors.taskFailure.vectorSpaceQuotaExceeded',
    )
    expect(toastMock.success).not.toHaveBeenCalled()
  })

  it('clears stale selection and refreshes after every re-index target is missing', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({ id: 'missing' })] }] }
    reindexMutation.mutateAsync.mockResolvedValue({
      bulkJobId: 'reindex-missing',
      items: [{ documentId: 'missing', status: 'not_found' }],
      total: 1,
    })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' }))
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.reindexDocuments' }))

    expect(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' })).not.toBeChecked()
    expect(
      screen.queryByRole('group', { name: 'knowledgeDocuments.bulkDocumentActions' }),
    ).not.toBeInTheDocument()
    expect(queryClient.invalidateQueries).toHaveBeenCalled()
    expect(toastMock.error).toHaveBeenCalledWith(
      'knowledgeSpace.documentsReindexPartial:{"missing":1,"queued":0}',
    )
  })

  it('counts only attention tasks and opens the designed task panel', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({ id: 'running', progressCompleted: 1, progressTotal: 3 }),
            task({
              id: 'failed',
              state: 'failed',
              errorMessage: 'Parser failed',
              progressCompleted: 8,
              progressTotal: 12,
            }),
            task({
              canRetry: true,
              id: 'canceled',
              state: 'canceled',
              progressCompleted: 2,
              progressTotal: 5,
            }),
            task({ id: 'done', state: 'succeeded' }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    const trigger = screen.getByRole('button', {
      name: 'knowledgeDocuments.tasksWithAttention:{"count":3}',
    })
    expect(trigger).toHaveTextContent('3')
    expect(trigger).toHaveAttribute('data-has-error', 'true')
    await user.click(trigger)
    const panel = screen.getByRole('dialog', { name: 'knowledgeSpace.backgroundTasks' })
    expect(within(panel).getByText('knowledgeTasks.backgroundTasksDescription')).toBeInTheDocument()
    expect(within(panel).getByText('knowledgeErrors.taskFailure.internal')).toBeInTheDocument()
    expect(
      within(panel).getByText((_, element) =>
        Boolean(
          element?.tagName === 'P' &&
          element.textContent?.includes('1/3') &&
          element.textContent.includes('—'),
        ),
      ),
    ).toBeInTheDocument()
    expect(
      within(panel).getByRole('button', {
        name: /knowledgeSpace\.retryTask.*canceled/,
      }),
    ).toBeInTheDocument()
  })

  it('dismisses a failed task from attention and restores it through undo', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              documentTitle: 'failed.pdf',
              id: 'failed-task',
              state: 'failed',
            }),
            task({ documentTitle: 'completed.pdf', id: 'completed-task', state: 'succeeded' }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )

    const panel = screen.getByRole('dialog', { name: 'knowledgeSpace.backgroundTasks' })
    await user.click(
      within(panel).getByRole('button', {
        name: /knowledgeTasks\.dismissTask.*failed-task/,
      }),
    )

    expect(within(panel).queryByText(/failed\.pdf/)).not.toBeInTheDocument()
    expect(within(panel).getByText(/completed\.pdf/)).toBeInTheDocument()
    expect(screen.getByText('knowledgeDocuments.taskAttentionClear')).toBeInTheDocument()
    expect(toastMock.info).toHaveBeenCalledWith('knowledgeTasks.taskDismissed', {
      actionProps: expect.objectContaining({
        children: 'knowledgeTasks.undoTaskDismissal',
      }),
    })

    const toastOptions = toastMock.info.mock.calls.at(-1)?.[1]
    act(() => toastOptions?.actionProps.onClick())

    expect(within(panel).getByText(/failed\.pdf/)).toBeInTheDocument()
    expect(
      screen.getByText('knowledgeDocuments.taskAttentionErrorCount:{"count":1}'),
    ).toBeInTheDocument()
  })

  it('keeps a dismissed failed task hidden after the page remounts', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({ documentTitle: 'failed.pdf', id: 'failed-task', state: 'failed' }),
            task({ documentTitle: 'completed.pdf', id: 'completed-task', state: 'succeeded' }),
          ],
        },
      ],
    }

    const firstRender = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(
      within(screen.getByRole('dialog')).getByRole('button', {
        name: /knowledgeTasks\.dismissTask.*failed-task/,
      }),
    )
    firstRender.unmount()

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('button', { name: 'knowledgeDocuments.tasks' }))

    const panel = screen.getByRole('dialog', { name: 'knowledgeSpace.backgroundTasks' })
    expect(within(panel).queryByText(/failed\.pdf/)).not.toBeInTheDocument()
    expect(within(panel).getByText(/completed\.pdf/)).toBeInTheDocument()
  })

  it('dismisses a completed task while keeping active tasks visible', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({ documentTitle: 'completed.pdf', id: 'completed-task', state: 'succeeded' }),
            task({ documentTitle: 'running.pdf', id: 'running-task', state: 'running' }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('button', { name: /^knowledgeDocuments\.tasks/ }))

    const panel = screen.getByRole('dialog', { name: 'knowledgeSpace.backgroundTasks' })
    await user.click(
      within(panel).getByRole('button', {
        name: /knowledgeTasks\.dismissTask.*completed-task/,
      }),
    )

    expect(within(panel).queryByText(/completed\.pdf/)).not.toBeInTheDocument()
    expect(within(panel).getByText(/running\.pdf/)).toBeInTheDocument()
    expect(
      within(panel).queryByRole('button', {
        name: /knowledgeTasks\.dismissTask.*running-task/,
      }),
    ).not.toBeInTheDocument()
  })

  it('shows document, bulk re-index, and source tasks returned by the task list', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    sourcesQuery.data = { pages: [{ items: [] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({ id: 'document-task', state: 'succeeded' }),
            backgroundTask({
              documentId: 'document-1',
              id: 'reindex-task',
              progressCompleted: 1,
              progressTotal: 1,
            }),
            backgroundTask({
              errorMessage: 'Source sync failed',
              id: 'source-task',
              operation: 'source_sync',
              sourceId: 'source-1',
              sourceTitle: 'Notion support SOP',
              state: 'failed',
              taskKind: 'source',
            }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )

    const panel = screen.getByRole('dialog', { name: 'knowledgeSpace.backgroundTasks' })
    expect(within(panel).getAllByRole('listitem')).toHaveLength(3)
    expect(
      within(panel).getByText('knowledgeSpace.reindexDocuments · sso-enterprise.pdf'),
    ).toBeInTheDocument()
    expect(
      within(panel).getByText('knowledgeTasks.overview.operation.source_sync · Notion support SOP'),
    ).toBeInTheDocument()
    expect(within(panel).queryByText(/ · 1$/)).not.toBeInTheDocument()
    expect(within(panel).getByText('knowledgeErrors.taskFailure.internal')).toBeInTheDocument()
  })

  it('shows a single deletion document title and its checkpoint progress', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            backgroundTask({
              documentId: 'deleted-document',
              documentTitle: 'dify使用问题反馈.xlsx',
              id: 'delete-task',
              operation: 'document_delete',
              progressCompleted: 0,
              progressPercent: 10,
              progressTotal: 1,
              state: 'running',
            }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )

    const panel = screen.getByRole('dialog', { name: 'knowledgeSpace.backgroundTasks' })
    expect(
      within(panel).getByText(
        'knowledgeTasks.overview.operation.document_delete · dify使用问题反馈.xlsx',
      ),
    ).toBeInTheDocument()
    expect(within(panel).getByText((content) => content.startsWith('10%'))).toBeInTheDocument()
    expect(
      within(panel).queryByText('knowledgeTasks.overview.operation.document_delete · 1'),
    ).not.toBeInTheDocument()
  })

  it('gives duplicate task actions distinct accessible names', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({ id: 'document-a', title: 'Alpha.pdf' }),
            document({ id: 'document-b', title: 'Beta.pdf' }),
          ],
        },
      ],
    }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({ documentId: 'document-a', id: 'task-a' }),
            task({ documentId: 'document-b', id: 'task-b' }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":2}',
      }),
    )

    expect(
      screen.getByRole('button', {
        name: 'knowledgeTasks.interruptTask · knowledgeSpace.addDocument · Alpha.pdf · task-a',
      }),
    ).toBeInTheDocument()
    expect(
      screen.getByRole('button', {
        name: 'knowledgeTasks.interruptTask · knowledgeSpace.addDocument · Beta.pdf · task-b',
      }),
    ).toBeInTheDocument()
  })

  it('shows task loading instead of an empty result while the task query is pending', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ state: 'running' })] }] }
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )

    // The task cache is reset and its first page has not arrived again yet.
    tasksQuery.isPending = true
    act(() => {
      void queryClient.resetQueries({
        queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.backgroundTasks.get.key(),
      })
    })
    await settle()

    const panel = screen.getByRole('dialog', { name: 'knowledgeSpace.backgroundTasks' })
    expect(within(panel).getByRole('progressbar', { name: 'common.loading' })).toBeInTheDocument()
    expect(within(panel).queryByText('knowledgeTasks.noBackgroundTasks')).not.toBeInTheDocument()
  })

  it('prevents duplicate interrupt requests and refreshes both resources', async () => {
    const user = userEvent.setup()
    let resolveCancel: ((value: DocumentProcessingTask) => void) | undefined
    cancelMutation.mutateAsync.mockImplementation(
      () =>
        new Promise((resolve) => {
          resolveCancel = resolve
        }),
    )
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'running' })] }] }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    const interrupt = screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' })
    await user.dblClick(interrupt)

    expect(cancelMutation.mutateAsync).toHaveBeenCalledOnce()
    expect(cancelMutation.mutateAsync).toHaveBeenCalledWith({
      params: {
        control_space_id: 'space-1',
        task_id: 'running',
        task_kind: 'document',
      },
    })
    await act(async () => resolveCancel?.(task({ id: 'running', state: 'canceled' })))
    expect(queryClient.invalidateQueries).toHaveBeenCalled()
    expect(screen.getByRole('button', { name: 'common.operation.close' })).toHaveFocus()
  })

  it('locks cancel and retry together while either task mutation is pending', async () => {
    const user = userEvent.setup()
    let resolveCancel: ((value: DocumentProcessingTask) => void) | undefined
    cancelMutation.mutateAsync.mockImplementation(
      () =>
        new Promise((resolve) => {
          resolveCancel = resolve
        }),
    )
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'shared-task' })] }] }
    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' }))

    tasksQuery.data = {
      pages: [{ items: [task({ id: 'shared-task', state: 'failed' })] }],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    const retry = screen.getByRole('button', { name: 'knowledgeSpace.retryTask' })
    expect(retry).toHaveAttribute('aria-disabled', 'true')
    await user.click(retry)
    expect(retryMutation.mutateAsync).not.toHaveBeenCalled()

    await act(async () => resolveCancel?.(task({ id: 'shared-task', state: 'canceled' })))
  })

  it('retries a failed task once and reports mutation errors in the panel', async () => {
    const user = userEvent.setup()
    retryMutation.mutateAsync.mockRejectedValueOnce(new Error('retry failed'))
    documentsQuery.data = {
      pages: [{ items: [document({ latestTask: task({ id: 'failed', state: 'failed' }) })] }],
    }
    tasksQuery.data = { pages: [{ items: [task({ id: 'failed', state: 'failed' })] }] }

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))

    expect(retryMutation.mutateAsync).toHaveBeenCalledOnce()
    expect(await screen.findByRole('alert')).toHaveTextContent('knowledgeSpace.taskActionFailed')

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'failed',
              state: 'running',
              updatedAt: '2026-07-20T10:02:00Z',
            }),
          ],
        },
      ],
    }
    await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(screen.queryByText('knowledgeSpace.taskActionFailed')).not.toBeInTheDocument()
  })

  it('shows a retry quota error in the task panel without treating it as a permission denial', async () => {
    const user = userEvent.setup()
    const failedTask = task({ id: 'failed', state: 'failed' })
    documentsQuery.data = { pages: [{ items: [document({ latestTask: failedTask })] }] }
    tasksQuery.data = { pages: [{ items: [failedTask] }] }
    retryMutation.mutateAsync.mockRejectedValueOnce(
      Response.json(
        {
          failure: {
            action: 'retry',
            category: 'configuration',
            code: 'DOCUMENT_COUNT_QUOTA_EXCEEDED',
            message: 'Upstream quota details',
            retryPolicy: 'manual',
          },
        },
        { status: 413 },
      ),
    )

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', { name: 'knowledgeDocuments.tasksWithAttention:{"count":1}' }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))

    expect(await screen.findByRole('alert')).toHaveTextContent(
      'knowledgeErrors.taskFailure.documentCountQuotaExceeded',
    )
    expect(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' })).toBeEnabled()
    expect(toastMock.error).not.toHaveBeenCalled()
  })

  it('does not restore an action failure after its drawer cycle closes', async () => {
    const user = userEvent.setup()
    let rejectCancel: ((reason?: unknown) => void) | undefined
    cancelMutation.mutateAsync.mockImplementation(
      () =>
        new Promise((_resolve, reject) => {
          rejectCancel = reject
        }),
    )
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task()] }] }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' }))
    await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
    await act(async () => rejectCancel?.(new Error('cancel failed after close')))

    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    expect(screen.queryByText('knowledgeSpace.taskActionFailed')).not.toBeInTheDocument()
  })

  it('does not move focus when an action from an older drawer cycle succeeds', async () => {
    const user = userEvent.setup()
    let resolveCancel: ((value: DocumentProcessingTask) => void) | undefined
    cancelMutation.mutateAsync.mockImplementation(
      () =>
        new Promise((resolve) => {
          resolveCancel = resolve
        }),
    )
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'old-action' })] }] }

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' }))
    await user.click(screen.getByRole('button', { name: 'common.operation.close' }))

    tasksQuery.data = {
      pages: [{ items: [task({ id: 'old-action' }), task({ id: 'new-action' })] }],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":2}',
      }),
    )
    const nextAction = screen.getByRole('button', {
      name: 'knowledgeTasks.interruptTask · knowledgeSpace.addDocument · sso-enterprise.pdf · new-action',
    })
    act(() => nextAction.focus())
    expect(nextAction).toHaveFocus()

    await act(async () => resolveCancel?.(task({ id: 'old-action', state: 'canceled' })))
    expect(nextAction).toHaveFocus()
  })

  it('does not move focus when the user leaves a pending task action', async () => {
    const user = userEvent.setup()
    let resolveCancel: ((value: DocumentProcessingTask) => void) | undefined
    cancelMutation.mutateAsync.mockImplementation(
      () =>
        new Promise((resolve) => {
          resolveCancel = resolve
        }),
    )
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [{ items: [task({ id: 'pending-action' }), task({ id: 'focus-target' })] }],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":2}',
      }),
    )
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeTasks.interruptTask · knowledgeSpace.addDocument · sso-enterprise.pdf · pending-action',
      }),
    )
    const nextAction = screen.getByRole('button', {
      name: 'knowledgeTasks.interruptTask · knowledgeSpace.addDocument · sso-enterprise.pdf · focus-target',
    })
    act(() => nextAction.focus())

    await act(async () => resolveCancel?.(task({ id: 'pending-action', state: 'canceled' })))
    expect(nextAction).toHaveFocus()
  })

  it('ignores a delayed action success after the task lifecycle advances', async () => {
    const user = userEvent.setup()
    let resolveRetry: ((value: DocumentProcessingTask) => void) | undefined
    retryMutation.mutateAsync.mockImplementation(
      () =>
        new Promise((resolve) => {
          resolveRetry = resolve
        }),
    )
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'advanced-success', state: 'failed' })] }] }

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))

    tasksQuery.data = {
      pages: [{ items: [task({ id: 'advanced-success', state: 'running' })] }],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await act(async () => resolveRetry?.(task({ id: 'advanced-success', state: 'queued' })))

    expect(screen.getByText(/45%/)).toBeInTheDocument()
  })

  it('ignores a delayed task action after document permission is revoked', async () => {
    const user = userEvent.setup()
    let resolveCancel: ((value: DocumentProcessingTask) => void) | undefined
    cancelMutation.mutateAsync.mockImplementation(
      () =>
        new Promise((resolve) => {
          resolveCancel = resolve
        }),
    )
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'revoked-action' })] }] }
    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' }))

    vi.mocked(queryClient.invalidateQueries).mockClear()
    documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await act(async () => resolveCancel?.(task({ id: 'revoked-action', state: 'canceled' })))
    expect(queryClient.invalidateQueries).not.toHaveBeenCalled()

    documentsQuery.error = null
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    ).toBeInTheDocument()
  })

  it('keeps a successful task action across a transient permission query failure', async () => {
    const user = userEvent.setup()
    let resolveCancel: ((value: DocumentProcessingTask) => void) | undefined
    cancelMutation.mutateAsync.mockImplementation(
      () =>
        new Promise((resolve) => {
          resolveCancel = resolve
        }),
    )
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'permission-query-action' })] }] }
    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' }))

    permissionStateMock.error = new Error('permission query unavailable')
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    vi.mocked(queryClient.invalidateQueries).mockClear()
    await act(async () =>
      resolveCancel?.(task({ id: 'permission-query-action', state: 'canceled' })),
    )

    expect(queryClient.invalidateQueries).toHaveBeenCalled()
    expect(screen.getByText(/knowledgeSpace\.processingTaskState\.canceled/)).toBeInTheDocument()
  })

  it('drops a delayed action failure after the task lifecycle advances', async () => {
    const user = userEvent.setup()
    let rejectRetry: ((reason?: unknown) => void) | undefined
    retryMutation.mutateAsync.mockImplementation(
      () =>
        new Promise((_resolve, reject) => {
          rejectRetry = reject
        }),
    )
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'advanced', state: 'failed' })] }] }

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))

    tasksQuery.data = { pages: [{ items: [task({ id: 'advanced', state: 'running' })] }] }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await act(async () => rejectRetry?.(new Error('late retry failure')))
    tasksQuery.data = { pages: [{ items: [task({ id: 'advanced', state: 'failed' })] }] }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.queryByText('knowledgeSpace.taskActionFailed')).not.toBeInTheDocument()
  })

  it('offers retry for an interrupted task when the operation is retryable', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = {
      pages: [{ items: [task({ canRetry: true, id: 'canceled', state: 'canceled' })] }],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )

    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))
    expect(retryMutation.mutateAsync).toHaveBeenCalledWith(
      expect.objectContaining({
        params: expect.objectContaining({ task_id: 'canceled', task_kind: 'document' }),
      }),
    )
  })

  it('clears an old failure across retry and shows the next terminal error', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({ id: 'retried-failure', state: 'failed', errorMessage: 'Old parser error' }),
          ],
        },
      ],
    }
    retryMutation.mutateAsync.mockResolvedValue(
      task({
        id: 'retried-failure',
        progressPercent: 0,
        state: 'queued',
        updatedAt: '2026-07-20T10:02:00Z',
      }),
    )
    streamProcessingTaskEvents.mockImplementation(async function* () {
      yield {
        data: {
          progressPercent: 20,
          stage: 'parsed' as const,
          state: 'failed' as const,
          updatedAt: '2026-07-20T10:03:00Z',
        },
        event: 'progress' as const,
        id: 'retried-failure:2026-07-20T10:03:00Z',
      }
      yield {
        data: { errorCode: 'NEW_PARSER_ERROR', state: 'failed' as const },
        event: 'terminal' as const,
        id: 'retried-failure:terminal',
      }
    })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))

    await waitFor(() => expect(screen.queryByText('Old parser error')).not.toBeInTheDocument())
    expect(await screen.findByText('knowledgeErrors.taskFailure.temporary')).toBeInTheDocument()
  })

  it('ignores a delayed retry response older than the current failed list snapshot', async () => {
    const user = userEvent.setup()
    let resolveRetry: ((snapshot: DocumentProcessingTask) => void) | undefined
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              errorCode: 'OLD_FAILURE',
              id: 'delayed-local-retry',
              state: 'failed',
              updatedAt: '2026-07-20T10:01:00Z',
            }),
          ],
        },
      ],
    }
    retryMutation.mutateAsync.mockReturnValue(
      new Promise<DocumentProcessingTask>((resolve) => {
        resolveRetry = resolve
      }),
    )

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              errorCode: 'NEWER_FAILURE',
              id: 'delayed-local-retry',
              state: 'failed',
              updatedAt: '2026-07-20T10:03:00Z',
            }),
          ],
        },
      ],
    }
    await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await act(async () =>
      resolveRetry?.(
        task({
          id: 'delayed-local-retry',
          state: 'dispatch_pending',
          updatedAt: '2026-07-20T10:02:00Z',
        }),
      ),
    )

    expect(await screen.findByText('knowledgeErrors.taskFailure.internal')).toBeInTheDocument()
    expect(
      screen.queryByRole('button', { name: 'knowledgeTasks.interruptTask' }),
    ).not.toBeInTheDocument()
  })

  it('accepts an exact active retry snapshot with the terminal timestamp', async () => {
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'same-time-retry' })] }] }
    getTaskSnapshot.mockResolvedValue(
      task({
        id: 'same-time-retry',
        progressPercent: 0,
        state: 'dispatch_pending',
        updatedAt: '2026-07-20T10:03:00Z',
      }),
    )
    let streamCount = 0
    streamProcessingTaskEvents.mockImplementation(async function* () {
      streamCount += 1
      if (streamCount === 1) {
        yield {
          data: {
            progressPercent: 80,
            stage: 'parsed' as const,
            state: 'failed' as const,
            updatedAt: '2026-07-20T10:03:00Z',
          },
          event: 'progress' as const,
          id: 'same-time-retry:2026-07-20T10:03:00Z',
        }
        yield {
          data: { errorCode: 'PARSER_FAILED', state: 'failed' as const },
          event: 'terminal' as const,
          id: 'same-time-retry:terminal',
        }
        return
      }
      await new Promise<void>(() => {})
    })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() =>
      expect(
        screen.getByRole('button', {
          name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
        }),
      ).toHaveTextContent('1'),
    )
    await waitFor(() => expect(streamProcessingTaskEvents).toHaveBeenCalledTimes(2))
    expect(getTaskSnapshot).toHaveBeenCalledWith(
      {
        params: { documentId: 'document-1', id: 'space-1', taskId: 'same-time-retry' },
      },
      expect.objectContaining({ signal: expect.any(AbortSignal) }),
    )
  })

  it('restarts an aborted equal-timestamp reconciliation after permission returns', async () => {
    const signals: AbortSignal[] = []
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'permission-reconciliation' })] }] }
    getTaskSnapshot.mockImplementation(
      (_input: unknown, options: { signal: AbortSignal }) =>
        new Promise<DocumentProcessingTask>((_resolve, reject) => {
          signals.push(options.signal)
          options.signal.addEventListener(
            'abort',
            () => reject(new DOMException('Aborted', 'AbortError')),
            { once: true },
          )
        }),
    )
    streamFailedTaskThenWait('permission-reconciliation')

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledOnce())
    tasksQuery.data = {
      pages: [
        {
          items: [task({ id: 'permission-reconciliation', updatedAt: '2026-07-20T10:03:00Z' })],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledTimes(2))

    documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() => expect(signals[1]?.aborted).toBe(true))
    documentsQuery.error = null
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await settle()

    // Recovery restarts the reconciliation; the task list it refetches may restart it once more.
    expect(getTaskSnapshot.mock.calls.length).toBeGreaterThanOrEqual(3)
    expect(signals.at(-1)?.aborted).toBe(false)
    expect(signals.slice(0, -1).every((signal) => signal.aborted)).toBe(true)
  })

  it('restores complete terminal error details from an equal list snapshot', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'listed-terminal-error' })] }] }
    getTaskSnapshot.mockRejectedValue(createHttpError(new Response(null, { status: 403 })))
    streamFailedTaskThenWait('listed-terminal-error')

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      await screen.findByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    expect(await screen.findByText('knowledgeErrors.taskFailure.temporary')).toBeInTheDocument()

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              errorCode: 'PARSER_FAILED',
              errorMessage: 'Parser failed at line 400 with complete server context',
              id: 'listed-terminal-error',
              state: 'failed',
              updatedAt: '2026-07-20T10:03:00Z',
            }),
          ],
        },
      ],
    }
    await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    const error = await screen.findByText('knowledgeErrors.taskFailure.temporary')
    expect(error).toHaveClass('whitespace-pre-wrap', 'wrap-break-word')
    expect(error).not.toHaveClass('truncate')
  })

  it('hides cached documents and closes tasks when terminal reconciliation loses read access', async () => {
    const user = userEvent.setup()
    let releaseStream!: () => void
    const streamGate = new Promise<void>((resolve) => {
      releaseStream = resolve
    })
    let resolveDocumentsRefetch!: (result: { error: null }) => void
    documentsQuery.data = { pages: [{ items: [document()] }] }
    documentsQuery.refetch.mockImplementation(
      () =>
        new Promise((resolve) => {
          resolveDocumentsRefetch = resolve
        }),
    )
    tasksQuery.data = { pages: [{ items: [task({ id: 'forbidden-reconciliation' })] }] }
    getTaskSnapshot.mockRejectedValue(createHttpError(new Response(null, { status: 403 })))
    streamProcessingTaskEvents.mockImplementation(async function* () {
      await streamGate
      yield {
        data: {
          progressPercent: 80,
          stage: 'parsed' as const,
          state: 'failed' as const,
          updatedAt: '2026-07-20T10:03:00Z',
        },
        event: 'progress' as const,
        id: 'forbidden-reconciliation:progress',
      }
      yield {
        data: { errorCode: 'PARSER_FAILED', state: 'failed' as const },
        event: 'terminal' as const,
        id: 'forbidden-reconciliation:terminal',
      }
    })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    expect(screen.getByRole('dialog')).toBeInTheDocument()

    await act(async () => releaseStream())

    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledOnce())
    await waitFor(() =>
      expect(screen.getByRole('alert')).toHaveTextContent(
        'knowledgeSpace.documentsPermissionDescription',
      ),
    )
    expect(screen.queryByText('sso-enterprise.pdf')).not.toBeInTheDocument()
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
    await waitFor(() => expect(documentsQuery.refetch).toHaveBeenCalled())

    await act(async () => resolveDocumentsRefetch({ error: null }))
    expect(await screen.findByText('sso-enterprise.pdf')).toBeInTheDocument()
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
  })

  it('blocks failed polling for a task version denied during terminal reconciliation', async () => {
    vi.useFakeTimers()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'denied-terminal-version' })] }] }
    getTaskSnapshot.mockRejectedValue(createHttpError(new Response(null, { status: 403 })))
    streamFailedTaskThenWait('denied-terminal-version')

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      await act(async () => {})
      expect(getTaskSnapshot).toHaveBeenCalledOnce()

      await act(async () => vi.advanceTimersByTime(5000))
      expect(getTaskSnapshot).toHaveBeenCalledOnce()
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('hides cached documents and closes tasks when the task event stream loses read access', async () => {
    const user = userEvent.setup()
    let rejectStream!: () => void
    const streamGate = new Promise<void>((_resolve, reject) => {
      rejectStream = () => reject(createHttpError(new Response(null, { status: 403 })))
    })
    let resolveDocumentsRefetch!: (result: { error: null }) => void
    documentsQuery.data = { pages: [{ items: [document()] }] }
    documentsQuery.refetch.mockImplementation(
      () =>
        new Promise((resolve) => {
          resolveDocumentsRefetch = resolve
        }),
    )
    tasksQuery.data = { pages: [{ items: [task({ id: 'forbidden-stream' })] }] }
    streamProcessingTaskEvents.mockImplementation(async function* () {
      await streamGate
    })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    expect(screen.getByRole('dialog')).toBeInTheDocument()

    await act(async () => rejectStream())

    await waitFor(() =>
      expect(screen.getByRole('alert')).toHaveTextContent(
        'knowledgeSpace.documentsPermissionDescription',
      ),
    )
    expect(screen.queryByText('sso-enterprise.pdf')).not.toBeInTheDocument()
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
    await waitFor(() => expect(documentsQuery.refetch).toHaveBeenCalled())

    await act(async () => resolveDocumentsRefetch({ error: null }))
    expect(await screen.findByText('sso-enterprise.pdf')).toBeInTheDocument()
    expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()
  })

  it('does not restart a denied stream version while the task list lags behind progress', async () => {
    let resolveDocumentsRefetch!: (result: { error: null }) => void
    documentsQuery.data = { pages: [{ items: [document()] }] }
    documentsQuery.refetch.mockImplementation(
      () =>
        new Promise((resolve) => {
          resolveDocumentsRefetch = resolve
        }),
    )
    tasksQuery.data = {
      pages: [
        {
          items: [task({ id: 'lagging-denied-stream', updatedAt: '2026-07-20T10:01:00Z' })],
        },
      ],
    }
    streamProcessingTaskEvents.mockImplementation(async function* () {
      yield {
        data: {
          progressPercent: 50,
          stage: 'parsed' as const,
          state: 'running' as const,
          updatedAt: '2026-07-20T10:02:00Z',
        },
        event: 'progress' as const,
        id: 'lagging-denied-stream:version-2',
      }
      throw createHttpError(new Response(null, { status: 403 }))
    })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() =>
      expect(screen.getByRole('alert')).toHaveTextContent(
        'knowledgeSpace.documentsPermissionDescription',
      ),
    )
    expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()

    await act(async () => resolveDocumentsRefetch({ error: null }))
    expect(await screen.findByText('sso-enterprise.pdf')).toBeInTheDocument()
    await act(async () => {})
    expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()
  })

  it('observes a same-version retry after the task list confirms a denied stream terminal', async () => {
    let resolveDocumentsRefetch!: (result: { error: null }) => void
    const deniedVersion = '2026-07-20T10:02:00Z'
    documentsQuery.data = { pages: [{ items: [document()] }] }
    documentsQuery.refetch.mockImplementation(
      () =>
        new Promise((resolve) => {
          resolveDocumentsRefetch = resolve
        }),
    )
    tasksQuery.data = {
      pages: [
        {
          items: [task({ id: 'same-version-terminal-retry' })],
        },
      ],
    }
    let streamCount = 0
    streamProcessingTaskEvents.mockImplementation(async function* () {
      streamCount += 1
      if (streamCount === 1) {
        yield {
          data: {
            progressPercent: 50,
            stage: 'parsed' as const,
            state: 'running' as const,
            updatedAt: deniedVersion,
          },
          event: 'progress' as const,
          id: 'same-version-terminal-retry:version-2',
        }
        throw createHttpError(new Response(null, { status: 403 }))
      }
      await new Promise<void>(() => {})
    })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() => expect(documentsQuery.refetch).toHaveBeenCalled())
    await act(async () => resolveDocumentsRefetch({ error: null }))

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'same-version-terminal-retry',
              state: 'failed',
              updatedAt: deniedVersion,
            }),
          ],
        },
      ],
    }
    await notifyTaskQuerySuccess()
    await act(async () => {})
    expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'same-version-terminal-retry',
              state: 'running',
              updatedAt: deniedVersion,
            }),
          ],
        },
      ],
    }
    await notifyTaskQuerySuccess()

    await waitFor(() => expect(streamProcessingTaskEvents).toHaveBeenCalledTimes(2))
  })

  it('restarts an active override after a structurally shared terminal confirmation', async () => {
    const user = userEvent.setup()
    let resolveDocumentsRefetch!: (result: { error: null }) => void
    const taskVersion = '2026-07-20T10:02:00Z'
    const sharedTerminalData = {
      pages: [
        {
          items: [
            task({
              id: 'shared-terminal-confirmation',
              state: 'failed',
              updatedAt: taskVersion,
            }),
          ],
        },
      ],
    }
    documentsQuery.data = { pages: [{ items: [document()] }] }
    documentsQuery.refetch.mockImplementation(
      () =>
        new Promise((resolve) => {
          resolveDocumentsRefetch = resolve
        }),
    )
    tasksQuery.data = sharedTerminalData
    retryMutation.mutateAsync.mockResolvedValue(
      task({
        id: 'shared-terminal-confirmation',
        state: 'dispatch_pending',
        updatedAt: taskVersion,
      }),
    )
    let streamCount = 0
    streamProcessingTaskEvents.mockImplementation(async function* () {
      streamCount += 1
      if (streamCount === 1) throw createHttpError(new Response(null, { status: 403 }))
      await new Promise<void>(() => {})
    })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))
    await waitFor(() => expect(documentsQuery.refetch).toHaveBeenCalled())
    expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()
    await act(async () => resolveDocumentsRefetch({ error: null }))

    tasksQuery.data = sharedTerminalData
    await notifyTaskQuerySuccess()

    await waitFor(() => expect(streamProcessingTaskEvents).toHaveBeenCalledTimes(2))
  })

  it('single-flights backed-off recovery polling until a denied stream gets a newer version', async () => {
    vi.useFakeTimers()
    let resolveDocumentsRefetch!: (result: { error: null }) => void
    let resolveTaskRefetch!: (result: { error: null }) => void
    documentsQuery.data = { pages: [{ items: [document()] }] }
    documentsQuery.refetch.mockImplementation(
      () =>
        new Promise((resolve) => {
          resolveDocumentsRefetch = resolve
        }),
    )
    tasksQuery.data = {
      pages: [
        {
          items: [task({ id: 'recovering-stream', updatedAt: '2026-07-20T10:01:00Z' })],
        },
      ],
    }
    let streamCount = 0
    streamProcessingTaskEvents.mockImplementation(async function* () {
      streamCount += 1
      if (streamCount === 1) {
        yield {
          data: {
            progressPercent: 50,
            stage: 'parsed' as const,
            state: 'running' as const,
            updatedAt: '2026-07-20T10:02:00Z',
          },
          event: 'progress' as const,
          id: 'recovering-stream:version-2',
        }
        throw createHttpError(new Response(null, { status: 403 }))
      }
      await new Promise<void>(() => {})
    })

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      await settle()
      expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()
      await act(async () => resolveDocumentsRefetch({ error: null }))
      tasksQuery.refetch.mockClear()
      tasksQuery.data = {
        pages: [
          {
            items: [task({ id: 'recovering-stream', updatedAt: '2026-07-20T10:02:00Z' })],
          },
        ],
      }
      await notifyTaskQuerySuccess()
      await settle()
      tasksQuery.refetch
        .mockImplementationOnce(
          () =>
            new Promise((resolve) => {
              resolveTaskRefetch = resolve
            }),
        )
        .mockResolvedValue({ error: null })

      await act(() => vi.advanceTimersByTimeAsync(5000))
      await settle()
      expect(tasksQuery.refetch).toHaveBeenCalled()
      expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()
      await act(() => vi.advanceTimersByTimeAsync(120000))
      expect(tasksQuery.refetch).toHaveBeenCalledOnce()

      await act(async () => resolveTaskRefetch({ error: null }))
      for (const delay of [10000, 20000, 30000, 30000, 30000, 30000])
        await act(() => vi.advanceTimersByTimeAsync(delay))
      expect(tasksQuery.refetch).toHaveBeenCalledTimes(7)
      expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()

      tasksQuery.data = {
        pages: [
          {
            items: [task({ id: 'recovering-stream', updatedAt: '2026-07-20T10:03:00Z' })],
          },
        ],
      }
      await notifyTaskQuerySuccess()
      await settle()

      expect(streamProcessingTaskEvents).toHaveBeenCalledTimes(2)
      tasksQuery.refetch.mockClear()
      await act(() => vi.advanceTimersByTimeAsync(60000))
      expect(tasksQuery.refetch).not.toHaveBeenCalled()
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('focuses the permission alert when an auxiliary retry becomes a document denial', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    documentsQuery.refetch
      .mockResolvedValueOnce({ error: new Error('verification unavailable') })
      .mockImplementationOnce(() => new Promise(() => {}))
    tasksQuery.data = { pages: [{ items: [task({ id: 'retry-document-denial' })] }] }
    streamProcessingTaskEvents.mockImplementation(async function* () {
      throw createHttpError(new Response(null, { status: 403 }))
    })

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const retry = await screen.findByRole('button', {
      name: 'common.operation.retry · knowledgeSpace.documentsPermissionDescription',
    })
    await user.click(retry)

    documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
    await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() => expect(screen.getByRole('alert')).toHaveFocus())
    expect(screen.queryByText('sso-enterprise.pdf')).not.toBeInTheDocument()
  })

  it('replaces an in-flight terminal reconciliation and aborts it on unmount', async () => {
    vi.useFakeTimers()
    const signals: AbortSignal[] = []
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'coalesced-reconciliation' })] }] }
    getTaskSnapshot.mockImplementation(
      (_input: unknown, options: { signal: AbortSignal }) =>
        new Promise<DocumentProcessingTask>((_resolve, reject) => {
          signals.push(options.signal)
          options.signal.addEventListener(
            'abort',
            () => reject(new DOMException('Aborted', 'AbortError')),
            { once: true },
          )
        }),
    )
    streamFailedTaskThenWait('coalesced-reconciliation')

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      await act(async () => {})
      expect(getTaskSnapshot).toHaveBeenCalledOnce()

      tasksQuery.data = {
        pages: [
          {
            items: [
              task({
                id: 'coalesced-reconciliation',
                state: 'dispatch_pending',
                updatedAt: '2026-07-20T10:03:00Z',
              }),
            ],
          },
        ],
      }
      await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
      await act(async () => {})

      expect(getTaskSnapshot).toHaveBeenCalledTimes(2)
      expect(signals[0]?.aborted).toBe(true)
      expect(signals[1]?.aborted).toBe(false)
      rendered.unmount()
      expect(signals[1]?.aborted).toBe(true)
      await act(async () => vi.advanceTimersByTime(60000))
      expect(getTaskSnapshot).toHaveBeenCalledTimes(2)
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('retries a terminal reconciliation after its request deadline', async () => {
    vi.useFakeTimers()
    const signals: AbortSignal[] = []
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'timed-reconciliation' })] }] }
    getTaskSnapshot
      .mockImplementationOnce(
        (_input: unknown, options: { signal: AbortSignal }) =>
          new Promise<DocumentProcessingTask>((_resolve, reject) => {
            signals.push(options.signal)
            options.signal.addEventListener(
              'abort',
              () => reject(new DOMException('Aborted', 'AbortError')),
              { once: true },
            )
          }),
      )
      .mockResolvedValueOnce(
        task({
          errorCode: 'TERMINAL_CONFIRMED',
          id: 'timed-reconciliation',
          state: 'failed',
          updatedAt: '2026-07-20T10:03:00Z',
        }),
      )
    streamFailedTaskThenWait('timed-reconciliation')

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      await act(async () => {})
      expect(getTaskSnapshot).toHaveBeenCalledOnce()

      await act(async () => vi.advanceTimersByTime(3000))
      expect(signals[0]?.aborted).toBe(true)
      await act(async () => vi.advanceTimersByTime(1000))

      expect(getTaskSnapshot).toHaveBeenCalledTimes(2)
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('replaces an older reconciliation backoff with the latest generation retry', async () => {
    vi.useFakeTimers()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'latest-reconciliation' })] }] }
    getTaskSnapshot
      .mockRejectedValueOnce(new Error('first snapshot unavailable'))
      .mockRejectedValueOnce(new Error('second snapshot unavailable'))
      .mockResolvedValueOnce(
        task({
          id: 'latest-reconciliation',
          state: 'dispatch_pending',
          updatedAt: '2026-07-20T10:03:00Z',
        }),
      )
    streamFailedTaskThenWait('latest-reconciliation')

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      await act(async () => {})
      expect(getTaskSnapshot).toHaveBeenCalledOnce()

      tasksQuery.data = {
        pages: [
          {
            items: [task({ id: 'latest-reconciliation', updatedAt: '2026-07-20T10:03:00Z' })],
          },
        ],
      }
      await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
      await act(async () => {})
      expect(getTaskSnapshot).toHaveBeenCalledTimes(2)

      await act(async () => vi.advanceTimersByTime(1000))
      expect(getTaskSnapshot).toHaveBeenCalledTimes(3)
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('accepts a later active list snapshot after exact reconciliation saw the terminal state', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'later-same-time-retry' })] }] }
    getTaskSnapshot
      .mockResolvedValueOnce(
        task({
          errorCode: 'PARSER_FAILED',
          id: 'later-same-time-retry',
          state: 'failed',
          updatedAt: '2026-07-20T10:03:00Z',
        }),
      )
      .mockResolvedValueOnce(
        task({
          id: 'later-same-time-retry',
          progressPercent: 0,
          state: 'dispatch_pending',
          updatedAt: '2026-07-20T10:03:00Z',
        }),
      )
    streamFailedTaskThenWait('later-same-time-retry')

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      await screen.findByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    expect(await screen.findByText('knowledgeErrors.taskFailure.temporary')).toBeInTheDocument()
    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledOnce())

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'later-same-time-retry',
              progressPercent: 0,
              state: 'dispatch_pending',
              updatedAt: '2026-07-20T10:03:00Z',
            }),
          ],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledTimes(2))
    expect(
      await screen.findByRole('button', { name: 'knowledgeTasks.interruptTask' }),
    ).toBeInTheDocument()
    expect(screen.queryByText('knowledgeErrors.taskFailure.temporary')).not.toBeInTheDocument()
    await waitFor(() => expect(streamProcessingTaskEvents).toHaveBeenCalledTimes(2))
  })

  it('uses a later active list snapshot when exact reconciliation fails', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'failed-reconciliation-retry' })] }] }
    getTaskSnapshot.mockRejectedValueOnce(new Error('snapshot unavailable')).mockResolvedValueOnce(
      task({
        id: 'failed-reconciliation-retry',
        progressPercent: 0,
        state: 'dispatch_pending',
        updatedAt: '2026-07-20T10:03:00Z',
      }),
    )
    streamFailedTaskThenWait('failed-reconciliation-retry')

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      await screen.findByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    expect(await screen.findByText('knowledgeErrors.taskFailure.temporary')).toBeInTheDocument()
    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledOnce())

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'failed-reconciliation-retry',
              progressPercent: 0,
              state: 'dispatch_pending',
              updatedAt: '2026-07-20T10:03:00Z',
            }),
          ],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledTimes(2))
    expect(
      await screen.findByRole('button', { name: 'knowledgeTasks.interruptTask' }),
    ).toBeInTheDocument()
    expect(screen.queryByText('knowledgeErrors.taskFailure.temporary')).not.toBeInTheDocument()
    await waitFor(() => expect(streamProcessingTaskEvents).toHaveBeenCalledTimes(2))
  })

  it('does not treat a stale active row from a completed cursor page as a retry', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [task({ id: 'stale-cursor-active', updatedAt: '2026-07-20T10:03:00Z' })],
        },
      ],
    }
    getTaskSnapshot.mockResolvedValue(
      task({
        errorCode: 'PARSER_FAILED',
        id: 'stale-cursor-active',
        state: 'failed',
        updatedAt: '2026-07-20T10:03:00Z',
      }),
    )
    streamFailedTaskThenWait('stale-cursor-active')

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      await screen.findByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    expect(await screen.findByText('knowledgeErrors.taskFailure.temporary')).toBeInTheDocument()
    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledOnce())

    tasksQuery.data = {
      pages: [
        {
          items: [task({ id: 'stale-cursor-active', updatedAt: '2026-07-20T10:03:00Z' })],
        },
        { items: [task({ id: 'another-page', state: 'succeeded' })] },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledTimes(2))
    expect(screen.getByText('knowledgeErrors.taskFailure.temporary')).toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' })).toBeInTheDocument()
    expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()
  })

  it('ignores a terminal reconciliation that resolves after a local retry', async () => {
    const user = userEvent.setup()
    let resolveSnapshot: ((snapshot: DocumentProcessingTask) => void) | undefined
    let reconciliationSignal: AbortSignal | undefined
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'local-retry-race' })] }] }
    getTaskSnapshot.mockImplementation(
      (_input: unknown, options: { signal: AbortSignal }) =>
        new Promise<DocumentProcessingTask>((resolve) => {
          reconciliationSignal = options.signal
          resolveSnapshot = resolve
        }),
    )
    retryMutation.mutateAsync.mockResolvedValue(
      task({
        id: 'local-retry-race',
        progressPercent: 0,
        state: 'dispatch_pending',
        updatedAt: '2026-07-20T10:03:00Z',
      }),
    )
    streamFailedTaskThenWait('local-retry-race')

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      await screen.findByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    expect(await screen.findByText('knowledgeErrors.taskFailure.temporary')).toBeInTheDocument()
    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledOnce())
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))
    expect(reconciliationSignal?.aborted).toBe(true)
    expect(
      await screen.findByRole('button', { name: 'knowledgeTasks.interruptTask' }),
    ).toBeInTheDocument()

    await act(async () => {
      resolveSnapshot?.(
        task({
          errorCode: 'PARSER_FAILED',
          id: 'local-retry-race',
          state: 'failed',
          updatedAt: '2026-07-20T10:03:00Z',
        }),
      )
    })

    expect(screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' })).toBeInTheDocument()
    expect(screen.queryByText('knowledgeErrors.taskFailure.temporary')).not.toBeInTheDocument()
    expect(
      screen.queryByRole('button', { name: 'knowledgeSpace.retryTask' }),
    ).not.toBeInTheDocument()
  })

  it('consumes the terminal error after final progress without duplicate side effects', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'failed-stream' })] }] }
    streamProcessingTaskEvents.mockImplementation(async function* () {
      yield {
        data: {
          progressPercent: 80,
          stage: 'parsed' as const,
          state: 'failed' as const,
          updatedAt: '2026-07-20T10:03:00Z',
        },
        event: 'progress' as const,
        id: 'failed-stream:2026-07-20T10:03:00Z',
      }
      yield {
        data: { errorCode: 'PARSER_FAILED', state: 'failed' as const },
        event: 'terminal' as const,
        id: 'failed-stream:terminal',
      }
    })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      await screen.findByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )

    expect(await screen.findByText('knowledgeErrors.taskFailure.temporary')).toBeInTheDocument()
    expect(toastMock.error).toHaveBeenCalledTimes(1)
    const space = consoleQuery.knowledgeFs.spaces.byControlSpaceId
    for (const queryKey of [space.logicalDocuments.get.key(), space.goldenQuestions.get.key()]) {
      expect(
        vi
          .mocked(queryClient.invalidateQueries)
          .mock.calls.filter(
            ([options]) => JSON.stringify(options?.queryKey) === JSON.stringify(queryKey),
          ),
      ).toHaveLength(1)
    }
  })

  it('applies task events and clears the attention badge after completion', async () => {
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'running' })] }] }
    let streamCount = 0
    streamProcessingTaskEvents.mockImplementation(async function* () {
      streamCount += 1
      if (streamCount === 1) {
        yield {
          data: {
            progressPercent: 100,
            stage: 'published' as const,
            state: 'succeeded' as const,
            updatedAt: '2026-07-20T10:06:00Z',
          },
          event: 'progress' as const,
          id: 'running:2026-07-20T10:06:00Z',
        }
        yield {
          data: { state: 'succeeded' as const },
          event: 'terminal' as const,
          id: 'running:terminal',
        }
        return
      }
      await new Promise<void>(() => {})
    })

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() =>
      expect(
        screen.getByRole('button', { name: 'knowledgeDocuments.tasks' }),
      ).not.toHaveTextContent('1'),
    )
    expect(streamProcessingTaskEvents).toHaveBeenCalledWith(
      expect.objectContaining({
        documentId: 'document-1',
        knowledgeSpaceId: 'space-1',
        taskId: 'running',
      }),
    )
    expect(queryClient.invalidateQueries).toHaveBeenCalled()

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'running',
              progressPercent: 90,
              state: 'running',
              updatedAt: '2026-07-20T10:05:00Z',
            }),
          ],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(screen.getByRole('button', { name: 'knowledgeDocuments.tasks' })).not.toHaveTextContent(
      '1',
    )

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'running',
              progressPercent: 100,
              state: 'succeeded',
              updatedAt: '2026-07-20T10:06:00Z',
            }),
          ],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() =>
      expect(
        screen.getByRole('button', { name: 'knowledgeDocuments.tasks' }),
      ).not.toHaveTextContent('1'),
    )

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'running',
              progressPercent: 0,
              state: 'queued',
              updatedAt: '2026-07-20T10:07:00Z',
            }),
          ],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() =>
      expect(
        screen.getByRole('button', {
          name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
        }),
      ).toHaveTextContent('1'),
    )
  })

  it('refreshes logical documents when task-list polling reports a terminal state', async () => {
    systemFeaturesStateMock.deploymentEdition = 'CLOUD'
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({
              active: null,
              activeRevision: undefined,
              status: 'pending',
            }),
          ],
        },
      ],
    }
    tasksQuery.data = {
      pages: [{ items: [task({ id: 'polled-terminal', state: 'queued' })] }],
    }

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(screen.getByText('knowledgeSpace.documentStatus.queued')).toBeInTheDocument()
    expect(queryClient.invalidateQueries).not.toHaveBeenCalled()

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'polled-terminal',
              progressPercent: 100,
              state: 'succeeded',
              updatedAt: '2026-07-20T10:06:00Z',
            }),
          ],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() =>
      expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
        expect.objectContaining({
          queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.get.key(),
        }),
      ),
    )
    expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
      expect.objectContaining({
        queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.get.key(),
      }),
    )
    expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.get.key() },
      { cancelRefetch: false },
    )
    expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.vectorSpace.get.key() },
      { cancelRefetch: false },
    )
  })

  it.each([1, 3])(
    'refreshes Cloud plan usage after a background deletion of %s documents finishes',
    async (total) => {
      systemFeaturesStateMock.deploymentEdition = 'CLOUD'
      const deletion = backgroundTask({
        id: 'delete-documents',
        operation: 'document_delete',
        progressCompleted: 0,
        progressPercent: 0,
        progressTotal: total,
        state: 'queued',
      })
      tasksQuery.data = { pages: [{ items: [deletion] }] }
      const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
      expect(queryClient.invalidateQueries).not.toHaveBeenCalled()

      tasksQuery.data = { pages: [{ items: [{ ...deletion, state: 'running' }] }] }
      await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
      expect(queryClient.invalidateQueries).not.toHaveBeenCalled()

      tasksQuery.data = {
        pages: [
          {
            items: [
              {
                ...deletion,
                progressCompleted: total,
                progressPercent: 100,
                state: 'succeeded',
                updatedAt: '2026-07-20T10:06:00Z',
              },
            ],
          },
        ],
      }
      await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
      await waitFor(() =>
        expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
          { queryKey: consoleQuery.features.get.key() },
          { cancelRefetch: false },
        ),
      )
      expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
        { queryKey: consoleQuery.features.vectorSpace.get.key() },
        { cancelRefetch: false },
      )

      vi.mocked(queryClient.invalidateQueries).mockClear()
      await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
      expect(queryClient.invalidateQueries).not.toHaveBeenCalled()
    },
  )

  it('does not refresh plan usage for completed deletions in Enterprise', async () => {
    const deletion = backgroundTask({
      id: 'delete-documents',
      operation: 'document_delete',
      state: 'running',
    })
    tasksQuery.data = { pages: [{ items: [deletion] }] }
    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    tasksQuery.data = { pages: [{ items: [{ ...deletion, state: 'succeeded' }] }] }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() => expect(queryClient.invalidateQueries).toHaveBeenCalled())

    expect(queryClient.invalidateQueries).not.toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.get.key() },
      { cancelRefetch: false },
    )
    expect(queryClient.invalidateQueries).not.toHaveBeenCalledWith(
      { queryKey: consoleQuery.features.vectorSpace.get.key() },
      { cancelRefetch: false },
    )
  })

  it('accepts an external retry newer than the terminal event version', async () => {
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'externally-retried' })] }] }
    let streamCount = 0
    streamProcessingTaskEvents.mockImplementation(async function* () {
      streamCount += 1
      if (streamCount === 1) {
        yield {
          data: {
            progressPercent: 100,
            stage: 'published' as const,
            state: 'succeeded' as const,
            updatedAt: '2026-07-20T10:04:00Z',
          },
          event: 'progress' as const,
          id: 'externally-retried:2026-07-20T10:04:00Z',
        }
        yield {
          data: { state: 'succeeded' as const },
          event: 'terminal' as const,
          id: 'externally-retried:terminal',
        }
        return
      }
      await new Promise<void>(() => {})
    })

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() =>
      expect(
        screen.getByRole('button', { name: 'knowledgeDocuments.tasks' }),
      ).not.toHaveTextContent('1'),
    )

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'externally-retried',
              progressPercent: 0,
              state: 'queued',
              updatedAt: '2026-07-20T10:05:00Z',
            }),
          ],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() =>
      expect(
        screen.getByRole('button', {
          name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
        }),
      ).toHaveTextContent('1'),
    )
    await waitFor(() => expect(streamProcessingTaskEvents).toHaveBeenCalledTimes(2), {
      timeout: 2000,
    })
  })

  it('ignores a stale terminal event after polling observes an external retry', async () => {
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'retry-race' })] }] }
    let releaseTerminal: (() => void) | undefined
    let streamCount = 0
    streamProcessingTaskEvents.mockImplementation(async function* () {
      streamCount += 1
      if (streamCount === 1) {
        await new Promise<void>((resolve) => {
          releaseTerminal = resolve
        })
        yield {
          data: {
            progressPercent: 100,
            stage: 'published' as const,
            state: 'succeeded' as const,
            updatedAt: '2026-07-20T10:03:00Z',
          },
          event: 'progress' as const,
          id: 'retry-race:progress',
        }
        yield {
          data: { state: 'succeeded' as const },
          event: 'terminal' as const,
          id: 'retry-race:terminal',
        }
        return
      }
      await new Promise<void>(() => {})
    })

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() => expect(releaseTerminal).toBeTypeOf('function'))

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'retry-race',
              progressPercent: 0,
              state: 'queued',
              updatedAt: '2026-07-20T10:05:00Z',
            }),
          ],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    await act(async () => releaseTerminal?.())
    await waitFor(() =>
      expect(
        screen.getByRole('button', {
          name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
        }),
      ).toHaveTextContent('1'),
    )
    await waitFor(() => expect(streamProcessingTaskEvents).toHaveBeenCalledTimes(2), {
      timeout: 2000,
    })
  })

  it('keeps one event stream and its resume cursor when polling updates task versions', async () => {
    let releaseStream: (() => void) | undefined
    streamProcessingTaskEvents.mockImplementation(async function* () {
      await new Promise<void>((resolve) => {
        releaseStream = resolve
      })
    })
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'streaming' })] }] }
    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() => expect(streamProcessingTaskEvents).toHaveBeenCalledOnce())

    tasksQuery.data = {
      pages: [
        {
          items: [task({ id: 'streaming', updatedAt: '2026-07-20T10:02:00Z' })],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()

    await act(async () => releaseStream?.())
  })

  it('keeps task event progress monotonic and yields to a newer server snapshot', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document({})] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'running' })] }] }
    streamProcessingTaskEvents.mockImplementation(async function* () {
      yield {
        data: {
          progressPercent: 80,
          stage: 'nodes_generated' as const,
          state: 'running' as const,
          updatedAt: '2026-07-20T10:03:00Z',
        },
        event: 'progress' as const,
        id: 'running:newer',
      }
      yield {
        data: {
          progressPercent: 20,
          stage: 'parsed' as const,
          state: 'running' as const,
          updatedAt: '2026-07-20T10:02:00Z',
        },
        event: 'progress' as const,
        id: 'running:stale',
      }
    })

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await waitFor(() => expect(screen.getByText(/80%/)).toBeInTheDocument())
    await act(async () => {})
    expect(screen.queryByText(/20%/)).not.toBeInTheDocument()
    await user.click(screen.getByRole('button', { name: 'common.operation.close' }))

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'running',
              progressPercent: 100,
              state: 'succeeded',
              updatedAt: '2026-07-20T10:04:00Z',
            }),
          ],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.getByRole('button', { name: 'knowledgeDocuments.tasks' })).toBeInTheDocument()
  })

  it('lets an equal-timestamp terminal list row replace an active stream override', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'equal-terminal', state: 'queued' })] }] }
    streamProcessingTaskEvents.mockImplementation(async function* () {
      yield {
        data: {
          progressPercent: 60,
          stage: 'parsed' as const,
          state: 'running' as const,
          updatedAt: '2026-07-20T10:01:00Z',
        },
        event: 'progress' as const,
        id: 'equal-terminal:running',
      }
      await new Promise<void>(() => {})
    })

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() => expect(streamProcessingTaskEvents).toHaveBeenCalledOnce())
    tasksQuery.data = {
      pages: [{ items: [task({ id: 'equal-terminal', state: 'failed' })] }],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )

    expect(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' })).toBeEnabled()
  })

  it('moves focus to the drawer close button when an external update removes a task action', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'external-terminal' })] }] }
    streamProcessingTaskEvents.mockImplementation(async function* () {
      await new Promise<void>(() => {})
    })
    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    const action = screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' })
    act(() => action.focus())

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'external-terminal',
              state: 'succeeded',
              updatedAt: '2026-07-20T10:02:00Z',
            }),
          ],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() =>
      expect(screen.getByRole('button', { name: 'common.operation.close' })).toHaveFocus(),
    )
  })

  it('limits rendered task history while retaining an active retry for an old document', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    const history = Array.from({ length: 150 }, (_, index) =>
      task({
        id: `history-${index}`,
        state: 'succeeded',
        updatedAt: new Date(Date.UTC(2026, 6, 20, 10, index)).toISOString(),
      }),
    )
    history[0] = task({
      createdAt: '2026-07-01T10:00:00Z',
      id: 'old-active-retry',
      state: 'running',
      updatedAt: '2026-07-01T10:00:00Z',
    })
    history[1] = task({
      createdAt: '2026-07-01T10:01:00Z',
      id: 'old-failed-retry',
      state: 'failed',
      updatedAt: '2026-08-01T10:00:00Z',
    })
    tasksQuery.data = { pages: [{ items: history }] }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":2}',
      }),
    )

    expect(screen.getAllByRole('listitem')).toHaveLength(100)
    expect(screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' })).toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' })).toBeInTheDocument()
  })

  it('keeps a failed task actionable when one hundred active tasks fill the drawer', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            ...Array.from({ length: 100 }, (_, index) =>
              task({
                id: `active-${index}`,
                updatedAt: new Date(Date.UTC(2026, 6, 20, 10, index)).toISOString(),
              }),
            ),
            task({
              id: 'failed-outside-active-limit',
              state: 'failed',
              updatedAt: '2026-07-01T10:00:00Z',
            }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":101}',
      }),
    )

    expect(screen.getAllByRole('listitem')).toHaveLength(100)
    expect(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' })).toBeInTheDocument()
  })

  it('keeps an active task actionable when one hundred failed tasks fill the drawer', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            ...Array.from({ length: 100 }, (_, index) =>
              task({
                id: `failed-${index}`,
                state: 'failed',
                updatedAt: new Date(Date.UTC(2026, 6, 20, 10, index)).toISOString(),
              }),
            ),
            task({
              id: 'active-outside-failed-limit',
              state: 'running',
              updatedAt: '2026-07-01T10:00:00Z',
            }),
          ],
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":101}',
      }),
    )

    expect(screen.getAllByRole('listitem')).toHaveLength(100)
    expect(screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' })).toBeInTheDocument()
    await user.click(
      within(screen.getByRole('dialog')).getByRole('button', {
        name: 'knowledgeSpace.loadMore',
      }),
    )
    expect(screen.getAllByRole('listitem')).toHaveLength(101)
  })

  it('moves focus to the drawer close button when the final task batch is revealed', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: Array.from({ length: 101 }, (_, index) =>
            task({
              id: `history-${index}`,
              state: 'succeeded',
              updatedAt: new Date(Date.UTC(2026, 6, 20, 10, index)).toISOString(),
            }),
          ),
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('button', { name: 'knowledgeDocuments.tasks' }))
    await user.click(
      within(screen.getByRole('dialog')).getByRole('button', {
        name: 'knowledgeSpace.loadMore',
      }),
    )

    await waitFor(() =>
      expect(screen.getByRole('button', { name: 'common.operation.close' })).toHaveFocus(),
    )
  })

  it('preserves focus when the user leaves a pending final-page control', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    const firstPage = [
      task({ id: 'active-focus-target' }),
      ...Array.from({ length: 99 }, (_, index) =>
        task({
          id: `history-${index}`,
          state: 'succeeded',
          updatedAt: new Date(Date.UTC(2026, 6, 20, 10, index)).toISOString(),
        }),
      ),
    ]
    tasksQuery.data = { pages: [{ items: firstPage, nextCursor: 'final-page' }] }
    tasksQuery.hasNextPage = true

    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1} · knowledgeDocuments.taskHistoryIncomplete',
      }),
    )
    await user.click(
      within(screen.getByRole('dialog')).getByRole('button', {
        name: 'knowledgeSpace.loadMore',
      }),
    )
    const action = screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' })
    act(() => action.focus())

    tasksQuery.data = {
      pages: [{ items: firstPage }, { items: [task({ id: 'last-task', state: 'succeeded' })] }],
    }
    tasksQuery.hasNextPage = false
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(action).toHaveFocus()
  })

  it('rotates a bounded task event stream pool without a duplicate list poller', async () => {
    vi.useFakeTimers()
    streamProcessingTaskEvents.mockImplementation(async function* () {
      await new Promise<void>(() => {})
    })
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: Array.from({ length: 20 }, (_, index) =>
            task({
              id: `active-${index}`,
              updatedAt: new Date(Date.UTC(2026, 6, 20, 10, index)).toISOString(),
            }),
          ),
        },
      ],
    }

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      await act(async () => {})
      expect(streamProcessingTaskEvents).toHaveBeenCalledTimes(6)
      await act(async () => vi.advanceTimersByTime(5000))
      expect(streamProcessingTaskEvents).toHaveBeenCalledTimes(12)
      // Streams carry progress for every active task, so the task list stops polling.
      const taskReads = server.reads.get('tasks')
      await act(async () => vi.advanceTimersByTime(10_000))
      expect(server.reads.get('tasks')).toBe(taskReads)
      expect(
        screen.getByRole('button', {
          name: 'knowledgeDocuments.tasksWithAttention:{"count":20}',
        }),
      ).toBeInTheDocument()
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('resumes a task event stream from its cursor after rotation', async () => {
    vi.useFakeTimers()
    const resumeCalls: Array<{ lastEventId?: string; taskId: string }> = []
    streamProcessingTaskEvents.mockImplementation(async function* ({
      lastEventId,
      taskId,
    }: {
      lastEventId?: string
      taskId: string
    }) {
      resumeCalls.push({ lastEventId, taskId })
      if (taskId === 'active-0' && !lastEventId) {
        yield {
          data: {
            progressPercent: 50,
            stage: 'parsed' as const,
            state: 'running' as const,
            updatedAt: '2026-07-20T10:30:00Z',
          },
          event: 'progress' as const,
          id: 'active-0:cursor',
        }
      }
      await new Promise<void>(() => {})
    })
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: Array.from({ length: 20 }, (_, index) =>
            task({
              id: `active-${index}`,
              updatedAt: new Date(Date.UTC(2026, 6, 20, 10, index)).toISOString(),
            }),
          ),
        },
      ],
    }

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      await act(async () => {})
      for (let index = 0; index < 3; index += 1) {
        await act(async () => vi.advanceTimersByTime(5000))
        await act(async () => {})
      }

      expect(resumeCalls.filter(({ taskId }) => taskId === 'active-0')).toEqual([
        { lastEventId: undefined, taskId: 'active-0' },
        { lastEventId: 'active-0:cursor', taskId: 'active-0' },
      ])
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('drops an event cursor after the task list reports a terminal state', async () => {
    const streamCalls: Array<{ lastEventId?: string; taskId: string }> = []
    streamProcessingTaskEvents.mockImplementation(async function* ({
      lastEventId,
      taskId,
    }: {
      lastEventId?: string
      taskId: string
    }) {
      streamCalls.push({ lastEventId, taskId })
      if (streamCalls.length === 1) {
        yield {
          data: {
            progressPercent: 60,
            stage: 'parsed' as const,
            state: 'running' as const,
            updatedAt: '2026-07-20T10:02:00Z',
          },
          event: 'progress' as const,
          id: 'restarted:old-cursor',
        }
      }
      await new Promise<void>(() => {})
    })
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'restarted' })] }] }
    const { rerender } = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() => expect(streamCalls).toHaveLength(1))

    tasksQuery.data = {
      pages: [
        {
          items: [task({ id: 'restarted', state: 'failed', updatedAt: '2026-07-20T10:03:00Z' })],
        },
      ],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    tasksQuery.data = {
      pages: [{ items: [task({ id: 'restarted', updatedAt: '2026-07-20T10:04:00Z' })] }],
    }
    await rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() => expect(streamCalls).toHaveLength(2))
    expect(streamCalls).toEqual([
      { lastEventId: undefined, taskId: 'restarted' },
      { lastEventId: undefined, taskId: 'restarted' },
    ])
  })

  it('keeps a retry cursor while the base task list still has the old terminal row', async () => {
    vi.useFakeTimers()
    const retryStreamCalls: Array<string | undefined> = []
    streamProcessingTaskEvents.mockImplementation(async function* ({
      lastEventId,
      taskId,
    }: {
      lastEventId?: string
      taskId: string
    }) {
      if (taskId === 'active-5') {
        retryStreamCalls.push(lastEventId)
        if (!lastEventId) {
          yield {
            data: {
              progressPercent: 55,
              stage: 'parsed' as const,
              state: 'running' as const,
              updatedAt: '2026-07-20T10:02:00Z',
            },
            event: 'progress' as const,
            id: 'active-5:retry-cursor',
          }
        }
      }
      await new Promise<void>(() => {})
    })
    retryMutation.mutateAsync.mockResolvedValue(
      task({ id: 'active-5', state: 'queued', updatedAt: '2026-07-20T10:01:00Z' }),
    )
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            ...Array.from({ length: 5 }, (_, index) => task({ id: `active-${index}` })),
            task({ id: 'active-5', state: 'failed' }),
            task({ id: 'active-6' }),
          ],
        },
      ],
    }

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      fireEvent.click(
        screen.getByRole('button', {
          name: 'knowledgeDocuments.tasksWithAttention:{"count":7}',
        }),
      )
      fireEvent.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))
      await act(async () => {})
      expect(retryStreamCalls).toEqual([undefined])

      await act(async () => vi.advanceTimersByTime(5000))
      await act(async () => vi.advanceTimersByTime(5000))
      await act(async () => {})

      expect(retryStreamCalls).toEqual([undefined, 'active-5:retry-cursor'])
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('rejects stale active progress and backs off repeated stale reconnects', async () => {
    vi.useFakeTimers()
    documentsQuery.data = {
      pages: [
        {
          items: [
            document({
              latestTask: task({
                id: 'stale-active-progress',
                state: 'queued',
                updatedAt: '2026-07-20T10:05:00Z',
              }),
            }),
          ],
        },
      ],
    }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'stale-active-progress',
              state: 'queued',
              updatedAt: '2026-07-20T10:05:00Z',
            }),
          ],
        },
      ],
    }
    let streamCount = 0
    streamProcessingTaskEvents.mockImplementation(async function* () {
      streamCount += 1
      yield {
        data: {
          progressPercent: streamCount < 3 ? 40 : 60,
          stage: 'parsed' as const,
          state: 'running' as const,
          updatedAt: streamCount < 3 ? '2026-07-20T10:04:00Z' : '2026-07-20T10:06:00Z',
        },
        event: 'progress' as const,
        id: `stale-active-progress:${streamCount}`,
      }
      await new Promise<void>(() => {})
    })

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      await act(async () => {})
      expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()
      expect(
        within(screen.getByRole('row', { name: /sso-enterprise\.pdf/ })).getByText(
          'knowledgeSpace.documentStatus.queued',
        ),
      ).toBeInTheDocument()
      await act(() => vi.advanceTimersByTimeAsync(1000))
      await settle()
      expect(streamProcessingTaskEvents).toHaveBeenCalledTimes(2)
      await act(() => vi.advanceTimersByTimeAsync(1000))
      await settle()
      expect(streamProcessingTaskEvents).toHaveBeenCalledTimes(2)
      await act(() => vi.advanceTimersByTimeAsync(1000))
      await settle()
      expect(streamProcessingTaskEvents).toHaveBeenCalledTimes(3)
      expect(
        within(screen.getByRole('row', { name: /sso-enterprise\.pdf/ })).getByText(
          'knowledgeSpace.documentStatus.processing',
        ),
      ).toBeInTheDocument()
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('keeps rotation membership stable when progress updates task timestamps', async () => {
    vi.useFakeTimers()
    const callsByTask = new Map<string, number>()
    streamProcessingTaskEvents.mockImplementation(async function* ({ taskId }: { taskId: string }) {
      callsByTask.set(taskId, (callsByTask.get(taskId) ?? 0) + 1)
      yield {
        data: {
          progressPercent: 50,
          stage: 'parsed' as const,
          state: 'running' as const,
          updatedAt: '2026-07-20T12:00:00Z',
        },
        event: 'progress' as const,
        id: `${taskId}:progress`,
      }
      await new Promise<void>(() => {})
    })
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: Array.from({ length: 12 }, (_, index) =>
            task({
              createdAt: new Date(Date.UTC(2026, 6, 20, 9, index)).toISOString(),
              id: `stable-${index}`,
              updatedAt: new Date(Date.UTC(2026, 6, 20, 10, index)).toISOString(),
            }),
          ),
        },
      ],
    }

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      await act(async () => {})
      await act(async () => vi.advanceTimersByTime(5000))
      await act(async () => {})

      expect(callsByTask).toHaveLength(12)
      expect([...callsByTask.values()]).toEqual(Array.from({ length: 12 }, () => 1))
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('preserves the latest progress version when a rotated stream returns terminal-only', async () => {
    vi.useFakeTimers()
    const streamCounts = new Map<string, number>()
    streamProcessingTaskEvents.mockImplementation(async function* ({ taskId }: { taskId: string }) {
      const streamCount = (streamCounts.get(taskId) ?? 0) + 1
      streamCounts.set(taskId, streamCount)
      if (taskId === 'rotated-terminal' && streamCount === 1) {
        yield {
          data: {
            progressPercent: 70,
            stage: 'nodes_generated' as const,
            state: 'running' as const,
            updatedAt: '2026-07-20T10:05:00Z',
          },
          event: 'progress' as const,
          id: 'rotated-terminal:progress',
        }
      } else if (taskId === 'rotated-terminal') {
        yield {
          data: { errorCode: 'ROTATED_FAILURE', state: 'failed' as const },
          event: 'terminal' as const,
          id: 'rotated-terminal:terminal',
        }
        return
      }
      await new Promise<void>(() => {})
    })
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({ id: 'rotated-terminal', updatedAt: '2026-07-20T10:01:00Z' }),
            ...Array.from({ length: 12 }, (_, index) =>
              task({ id: `rotation-peer-${index}`, updatedAt: '2026-07-20T10:01:00Z' }),
            ),
          ],
        },
      ],
    }
    getTaskSnapshot.mockResolvedValue(
      task({
        errorCode: 'ROTATED_FAILURE',
        id: 'rotated-terminal',
        state: 'failed',
        updatedAt: '2026-07-20T10:05:00Z',
      }),
    )

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      await act(async () => {})
      await act(async () => vi.advanceTimersByTime(5000))
      await act(async () => vi.advanceTimersByTime(5000))
      await act(async () => {})

      expect(streamCounts.get('rotated-terminal')).toBe(2)
      expect(toastMock.error).toHaveBeenCalledWith('knowledgeTasks.taskFailedNotification')
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('relies on bounded reconnect backoff instead of invalidating queries on stream closure', async () => {
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'closed-stream' })] }] }
    streamProcessingTaskEvents.mockImplementation(async function* () {})

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() => expect(streamProcessingTaskEvents).toHaveBeenCalledOnce())
    expect(queryClient.invalidateQueries).not.toHaveBeenCalled()
  })

  it('does not poll terminal tasks while the background-task drawer is closed', async () => {
    vi.useFakeTimers()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [{ items: [task({ id: 'closed-drawer-failure', state: 'failed' })] }],
    }

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      await act(async () => vi.advanceTimersByTime(60000))
      expect(getTaskSnapshot).not.toHaveBeenCalled()
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('polls failed tasks through a bounded exact-snapshot pool for external retries', async () => {
    vi.useFakeTimers()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [{ items: [task({ id: 'external-retry', state: 'failed' })] }],
    }
    getTaskSnapshot.mockResolvedValue(
      task({
        id: 'external-retry',
        progressPercent: 0,
        state: 'dispatch_pending',
        updatedAt: '2026-07-20T10:03:00Z',
      }),
    )

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      openTasksDrawer()
      await act(async () => vi.advanceTimersByTime(5000))
      expect(getTaskSnapshot).toHaveBeenCalledOnce()
      await act(async () => {})
      expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it.each(['running', 'failed'] as const)(
    'observes newer %s history while the document still has a canceled snapshot',
    async (state) => {
      vi.useFakeTimers()
      const taskId = 'external-retry'
      const updatedAt = '2026-07-20T10:03:00Z'
      documentsQuery.data = {
        pages: [
          {
            items: [
              document({
                latestTask: task({
                  id: taskId,
                  state: 'canceled',
                  updatedAt: '2026-07-20T09:00:00Z',
                }),
              }),
            ],
          },
        ],
      }
      tasksQuery.data = { pages: [{ items: [task({ id: taskId, state, updatedAt })] }] }
      getTaskSnapshot.mockResolvedValue(task({ id: taskId, state: 'running', updatedAt }))
      streamProcessingTaskEvents.mockImplementation(async function* () {
        yield {
          data: {
            progressPercent: 30,
            stage: 'parsed' as const,
            state: 'running' as const,
            updatedAt,
          },
          event: 'progress' as const,
          id: `${taskId}:progress`,
        }
        await new Promise<void>(() => {})
      })

      const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
      try {
        openTasksDrawer()
        await act(async () => vi.advanceTimersByTime(5000))
        if (state === 'failed') expect(getTaskSnapshot).toHaveBeenCalledOnce()
        expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()
        vi.useRealTimers()
        await userEvent.setup().keyboard('{Escape}')
        expect(
          within(screen.getByRole('row', { name: /sso-enterprise\.pdf/ })).getByText(
            'knowledgeSpace.documentStatus.processing',
          ),
        ).toBeInTheDocument()
      } finally {
        rendered.unmount()
        vi.useRealTimers()
      }
    },
  )

  it('keeps a confirmed task failure when the document refresh fails with an older running snapshot', async () => {
    const running = task({ id: 'confirmed-failure', state: 'running' })
    documentsQuery.data = { pages: [{ items: [document({ latestTask: running })] }] }
    tasksQuery.data = { pages: [{ items: [running] }] }
    getTaskSnapshot.mockImplementation(() => new Promise(() => {}))
    streamFailedTaskThenWait(running.id)

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const row = within(screen.getByRole('row', { name: /sso-enterprise\.pdf/ }))
    expect(await row.findByText('knowledgeSpace.documentStatus.failed')).toBeInTheDocument()

    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: running.id,
              state: 'failed',
              updatedAt: '2026-07-20T10:03:00Z',
            }),
          ],
        },
      ],
    }
    documentsQuery.error = createHttpError(new Response(null, { status: 503 }))
    await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(await row.findByText('knowledgeSpace.documentStatus.failed')).toBeInTheDocument()
    expect(row.queryByText('knowledgeSpace.documentStatus.processing')).not.toBeInTheDocument()
  })

  it('keeps one failed-task poll in flight and ignores it after a local retry', async () => {
    vi.useFakeTimers()
    let resolvePoll: ((snapshot: DocumentProcessingTask) => void) | undefined
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [{ items: [task({ id: 'slow-failed-poll', state: 'failed' })] }],
    }
    getTaskSnapshot.mockReturnValue(
      new Promise<DocumentProcessingTask>((resolve) => {
        resolvePoll = resolve
      }),
    )
    retryMutation.mutateAsync.mockResolvedValue(
      task({
        id: 'slow-failed-poll',
        progressPercent: 0,
        state: 'dispatch_pending',
        updatedAt: '2026-07-20T10:03:00Z',
      }),
    )

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      fireEvent.click(
        screen.getByRole('button', {
          name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
        }),
      )
      await act(async () => vi.advanceTimersByTime(5000))
      expect(getTaskSnapshot).toHaveBeenCalledOnce()
      fireEvent.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))
      await act(async () => {})
      expect(
        screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' }),
      ).toBeInTheDocument()

      await act(async () => {
        resolvePoll?.(
          task({
            errorCode: 'OLD_FAILURE',
            id: 'slow-failed-poll',
            state: 'failed',
            updatedAt: '2026-07-20T10:01:00Z',
          }),
        )
      })

      expect(
        screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' }),
      ).toBeInTheDocument()
      expect(screen.queryByText('OLD_FAILURE')).not.toBeInTheDocument()
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('ignores a delayed permanent poll rejection after a local retry', async () => {
    vi.useFakeTimers()
    let rejectPoll: ((error: unknown) => void) | undefined
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [{ items: [task({ id: 'rejected-failed-poll', state: 'failed' })] }],
    }
    getTaskSnapshot
      .mockReturnValueOnce(
        new Promise<DocumentProcessingTask>((_resolve, reject) => {
          rejectPoll = reject
        }),
      )
      .mockResolvedValueOnce(
        task({
          id: 'rejected-failed-poll',
          progressPercent: 0,
          state: 'dispatch_pending',
          updatedAt: '2026-07-20T10:05:00Z',
        }),
      )
    retryMutation.mutateAsync.mockResolvedValue(
      task({
        id: 'rejected-failed-poll',
        progressPercent: 0,
        state: 'dispatch_pending',
        updatedAt: '2026-07-20T10:03:00Z',
      }),
    )

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      fireEvent.click(
        screen.getByRole('button', {
          name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
        }),
      )
      await act(async () => vi.advanceTimersByTime(5000))
      expect(getTaskSnapshot).toHaveBeenCalledOnce()
      fireEvent.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))
      await act(async () => {})
      await act(async () => rejectPoll?.(createHttpError(new Response(null, { status: 403 }))))

      tasksQuery.data = {
        pages: [
          {
            items: [
              task({
                id: 'rejected-failed-poll',
                state: 'failed',
                updatedAt: '2026-07-20T10:04:00Z',
              }),
            ],
          },
        ],
      }
      await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
      await act(async () => vi.advanceTimersByTime(5000))

      expect(getTaskSnapshot).toHaveBeenCalledTimes(2)
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('does not repoll the same failed snapshot after document read recovery', async () => {
    vi.useFakeTimers()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [{ items: [task({ id: 'forbidden-failed-poll', state: 'failed' })] }],
    }
    getTaskSnapshot.mockRejectedValue(createHttpError(new Response(null, { status: 403 })))

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      openTasksDrawer()
      await act(async () => vi.advanceTimersByTime(5000))
      expect(getTaskSnapshot).toHaveBeenCalledOnce()
      tasksQuery.data = {
        pages: [{ items: [task({ id: 'forbidden-failed-poll', state: 'failed' })] }],
      }
      await notifyTaskQuerySuccess()
      await act(async () => vi.advanceTimersByTime(60000))
      expect(getTaskSnapshot).toHaveBeenCalledOnce()
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('accepts a same-version active list lifecycle after a failed poll is denied', async () => {
    vi.useFakeTimers()
    const taskVersion = '2026-07-20T10:01:00Z'
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({ id: 'denied-failed-poll-retry', state: 'failed', updatedAt: taskVersion }),
          ],
        },
      ],
    }
    getTaskSnapshot.mockRejectedValueOnce(createHttpError(new Response(null, { status: 403 })))
    streamProcessingTaskEvents.mockImplementation(async function* () {
      await new Promise<void>(() => {})
    })

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      openTasksDrawer()
      await act(async () => vi.advanceTimersByTime(5000))
      expect(getTaskSnapshot).toHaveBeenCalledOnce()

      tasksQuery.data = {
        pages: [
          {
            items: [
              task({ id: 'denied-failed-poll-retry', state: 'running', updatedAt: taskVersion }),
            ],
          },
        ],
      }
      await notifyTaskQuerySuccess()
      await act(async () => {})

      expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('advances one batched failed-task poll when a snapshot request never settles', async () => {
    vi.useFakeTimers()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: Array.from({ length: 7 }, (_, index) =>
            task({ id: `failed-${index}`, state: 'failed' }),
          ),
        },
      ],
    }
    getTaskSnapshot
      .mockReturnValueOnce(new Promise<DocumentProcessingTask[]>(() => {}))
      .mockResolvedValueOnce(
        Array.from({ length: 6 }, (_, index) =>
          task({
            id: `failed-${index}`,
            state: index === 0 ? 'dispatch_pending' : 'failed',
            updatedAt: '2026-07-20T10:02:00Z',
          }),
        ),
      )

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      openTasksDrawer()
      await act(async () => vi.advanceTimersByTime(5000))
      expect(getTaskSnapshot).toHaveBeenCalledOnce()
      await act(async () => vi.advanceTimersByTime(3000))
      await act(async () => vi.advanceTimersByTime(5000))
      expect(getTaskSnapshot).toHaveBeenCalledTimes(2)
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('forgets permanent poll failures after a task leaves the cursor result', async () => {
    vi.useFakeTimers()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [{ items: [task({ id: 'removed-failed-task', state: 'failed' })] }],
    }
    getTaskSnapshot.mockRejectedValue(createHttpError(new Response(null, { status: 403 })))

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      openTasksDrawer()
      await act(async () => vi.advanceTimersByTime(5000))
      expect(getTaskSnapshot).toHaveBeenCalledOnce()

      tasksQuery.data = { pages: [{ items: [] }] }
      await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
      await act(async () => {})
      tasksQuery.data = {
        pages: [{ items: [task({ id: 'removed-failed-task', state: 'failed' })] }],
      }
      await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
      await act(async () => vi.advanceTimersByTime(5000))

      expect(getTaskSnapshot).toHaveBeenCalledTimes(2)
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('ignores an older active snapshot while polling a newer failed task', async () => {
    vi.useFakeTimers()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              errorCode: 'LATEST_FAILURE',
              id: 'stale-active-poll',
              state: 'failed',
              updatedAt: '2026-07-20T10:03:00.123789Z',
            }),
          ],
        },
      ],
    }
    getTaskSnapshot.mockResolvedValue(
      task({
        id: 'stale-active-poll',
        state: 'dispatch_pending',
        updatedAt: '2026-07-20T10:03:00.123456Z',
      }),
    )

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      openTasksDrawer()
      await act(async () => vi.advanceTimersByTime(5000))
      expect(getTaskSnapshot).toHaveBeenCalledOnce()
      expect(streamProcessingTaskEvents).not.toHaveBeenCalled()
      expect(screen.getByText('knowledgeErrors.taskFailure.internal')).toBeInTheDocument()
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('accepts a terminal-only stream after an exact snapshot observes an external retry', async () => {
    vi.useFakeTimers()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              errorCode: 'OLD_FAILURE',
              id: 'terminal-only-external-retry',
              state: 'failed',
              updatedAt: '2026-07-20T10:01:00Z',
            }),
          ],
        },
      ],
    }
    getTaskSnapshot
      .mockResolvedValueOnce(
        task({
          id: 'terminal-only-external-retry',
          state: 'dispatch_pending',
          updatedAt: '2026-07-20T10:03:00Z',
        }),
      )
      .mockResolvedValueOnce(
        task({
          errorCode: 'NEW_FAILURE',
          id: 'terminal-only-external-retry',
          state: 'failed',
          updatedAt: '2026-07-20T10:03:00Z',
        }),
      )
    streamProcessingTaskEvents.mockImplementation(async function* () {
      yield {
        data: { errorCode: 'NEW_FAILURE', state: 'failed' as const },
        event: 'terminal' as const,
        id: 'terminal-only-external-retry:terminal',
      }
    })

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      openTasksDrawer()
      await act(async () => vi.advanceTimersByTime(5000))
      await act(async () => {})
      expect(getTaskSnapshot).toHaveBeenCalledTimes(2)
      expect(screen.getByText('knowledgeErrors.taskFailure.internal')).toBeInTheDocument()
      expect(
        screen.queryByRole('button', { name: 'knowledgeTasks.interruptTask' }),
      ).not.toBeInTheDocument()
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('unblocks failed-task polling after an active list snapshot without a terminal pin', async () => {
    vi.useFakeTimers()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [{ items: [task({ id: 'list-retry-after-block', state: 'failed' })] }],
    }
    getTaskSnapshot
      .mockRejectedValueOnce(createHttpError(new Response(null, { status: 403 })))
      .mockResolvedValueOnce(
        task({
          id: 'list-retry-after-block',
          state: 'dispatch_pending',
          updatedAt: '2026-07-20T10:05:00Z',
        }),
      )

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      openTasksDrawer()
      await act(async () => vi.advanceTimersByTime(5000))
      expect(getTaskSnapshot).toHaveBeenCalledOnce()

      tasksQuery.data = {
        pages: [
          {
            items: [
              task({
                id: 'list-retry-after-block',
                state: 'dispatch_pending',
                updatedAt: '2026-07-20T10:03:00Z',
              }),
            ],
          },
        ],
      }
      await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
      await act(async () => {})
      tasksQuery.data = {
        pages: [
          {
            items: [
              task({
                id: 'list-retry-after-block',
                state: 'failed',
                updatedAt: '2026-07-20T10:04:00Z',
              }),
            ],
          },
        ],
      }
      await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
      await act(async () => vi.advanceTimersByTime(5000))

      expect(getTaskSnapshot).toHaveBeenCalledTimes(2)
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('retries exact polling when a permanently blocked failed task advances version', async () => {
    vi.useFakeTimers()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [
            task({
              id: 'new-failed-generation',
              state: 'failed',
              updatedAt: '2026-07-20T10:01:00Z',
            }),
          ],
        },
      ],
    }
    getTaskSnapshot
      .mockRejectedValueOnce(createHttpError(new Response(null, { status: 403 })))
      .mockResolvedValueOnce(
        task({
          id: 'new-failed-generation',
          state: 'dispatch_pending',
          updatedAt: '2026-07-20T10:03:00Z',
        }),
      )

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      openTasksDrawer()
      await act(async () => vi.advanceTimersByTime(5000))
      expect(getTaskSnapshot).toHaveBeenCalledOnce()

      tasksQuery.data = {
        pages: [
          {
            items: [
              task({
                id: 'new-failed-generation',
                state: 'failed',
                updatedAt: '2026-07-20T10:02:00Z',
              }),
            ],
          },
        ],
      }
      await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
      await act(async () => vi.advanceTimersByTime(5000))

      expect(getTaskSnapshot).toHaveBeenCalledTimes(2)
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('aborts an in-flight failed-task poll on unmount', async () => {
    vi.useFakeTimers()
    let pollSignal: AbortSignal | undefined
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [{ items: [task({ id: 'aborted-failed-poll', state: 'failed' })] }],
    }
    getTaskSnapshot.mockImplementation(
      (_input: unknown, options: { signal: AbortSignal }) =>
        new Promise<DocumentProcessingTask>((_resolve, reject) => {
          pollSignal = options.signal
          options.signal.addEventListener(
            'abort',
            () => reject(new DOMException('Aborted', 'AbortError')),
            { once: true },
          )
        }),
    )

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      openTasksDrawer()
      await act(async () => vi.advanceTimersByTime(5000))
      expect(pollSignal?.aborted).toBe(false)
      rendered.unmount()
      expect(pollSignal?.aborted).toBe(true)
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('renders large document results in bounded batches', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: Array.from({ length: 150 }, (_, index) =>
            document({ id: `document-${index}`, title: `Document ${index}` }),
          ),
        },
      ],
    }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.getAllByRole('row')).toHaveLength(101)
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.loadMore' }))
    expect(screen.getAllByRole('row')).toHaveLength(151)
    expect(screen.getByRole('table').parentElement).toHaveFocus()
  })

  it('loads unresolved source labels without exhausting task history', async () => {
    documentsQuery.data = {
      pages: [{ items: [document({ sourceId: 'source-on-later-page' })] }],
    }
    tasksQuery.data = { pages: [{ items: [task({ state: 'succeeded' })], nextCursor: 'next' }] }
    tasksQuery.hasNextPage = true
    sourcesQuery.data = {
      pages: [{ items: [], nextCursor: 'source-next' }],
    }
    sourcesQuery.hasNextPage = true

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(tasksQuery.fetchNextPage).not.toHaveBeenCalled()
    expect(sourcesQuery.fetchNextPage).toHaveBeenCalledOnce()
  })

  it.each(['running', 'failed'] as const)(
    'uses the embedded %s snapshot without loading history',
    async (state) => {
      documentsQuery.data = { pages: [{ items: [document({ latestTask: task({ state }) })] }] }
      tasksQuery.data = { pages: [{ items: [], nextCursor: 'older-tasks' }] }
      tasksQuery.hasNextPage = true
      await render(<DocumentsPage knowledgeSpaceId="space-1" />)
      expect(
        screen.getByText(
          `knowledgeSpace.documentStatus.${state === 'running' ? 'processing' : 'failed'}`,
        ),
      ).toBeInTheDocument()
      expect(tasksQuery.fetchNextPage).not.toHaveBeenCalled()
    },
  )

  it('retries task history without blocking the document snapshot', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [], nextCursor: 'older-tasks' }] }
    tasksQuery.isFetchNextPageError = true
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(tasksQuery.fetchNextPage).not.toHaveBeenCalled()
    // Older task history fails to load from the drawer, which the user then closes.
    await user.click(
      screen.getByRole('button', { name: /knowledgeDocuments\.taskHistoryIncomplete/ }),
    )
    await user.click(
      within(screen.getByRole('dialog')).getByRole('button', { name: 'knowledgeSpace.loadMore' }),
    )
    await settle()
    expect(tasksQuery.fetchNextPage).toHaveBeenCalledOnce()
    await user.keyboard('{Escape}')
    expect(
      within(screen.getByRole('row', { name: /sso-enterprise\.pdf/ })).getByText(
        'knowledgeSpace.documentStatus.ready',
      ),
    ).toBeInTheDocument()
    await user.click(
      screen.getByRole('button', {
        name: 'common.operation.retry · knowledgeSpace.tasksErrorDescription',
      }),
    )
    await settle()
    expect(tasksQuery.fetchNextPage).toHaveBeenCalledTimes(2)
    expect(tasksQuery.refetch).not.toHaveBeenCalled()
  })

  it('finishes a server search without waiting for unrelated source pages', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: [
        {
          items: [document({ sourceId: 'later-source', userMetadata: {} })],
        },
      ],
    }
    sourcesQuery.data = {
      pages: Array.from({ length: 20 }, () => ({ items: [], nextCursor: 'next' })),
    }
    sourcesQuery.hasNextPage = true

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.type(
      screen.getByRole('searchbox', { name: 'knowledgeDocuments.searchDocuments' }),
      'source title from next page',
    )

    expect(await screen.findByText('knowledgeDocuments.noMatchingDocuments')).toBeInTheDocument()
    expect(documentsQuery.fetchNextPage).not.toHaveBeenCalled()
  })

  it('does not scan task or source history when paging search matches', async () => {
    const user = userEvent.setup()
    documentsQuery.data = {
      pages: Array.from({ length: 20 }, (_, index) => ({
        items: index === 0 ? [document({ sourceId: 'source-on-later-page' })] : [],
        nextCursor: 'next',
      })),
    }
    documentsQuery.hasNextPage = true
    tasksQuery.data = {
      pages: Array.from({ length: 20 }, () => ({ items: [], nextCursor: 'next' })),
    }
    tasksQuery.hasNextPage = true
    sourcesQuery.data = {
      pages: Array.from({ length: 20 }, (_, index) => ({
        items: index === 0 ? [source()] : [],
        nextCursor: 'next',
      })),
    }
    sourcesQuery.hasNextPage = true
    // Twenty pages of each list are already loaded, the automatic pagination limit.
    preload('documents', 'sources', 'tasks')

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.type(
      screen.getByRole('searchbox', { name: 'knowledgeDocuments.searchDocuments' }),
      'sso',
    )
    await waitFor(() => expect(lastInput('documents')).toMatchObject({ query: { query: 'sso' } }))
    await settle()

    expect(documentsQuery.fetchNextPage).not.toHaveBeenCalled()
    expect(screen.getByText('knowledgeDocuments.partialDocumentResults')).toBeInTheDocument()
    expect(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' })).toHaveAttribute(
      'aria-describedby',
      'partial-document-results',
    )
    await user.clear(screen.getByRole('searchbox'))
    await user.type(screen.getByRole('searchbox'), 'missing')
    await waitFor(() =>
      expect(lastInput('documents')).toMatchObject({ query: { query: 'missing' } }),
    )
    await settle()
    expect(screen.queryByText('knowledgeDocuments.noMatchingDocuments')).not.toBeInTheDocument()
    expect(screen.getByText('knowledgeDocuments.partialDocumentResults')).toBeInTheDocument()
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.loadMore' }))
    await settle()
    expect(documentsQuery.fetchNextPage).toHaveBeenCalledOnce()
    expect(tasksQuery.fetchNextPage).not.toHaveBeenCalled()
    expect(sourcesQuery.fetchNextPage).not.toHaveBeenCalled()
  })

  it('keeps task-history pagination out of document result pagination', async () => {
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: Array.from({ length: 20 }, () => ({
        items: [task({ state: 'succeeded' })],
        nextCursor: 'next',
      })),
    }
    tasksQuery.hasNextPage = true

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(
      screen.queryByRole('button', { name: 'knowledgeSpace.loadMore' }),
    ).not.toBeInTheDocument()
    expect(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' })).not.toHaveAttribute(
      'aria-disabled',
    )
  })

  it('keeps known documents actionable while older task and source pages remain', async () => {
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: Array.from({ length: 20 }, () => ({
        items: [task({ state: 'succeeded' })],
        nextCursor: 'next',
      })),
    }
    tasksQuery.hasNextPage = true
    sourcesQuery.data = {
      pages: Array.from({ length: 20 }, (_, index) => ({
        items: index === 0 ? [source()] : [],
        nextCursor: 'next',
      })),
    }
    sourcesQuery.hasNextPage = true

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' })).not.toHaveAttribute(
      'aria-disabled',
    )
    expect(
      within(screen.getByRole('row', { name: /sso-enterprise\.pdf/ })).getByText(
        'knowledgeSpace.documentStatus.ready',
      ),
    ).toBeInTheDocument()
    expect(
      screen.queryByRole('button', { name: 'knowledgeSpace.loadMore' }),
    ).not.toBeInTheDocument()
  })

  it('locks cached documents when the task query returns a permission denial', async () => {
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task()] }] }
    tasksQuery.error = createHttpError(new Response(null, { status: 403 }))

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)

    expect(screen.getByRole('alert')).toHaveTextContent(
      'knowledgeDocuments.documentsPermissionTitle',
    )
    expect(screen.queryByText('sso-enterprise.pdf')).not.toBeInTheDocument()
    expect(screen.queryByLabelText('knowledgeCreate.uploadDocuments')).not.toBeInTheDocument()
    expect(
      screen.queryByRole('button', { name: 'knowledgeDocuments.tasksWithAttention:{"count":1}' }),
    ).not.toBeInTheDocument()
  })

  it('retires a failed task action before background invalidation settles', async () => {
    const user = userEvent.setup()
    retryMutation.mutateAsync.mockRejectedValueOnce(new Error('retry failed'))
    vi.mocked(queryClient.invalidateQueries).mockImplementation(() => new Promise<void>(() => {}))
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task({ id: 'failed', state: 'failed' })] }] }

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))

    expect(await screen.findByText('knowledgeSpace.taskActionFailed')).toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' })).not.toHaveAttribute(
      'aria-disabled',
      'true',
    )
  })

  it('trusts same-version stream progress after a local retry', async () => {
    const user = userEvent.setup()
    const retryVersion = '2026-07-20T10:01:00Z'
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [task({ id: 'same-version-retry', state: 'failed', updatedAt: retryVersion })],
        },
      ],
    }
    retryMutation.mutateAsync.mockResolvedValue(
      task({ id: 'same-version-retry', state: 'queued', updatedAt: retryVersion }),
    )
    streamProcessingTaskEvents.mockImplementation(async function* () {
      yield {
        data: {
          progressPercent: 20,
          stage: 'parsed' as const,
          state: 'running' as const,
          updatedAt: retryVersion,
        },
        event: 'progress' as const,
        id: 'same-version-retry:running',
      }
      await new Promise<void>(() => {})
    })

    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))

    await waitFor(() => expect(streamProcessingTaskEvents).toHaveBeenCalled())
    expect(
      await screen.findByRole('button', { name: 'knowledgeTasks.interruptTask' }),
    ).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'knowledgeSpace.retryTask' })).toBeNull()
  })

  it('retries a permission-blocked failed-task poll after permission returns', async () => {
    vi.useFakeTimers()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [task({ id: 'permission-blocked-poll', state: 'failed' })],
        },
      ],
    }
    getTaskSnapshot
      .mockRejectedValueOnce(createHttpError(new Response(null, { status: 403 })))
      .mockResolvedValueOnce(
        task({
          id: 'permission-blocked-poll',
          state: 'dispatch_pending',
          updatedAt: '2026-07-20T10:02:00Z',
        }),
      )

    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    try {
      openTasksDrawer()
      await act(async () => vi.advanceTimersByTime(5000))
      expect(getTaskSnapshot).toHaveBeenCalledOnce()

      documentsQuery.error = createHttpError(new Response(null, { status: 403 }))
      await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
      documentsQuery.error = null
      await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
      openTasksDrawer()
      await act(async () => vi.advanceTimersByTime(5000))

      expect(getTaskSnapshot).toHaveBeenCalledTimes(2)
    } finally {
      rendered.unmount()
      vi.useRealTimers()
    }
  })

  it('restores document focus when a focused bulk toolbar is cleared', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' }))
    await user.click(
      screen.getByRole('button', { name: 'knowledgeDocuments.clearDocumentSelection' }),
    )

    await waitFor(() =>
      expect(screen.getByRole('heading', { name: 'knowledgeSpace.documents' })).toHaveFocus(),
    )
    rendered.unmount()
  })

  it('keeps upload and re-index actions focusable and unavailable while pending', async () => {
    const user = userEvent.setup()
    uploadMutation.mutateAsync.mockImplementation(() => new Promise(() => {}))
    const emptyPage = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    await user.upload(
      screen.getByLabelText('knowledgeCreate.uploadDocuments'),
      new File(['one'], 'one.md', { type: 'text/markdown' }),
    )
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))
    expect(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' })).toHaveAttribute(
      'aria-disabled',
      'true',
    )
    emptyPage.unmount()

    reindexMutation.mutateAsync.mockImplementation(() => new Promise(() => {}))
    documentsQuery.data = { pages: [{ items: [document()] }] }
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' }))
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.reindexDocuments' }))
    expect(screen.getByRole('button', { name: 'knowledgeSpace.reindexDocuments' })).toHaveAttribute(
      'aria-disabled',
      'true',
    )
  })

  it('locks uploads after a write mutation reveals revoked permission', async () => {
    const user = userEvent.setup()
    uploadMutation.mutateAsync.mockRejectedValueOnce(
      createHttpError(new Response(null, { status: 403 })),
    )
    permissionStateMock.refreshAfterDenial.mockResolvedValueOnce({
      data: { dataset: { default_permission_keys: ['dataset.acl.readonly'] } },
      error: null,
    })
    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    const addDocument = screen.getByRole('button', { name: 'knowledgeSpace.addDocument' })
    await user.click(addDocument)

    await user.upload(
      screen.getByLabelText('knowledgeCreate.uploadDocuments'),
      new File(['one'], 'one.md', { type: 'text/markdown' }),
    )
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))

    await waitFor(() => expect(permissionStateMock.refreshAfterDenial).toHaveBeenCalledOnce())
    expect(toastMock.error).not.toHaveBeenCalledWith('knowledgeSpace.documentUploadFailed')
    const restriction = screen.getByText('knowledgeSpace.documentPermissionRestricted')
    expect(restriction).toBeInTheDocument()
    expect(restriction).toHaveAttribute('role', 'status')
    expect(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' })).toBeDisabled()
    expect(screen.getByRole('heading', { name: 'knowledgeSpace.documents' })).toHaveFocus()

    permissionStateMock.datasetKeys = ['dataset.acl.readonly']
    permissionStateMock.spaceKeys = []
    await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    expect(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' })).toBeDisabled()

    permissionStateMock.datasetKeys = ['dataset.acl.edit']
    permissionStateMock.spaceKeys = ['knowledge_space_document_write']
    await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    await waitFor(() =>
      expect(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' })).toBeEnabled(),
    )
  })

  it('preserves a newer focus target when an upload later loses write permission', async () => {
    const user = userEvent.setup()
    let rejectUpload!: (error: unknown) => void
    uploadMutation.mutateAsync.mockImplementation(
      () =>
        new Promise((_resolve, reject) => {
          rejectUpload = reject
        }),
    )
    permissionStateMock.refreshAfterDenial.mockResolvedValueOnce({
      data: { dataset: { default_permission_keys: ['dataset.acl.readonly'] } },
      error: null,
    })
    tasksQuery.data = { pages: [{ items: [task()] }] }
    await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?upload=1' })

    await user.upload(
      screen.getByLabelText('knowledgeCreate.uploadDocuments'),
      new File(['one'], 'one.md', { type: 'text/markdown' }),
    )
    await waitForDocumentFilesStaged()
    await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))
    const documentsHeading = screen.getByRole('heading', {
      name: 'knowledgeSpace.addDocument',
    })
    documentsHeading.focus()
    expect(documentsHeading).toHaveFocus()

    await act(async () => rejectUpload(createHttpError(new Response(null, { status: 403 }))))
    await waitFor(() => expect(permissionStateMock.refreshAfterDenial).toHaveBeenCalledOnce())

    expect(screen.getByRole('heading', { name: 'knowledgeSpace.documents' })).toHaveFocus()
  })

  it('locks re-indexing after a write mutation reveals revoked permission', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    reindexMutation.mutateAsync.mockRejectedValueOnce(
      createHttpError(new Response(null, { status: 403 })),
    )
    permissionStateMock.refreshAfterDenial.mockResolvedValueOnce({
      data: { dataset: { default_permission_keys: ['dataset.acl.readonly'] } },
      error: null,
    })
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' }))
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.reindexDocuments' }))

    await waitFor(() => expect(permissionStateMock.refreshAfterDenial).toHaveBeenCalledOnce())
    expect(toastMock.error).not.toHaveBeenCalledWith('knowledgeDocuments.documentsReindexFailed')
    const actions = screen.getByRole('group', { name: 'knowledgeDocuments.bulkDocumentActions' })
    expect(
      within(actions).queryByRole('button', { name: 'knowledgeSpace.reindexDocuments' }),
    ).not.toBeInTheDocument()
    expect(
      within(actions).getByRole('button', { name: 'knowledgeDocuments.downloadDocuments' }),
    ).toBeEnabled()
    expect(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' })).not.toHaveAttribute(
      'aria-disabled',
    )
    expect(screen.getByRole('heading', { name: 'knowledgeSpace.documents' })).toHaveFocus()
  })

  it('locks task actions after a write mutation reveals revoked permission', async () => {
    const user = userEvent.setup()
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task()] }] }
    cancelMutation.mutateAsync.mockRejectedValueOnce(
      createHttpError(new Response(null, { status: 403 })),
    )
    permissionStateMock.refreshAfterDenial.mockResolvedValueOnce({
      data: { dataset: { default_permission_keys: ['dataset.acl.readonly'] } },
      error: null,
    })
    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' }))

    await waitFor(() => expect(permissionStateMock.refreshAfterDenial).toHaveBeenCalledOnce())
    expect(
      within(screen.getByRole('dialog')).getByText('knowledgeSpace.documentPermissionRestricted'),
    ).toBeInTheDocument()
    expect(screen.queryByText('knowledgeSpace.taskActionFailed')).not.toBeInTheDocument()
    expect(
      screen.queryByRole('button', { name: 'knowledgeTasks.interruptTask' }),
    ).not.toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'common.operation.close' })).toHaveFocus()

    permissionStateMock.error = new Error('permission refresh failed')
    await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)
    const dialog = screen.getByRole('dialog')
    expect(
      within(dialog).getByText('knowledgeSpace.documentPermissionRestricted'),
    ).toBeInTheDocument()
    expect(within(dialog).queryByRole('alert')).not.toBeInTheDocument()
  })

  it('does not let an older permission refresh release the latest write lock', async () => {
    const user = userEvent.setup()
    let rejectUpload: ((reason: unknown) => void) | undefined
    let rejectCancel: ((reason: unknown) => void) | undefined
    let resolveFirstRefresh: ((value: unknown) => void) | undefined
    let resolveSecondRefresh: ((value: unknown) => void) | undefined
    uploadMutation.mutateAsync.mockImplementationOnce(
      () =>
        new Promise((_resolve, reject) => {
          rejectUpload = reject
        }),
    )
    cancelMutation.mutateAsync.mockImplementationOnce(
      () =>
        new Promise((_resolve, reject) => {
          rejectCancel = reject
        }),
    )
    permissionStateMock.refreshAfterDenial
      .mockImplementationOnce(
        () =>
          new Promise((resolve) => {
            resolveFirstRefresh = resolve
          }),
      )
      .mockImplementationOnce(
        () =>
          new Promise((resolve) => {
            resolveSecondRefresh = resolve
          }),
      )
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = { pages: [{ items: [task()] }] }
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeTasks.interruptTask' }))
    await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
    fireEvent.click(screen.getByRole('button', { name: 'knowledgeSpace.addDocument' }))
    fireEvent.change(screen.getByLabelText('knowledgeCreate.uploadDocuments'), {
      target: { files: [new File(['one'], 'one.md', { type: 'text/markdown' })] },
    })
    await waitForDocumentFilesStaged()
    fireEvent.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))
    expect(cancelMutation.mutateAsync).toHaveBeenCalledOnce()
    await waitFor(() => expect(uploadMutation.mutateAsync).toHaveBeenCalledOnce())

    await act(async () => rejectUpload?.(createHttpError(new Response(null, { status: 403 }))))
    await waitFor(() => expect(permissionStateMock.refreshAfterDenial).toHaveBeenCalledOnce())
    await act(async () => rejectCancel?.(createHttpError(new Response(null, { status: 403 }))))
    await waitFor(() => expect(permissionStateMock.refreshAfterDenial).toHaveBeenCalledTimes(2))

    await act(async () =>
      resolveFirstRefresh?.({
        data: { dataset: { default_permission_keys: ['dataset.acl.edit'] } },
        error: null,
      }),
    )
    expect(
      screen.queryByRole('button', { name: 'knowledgeTasks.interruptTask' }),
    ).not.toBeInTheDocument()

    await act(async () =>
      resolveSecondRefresh?.({
        data: { dataset: { default_permission_keys: ['dataset.acl.readonly'] } },
        error: null,
      }),
    )
    expect(
      screen.queryByRole('button', { name: 'knowledgeTasks.interruptTask' }),
    ).not.toBeInTheDocument()
  })

  it('observes a structurally shared same-version retry when response timestamps collide', async () => {
    const user = userEvent.setup()
    const taskVersion = '2026-07-20T10:03:00Z'
    const sharedTaskData = {
      pages: [{ items: [task({ id: 'shared-active-retry', updatedAt: taskVersion })] }],
    }
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = sharedTaskData
    getTaskSnapshot
      .mockRejectedValueOnce(new Error('snapshot unavailable'))
      .mockResolvedValueOnce(
        task({ id: 'shared-active-retry', state: 'running', updatedAt: taskVersion }),
      )
    streamFailedTaskThenWait('shared-active-retry')
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    expect(await screen.findByText('knowledgeErrors.taskFailure.temporary')).toBeInTheDocument()
    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledOnce())

    tasksQuery.data = sharedTaskData
    await notifyTaskQuerySuccess()

    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledTimes(2))
    expect(
      await screen.findByRole('button', { name: 'knowledgeTasks.interruptTask' }),
    ).toBeInTheDocument()
  })

  it('rechecks a same-version active lifecycle after a denied terminal snapshot', async () => {
    const taskVersion = '2026-07-20T10:03:00Z'
    const sharedTaskData = {
      pages: [{ items: [task({ id: 'denied-active-retry', updatedAt: taskVersion })] }],
    }
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = sharedTaskData
    getTaskSnapshot
      .mockRejectedValueOnce(createHttpError(new Response(null, { status: 403 })))
      .mockResolvedValueOnce(
        task({ id: 'denied-active-retry', state: 'running', updatedAt: taskVersion }),
      )
    streamFailedTaskThenWait('denied-active-retry')
    await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    openTasksDrawer()
    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledOnce())

    tasksQuery.data = sharedTaskData
    await notifyTaskQuerySuccess()

    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledTimes(2))
    expect(
      await screen.findByRole('button', { name: 'knowledgeTasks.interruptTask' }),
    ).toBeInTheDocument()
  })

  it('reconciles a same-version terminal list after trusted local retry progress', async () => {
    const user = userEvent.setup()
    const taskVersion = '2026-07-20T10:01:00Z'
    documentsQuery.data = { pages: [{ items: [document()] }] }
    tasksQuery.data = {
      pages: [
        {
          items: [task({ id: 'trusted-terminal', state: 'failed', updatedAt: taskVersion })],
        },
      ],
    }
    retryMutation.mutateAsync.mockImplementation(async () => {
      // The server lists the retried task as queued until it fails again.
      const retried = task({ id: 'trusted-terminal', state: 'queued', updatedAt: taskVersion })
      tasksQuery.data = { pages: [{ items: [retried] }] }
      return retried
    })
    getTaskSnapshot.mockResolvedValue(
      task({
        errorCode: 'TERMINAL_CONFIRMED',
        id: 'trusted-terminal',
        state: 'failed',
        updatedAt: taskVersion,
      }),
    )
    streamProcessingTaskEvents.mockImplementation(async function* () {
      yield {
        data: {
          progressPercent: 30,
          stage: 'parsed' as const,
          state: 'running' as const,
          updatedAt: taskVersion,
        },
        event: 'progress' as const,
        id: 'trusted-terminal:running',
      }
      await new Promise<void>(() => {})
    })
    const rendered = await render(<DocumentsPage knowledgeSpaceId="space-1" />)
    await user.click(
      screen.getByRole('button', {
        name: 'knowledgeDocuments.tasksWithAttention:{"count":1}',
      }),
    )
    await user.click(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' }))
    expect(
      await screen.findByRole('button', { name: 'knowledgeTasks.interruptTask' }),
    ).toBeInTheDocument()

    tasksQuery.data = {
      pages: [
        {
          items: [task({ id: 'trusted-terminal', state: 'failed', updatedAt: taskVersion })],
        },
      ],
    }
    await rendered.rerender(<DocumentsPage knowledgeSpaceId="space-1" />)

    await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalled())
    expect(await screen.findByText('knowledgeErrors.taskFailure.internal')).toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'knowledgeSpace.retryTask' })).toBeInTheDocument()
  })
})