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 IP Policies accessibility (#44548)

Joel6634ed6366f3
diff --git a/web/app/components/header/account-setting/ip-policies-page/__tests__/index.browser.spec.tsx b/web/app/components/header/account-setting/ip-policies-page/__tests__/index.browser.spec.tsx
new file mode 100644
index 00000000000..6ed33367ea6
--- /dev/null
+++ b/web/app/components/header/account-setting/ip-policies-page/__tests__/index.browser.spec.tsx
@@ -0,0 +1,213 @@
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { page, userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import {
+ createNetworkAccessGroupFixture,
+ seedNetworkAccessGroups,
+} from '@/test/console/network-access'
+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 request = vi.hoisted(() => vi.fn<(path: string) => unknown>())
+
+vi.mock('@/service/console/browser', () => ({
+ consoleBrowserLink: {
+ call: (path: readonly string[]) => request(path.join('.')),
+ },
+}))
+vi.mock('@/app/components/base/amplitude', () => ({ trackEvent: vi.fn() }))
+vi.mock('@/next/navigation', () => ({ useRouter: () => ({ refresh: vi.fn() }) }))
+vi.mock('#i18n', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('#i18n')>()),
+ useLocale: () => 'en-US',
+}))
+vi.mock('@/i18n/client', () => ({ setLocaleOnClient: vi.fn().mockResolvedValue(undefined) }))
+vi.mock('next-themes', () => ({
+ useTheme: () => ({ theme: 'light', setTheme: vi.fn() }),
+}))
+vi.mock('react-i18next', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('react-i18next')>()
+ const { createReactI18nextMock } = await import('@/test/i18n-mock')
+ const namespaces = {
+ accountSettings: (await import('@/i18n/locales/en-US/account-settings.json')).default,
+ common: (await import('@/i18n/locales/en-US/common.json')).default,
+ navigation: (await import('@/i18n/locales/en-US/navigation.json')).default,
+ deployments: (await import('@/i18n/locales/en-US/deployments.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 renderPoliciesSettings(width = 320) {
+ await page.viewport(width, 800)
+ const { queryClient } = createConsoleQueryWrapper({
+ currentWorkspace: { role: 'owner', plan: 'team' },
+ accountProfile: { timezone: 'Asia/Shanghai', interface_language: 'en-US' },
+ systemFeatures: { deployment_edition: 'CLOUD', rbac_enabled: false },
+ })
+ const groups = [
+ createNetworkAccessGroupFixture({ name: 'Internal Network', used_by_count: 2 }),
+ createNetworkAccessGroupFixture({
+ id: 'group-2',
+ name: 'Engineering Office',
+ allowed_cidrs: ['192.0.2.0/24'],
+ }),
+ ]
+ seedNetworkAccessGroups(queryClient, { groups })
+ request.mockImplementation((path) => {
+ if (path === 'workspaces.current.networkAccessGroups.get')
+ return { tenant_id: 'workspace-1', entitled: true, groups }
+ if (path === 'workspaces.current.networkAccessGroups.currentIp.get')
+ return { client_ip: '203.0.113.42' }
+ throw new Error(`Unexpected console request: ${path}`)
+ })
+ const screen = await render(
+ <QueryClientTestProvider queryClient={queryClient}>
+ <NuqsTestingAdapter>
+ <AccountSetting
+ activeTab={ACCOUNT_SETTING_TAB.IP_POLICIES}
+ onCancelAction={vi.fn()}
+ onTabChangeAction={vi.fn()}
+ />
+ </NuqsTestingAdapter>
+ </QueryClientTestProvider>,
+ )
+ await expect.element(screen.getByRole('table', { name: 'IP Policies' })).toBeVisible()
+ return { screen, queryClient, groups }
+}
+
+async function expectReadableText(content: Element, viewport: HTMLElement) {
+ const range = document.createRange()
+ range.selectNodeContents(content)
+ const text = range.getBoundingClientRect()
+ const bounds = viewport.getBoundingClientRect()
+ const delta =
+ text.left < bounds.left
+ ? text.left - bounds.left - 1
+ : text.right > bounds.right
+ ? text.right - bounds.right + 1
+ : 0
+ if (delta !== 0) {
+ const previous = viewport.scrollLeft
+ await page.elementLocator(viewport).wheel({ delta: { x: delta, y: 0 } })
+ await expect.poll(() => viewport.scrollLeft).not.toBe(previous)
+ }
+ await expect
+ .poll(
+ () => {
+ const visible = viewport.getBoundingClientRect()
+ const fragments = Array.from(range.getClientRects())
+ return (
+ fragments.length > 0 &&
+ fragments.every(
+ (fragment) =>
+ fragment.width > 0 &&
+ fragment.left >= visible.left - 1 &&
+ fragment.right <= visible.right + 1,
+ )
+ )
+ },
+ { message: `Full text must be readable: ${content.textContent}` },
+ )
+ .toBe(true)
+}
+
+it('keeps policy data readable and keyboard scrollable inside Settings at 320 px', async () => {
+ // Unit tests miss columns clipped by Settings and native focus, arrow-key and wheel scrolling.
+ const { screen, queryClient, groups } = await renderPoliciesSettings()
+ try {
+ const add = screen.getByRole('button', { name: 'Add', exact: true })
+ const region = screen.getByRole('region', { name: 'IP Policies', exact: true })
+ const table = screen.getByRole('table', { name: 'IP Policies', exact: true })
+ add.element().focus()
+ await expect.element(add).toHaveFocus()
+ await userEvent.tab()
+ await expect.element(region).toHaveFocus()
+ expect(region.element().matches(':focus-visible')).toBe(true)
+ const viewport = region.element() as HTMLElement
+ const initial = viewport.scrollLeft
+ const keyboardScrollEnd = new Promise<void>((resolve) =>
+ viewport.addEventListener('scrollend', () => resolve(), { once: true }),
+ )
+ await userEvent.keyboard('{ArrowRight}')
+ await keyboardScrollEnd
+ await expect.poll(() => viewport.scrollLeft).toBeGreaterThan(initial)
+
+ for (const name of ['Name', 'IP Entries', 'Used by', 'Updated at'])
+ await expectReadableText(
+ table.getByRole('columnheader', { name, exact: true }).element(),
+ viewport,
+ )
+ for (const [index, group] of groups.entries()) {
+ const cells = table
+ .getByRole('row')
+ .nth(index + 1)
+ .getByRole('cell')
+ await expect.element(cells.nth(0)).toHaveTextContent(group.name)
+ await expect.element(cells.nth(1)).toHaveTextContent(String(group.allowed_cidrs.length))
+ await expect.element(cells.nth(2)).toHaveTextContent(`${group.used_by_count} apps`)
+ expect(cells.nth(3).element().textContent?.trim()).toBeTruthy()
+ for (let column = 0; column < 4; column++)
+ await expectReadableText(cells.nth(column).element(), viewport)
+ }
+ const more = screen.getByRole('button', {
+ name: 'More actions for Internal Network',
+ exact: true,
+ })
+ await more.click()
+ await expect.element(screen.getByRole('menuitem', { name: 'Edit', exact: true })).toBeVisible()
+ await userEvent.keyboard('{Escape}')
+ await expect.element(screen.getByRole('menu')).not.toBeInTheDocument()
+ await expect.element(more).toHaveFocus()
+ } finally {
+ await screen.unmount()
+ queryClient.clear()
+ }
+})
+
+it('keeps Add clear of Settings Close at 320 px and preserves the desktop action order', async () => {
+ // Real hit testing catches the global Close overlay; the desktop order must survive reflow.
+ const { screen, queryClient } = await renderPoliciesSettings()
+ try {
+ const settings = screen.getByRole('dialog', { name: 'Settings', exact: true })
+ const add = settings.getByRole('button', { name: 'Add', exact: true })
+ const close = settings.getByRole('button', { name: 'Close', exact: true })
+ const bounds = add.element().getBoundingClientRect()
+ const other = close.element().getBoundingClientRect()
+ const overlap =
+ Math.max(0, Math.min(bounds.right, other.right) - Math.max(bounds.left, other.left)) *
+ Math.max(0, Math.min(bounds.bottom, other.bottom) - Math.max(bounds.top, other.top))
+ expect(overlap, 'Add must not sit beneath the global Close button').toBe(0)
+ await add.click()
+ const editor = screen.getByRole('dialog', { name: 'New IP Policy', exact: true })
+ await expect.element(editor).toBeVisible()
+ await editor.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await expect.element(editor).not.toBeInTheDocument()
+ await expect.element(add).toHaveFocus()
+
+ await page.viewport(1280, 800)
+ await expect
+ .element(settings.getByRole('region', { name: 'IP Policies', exact: true }))
+ .toHaveAttribute('tabindex', '-1')
+ const order = [
+ settings.getByRole('button', { name: 'Internal Network', exact: true }),
+ settings.getByRole('button', { name: 'More actions for Internal Network', exact: true }),
+ settings.getByRole('button', { name: 'Engineering Office', exact: true }),
+ settings.getByRole('button', { name: 'More actions for Engineering Office', exact: true }),
+ close,
+ ]
+ for (const target of order) {
+ await userEvent.tab()
+ await expect.element(target).toHaveFocus()
+ }
+ } finally {
+ await screen.unmount()
+ queryClient.clear()
+ }
+})
diff --git a/web/app/components/header/account-setting/ip-policies-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/ip-policies-page/__tests__/index.spec.tsx
index dbee54d30f0..5550fb03a10 100644
--- a/web/app/components/header/account-setting/ip-policies-page/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/ip-policies-page/__tests__/index.spec.tsx
@@ -35,6 +35,42 @@ describe('IpPoliciesPage', () => {
})
})
+ it('exposes policy data in cells associated with their column headers', () => {
+ const queryClient = createConsoleQueryClient()
+ seedNetworkAccessGroups(queryClient, {
+ groups: [
+ createNetworkAccessGroupFixture({ allowed_cidrs: ['203.0.113.42/32'], used_by_count: 0 }),
+ ],
+ })
+ renderWithConsoleQuery(
+ <NuqsTestingAdapter>
+ <IpPoliciesPage />
+ </NuqsTestingAdapter>,
+ {
+ queryClient,
+ currentWorkspace: { role: 'admin' },
+ systemFeatures: { deployment_edition: 'CLOUD' },
+ },
+ )
+
+ const table = screen.getByRole('table', { name: 'IP Policies' })
+ expect(
+ within(table)
+ .getAllByRole('columnheader')
+ .map((header) => header.textContent),
+ ).toEqual(['Name', 'IP Entries', 'Used by', 'Updated at', 'More actions'])
+ const row = within(table).getAllByRole('row')[1]!
+ const cells = within(row).getAllByRole('cell')
+ expect(cells).toHaveLength(5)
+ expect(within(cells[0]!).getByRole('button', { name: 'Internal Network' })).toBeInTheDocument()
+ expect(cells[1]).toHaveTextContent('1')
+ expect(cells[2]).toHaveTextContent('0 apps')
+ expect(cells[3]).not.toBeEmptyDOMElement()
+ expect(
+ within(cells[4]!).getByRole('button', { name: 'More actions for Internal Network' }),
+ ).toBeInTheDocument()
+ })
+
it.each([true, false])(
'lets an editor read the complete policy without management actions (entitled: %s)',
async (entitled) => {
@@ -1071,7 +1107,9 @@ describe('IpPoliciesPage', () => {
)
expect(screen.getByText('Used by')).toBeInTheDocument()
expect(
- within(screen.getByRole('button', { name: 'Internal Network' })).getByText('2 apps'),
+ within(screen.getByRole('table', { name: 'IP Policies' })).getByRole('cell', {
+ name: '2 apps',
+ }),
).toBeInTheDocument()
expect(screen.queryByText('Enforcing')).not.toBeInTheDocument()
},
diff --git a/web/app/components/header/account-setting/ip-policies-page/__tests__/policy-item.browser.spec.tsx b/web/app/components/header/account-setting/ip-policies-page/__tests__/policy-item.browser.spec.tsx
index 4d8b2c16c5c..d3163457f18 100644
--- a/web/app/components/header/account-setting/ip-policies-page/__tests__/policy-item.browser.spec.tsx
+++ b/web/app/components/header/account-setting/ip-policies-page/__tests__/policy-item.browser.spec.tsx
@@ -15,7 +15,9 @@ async function renderPolicy(canMutate = true) {
<ConsoleProvider>
<button type="button">Before policy</button>
<section aria-label="IP policy row" style={{ width: 800 }}>
- <PolicyItem group={group} canMutate={canMutate} onView={onView} onEdit={onEdit} />
+ <div role="table" aria-label="IP policies">
+ <PolicyItem group={group} canMutate={canMutate} onView={onView} onEdit={onEdit} />
+ </div>
</section>
</ConsoleProvider>,
)
diff --git a/web/app/components/header/account-setting/ip-policies-page/index.tsx b/web/app/components/header/account-setting/ip-policies-page/index.tsx
index e01e6c191bc..aac57642dbb 100644
--- a/web/app/components/header/account-setting/ip-policies-page/index.tsx
+++ b/web/app/components/header/account-setting/ip-policies-page/index.tsx
@@ -4,11 +4,18 @@ import type { NetworkAccessGroupResponse } from '@dify/contracts/api/console/wor
import type { IpPolicySource } from '@/features/network-access/analytics'
import type { IpPolicyFormSession } from '@/features/network-access/policy-editor/policy-form-analytics'
import { Button } from '@langgenius/dify-ui/button'
+import {
+ ScrollArea,
+ ScrollAreaContent,
+ ScrollAreaScrollbar,
+ ScrollAreaThumb,
+ ScrollAreaViewport,
+} from '@langgenius/dify-ui/scroll-area'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import Image from 'next/image'
import { useQueryState } from 'nuqs'
-import { useEffect, useRef, useState } from 'react'
+import { useEffect, useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { SkeletonContainer, SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'
import {
@@ -65,6 +72,7 @@ function IpPoliciesListSkeleton() {
export default function IpPoliciesPage() {
const { t } = useTranslation(['common', 'deployments'])
+ const titleId = useId()
const queryClient = useQueryClient()
const { plan } = useAtomValue(currentWorkspaceAtom)
const canReadPolicies = useAtomValue(canReadNetworkAccessAtom)
@@ -160,10 +168,10 @@ export default function IpPoliciesPage() {
if (!canReadPolicies) return null
return (
- <div className="flex flex-col gap-4">
- <div className="flex min-h-15 items-start justify-between gap-4 py-2">
+ <div className="@container flex flex-col gap-4">
+ <div className="flex min-h-15 items-start justify-between gap-4 py-2 @max-[480px]:flex-col">
<div className="flex min-w-0 flex-col gap-1">
- <h2 className="title-2xl-semi-bold text-text-primary">
+ <h2 id={titleId} className="title-2xl-semi-bold text-text-primary">
{t(($) => $['settings.ipPolicies'], { ns: 'common' })}
</h2>
<p className="system-sm-regular text-text-tertiary">
@@ -217,37 +225,55 @@ export default function IpPoliciesPage() {
)}
{!isPending && groups.length > 0 && (
- <div className="min-w-0">
- <div
- className={`${policyRowClassName} border-b border-divider-subtle py-2 system-xs-medium-uppercase text-text-tertiary`}
+ <ScrollArea className="min-w-0">
+ <ScrollAreaViewport
+ role="region"
+ aria-labelledby={titleId}
+ style={{ overflowY: 'hidden' }}
>
- <div className={policyNameColClassName}>
- {t(($) => $['settings.ipPolicyColumnName'], { ns: 'common' })}
- </div>
- <div className={policyIpEntriesColClassName}>
- {t(($) => $['settings.ipPolicyColumnIpEntries'], { ns: 'common' })}
- </div>
- <div className={policyUsedByColClassName}>
- {t(($) => $['settings.ipPolicyColumnUsedBy'], { ns: 'common' })}
- </div>
- <div className={policyUpdatedColClassName}>
- {t(($) => $['settings.ipPolicyColumnUpdatedAt'], { ns: 'common' })}
- </div>
- <div className={policyActionsColClassName} />
- </div>
- {groups.map((group) => (
- <PolicyItem
- key={group.id}
- group={group}
- canMutate={canMutate}
- onView={(group) => openDialog({ mode: canMutate ? 'edit' : 'view', group })}
- onEdit={(group) => {
- if (!canMutate) return
- openDialog({ mode: 'edit', group }, 'list_row_menu')
- }}
- />
- ))}
- </div>
+ <ScrollAreaContent style={{ minWidth: 0 }}>
+ <div role="table" aria-labelledby={titleId} className="w-full min-w-160">
+ <div
+ role="row"
+ className={`${policyRowClassName} border-b border-divider-subtle py-2 system-xs-medium-uppercase text-text-tertiary`}
+ >
+ <div role="columnheader" className={policyNameColClassName}>
+ {t(($) => $['settings.ipPolicyColumnName'], { ns: 'common' })}
+ </div>
+ <div role="columnheader" className={policyIpEntriesColClassName}>
+ {t(($) => $['settings.ipPolicyColumnIpEntries'], { ns: 'common' })}
+ </div>
+ <div role="columnheader" className={policyUsedByColClassName}>
+ {t(($) => $['settings.ipPolicyColumnUsedBy'], { ns: 'common' })}
+ </div>
+ <div role="columnheader" className={policyUpdatedColClassName}>
+ {t(($) => $['settings.ipPolicyColumnUpdatedAt'], { ns: 'common' })}
+ </div>
+ <div role="columnheader" className={policyActionsColClassName}>
+ <span className="sr-only">
+ {t(($) => $['operation.moreActions'], { ns: 'common' })}
+ </span>
+ </div>
+ </div>
+ {groups.map((group) => (
+ <PolicyItem
+ key={group.id}
+ group={group}
+ canMutate={canMutate}
+ onView={(group) => openDialog({ mode: canMutate ? 'edit' : 'view', group })}
+ onEdit={(group) => {
+ if (!canMutate) return
+ openDialog({ mode: 'edit', group }, 'list_row_menu')
+ }}
+ />
+ ))}
+ </div>
+ </ScrollAreaContent>
+ </ScrollAreaViewport>
+ <ScrollAreaScrollbar orientation="horizontal" className="bottom-0">
+ <ScrollAreaThumb />
+ </ScrollAreaScrollbar>
+ </ScrollArea>
)}
{dialogState && (dialogState.mode !== 'create' || canMutate) && (
diff --git a/web/app/components/header/account-setting/ip-policies-page/policy-item.tsx b/web/app/components/header/account-setting/ip-policies-page/policy-item.tsx
index 412b0fc7ab5..e4ae3d909bf 100644
--- a/web/app/components/header/account-setting/ip-policies-page/policy-item.tsx
+++ b/web/app/components/header/account-setting/ip-policies-page/policy-item.tsx
@@ -86,29 +86,40 @@ export function PolicyItem({ group, canMutate, onView, onEdit }: PolicyItemProps
return (
<div
+ role="row"
className={`${policyRowClassName} relative border-b border-divider-subtle py-3 hover:bg-state-base-hover`}
>
- {/* Extend the native button's hit area across the row without nesting the actions. */}
- <Button
- variant="ghost"
- aria-label={group.name}
- className="h-auto min-w-0 flex-1 justify-start gap-0 overflow-visible rounded-none p-0 text-left after:absolute after:inset-0 hover:bg-transparent"
- onClick={() => onView(group)}
+ <div role="cell" className="flex min-w-0 flex-1">
+ {/* Extend the name button's hit area across the row without nesting the actions. */}
+ <Button
+ variant="ghost"
+ className="h-auto w-full min-w-0 justify-start gap-0 overflow-visible rounded-none p-0 text-left after:absolute after:inset-0 hover:bg-transparent"
+ onClick={() => onView(group)}
+ >
+ <span className={`${policyNameColClassName} system-sm-medium text-text-secondary`}>
+ {group.name}
+ </span>
+ </Button>
+ </div>
+ <div
+ role="cell"
+ className={`${policyIpEntriesColClassName} system-sm-regular text-text-tertiary`}
+ >
+ {group.allowed_cidrs.length}
+ </div>
+ <div
+ role="cell"
+ className={`${policyUsedByColClassName} system-sm-regular text-text-tertiary`}
>
- <span className={`${policyNameColClassName} system-sm-medium text-text-secondary`}>
- {group.name}
- </span>
- <span className={`${policyIpEntriesColClassName} system-sm-regular text-text-tertiary`}>
- {group.allowed_cidrs.length}
- </span>
- <span className={`${policyUsedByColClassName} system-sm-regular text-text-tertiary`}>
- {usedByLabel}
- </span>
- <span className={`${policyUpdatedColClassName} system-sm-regular text-text-tertiary`}>
- {formatTimeFromNow(Date.parse(group.updated_at))}
- </span>
- </Button>
- <div className={`${policyActionsColClassName} pointer-events-none relative`}>
+ {usedByLabel}
+ </div>
+ <div
+ role="cell"
+ className={`${policyUpdatedColClassName} system-sm-regular text-text-tertiary`}
+ >
+ {formatTimeFromNow(Date.parse(group.updated_at))}
+ </div>
+ <div role="cell" className={`${policyActionsColClassName} pointer-events-none relative`}>
{canMutate && (
<DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
<Tooltip>
diff --git a/web/features/network-access/policy-editor/__tests__/focus.browser.spec.tsx b/web/features/network-access/policy-editor/__tests__/focus.browser.spec.tsx
new file mode 100644
index 00000000000..13fb6651490
--- /dev/null
+++ b/web/features/network-access/policy-editor/__tests__/focus.browser.spec.tsx
@@ -0,0 +1,133 @@
+import type { ComponentProps } from 'react'
+import { userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { IpPolicyDialog } from '@/features/network-access/policy-editor'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
+
+const requests = vi.hoisted(() => ({
+ currentIp: vi.fn<() => Promise<{ client_ip: string }>>(),
+}))
+
+vi.mock('@/service/console/browser', () => ({
+ consoleBrowserLink: {
+ call: (path: readonly string[]) => {
+ if (path.join('.') === 'workspaces.current.networkAccessGroups.currentIp.get')
+ return requests.currentIp()
+ 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 { default: translations } = await import('@/i18n/locales/en-US/common.json')
+ return { ...actual, ...createReactI18nextMock(translations) }
+})
+
+beforeEach(() => {
+ requests.currentIp.mockReset()
+})
+
+async function renderEditor(props: Partial<ComponentProps<typeof IpPolicyDialog>> = {}) {
+ const { queryClient, wrapper: ConsoleProvider } = createConsoleQueryWrapper()
+ const screen = await render(
+ <ConsoleProvider>
+ <IpPolicyDialog open mode="edit" initialName="Office" onOpenChange={vi.fn()} {...props} />
+ </ConsoleProvider>,
+ )
+ return { screen, queryClient }
+}
+
+// Chromium loses native focus when the focused row is removed; happy-dom cannot prove recovery.
+it.each([0, 1])(
+ 'keeps keyboard navigation at the adjacent input after removing row %i',
+ async (index) => {
+ const { screen, queryClient } = await renderEditor({
+ initialEntries: ['10.0.0.0/8', '203.0.113.42'],
+ currentIp: '192.0.2.1',
+ })
+
+ try {
+ const inputs = screen.getByRole('textbox', { name: 'Allowlist', exact: true }).all()
+ await inputs[index]!.click()
+ await userEvent.tab()
+ await expect
+ .element(screen.getByRole('button', { name: 'Remove entry', exact: true }).nth(index))
+ .toHaveFocus()
+ await userEvent.keyboard('{Enter}')
+
+ const remaining = screen.getByRole('textbox', { name: 'Allowlist', exact: true })
+ await expect.element(remaining).toHaveValue(index === 0 ? '203.0.113.42' : '10.0.0.0/8')
+ await expect.element(remaining).toHaveFocus()
+ await userEvent.tab()
+ await expect
+ .element(screen.getByRole('button', { name: 'Remove entry', exact: true }))
+ .toHaveFocus()
+ expect(requests.currentIp).not.toHaveBeenCalled()
+ } finally {
+ await screen.unmount()
+ queryClient.clear()
+ }
+ },
+)
+
+// The retry button previously unmounted while loading, and Add it could become natively disabled.
+// Real Chromium verifies focus through both transitions, including an already allowed address.
+it.each([false, true])(
+ 'retains current-IP action focus through retry (already allowed: %s)',
+ async (alreadyAllowed) => {
+ const response = createDeferred<{ client_ip: string }>()
+ requests.currentIp
+ .mockRejectedValueOnce(new Error('IP unavailable'))
+ .mockReturnValueOnce(response.promise)
+ const { screen, queryClient } = await renderEditor()
+
+ try {
+ const retry = screen.getByRole('button', { name: 'Retry', exact: true })
+ await expect.element(retry).toBeVisible()
+ const input = screen.getByRole('textbox', { name: 'Allowlist', exact: true })
+ await input.fill(alreadyAllowed ? '203.0.113.42' : '')
+ await userEvent.tab()
+ await expect
+ .element(screen.getByRole('button', { name: 'Remove entry', exact: true }))
+ .toHaveFocus()
+ await userEvent.tab()
+ await expect.element(screen.getByRole('button', { name: 'Add', exact: true })).toHaveFocus()
+ await userEvent.tab()
+ await expect.element(retry).toHaveFocus()
+ await userEvent.keyboard('{Enter}')
+
+ await expect.element(retry).toHaveAttribute('aria-disabled', 'true')
+ await expect.element(retry).toHaveFocus()
+ await expect.poll(() => requests.currentIp.mock.calls.length).toBe(2)
+ await userEvent.keyboard('{Enter}')
+ expect(requests.currentIp).toHaveBeenCalledTimes(2)
+
+ response.resolve({ client_ip: '203.0.113.42' })
+ const addCurrentIp = screen.getByRole('button', { name: 'Add it', exact: true })
+ await expect.element(addCurrentIp).toHaveFocus()
+ if (alreadyAllowed)
+ await expect.element(addCurrentIp).toHaveAttribute('aria-disabled', 'true')
+ else await expect.element(addCurrentIp).not.toHaveAttribute('aria-disabled', 'true')
+ await expect.element(input).toHaveValue(alreadyAllowed ? '203.0.113.42' : '')
+
+ if (!alreadyAllowed) {
+ await userEvent.keyboard('{Enter}')
+ await expect.element(input).toHaveValue('203.0.113.42')
+ await expect.element(addCurrentIp).toHaveAttribute('aria-disabled', 'true')
+ await expect.element(addCurrentIp).toHaveFocus()
+ }
+ await userEvent.tab()
+ await expect
+ .element(screen.getByRole('button', { name: 'Cancel', exact: true }))
+ .toHaveFocus()
+ expect(requests.currentIp).toHaveBeenCalledTimes(2)
+ } finally {
+ response.resolve({ client_ip: '203.0.113.42' })
+ await screen.unmount()
+ queryClient.clear()
+ }
+ },
+)
diff --git a/web/features/network-access/policy-editor/__tests__/index.spec.tsx b/web/features/network-access/policy-editor/__tests__/index.spec.tsx
index 74070509c60..40063f1346a 100644
--- a/web/features/network-access/policy-editor/__tests__/index.spec.tsx
+++ b/web/features/network-access/policy-editor/__tests__/index.spec.tsx
@@ -2,6 +2,7 @@ import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
import { IpPolicyDialog } from '..'
const translations = vi.hoisted(() => ({
@@ -140,7 +141,7 @@ describe('trusted current IP and allowlist editing', () => {
expect(
screen.getAllByPlaceholderText('10.0.0.0/8').map((row) => (row as HTMLInputElement).value),
).toEqual(['10.0.0.0/8', '203.0.113.42'])
- expect(screen.getByRole('button', { name: 'Add it' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'Add it' })).toHaveAttribute('aria-disabled', 'true')
await user.click(screen.getByRole('button', { name: 'Cancel' }))
expect(onSubmit).not.toHaveBeenCalled()
})
@@ -157,7 +158,40 @@ describe('trusted current IP and allowlist editing', () => {
expect(screen.queryByRole('button', { name: 'Add it' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Retry' }))
expect(await screen.findByText('Your current IP is 203.0.113.42')).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'Add it' })).toBeEnabled()
+ expect(screen.getByRole('button', { name: 'Add it' })).not.toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ )
+ })
+
+ it('announces current-IP loading, failure, retry, and success through one persistent status', async () => {
+ const user = userEvent.setup()
+ const firstResponse = createDeferred<Response>()
+ const retryResponse = createDeferred<Response>()
+ vi.mocked(globalThis.fetch)
+ .mockReturnValueOnce(firstResponse.promise)
+ .mockReturnValueOnce(retryResponse.promise)
+ render(<DialogHarness />)
+
+ const status = screen.getByRole('status')
+ expect(status).toHaveTextContent('Checking your IP address…')
+ expect(screen.queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument()
+
+ firstResponse.resolve(Response.json({ message: 'IP unavailable' }, { status: 503 }))
+ const retry = await screen.findByRole('button', { name: 'Retry' })
+ expect(screen.getByRole('status')).toBe(status)
+ expect(status).toHaveTextContent('Unable to check your IP address. Please try again.')
+ expect(status).not.toContainElement(retry)
+
+ await user.click(retry)
+ await waitFor(() => expect(status).toHaveTextContent('Checking your IP address…'))
+ expect(screen.getByRole('status')).toBe(status)
+
+ retryResponse.resolve(Response.json({ client_ip: '203.0.113.42' }))
+ const addCurrentIp = await screen.findByRole('button', { name: 'Add it' })
+ expect(screen.getByRole('status')).toBe(status)
+ expect(status).toHaveTextContent('Your current IP is 203.0.113.42')
+ expect(status).not.toContainElement(addCurrentIp)
})
it.each(['203.0.113.42/32', '::ffff:203.0.113.42/128'])(
@@ -172,7 +206,10 @@ describe('trusted current IP and allowlist editing', () => {
onOpenChange={vi.fn()}
/>,
)
- expect(await screen.findByRole('button', { name: 'Add it' })).toBeDisabled()
+ expect(await screen.findByRole('button', { name: 'Add it' })).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ )
},
)
@@ -186,7 +223,10 @@ describe('trusted current IP and allowlist editing', () => {
onOpenChange={vi.fn()}
/>,
)
- expect(await screen.findByRole('button', { name: 'Add it' })).toBeDisabled()
+ expect(await screen.findByRole('button', { name: 'Add it' })).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ )
expect(screen.getByRole('button', { name: 'Add' })).toBeDisabled()
expect(screen.getAllByPlaceholderText('10.0.0.0/8')).toHaveLength(100)
})
diff --git a/web/features/network-access/policy-editor/allowlist-field.tsx b/web/features/network-access/policy-editor/allowlist-field.tsx
index a5541a1a8ca..919ce749707 100644
--- a/web/features/network-access/policy-editor/allowlist-field.tsx
+++ b/web/features/network-access/policy-editor/allowlist-field.tsx
@@ -6,6 +6,7 @@ import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Input } from '@langgenius/dify-ui/input'
+import { useId, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import {
IP_POLICY_CIDR_MAX_COUNT,
@@ -18,6 +19,7 @@ type AllowlistFieldProps = {
entries: AllowlistRow[]
currentIp?: string
currentIpStatus?: 'loading' | 'error'
+ isRetryingCurrentIp?: boolean
onRetryCurrentIp?: () => void
onEntriesChange: (entries: AllowlistRow[]) => void
}
@@ -26,10 +28,18 @@ export function AllowlistField({
entries,
currentIp,
currentIpStatus,
+ isRetryingCurrentIp = false,
onRetryCurrentIp,
onEntriesChange,
}: AllowlistFieldProps) {
const { t } = useTranslation(['common'])
+ const entryInputsRef = useRef(new Map<string, HTMLInputElement>())
+ const currentIpActionLabelId = useId()
+ const currentIpActionDisabled =
+ !!currentIp &&
+ (entries.some((entry) => isSameIpAddress(entry.value, currentIp)) ||
+ (entries.length >= IP_POLICY_CIDR_MAX_COUNT &&
+ entries.every((entry) => entry.value.trim() !== '')))
const errorMessage = (code: IpEntryErrorCode, max?: 32 | 128) => {
switch (code) {
@@ -55,6 +65,9 @@ export function AllowlistField({
}
const removeEntry = (id: string) => {
+ const index = entries.findIndex((entry) => entry.id === id)
+ const nextEntry = entries[index + 1] ?? entries[index - 1] ?? entries[index]
+ if (nextEntry) entryInputsRef.current.get(nextEntry.id)?.focus()
if (entries.length === 1) {
const row = entries[0]
if (!row) return
@@ -95,6 +108,10 @@ export function AllowlistField({
<div className="flex items-center gap-2">
<div className="relative min-w-0 flex-1">
<Input
+ ref={(input) => {
+ if (input) entryInputsRef.current.set(entry.id, input)
+ else entryInputsRef.current.delete(entry.id)
+ }}
value={entry.value}
placeholder="10.0.0.0/8"
aria-label={t(($) => $['settings.ipPolicyAllowlist'], { ns: 'common' })}
@@ -139,40 +156,38 @@ export function AllowlistField({
{t(($) => $['settings.ipPolicyAddEntry'], { ns: 'common' })}
</Button>
- {currentIpStatus && (
- <p
- role="status"
- className="flex min-h-6 shrink-0 flex-wrap items-center gap-1.5 system-xs-regular text-text-tertiary"
- >
- {currentIpStatus === 'loading'
- ? t(($) => $['settings.ipPolicyCurrentIpLoading'], { ns: 'common' })
- : t(($) => $['settings.ipPolicyCurrentIpError'], { ns: 'common' })}
- {currentIpStatus === 'error' && onRetryCurrentIp && (
- <Button type="button" variant="ghost" size="small" onClick={onRetryCurrentIp}>
- {t(($) => $['operation.retry'], { ns: 'common' })}
+ {(currentIpStatus || currentIp) && (
+ <p className="flex min-h-6 shrink-0 flex-wrap items-center gap-1.5 system-xs-regular text-text-tertiary">
+ <span role="status">
+ {currentIpStatus === 'loading'
+ ? t(($) => $['settings.ipPolicyCurrentIpLoading'], { ns: 'common' })
+ : currentIpStatus === 'error'
+ ? t(($) => $['settings.ipPolicyCurrentIpError'], { ns: 'common' })
+ : currentIp &&
+ t(($) => $['settings.ipPolicyCurrentIp'], { ns: 'common', ip: currentIp })}
+ </span>
+ {(currentIp ||
+ ((currentIpStatus === 'error' || isRetryingCurrentIp) && onRetryCurrentIp)) && (
+ <Button
+ type="button"
+ variant={currentIp ? 'ghost-accent' : 'ghost'}
+ size="small"
+ aria-labelledby={currentIpActionLabelId}
+ loading={isRetryingCurrentIp}
+ disabled={currentIpActionDisabled}
+ focusableWhenDisabled
+ tabIndex={currentIpActionDisabled ? -1 : 0}
+ onClick={currentIp ? addCurrentIp : onRetryCurrentIp}
+ >
+ <span id={currentIpActionLabelId}>
+ {currentIp
+ ? t(($) => $['settings.ipPolicyAddCurrentIp'], { ns: 'common' })
+ : t(($) => $['operation.retry'], { ns: 'common' })}
+ </span>
</Button>
)}
</p>
)}
-
- {currentIp && (
- <p className="flex min-h-6 shrink-0 flex-wrap items-center gap-1.5 system-xs-regular text-text-tertiary">
- <span>{t(($) => $['settings.ipPolicyCurrentIp'], { ns: 'common', ip: currentIp })}</span>
- <Button
- type="button"
- variant="ghost-accent"
- size="small"
- disabled={
- entries.some((entry) => isSameIpAddress(entry.value, currentIp)) ||
- (entries.length >= IP_POLICY_CIDR_MAX_COUNT &&
- entries.every((entry) => entry.value.trim() !== ''))
- }
- onClick={addCurrentIp}
- >
- {t(($) => $['settings.ipPolicyAddCurrentIp'], { ns: 'common' })}
- </Button>
- </p>
- )}
</Field>
)
}
diff --git a/web/features/network-access/policy-editor/index.tsx b/web/features/network-access/policy-editor/index.tsx
index 210d966ece4..f411ef44fb7 100644
--- a/web/features/network-access/policy-editor/index.tsx
+++ b/web/features/network-access/policy-editor/index.tsx
@@ -179,6 +179,11 @@ export function IpPolicyDialog({
entries={entries}
currentIp={resolvedCurrentIp}
currentIpStatus={currentIpStatus}
+ isRetryingCurrentIp={
+ currentIpStatus !== undefined &&
+ currentIpQuery.isFetched &&
+ (currentIpQuery.isFetching || currentIpQuery.isPaused)
+ }
onRetryCurrentIp={() => {
void currentIpQuery.refetch()
}}