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.

fix: improve archived logs accessibility (#44535)

Joel405c39692da2
diff --git a/web/app/components/header/account-setting/workflow-log-archives-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/workflow-log-archives-page/__tests__/index.spec.tsx
index 321af195197..6cfd4b44699 100644
--- a/web/app/components/header/account-setting/workflow-log-archives-page/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/workflow-log-archives-page/__tests__/index.spec.tsx
@@ -2,12 +2,14 @@ import type { CloudPlan } from '@dify/contracts/api/console/features/types.gen'
import type {
GetWorkflowRunArchivesResponse,
WorkflowRunArchiveDeletionTaskResponse,
+ WorkflowRunArchiveDownloadTaskResponse,
} from '@dify/contracts/api/console/workflow-run-archives/types.gen'
import type { GetWorkspacesCurrentSummaryResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import {
createConsoleQueryClient,
@@ -20,6 +22,7 @@ const archiveRequests = vi.hoisted(() => ({
list: vi.fn(),
delete: vi.fn(),
prepareDownload: vi.fn(),
+ download: vi.fn(),
}))
vi.mock('@/service/console/browser', () => ({
@@ -32,6 +35,8 @@ vi.mock('@/service/console/browser', () => ({
return archiveRequests.delete(input)
case 'workflowRunArchives.downloads.post':
return archiveRequests.prepareDownload(input)
+ case 'workflowRunArchives.downloads.byDownloadId.get':
+ return archiveRequests.download(input)
default:
throw new Error(`Unexpected console request: ${path.join('.')}`)
}
@@ -61,6 +66,19 @@ const archiveData: GetWorkflowRunArchivesResponse = {
months: [archiveMonth],
}
+const downloadTask: WorkflowRunArchiveDownloadTaskResponse = {
+ download_id: 'archive-download',
+ status: 'pending',
+ error: null,
+ year: 2025,
+ month: 3,
+ archive_bytes: 1048576,
+ bundle_count: 2,
+ created_at: '2025-03-03T00:00:00Z',
+ updated_at: '2025-03-03T00:00:00Z',
+ expires_at: '2025-03-04T00:00:00Z',
+}
+
let plan: CloudPlan = 'professional'
function renderPage(
@@ -94,6 +112,7 @@ describe('WorkflowLogArchivesPage', () => {
error: null,
})
archiveRequests.prepareDownload.mockImplementation(() => new Promise(() => {}))
+ archiveRequests.download.mockImplementation(() => new Promise(() => {}))
plan = 'professional'
})
@@ -323,6 +342,7 @@ describe('WorkflowLogArchivesPage', () => {
)
expect(await screen.findByText('appLog.archives.empty.title')).toBeInTheDocument()
+ expect(screen.getByRole('status')).toHaveTextContent('appLog.archives.empty.title')
expect(screen.queryByRole('row', { name: /2025-03/ })).not.toBeInTheDocument()
const runCount = screen.getByText('appLog.archives.summary.runs').parentElement
expect(runCount).toHaveTextContent('0')
@@ -466,9 +486,350 @@ describe('WorkflowLogArchivesPage', () => {
afterEach(() => {
vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ describe('Download status announcements', () => {
+ it('resumes polling when another page retries a failed task with the same ID', async () => {
+ vi.useFakeTimers()
+ try {
+ archiveRequests.download.mockResolvedValue({ ...downloadTask, status: 'failed' })
+ const { queryClient } = renderPage({
+ ...archiveData,
+ months: [{ ...archiveMonth, download_task: downloadTask }],
+ })
+ await act(async () => vi.advanceTimersByTimeAsync(3001))
+ expect(screen.getByRole('button', { name: 'common.operation.retry 2025-03' })).toBeEnabled()
+
+ const retriedTask = { ...downloadTask, updated_at: '2025-03-03T00:00:01Z' }
+ archiveRequests.download
+ .mockResolvedValueOnce({ ...downloadTask, status: 'failed' })
+ .mockResolvedValue({
+ ...retriedTask,
+ status: 'ready',
+ updated_at: '2025-03-03T00:00:02Z',
+ })
+ archiveRequests.list.mockResolvedValue({
+ ...archiveData,
+ months: [{ ...archiveMonth, download_task: retriedTask }],
+ })
+ await act(async () =>
+ queryClient.refetchQueries({ queryKey: consoleQuery.workflowRunArchives.get.queryKey() }),
+ )
+ await act(async () => vi.advanceTimersByTimeAsync(10000))
+
+ expect(
+ screen.getByRole('button', { name: 'common.operation.download 2025-03' }),
+ ).toBeEnabled()
+ const row = screen.getByRole('row', { name: /2025-03/ })
+ expect(within(row).getByRole('status')).toHaveTextContent(
+ '2025-03: appLog.archives.downloadHint.ready',
+ )
+ const pollCount = archiveRequests.download.mock.calls.length
+ await act(async () => vi.advanceTimersByTimeAsync(6000))
+ expect(archiveRequests.download).toHaveBeenCalledTimes(pollCount)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('uses a newer list result after preparing a download in this page', async () => {
+ const user = userEvent.setup()
+ archiveRequests.prepareDownload.mockResolvedValue(downloadTask)
+ const { queryClient } = renderPage()
+ await user.click(
+ screen.getByRole('button', { name: 'appLog.archives.action.prepareDownload 2025-03' }),
+ )
+ expect(
+ screen.getByRole('button', { name: 'appLog.archives.action.preparing 2025-03' }),
+ ).toHaveAttribute('aria-disabled', 'true')
+ archiveRequests.list.mockResolvedValue({
+ ...archiveData,
+ months: [
+ {
+ ...archiveMonth,
+ download_task: { ...downloadTask, status: 'ready', updated_at: '2025-03-03T00:00:01Z' },
+ },
+ ],
+ })
+ await act(async () =>
+ queryClient.refetchQueries({ queryKey: consoleQuery.workflowRunArchives.get.queryKey() }),
+ )
+
+ expect(
+ await screen.findByRole('button', { name: 'common.operation.download 2025-03' }),
+ ).toBeEnabled()
+ const row = screen.getByRole('row', { name: /2025-03/ })
+ expect(within(row).getByRole('status')).toHaveTextContent(
+ '2025-03: appLog.archives.downloadHint.ready',
+ )
+ })
+
+ it.each(['ready', 'failed'] as const)(
+ 'reports a newer %s result from the archive list instead of stale polling data',
+ async (status) => {
+ archiveRequests.download.mockResolvedValue({ ...downloadTask, status: 'processing' })
+ const data = {
+ ...archiveData,
+ months: [
+ { ...archiveMonth, download_task: downloadTask },
+ { ...archiveMonth, month: 2 },
+ ],
+ }
+ const { queryClient } = renderPage(data)
+ const row = screen.getByRole('row', { name: /2025-03/ })
+ const announcement = within(row).getByRole('status')
+ await waitFor(() => expect(archiveRequests.download).toHaveBeenCalled())
+ expect(announcement).toBeEmptyDOMElement()
+ archiveRequests.list.mockResolvedValue({
+ ...data,
+ months: [
+ {
+ ...archiveMonth,
+ download_task: { ...downloadTask, status, updated_at: '2025-03-03T00:00:00.500000Z' },
+ },
+ { ...archiveMonth, month: 2 },
+ ],
+ })
+
+ await act(async () =>
+ queryClient.refetchQueries({
+ queryKey: consoleQuery.workflowRunArchives.get.queryKey(),
+ }),
+ )
+
+ expect(
+ await within(row).findByRole('button', {
+ name:
+ status === 'ready'
+ ? 'common.operation.download 2025-03'
+ : 'common.operation.retry 2025-03',
+ }),
+ ).toBeEnabled()
+ expect(announcement).toHaveTextContent(`2025-03: appLog.archives.downloadHint.${status}`)
+ },
+ )
+
+ it.each(['ready', 'failed'] as const)(
+ 'keeps announcing a %s list result after the initial download status request fails',
+ async (status) => {
+ archiveRequests.download.mockRejectedValue(new Error('Temporary status failure'))
+ const deletingMonth = { ...archiveMonth, month: 2, deletion_status: 'processing' as const }
+ const data = {
+ ...archiveData,
+ months: [{ ...archiveMonth, download_task: downloadTask }, deletingMonth],
+ }
+ const { queryClient } = renderPage(data)
+ const row = screen.getByRole('row', { name: /2025-03/ })
+ const announcement = within(row).getByRole('status')
+ const taskQueryKey = consoleQuery.workflowRunArchives.downloads.byDownloadId.get.queryKey({
+ input: { params: { download_id: downloadTask.download_id } },
+ })
+ await waitFor(() => expect(queryClient.getQueryState(taskQueryKey)?.status).toBe('error'))
+ expect(announcement).toBeEmptyDOMElement()
+ archiveRequests.list.mockResolvedValue({
+ ...data,
+ months: [
+ {
+ ...archiveMonth,
+ download_task: { ...downloadTask, status, updated_at: '2025-03-03T00:00:00.500000Z' },
+ },
+ deletingMonth,
+ ],
+ })
+
+ for (let refresh = 0; refresh < 2; refresh++) {
+ await act(async () =>
+ queryClient.refetchQueries({
+ queryKey: consoleQuery.workflowRunArchives.get.queryKey(),
+ }),
+ )
+
+ expect(
+ await within(row).findByRole('button', {
+ name:
+ status === 'ready'
+ ? 'common.operation.download 2025-03'
+ : 'common.operation.retry 2025-03',
+ }),
+ ).toBeEnabled()
+ await waitFor(() =>
+ expect(announcement).toHaveTextContent(
+ `2025-03: appLog.archives.downloadHint.${status}`,
+ ),
+ )
+ }
+ },
+ )
+
+ it.each([
+ { status: 'ready', error: null, hint: 'appLog.archives.downloadHint.ready' },
+ {
+ status: 'failed',
+ error: 'Storage unavailable',
+ hint: 'appLog.archives.downloadHint.failedWithReason:{"reason":"Storage unavailable"}',
+ },
+ { status: 'failed', error: ' ', hint: 'appLog.archives.downloadHint.failed' },
+ ] as const)(
+ 'reports a background download becoming $status with month context',
+ async ({ status, error, hint }) => {
+ vi.useFakeTimers()
+ try {
+ archiveRequests.download
+ .mockResolvedValueOnce({ ...downloadTask, status: 'processing' })
+ .mockResolvedValue({ ...downloadTask, status, error })
+ renderPage({ ...archiveData, months: [{ ...archiveMonth, download_task: downloadTask }] })
+ const row = screen.getByRole('row', { name: /2025-03/ })
+ const announcement = within(row).getByRole('status')
+ expect(announcement).toBeEmptyDOMElement()
+ const deletion = within(row).getByRole('button', {
+ name: 'common.operation.delete 2025-03',
+ })
+ act(() => deletion.focus())
+ expect(deletion).toHaveFocus()
+
+ await act(async () => vi.advanceTimersByTimeAsync(3001))
+
+ expect(announcement).toHaveTextContent(`2025-03: ${hint}`)
+ expect(announcement).toHaveAttribute('aria-atomic', 'true')
+ expect(deletion).toHaveFocus()
+ const pollCount = archiveRequests.download.mock.calls.length
+ await act(async () => vi.advanceTimersByTimeAsync(6000))
+ expect(archiveRequests.download).toHaveBeenCalledTimes(pollCount)
+ expect(announcement).toHaveTextContent(`2025-03: ${hint}`)
+ } finally {
+ vi.useRealTimers()
+ }
+ },
+ )
+
+ it.each(['ready', 'failed'] as const)(
+ 'does not announce an initially %s download as a new result',
+ (status) => {
+ renderPage({
+ ...archiveData,
+ months: [{ ...archiveMonth, download_task: { ...downloadTask, status } }],
+ })
+
+ const row = screen.getByRole('row', { name: /2025-03/ })
+ expect(within(row).getByRole('status')).toBeEmptyDOMElement()
+ expect(archiveRequests.download).not.toHaveBeenCalled()
+ },
+ )
+
+ it.each([
+ { status: 'ready', error: null, notification: 'appLog.archives.action.downloadReady' },
+ { status: 'failed', error: null, notification: 'appLog.archives.action.prepareStarted' },
+ ] as const)(
+ 'preserves the existing notification for an immediately $status task ($error)',
+ async ({ status, error: failureReason, notification }) => {
+ const user = userEvent.setup()
+ const success = vi.spyOn(toast, 'success')
+ const error = vi.spyOn(toast, 'error')
+ archiveRequests.prepareDownload.mockResolvedValue({
+ ...downloadTask,
+ status,
+ error: failureReason,
+ })
+ renderPage()
+
+ await user.click(
+ screen.getByRole('button', {
+ name: 'appLog.archives.action.prepareDownload 2025-03',
+ }),
+ )
+
+ const row = screen.getByRole('row', { name: /2025-03/ })
+ expect(within(row).getByRole('status')).toBeEmptyDOMElement()
+ expect(success).toHaveBeenCalledExactlyOnceWith(notification)
+ expect(error).not.toHaveBeenCalled()
+ },
+ )
+
+ it('retries the same download ID and announces completion through automatic polling', async () => {
+ const user = userEvent.setup()
+ archiveRequests.download.mockResolvedValue({ ...downloadTask, status: 'failed' })
+ renderPage({
+ ...archiveData,
+ months: [{ ...archiveMonth, download_task: downloadTask }],
+ })
+ const retry = await screen.findByRole('button', { name: 'common.operation.retry 2025-03' })
+ const row = screen.getByRole('row', { name: /2025-03/ })
+ const announcement = within(row).getByRole('status')
+ expect(announcement).toHaveTextContent('2025-03: appLog.archives.downloadHint.failed')
+
+ let resolveRetry!: (task: WorkflowRunArchiveDownloadTaskResponse) => void
+ archiveRequests.prepareDownload.mockImplementation(
+ () =>
+ new Promise<WorkflowRunArchiveDownloadTaskResponse>((resolve) => {
+ resolveRetry = resolve
+ }),
+ )
+ const retriedTask = { ...downloadTask, updated_at: '2025-03-03T00:00:01Z' }
+ archiveRequests.download.mockResolvedValue({
+ ...retriedTask,
+ status: 'ready',
+ updated_at: '2025-03-03T00:00:02Z',
+ })
+ await user.click(retry)
+ expect(announcement).toBeEmptyDOMElement()
+
+ vi.useFakeTimers()
+ try {
+ await act(async () => resolveRetry(retriedTask))
+ await act(async () => vi.advanceTimersByTimeAsync(0))
+ expect(
+ within(row).getByRole('button', { name: 'appLog.archives.action.preparing 2025-03' }),
+ ).toHaveAttribute('aria-disabled', 'true')
+ expect(announcement).toBeEmptyDOMElement()
+
+ await act(async () => vi.advanceTimersByTimeAsync(3001))
+
+ expect(
+ within(row).getByRole('button', { name: 'common.operation.download 2025-03' }),
+ ).toBeEnabled()
+ expect(announcement).toHaveTextContent('2025-03: appLog.archives.downloadHint.ready')
+ expect(archiveRequests.prepareDownload).toHaveBeenCalledExactlyOnceWith({
+ body: { year: 2025, month: 3 },
+ })
+ } finally {
+ vi.useRealTimers()
+ }
+ })
})
describe('Archive table states', () => {
+ it('announces an asynchronous empty result in an already mounted status region', async () => {
+ let resolveArchives!: (data: GetWorkflowRunArchivesResponse) => void
+ archiveRequests.list.mockImplementation(
+ () =>
+ new Promise<GetWorkflowRunArchivesResponse>((resolve) => {
+ resolveArchives = resolve
+ }),
+ )
+ renderPage(null)
+ const announcement = screen.getByRole('status')
+ expect(announcement).toBeEmptyDOMElement()
+ await waitFor(() => expect(archiveRequests.list).toHaveBeenCalled())
+
+ await act(async () =>
+ resolveArchives({
+ months: [],
+ summary: {
+ archived_month_count: 0,
+ workflow_run_count: 0,
+ archive_bytes: 0,
+ latest_archived_at: null,
+ },
+ }),
+ )
+
+ await waitFor(() => expect(announcement).toHaveTextContent('appLog.archives.empty.title'))
+ expect(announcement).toHaveTextContent('appLog.archives.empty.description')
+ expect(announcement).toHaveAttribute('aria-atomic', 'true')
+ expect(screen.getByRole('status')).toBe(announcement)
+ })
+
it('should hide loading rows from assistive technology until archives arrive', async () => {
const queryClient = createConsoleQueryClient()
let resolveArchives!: (data: GetWorkflowRunArchivesResponse) => void
@@ -496,7 +857,7 @@ describe('WorkflowLogArchivesPage', () => {
expect(within(table).getAllByRole('row', { hidden: true })).toHaveLength(2)
})
- it('should present an archive request error in a cell spanning the table columns', async () => {
+ it('presents an archive request error below the table headers', async () => {
const queryClient = createConsoleQueryClient()
const queryKey = consoleQuery.workflowRunArchives.get.queryKey()
queryClient.setQueryDefaults(queryKey, { retryOnMount: false })
@@ -510,14 +871,47 @@ describe('WorkflowLogArchivesPage', () => {
renderPage(null, queryClient)
const table = screen.getByRole('table')
- const errorCell = within(table).getByRole('cell', { name: /appLog\.archives\.error\.title/ })
- expect(errorCell).toHaveAttribute('colspan', '4')
- expect(within(errorCell).getByText('appLog.archives.error.description')).toBeInTheDocument()
- expect(within(table).queryByText('appLog.archives.empty.title')).not.toBeInTheDocument()
+ const headerRow = within(table).getByRole('row', { name: /appLog\.archives\.table\.month/ })
+ const errorRow = within(table).getByRole('row', { name: /appLog\.archives\.error\.title/ })
+ expect(within(table).getAllByRole('row')).toEqual([headerRow, errorRow])
+ expect(within(headerRow).getAllByRole('columnheader')).toHaveLength(4)
+ expect(within(errorRow).getByText('appLog.archives.error.title')).toBeInTheDocument()
+ expect(within(errorRow).getByText('appLog.archives.error.description')).toBeInTheDocument()
+ expect(screen.queryByText('appLog.archives.empty.title')).not.toBeInTheDocument()
expect(within(table).queryByRole('button')).not.toBeInTheDocument()
})
- it('should present an empty archive message in a cell spanning the table columns', () => {
+ it('keeps a refresh error between the headers and retained archive rows', async () => {
+ const { queryClient } = renderPage()
+ archiveRequests.list.mockRejectedValue(new Error('Archives unavailable'))
+
+ await act(async () =>
+ queryClient.refetchQueries({
+ queryKey: consoleQuery.workflowRunArchives.get.queryKey(),
+ }),
+ )
+ await screen.findByText('appLog.archives.error.title')
+
+ const table = screen.getByRole('table')
+ const headerRow = within(table).getByRole('row', { name: /appLog\.archives\.table\.month/ })
+ const errorRow = within(table).getByRole('row', { name: /appLog\.archives\.error\.title/ })
+ const archiveRow = within(table).getByRole('row', { name: /2025-03/ })
+ expect(within(table).getAllByRole('row')).toEqual([headerRow, errorRow, archiveRow])
+ expect(within(headerRow).getAllByRole('columnheader')).toHaveLength(4)
+ expect(
+ within(errorRow).getByRole('cell', {
+ name: /appLog\.archives\.error\.title/,
+ }),
+ ).toHaveAttribute('colspan', '4')
+ expect(archiveRow).toHaveTextContent('2025-03')
+ expect(
+ within(archiveRow).getByRole('button', {
+ name: 'appLog.archives.action.prepareDownload 2025-03',
+ }),
+ ).toBeInTheDocument()
+ })
+
+ it('presents an empty archive message outside the scrolling table', () => {
renderPage({
months: [],
summary: {
@@ -529,10 +923,10 @@ describe('WorkflowLogArchivesPage', () => {
})
const table = screen.getByRole('table')
- const emptyCell = within(table).getByRole('cell', { name: /appLog\.archives\.empty\.title/ })
- expect(emptyCell).toHaveAttribute('colspan', '4')
- expect(within(emptyCell).getByText('appLog.archives.empty.description')).toBeInTheDocument()
- expect(within(table).queryByText('appLog.archives.error.title')).not.toBeInTheDocument()
+ expect(screen.getByText('appLog.archives.empty.title')).toBeInTheDocument()
+ expect(screen.getByText('appLog.archives.empty.description')).toBeInTheDocument()
+ expect(within(table).queryByText('appLog.archives.empty.title')).not.toBeInTheDocument()
+ expect(screen.queryByText('appLog.archives.error.title')).not.toBeInTheDocument()
expect(within(table).queryByRole('button')).not.toBeInTheDocument()
})
@@ -588,6 +982,12 @@ describe('WorkflowLogArchivesPage', () => {
plan = 'sandbox'
renderPage()
+ expect(
+ screen.getByRole('heading', {
+ level: 4,
+ name: 'appLog.archives.upgradeTip.title',
+ }),
+ ).toBeInTheDocument()
expect(screen.queryByRole('table')).not.toBeInTheDocument()
expect(archiveRequests.list).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'billing.upgradeBtn.encourageShort' }))
@@ -597,7 +997,7 @@ describe('WorkflowLogArchivesPage', () => {
)
})
- it('discloses download failure details before retrying the affected month', async () => {
+ it('describes the failed download when its retry button receives keyboard focus', async () => {
const user = userEvent.setup()
renderPage({
...archiveData,
@@ -622,16 +1022,14 @@ describe('WorkflowLogArchivesPage', () => {
const retry = screen.getByRole('button', { name: 'common.operation.retry 2025-03' })
expect(retry).toBeEnabled()
- await user.hover(retry)
- expect(
- await screen.findByText(
- 'appLog.archives.downloadHint.failedWithReason:{"reason":"Storage unavailable"}',
- ),
- ).toBeVisible()
+ await user.tab()
+ expect(retry).toHaveFocus()
+ const tooltip = await screen.findByRole('tooltip')
+ const failureHint =
+ 'appLog.archives.downloadHint.failedWithReason:{"reason":"Storage unavailable"}'
+ expect(tooltip).toHaveTextContent(failureHint)
+ expect(retry).toHaveAccessibleDescription(failureHint)
expect(archiveRequests.prepareDownload).not.toHaveBeenCalled()
- expect(
- screen.queryByRole('button', { name: 'common.operation.learnMore: 2025-03' }),
- ).not.toBeInTheDocument()
await user.click(retry)
expect(archiveRequests.prepareDownload).toHaveBeenCalledWith({
body: { year: 2025, month: 3 },
diff --git a/web/app/components/header/account-setting/workflow-log-archives-page/__tests__/reflow.browser.spec.tsx b/web/app/components/header/account-setting/workflow-log-archives-page/__tests__/reflow.browser.spec.tsx
new file mode 100644
index 00000000000..a52021637e8
--- /dev/null
+++ b/web/app/components/header/account-setting/workflow-log-archives-page/__tests__/reflow.browser.spec.tsx
@@ -0,0 +1,151 @@
+import type { GetWorkflowRunArchivesResponse } from '@dify/contracts/api/console/workflow-run-archives/types.gen'
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { page, userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { QueryClientTestProvider } from '@/test/console/query-provider'
+import { ACCOUNT_SETTING_TAB } from '../../constants'
+import AccountSetting from '../../index'
+
+const archiveListRequest = vi.hoisted(() => vi.fn())
+
+vi.mock('@/service/console/browser', () => ({
+ consoleBrowserLink: {
+ call: (path: readonly string[], input: unknown) => {
+ if (path.join('.') === 'workflowRunArchives.get') return archiveListRequest(input)
+ throw new Error(`Unexpected console request: ${path.join('.')}`)
+ },
+ },
+}))
+
+vi.mock('react-i18next', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('react-i18next')>()
+ const { createReactI18nextMock } = await import('@/test/i18n-mock')
+ const namespaces = {
+ appLog: (await import('@/i18n/locales/en-US/app-log.json')).default,
+ common: (await import('@/i18n/locales/en-US/common.json')).default,
+ navigation: (await import('@/i18n/locales/en-US/navigation.json')).default,
+ }
+ const translations = Object.fromEntries(
+ Object.entries(namespaces).flatMap(([namespace, messages]) =>
+ Object.entries(messages).map(([key, value]) => [`${namespace}.${key}`, value]),
+ ),
+ )
+ return { ...actual, ...createReactI18nextMock(translations) }
+})
+
+async function renderSettings(archives: GetWorkflowRunArchivesResponse) {
+ await page.viewport(320, 800)
+ const { queryClient } = createConsoleQueryWrapper({
+ currentWorkspace: { role: 'owner' },
+ features: { billing: { subscription: { plan: 'team' } } },
+ systemFeatures: { deployment_edition: 'CLOUD', rbac_enabled: false },
+ })
+ queryClient.setQueryData(consoleQuery.workflowRunArchives.get.queryKey(), archives)
+ const screen = await render(
+ <QueryClientTestProvider queryClient={queryClient}>
+ <NuqsTestingAdapter>
+ <AccountSetting
+ activeTab={ACCOUNT_SETTING_TAB.WORKFLOW_LOG_ARCHIVES}
+ onCancelAction={vi.fn()}
+ onTabChangeAction={vi.fn()}
+ />
+ </NuqsTestingAdapter>
+ </QueryClientTestProvider>,
+ )
+ return { dialog: screen.getByRole('dialog', { name: 'Settings' }), queryClient }
+}
+
+it('keeps the complete empty message readable without horizontal scrolling at 320 CSS pixels', async () => {
+ // The real Settings shell supplies the available width; happy-dom cannot detect clipped text.
+ const { dialog, queryClient } = await renderSettings({
+ months: [],
+ summary: {
+ archived_month_count: 0,
+ workflow_run_count: 0,
+ archive_bytes: 0,
+ latest_archived_at: null,
+ },
+ })
+
+ try {
+ const title = dialog.getByText('No archived logs')
+ const description = dialog.getByText(
+ 'Archived workflow run logs will appear here after the retention job finishes.',
+ )
+ await expect.element(description).toBeVisible()
+ for (const message of [title, description]) {
+ const rect = message.element().getBoundingClientRect()
+ expect(rect.left).toBeGreaterThanOrEqual(0)
+ expect(rect.right).toBeLessThanOrEqual(320)
+ }
+ expect(description.element().clientWidth).toBeGreaterThanOrEqual(
+ description.element().scrollWidth,
+ )
+ } finally {
+ queryClient.clear()
+ }
+})
+
+it('keeps a refresh error above retained rows and readable while scrolling a narrow table', async () => {
+ const { dialog, queryClient } = await renderSettings({
+ summary: {
+ archived_month_count: 1,
+ workflow_run_count: 125,
+ archive_bytes: 1048576,
+ latest_archived_at: '2025-03-03T00:00:00Z',
+ },
+ months: [
+ {
+ year: 2025,
+ month: 3,
+ workflow_run_count: 125,
+ row_count: 1125,
+ archive_bytes: 1048576,
+ bundle_count: 2,
+ latest_archived_at: '2025-03-03T00:00:00Z',
+ download_task: null,
+ deletion_status: null,
+ },
+ ],
+ })
+
+ try {
+ archiveListRequest.mockRejectedValue(new Error('Archives unavailable'))
+ await queryClient.refetchQueries({ queryKey: consoleQuery.workflowRunArchives.get.queryKey() })
+ const title = dialog.getByText('Could not load archived logs')
+ const description = dialog.getByText('Refresh the page or try again later.')
+ await expect.element(title).toBeVisible()
+ const header = dialog.getByRole('row', { name: /^month runs size action$/i })
+ const row = dialog.getByRole('row', { name: /2025-03/ })
+ const table = dialog.getByRole('table')
+ const tableLeft = table.element().getBoundingClientRect().left
+ expect(title.element().getBoundingClientRect().top).toBeGreaterThanOrEqual(
+ header.element().getBoundingClientRect().bottom,
+ )
+ expect(description.element().getBoundingClientRect().bottom).toBeLessThanOrEqual(
+ row.element().getBoundingClientRect().top,
+ )
+ const expectReadable = () => {
+ for (const message of [title, description]) {
+ const element = message.element()
+ const rect = element.getBoundingClientRect()
+ expect(rect.left).toBeGreaterThanOrEqual(0)
+ expect(rect.right).toBeLessThanOrEqual(320)
+ expect(element.clientWidth).toBeGreaterThanOrEqual(element.scrollWidth)
+ }
+ }
+ expectReadable()
+
+ const download = row.getByRole('button', { name: 'Prepare download 2025-03' })
+ for (let index = 0; index < 12 && document.activeElement !== download.element(); index++) {
+ await userEvent.tab()
+ }
+ await expect.element(download).toHaveFocus()
+ expect(table.element().getBoundingClientRect().left).toBeLessThan(tableLeft)
+ expectReadable()
+ } finally {
+ queryClient.clear()
+ }
+})
diff --git a/web/app/components/header/account-setting/workflow-log-archives-page/index.tsx b/web/app/components/header/account-setting/workflow-log-archives-page/index.tsx
index 8324a80a26c..6a4969ad3d2 100644
--- a/web/app/components/header/account-setting/workflow-log-archives-page/index.tsx
+++ b/web/app/components/header/account-setting/workflow-log-archives-page/index.tsx
@@ -73,6 +73,17 @@ function isPreparingStatus(status: WorkflowRunArchiveDownloadStatus | undefined)
return status === 'pending' || status === 'processing'
}
+function latestDownloadTask(
+ snapshot: WorkflowRunArchiveDownloadTaskResponse | null | undefined,
+ candidate: WorkflowRunArchiveDownloadTaskResponse | null | undefined,
+) {
+ if (!candidate) return snapshot
+ if (!snapshot || Date.parse(candidate.updated_at) >= Date.parse(snapshot.updated_at)) {
+ return candidate
+ }
+ return snapshot
+}
+
function isDeletingStatus(status: WorkflowRunArchiveMonthResponse['deletion_status']) {
return status === 'pending' || status === 'processing'
}
@@ -110,6 +121,7 @@ export default function WorkflowLogArchivesPage() {
const summary = archiveData?.summary
const isLoading =
(deploymentEdition === 'CLOUD' && plan === undefined) || archiveListQuery.isLoading
+ const isEmpty = !isLoading && !archiveListQuery.isError && archiveMonths.length === 0
const hasMoreArchives = visibleArchiveMonths.length < archiveMonths.length
useEffect(() => {
@@ -190,7 +202,7 @@ export default function WorkflowLogArchivesPage() {
</div>
<div className="overflow-hidden rounded-xl border-[0.5px] border-components-card-border bg-components-card-bg shadow-xs">
- <div className="overflow-x-auto">
+ <div className="@container overflow-x-auto">
<table className="w-full min-w-140 table-auto">
<colgroup>
<col />
@@ -242,7 +254,7 @@ export default function WorkflowLogArchivesPage() {
{!isLoading && archiveListQuery.isError && (
<tr>
<td colSpan={4}>
- <div className="flex min-h-36 flex-col items-center justify-center gap-2 px-4 text-center">
+ <div className="sticky start-0 flex min-h-36 max-w-[100cqw] flex-col items-center justify-center gap-2 px-4 py-4 text-center">
<span
className="i-ri-error-warning-line size-6 text-text-tertiary"
aria-hidden="true"
@@ -257,24 +269,6 @@ export default function WorkflowLogArchivesPage() {
</td>
</tr>
)}
- {!isLoading && !archiveListQuery.isError && archiveMonths.length === 0 && (
- <tr>
- <td colSpan={4}>
- <div className="flex min-h-36 flex-col items-center justify-center gap-2 px-4 text-center">
- <span
- className="i-ri-archive-line size-6 text-text-tertiary"
- aria-hidden="true"
- />
- <div className="system-sm-semibold text-text-secondary">
- {t(($) => $['archives.empty.title'], { ns: 'appLog' })}
- </div>
- <div className="system-xs-regular text-text-tertiary">
- {t(($) => $['archives.empty.description'], { ns: 'appLog' })}
- </div>
- </div>
- </td>
- </tr>
- )}
{!isLoading &&
visibleArchiveMonths.map((archive) => {
const archiveMonth = formatMonth(archive.year, archive.month)
@@ -296,6 +290,19 @@ export default function WorkflowLogArchivesPage() {
</tbody>
</table>
</div>
+ <div role="status" aria-atomic="true" className={isEmpty ? 'p-px' : undefined}>
+ {isEmpty && (
+ <div className="flex min-h-36 flex-col items-center justify-center gap-2 px-4 py-4 text-center">
+ <span className="i-ri-archive-line size-6 text-text-tertiary" aria-hidden="true" />
+ <div className="system-sm-semibold text-text-secondary">
+ {t(($) => $['archives.empty.title'], { ns: 'appLog' })}
+ </div>
+ <div className="system-xs-regular text-text-tertiary">
+ {t(($) => $['archives.empty.description'], { ns: 'appLog' })}
+ </div>
+ </div>
+ )}
+ </div>
</div>
</div>
)
@@ -308,9 +315,9 @@ function ArchivedLogsUpgradeBanner() {
return (
<div className="flex flex-col gap-4 rounded-xl bg-linear-to-r from-components-input-border-active-prompt-1 to-components-input-border-active-prompt-2 p-4 pl-6 shadow-lg backdrop-blur-xs sm:flex-row sm:items-center sm:justify-between">
<div className="space-y-1 text-text-primary-on-surface">
- <div className="title-xl-semi-bold">
+ <h4 className="title-xl-semi-bold">
{t(($) => $['archives.upgradeTip.title'], { ns: 'appLog' })}
- </div>
+ </h4>
<div className="system-sm-regular">
{t(($) => $['archives.upgradeTip.description'], { ns: 'appLog' })}
</div>
@@ -331,6 +338,7 @@ function WorkflowArchiveMonthRow({ archive }: { archive: WorkflowRunArchiveMonth
const isCurrentWorkspaceOwner = useAtomValue(isCurrentWorkspaceOwnerAtom)
const archiveMonthLabelId = useId()
const downloadActionLabelId = useId()
+ const downloadHintId = useId()
const deleteActionLabelId = useId()
const confirmDeleteLabelId = useId()
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
@@ -347,7 +355,7 @@ function WorkflowArchiveMonthRow({ archive }: { archive: WorkflowRunArchiveMonth
const isDeleting = deleteArchiveMutation.isPending || isDeletionActive
const isDownloadUnavailable = deleteArchiveMutation.isPending || archive.deletion_status != null
- const cachedTask = downloadTask ?? archive.download_task ?? null
+ const cachedTask = latestDownloadTask(archive.download_task, downloadTask)
const downloadTaskId = cachedTask?.download_id
const taskQuery = useQuery(
consoleQuery.workflowRunArchives.downloads.byDownloadId.get.queryOptions({
@@ -358,9 +366,13 @@ function WorkflowArchiveMonthRow({ archive }: { archive: WorkflowRunArchiveMonth
},
}
: skipToken,
- enabled: !!downloadTaskId && !isDownloadUnavailable && isPreparingStatus(cachedTask?.status),
+ enabled: (query) =>
+ !!downloadTaskId &&
+ !isDownloadUnavailable &&
+ isPreparingStatus(latestDownloadTask(cachedTask, query.state.data)?.status),
refetchInterval: (query) =>
- !isDownloadUnavailable && isPreparingStatus(query.state.data?.status ?? cachedTask?.status)
+ !isDownloadUnavailable &&
+ isPreparingStatus(latestDownloadTask(cachedTask, query.state.data)?.status)
? DOWNLOAD_TASK_POLLING_INTERVAL
: false,
}),
@@ -368,8 +380,22 @@ function WorkflowArchiveMonthRow({ archive }: { archive: WorkflowRunArchiveMonth
const createDownloadMutation = useMutation(
consoleQuery.workflowRunArchives.downloads.post.mutationOptions(),
)
- const currentTask = taskQuery.data ?? cachedTask
- const isPreparing = createDownloadMutation.isPending || isPreparingStatus(currentTask?.status)
+ const currentTask = latestDownloadTask(cachedTask, taskQuery.data)
+ const isTaskPreparing = isPreparingStatus(currentTask?.status)
+ const isPreparing = createDownloadMutation.isPending || isTaskPreparing
+ const [observedPreparingTaskId, setObservedPreparingTaskId] = useState(
+ isTaskPreparing ? currentTask?.download_id : undefined,
+ )
+ // A list refresh can replace every preparing snapshot with the completed task.
+ if (
+ isTaskPreparing &&
+ !createDownloadMutation.isPending &&
+ observedPreparingTaskId !== currentTask?.download_id
+ ) {
+ setObservedPreparingTaskId(currentTask?.download_id)
+ } else if (observedPreparingTaskId && observedPreparingTaskId !== currentTask?.download_id) {
+ setObservedPreparingTaskId(undefined)
+ }
const isReady = currentTask?.status === 'ready'
const isFailed = currentTask?.status === 'failed'
const failureReason = isFailed ? currentTask?.error?.trim() : undefined
@@ -389,10 +415,16 @@ function WorkflowArchiveMonthRow({ archive }: { archive: WorkflowRunArchiveMonth
: isPreparing
? t(($) => $['archives.downloadHint.preparing'], { ns: 'appLog' })
: t(($) => $['archives.downloadHint.prepare'], { ns: 'appLog' })
+ const announceDownloadResult =
+ !createDownloadMutation.isPending &&
+ !isDownloadUnavailable &&
+ observedPreparingTaskId === currentTask?.download_id &&
+ (isReady || isFailed)
const prepareDownload = () => {
if (createDownloadMutation.isPending || isDownloadUnavailable) return
+ setObservedPreparingTaskId(undefined)
createDownloadMutation.mutate(
{
body: {
@@ -456,6 +488,9 @@ function WorkflowArchiveMonthRow({ archive }: { archive: WorkflowRunArchiveMonth
</td>
<td className="px-2 py-3 text-center">
<div className="flex flex-col items-center gap-2">
+ <span role="status" aria-atomic="true" className="sr-only">
+ {announceDownloadResult ? `${archiveMonth}: ${downloadHint}` : ''}
+ </span>
<div className="flex items-center justify-center gap-1">
<Tooltip>
<TooltipTrigger
@@ -468,6 +503,7 @@ function WorkflowArchiveMonthRow({ archive }: { archive: WorkflowRunArchiveMonth
focusableWhenDisabled
className="shrink-0 px-2"
aria-labelledby={`${downloadActionLabelId} ${archiveMonthLabelId}`}
+ aria-describedby={downloadHintId}
onClick={onAction}
/>
}
@@ -480,7 +516,9 @@ function WorkflowArchiveMonthRow({ archive }: { archive: WorkflowRunArchiveMonth
)}
<span id={downloadActionLabelId}>{buttonContent}</span>
</TooltipTrigger>
- <TooltipContent>{downloadHint}</TooltipContent>
+ <TooltipContent id={downloadHintId} role="tooltip">
+ {downloadHint}
+ </TooltipContent>
</Tooltip>
{isCurrentWorkspaceOwner && (
<AlertDialog
diff --git a/web/service/console/query-policies.ts b/web/service/console/query-policies.ts
index 3119def38c2..e43f78c25d6 100644
--- a/web/service/console/query-policies.ts
+++ b/web/service/console/query-policies.ts
@@ -22,6 +22,20 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
path: ['console'],
experimental_defaults: {
workflowRunArchives: {
+ downloads: {
+ post: {
+ mutationOptions: {
+ onSuccess: (task, _variables, _onMutateResult, context) => {
+ context.client.setQueryData(
+ consoleQuery.workflowRunArchives.downloads.byDownloadId.get.queryKey({
+ input: { params: { download_id: task.download_id } },
+ }),
+ task,
+ )
+ },
+ },
+ },
+ },
byYear: {
byMonth: {
delete: {