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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
import type {
AgentApiAccessResponse,
AgentAppDetailWithSite,
} from '@dify/contracts/api/console/agent/types.gen'
import type { AppDetail } from '@dify/contracts/api/console/apps/types.gen'
import type React from 'react'
import { QueryClient, useQuery } from '@tanstack/react-query'
import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
import { toast } from '@/app/notifications'
import { AgentPermission } from '@/features/agent-v2/acl'
import { AccessMode } from '@/models/access-control'
import { consoleQuery } from '@/service/console'
import { seedAccountProfileQuery } from '@/test/console/account-profile'
import { createQueryClientWrapper } from '@/test/console/query-client'
import { seedFeatures, seedSystemFeatures } from '@/test/console/query-data'
import { createAgentFixture } from '@/test/fixtures/agent'
import { createAppDetailFixture, createAppSiteFixture } from '@/test/fixtures/app'
import { ServiceApiAccessCard } from '../service-api-access-card'
import { WebAppAccessCard } from '../web-app-access-card'
const mocks = vi.hoisted(() => ({
getUserCanAccess:
vi.fn<(appId: string, isInstalledApp: boolean) => Promise<{ result: boolean }>>(),
agentDetailQueryFn: vi.fn(),
apiAccessQueryFn: vi.fn(),
apiKeysQueryFn: vi.fn(),
siteEnableMutation: vi.fn(),
siteMutation: vi.fn(),
siteAccessTokenResetMutation: vi.fn(),
apiEnableMutation: vi.fn(),
createApiKeyMutation: vi.fn(),
deleteApiKeyMutation: vi.fn(),
updateAccessMutation: vi.fn(),
accessSubjectsQueryFn: vi.fn(),
}))
vi.mock('@/service/share', () => ({
getUserCanAccess: mocks.getUserCanAccess,
}))
vi.mock('@/context/i18n', () => ({
useDocLink: () => (path: string) => `https://docs.example.test${path}`,
}))
vi.mock('@/app/notifications', () => ({
toast: {
error: vi.fn(),
success: vi.fn(),
},
}))
vi.mock('@/hooks/use-timestamp', () => ({
default: () => ({
formatTime: (value: number) => `formatted-${value}`,
}),
}))
vi.mock('@/context/workspace-state', async () => {
const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture')
return createWorkspaceStateModuleMock(() => ({
userProfile: { id: 'user-1' },
currentWorkspace: { id: 'workspace-1' },
workspacePermissionKeys: ['app.acl.edit'],
langGeniusVersionInfo: {
current_env: 'PRODUCTION',
current_version: '',
latest_version: '',
version: '',
release_notes: '',
},
}))
})
vi.mock('@/context/permission-state', async () => {
const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
return createPermissionStateModuleMock(() => ({
userProfile: { id: 'user-1' },
currentWorkspace: { id: 'workspace-1' },
workspacePermissionKeys: ['app.acl.edit'],
langGeniusVersionInfo: {
current_env: 'PRODUCTION',
current_version: '',
latest_version: '',
version: '',
release_notes: '',
},
}))
})
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleResponses } = await import('@/test/console/service-responses')
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'enterprise.webAppAuth.getWebAppWhitelistSubjects': mocks.accessSubjectsQueryFn,
'enterprise.webAppAuth.updateWebAppWhitelistSubjects': mocks.updateAccessMutation,
'apps.byAppId.siteEnable.post': mocks.siteEnableMutation,
'apps.byAppId.site.post': mocks.siteMutation,
'apps.byAppId.site.accessTokenReset.post': mocks.siteAccessTokenResetMutation,
'agent.byAgentId.get': mocks.agentDetailQueryFn,
'agent.byAgentId.apiAccess.get': mocks.apiAccessQueryFn,
'agent.byAgentId.apiEnable.post': mocks.apiEnableMutation,
'agent.byAgentId.apiKeys.get': mocks.apiKeysQueryFn,
'agent.byAgentId.apiKeys.post': mocks.createApiKeyMutation,
'agent.byAgentId.apiKeys.byApiKeyId.delete': mocks.deleteApiKeyMutation,
}),
}
})
function createAgent(overrides: Partial<AgentAppDetailWithSite> = {}) {
return createAgentFixture({
permission_keys: Object.values(AgentPermission),
access_ready: true,
enable_api: true,
enable_site: true,
icon_url: null,
id: 'agent-1',
mode: 'agent',
name: 'Support Agent',
app_id: 'app-1',
backing_app_id: 'app-1',
api_base_url: 'https://api.example.test/v1',
access_mode: 'sso_verified',
site: createAppSiteFixture({
app_base_url: 'https://chat.example.test',
title: 'Support Agent',
}),
...overrides,
})
}
function createAppDetailResponse(overrides: Partial<AppDetail> = {}): AppDetail {
return createAppDetailFixture({
enable_api: true,
enable_site: true,
id: 'app-1',
mode: 'agent',
name: 'Support Agent',
...overrides,
})
}
function createAgentApiAccessResponse(
overrides: Partial<AgentApiAccessResponse> = {},
): AgentApiAccessResponse {
const serviceApiBaseUrl = 'https://api.example.test/v1'
return {
access_ready: true,
api_key_count: 2,
api_rph: 0,
api_rpm: 0,
chat_endpoint: `${serviceApiBaseUrl}/chat-messages`,
conversations_endpoint: `${serviceApiBaseUrl}/conversations`,
enabled: true,
files_upload_endpoint: `${serviceApiBaseUrl}/files/upload`,
info_endpoint: `${serviceApiBaseUrl}/info`,
messages_endpoint: `${serviceApiBaseUrl}/messages`,
meta_endpoint: `${serviceApiBaseUrl}/meta`,
parameters_endpoint: `${serviceApiBaseUrl}/parameters`,
service_api_base_url: serviceApiBaseUrl,
stop_endpoint: `${serviceApiBaseUrl}/chat-messages/{task_id}/stop`,
streaming_only: true,
...overrides,
}
}
function createAccessCardWrapper(queryClient: QueryClient) {
const QueryWrapper = createQueryClientWrapper(queryClient)
return function AccessCardWrapper({ children }: { children: React.ReactNode }) {
return (
<NuqsTestingAdapter>
<QueryWrapper>{children}</QueryWrapper>
</NuqsTestingAdapter>
)
}
}
function renderWithQueryClient(
ui: React.ReactElement,
{
webAppAuthEnabled = true,
agent,
}: { webAppAuthEnabled?: boolean; agent?: AgentAppDetailWithSite } = {},
) {
const queryClient = createConsoleQueryClient(webAppAuthEnabled, agent)
render(ui, { wrapper: createAccessCardWrapper(queryClient) })
return queryClient
}
function createConsoleQueryClient(
webAppAuthEnabled = true,
agent: AgentAppDetailWithSite = createAgent(),
) {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
staleTime: Infinity,
},
mutations: {
retry: false,
},
},
})
seedSystemFeatures(queryClient, {
webapp_auth: {
enabled: webAppAuthEnabled,
},
})
seedAccountProfileQuery(queryClient, { id: 'user-1' })
queryClient.setQueryData<AgentAppDetailWithSite>(
consoleQuery.agent.byAgentId.get.queryOptions({ input: { params: { agent_id: 'agent-1' } } })
.queryKey,
agent,
)
seedFeatures(queryClient)
return queryClient
}
function QueryOwnedWebAppCard() {
const { data: agent, isPending } = useQuery({
...consoleQuery.agent.byAgentId.get.queryOptions({
input: { params: { agent_id: 'agent-1' } },
}),
retry: false,
})
return <WebAppAccessCard agent={agent} agentId="agent-1" isLoading={isPending} />
}
function createDeferredPromise<T>() {
let resolve!: (value: T) => void
let reject!: (reason?: unknown) => void
const promise = new Promise<T>((promiseResolve, promiseReject) => {
resolve = promiseResolve
reject = promiseReject
})
return { promise, reject, resolve }
}
describe('Agent access surface cards', () => {
beforeEach(() => {
vi.resetAllMocks()
vi.spyOn(HTMLImageElement.prototype, 'complete', 'get').mockReturnValue(true)
vi.spyOn(HTMLImageElement.prototype, 'naturalWidth', 'get').mockReturnValue(32)
mocks.agentDetailQueryFn.mockResolvedValue(createAgent())
mocks.getUserCanAccess.mockResolvedValue({ result: true })
mocks.accessSubjectsQueryFn.mockResolvedValue({ groups: [], members: [] })
mocks.updateAccessMutation.mockResolvedValue({ result: 'success' })
})
afterEach(() => vi.restoreAllMocks())
describe('Web app access', () => {
it('disables Open when the user cannot access the backing Web App', async () => {
const user = userEvent.setup()
mocks.getUserCanAccess.mockResolvedValue({ result: false })
renderWithQueryClient(
<WebAppAccessCard
agent={createAgent({
access_mode: AccessMode.SPECIFIC_GROUPS_MEMBERS,
app_id: 'source-app-1',
backing_app_id: 'backing-app-1',
})}
agentId="agent-1"
isLoading={false}
/>,
)
const openButton = screen.getByRole('button', {
name: 'agentV2.agentDetail.access.webApp.actions.open',
})
await user.hover(openButton)
expect(await screen.findByText('app.noAccessPermission')).toBeVisible()
expect(openButton).toHaveAttribute('aria-disabled', 'true')
expect(screen.queryByRole('link', { name: /webApp\.actions\.open/ })).not.toBeInTheDocument()
expect(mocks.getUserCanAccess).toHaveBeenCalledWith('backing-app-1', true)
})
it('keeps Open disabled until Web App access is confirmed', async () => {
const permission = createDeferredPromise<{ result: boolean }>()
mocks.getUserCanAccess.mockReturnValueOnce(permission.promise)
renderWithQueryClient(
<WebAppAccessCard
agent={createAgent({ access_mode: AccessMode.ORGANIZATION })}
agentId="agent-1"
isLoading={false}
/>,
)
expect(screen.getByRole('button', { name: /webApp\.actions\.open/ })).toHaveAttribute(
'aria-disabled',
'true',
)
permission.resolve({ result: true })
expect(await screen.findByRole('link', { name: /webApp\.actions\.open/ })).toHaveAttribute(
'href',
'https://chat.example.test/agent/site-token',
)
})
it('allows external-member Web Apps without platform access', () => {
mocks.getUserCanAccess.mockResolvedValue({ result: false })
renderWithQueryClient(
<WebAppAccessCard
agent={createAgent({ access_mode: AccessMode.EXTERNAL_MEMBERS })}
agentId="agent-1"
isLoading={false}
/>,
)
expect(screen.getByRole('link', { name: /webApp\.actions\.open/ })).toHaveAttribute(
'href',
'https://chat.example.test/agent/site-token',
)
})
it('allows opening without a permission query when Web App auth is disabled', () => {
renderWithQueryClient(
<WebAppAccessCard
agent={createAgent({ access_mode: AccessMode.ORGANIZATION })}
agentId="agent-1"
isLoading={false}
/>,
{ webAppAuthEnabled: false },
)
expect(screen.getByRole('link', { name: /webApp\.actions\.open/ })).toHaveAttribute(
'href',
'https://chat.example.test/agent/site-token',
)
expect(mocks.getUserCanAccess).not.toHaveBeenCalled()
})
it('refreshes Open after saving Web App access permissions', async () => {
const user = userEvent.setup()
mocks.getUserCanAccess.mockResolvedValue({ result: false })
renderWithQueryClient(
<WebAppAccessCard
agent={createAgent({ access_mode: AccessMode.SPECIFIC_GROUPS_MEMBERS })}
agentId="agent-1"
isLoading={false}
/>,
)
await user.click(
screen.getByRole('button', { name: /accessControlDialog\.accessItems\.specific/ }),
)
const dialog = await screen.findByRole('dialog', { name: 'app.accessControlDialog.title' })
expect(
screen.getByRole('button', { name: /webApp\.actions\.open/, hidden: true }),
).toHaveAttribute('aria-disabled', 'true')
await user.click(
within(dialog).getByRole('radio', {
name: 'app.accessControlDialog.accessItems.organization',
}),
)
mocks.getUserCanAccess.mockResolvedValue({ result: true })
await user.click(within(dialog).getByRole('button', { name: 'common.operation.confirm' }))
await waitFor(() =>
expect(mocks.updateAccessMutation).toHaveBeenCalledExactlyOnceWith({
body: { appId: 'app-1', accessMode: AccessMode.ORGANIZATION },
}),
)
expect(await screen.findByRole('link', { name: /webApp\.actions\.open/ })).toHaveAttribute(
'href',
'https://chat.example.test/agent/site-token',
)
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
it('should serialize Web App toggles and cache each confirmed response', async () => {
const user = userEvent.setup()
const firstToggle = createDeferredPromise<AppDetail>()
const secondToggle = createDeferredPromise<AppDetail>()
mocks.siteEnableMutation
.mockReturnValueOnce(firstToggle.promise)
.mockReturnValueOnce(secondToggle.promise)
const agent = createAgent()
const queryClient = renderWithQueryClient(
<WebAppAccessCard agent={agent} agentId="agent-1" isLoading={false} />,
{ agent },
)
expect(screen.getByText('https://chat.example.test/agent/site-token')).toBeInTheDocument()
expect(
screen.getByRole('link', { name: 'agentV2.agentDetail.access.webApp.actions.open' }),
).toHaveAttribute('href', 'https://chat.example.test/agent/site-token')
expect(screen.getByText('agentV2.agentDetail.access.webApp.description')).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.copyAccessUrl' }),
).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.showQrCode' }),
).toBeInTheDocument()
const accessSwitch = screen.getByRole('switch', {
name: 'agentV2.agentDetail.access.toggleSurface:{"name":"agentV2.agentDetail.access.webApp.title"}',
})
await user.click(accessSwitch)
expect(accessSwitch).toHaveAttribute('aria-checked', 'false')
expect(accessSwitch).toBeEnabled()
expect(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.open' }),
).toBeDisabled()
expect(mocks.siteEnableMutation).toHaveBeenNthCalledWith(1, {
params: {
app_id: 'app-1',
},
body: {
enable_site: false,
},
})
await user.click(accessSwitch)
expect(accessSwitch).toHaveAttribute('aria-checked', 'true')
expect(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.open' }),
).toBeDisabled()
expect(mocks.siteEnableMutation).toHaveBeenCalledTimes(1)
firstToggle.resolve(
createAppDetailResponse({
enable_site: false,
updated_at: 1781660200,
updated_by: 'user-2',
}),
)
await waitFor(() => {
expect(mocks.siteEnableMutation).toHaveBeenNthCalledWith(2, {
params: {
app_id: 'app-1',
},
body: {
enable_site: true,
},
})
})
expect(
queryClient.getQueryData(
consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: 'agent-1' } } }),
),
).toMatchObject({
enable_site: false,
updated_at: 1781660200,
updated_by: 'user-2',
})
secondToggle.resolve(
createAppDetailResponse({
enable_site: true,
updated_at: 1781660300,
updated_by: 'user-3',
}),
)
await waitFor(() => {
expect(
queryClient.getQueryData(
consoleQuery.agent.byAgentId.get.queryKey({
input: { params: { agent_id: 'agent-1' } },
}),
),
).toMatchObject({
enable_site: true,
updated_at: 1781660300,
updated_by: 'user-3',
})
})
expect(
await screen.findByRole('link', {
name: 'agentV2.agentDetail.access.webApp.actions.open',
}),
).toHaveAttribute('href', 'https://chat.example.test/agent/site-token')
expect(toast.success).not.toHaveBeenCalled()
})
it('should keep open disabled while enabling is pending and roll back after failure', async () => {
const user = userEvent.setup()
const toggle = createDeferredPromise<AppDetail>()
mocks.siteEnableMutation.mockReturnValueOnce(toggle.promise)
renderWithQueryClient(
<WebAppAccessCard
agent={createAgent({ enable_site: false })}
agentId="agent-1"
isLoading={false}
/>,
)
const accessSwitch = screen.getByRole('switch', {
name: 'agentV2.agentDetail.access.toggleSurface:{"name":"agentV2.agentDetail.access.webApp.title"}',
})
const openButton = screen.getByRole('button', {
name: 'agentV2.agentDetail.access.webApp.actions.open',
})
await user.click(accessSwitch)
expect(accessSwitch).toHaveAttribute('aria-checked', 'true')
expect(accessSwitch).toBeEnabled()
expect(openButton).toBeDisabled()
expect(
screen.queryByRole('link', { name: 'agentV2.agentDetail.access.webApp.actions.open' }),
).not.toBeInTheDocument()
toggle.reject(new Error('request failed'))
await waitFor(() => {
expect(accessSwitch).toHaveAttribute('aria-checked', 'false')
})
expect(openButton).toBeDisabled()
expect(toast.error).toHaveBeenCalledWith('request failed')
})
it('should replace the Web App URL token without discarding the cached site settings', async () => {
const user = userEvent.setup()
const agent = createAgent()
const queryClient = renderWithQueryClient(
<WebAppAccessCard agent={agent} agentId="agent-1" isLoading={false} />,
{ agent },
)
mocks.siteAccessTokenResetMutation.mockResolvedValueOnce(
createAppSiteFixture({ code: 'new-site-token' }),
)
await user.click(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.refreshUrl' }),
)
expect(mocks.siteAccessTokenResetMutation).toHaveBeenNthCalledWith(1, {
params: { app_id: 'app-1' },
})
await waitFor(() => {
expect(
queryClient.getQueryData<AgentAppDetailWithSite>(
consoleQuery.agent.byAgentId.get.queryKey({
input: { params: { agent_id: 'agent-1' } },
}),
)?.site,
).toMatchObject({
code: 'new-site-token',
access_token: 'new-site-token',
title: 'Support Agent',
})
})
})
it('should open the customize dialog with the backing app id and API base URL', async () => {
const user = userEvent.setup()
renderWithQueryClient(
<WebAppAccessCard agent={createAgent()} agentId="agent-1" isLoading={false} />,
)
await user.click(
screen.getByRole('button', {
name: 'agentV2.agentDetail.access.webApp.actions.customFrontend',
}),
)
const dialog = await screen.findByRole('dialog', {
name: 'appOverview.overview.appInfo.customize.title',
})
expect(dialog.textContent).toMatch(/NEXT_PUBLIC_APP_ID=\s*'app-1'/)
expect(dialog.textContent).toMatch(
/NEXT_PUBLIC_API_URL=\s*'https:\/\/api\.example\.test\/v1'/,
)
expect(
within(dialog).getByRole('link', {
name: /appOverview\.overview\.appInfo\.customize\.way1\.step1Operation/,
}),
).toHaveAttribute('href', 'https://github.com/langgenius/webapp-conversation')
})
it('should open the embedded dialog with the Agent web app route', async () => {
const user = userEvent.setup()
renderWithQueryClient(
<WebAppAccessCard agent={createAgent()} agentId="agent-1" isLoading={false} />,
)
await user.click(
screen.getByRole('button', {
name: 'agentV2.agentDetail.access.webApp.actions.embedIntoSite',
}),
)
const dialog = await screen.findByRole('dialog', {
name: 'appOverview.overview.appInfo.embedded.title',
})
await waitFor(() => {
expect(dialog).toHaveTextContent('https://chat.example.test/agent/site-token')
})
await user.click(
within(dialog).getByRole('tab', {
name: 'appOverview.overview.appInfo.embedded.scripts',
}),
)
await waitFor(() => {
expect(dialog).toHaveTextContent("routeSegment: 'agent'")
})
})
it('should save settings through the backing app id and invalidate agent detail', async () => {
const user = userEvent.setup()
mocks.getUserCanAccess.mockResolvedValue({ result: false })
const agent = createAgent({
access_mode: AccessMode.SPECIFIC_GROUPS_MEMBERS,
site: {
...createAgent().site!,
icon_url: 'https://files.example.test/old-icon.png',
},
})
mocks.siteMutation.mockResolvedValueOnce({
app_id: 'app-1',
code: 'new-site-token',
copyright: '',
custom_disclaimer: '',
customize_domain: null,
customize_token_strategy: 'allow',
default_language: 'en-US',
description: 'Updated web description.',
icon: '🤖',
icon_background: '#FFEAD5',
privacy_policy: '',
prompt_public: false,
show_workflow_steps: false,
title: 'Support Portal',
use_icon_as_answer_icon: true,
})
const queryClient = renderWithQueryClient(
<WebAppAccessCard agent={agent} agentId="agent-1" isLoading={false} />,
{ agent },
)
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries')
await user.click(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.settings' }),
)
const dialog = await screen.findByRole('dialog', {
name: 'appOverview.overview.appInfo.settings.title',
})
await user.clear(within(dialog).getByPlaceholderText('app.appNamePlaceholder'))
await user.type(
within(dialog).getByPlaceholderText('app.appNamePlaceholder'),
'Support Portal',
)
await user.clear(
within(dialog).getByRole('textbox', {
name: 'appOverview.overview.appInfo.settings.webDesc',
}),
)
await user.type(
within(dialog).getByRole('textbox', {
name: 'appOverview.overview.appInfo.settings.webDesc',
}),
'Updated web description.',
)
await user.clear(within(dialog).getByPlaceholderText('E.g #A020F0'))
await user.type(within(dialog).getByPlaceholderText('E.g #A020F0'), '#123456')
await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => {
expect(mocks.siteMutation).toHaveBeenNthCalledWith(1, {
params: {
app_id: 'app-1',
},
body: expect.objectContaining({
title: 'Support Portal',
description: 'Updated web description.',
chat_color_theme: '#123456',
}),
})
})
expect(mocks.siteMutation.mock.calls[0]?.[0].body).not.toHaveProperty('enable_sso')
await waitFor(() => {
expect(invalidateSpy).toHaveBeenCalledWith({
queryKey: consoleQuery.agent.byAgentId.get.queryKey({
input: { params: { agent_id: 'agent-1' } },
}),
})
})
})
it('preserves the draft after POST failure and closes on retry before detail refresh completes', async () => {
const user = userEvent.setup()
const refreshed = createDeferredPromise<AgentAppDetailWithSite>()
mocks.siteMutation.mockResolvedValue({}).mockRejectedValueOnce(new Error('Save failed'))
const queryClient = renderWithQueryClient(<QueryOwnedWebAppCard />)
const trigger = screen.getByRole('button', {
name: 'agentV2.agentDetail.access.webApp.actions.settings',
})
await user.click(trigger)
const dialog = await screen.findByRole('dialog', {
name: 'appOverview.overview.appInfo.settings.title',
})
const name = within(dialog).getByPlaceholderText('app.appNamePlaceholder')
await user.clear(name)
await user.type(name, 'Committed portal')
await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1))
expect(dialog).toBeInTheDocument()
expect(name).toHaveValue('Committed portal')
expect(mocks.agentDetailQueryFn).not.toHaveBeenCalled()
mocks.agentDetailQueryFn.mockReturnValueOnce(refreshed.promise)
await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(toast.success).toHaveBeenCalledTimes(1)
expect(mocks.agentDetailQueryFn).toHaveBeenCalledTimes(1)
const updated = createAgent({
site: { ...createAgent().site!, title: 'Committed portal', chat_color_theme: '#123456' },
})
await act(async () => refreshed.resolve(updated))
await waitFor(() =>
expect(
queryClient.getQueryData(
consoleQuery.agent.byAgentId.get.queryKey({
input: { params: { agent_id: 'agent-1' } },
}),
),
).toEqual(updated),
)
await user.click(trigger)
const reopened = await screen.findByRole('dialog', {
name: 'appOverview.overview.appInfo.settings.title',
})
expect(within(reopened).getByPlaceholderText('app.appNamePlaceholder')).toHaveValue(
'Committed portal',
)
expect(within(reopened).getByPlaceholderText('E.g #A020F0')).toHaveValue('#123456')
})
it('closes after a successful POST even when background agent refresh fails', async () => {
const user = userEvent.setup()
mocks.siteMutation.mockResolvedValue({})
mocks.agentDetailQueryFn.mockRejectedValue(new Error('Refresh failed'))
const queryClient = renderWithQueryClient(<QueryOwnedWebAppCard />)
await user.click(
screen.getByRole('button', {
name: 'agentV2.agentDetail.access.webApp.actions.settings',
}),
)
const dialog = await screen.findByRole('dialog', {
name: 'appOverview.overview.appInfo.settings.title',
})
await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
await waitFor(() =>
expect(
queryClient.getQueryState(
consoleQuery.agent.byAgentId.get.queryKey({
input: { params: { agent_id: 'agent-1' } },
}),
)?.status,
).toBe('error'),
)
expect(toast.success).toHaveBeenCalledTimes(1)
expect(toast.error).not.toHaveBeenCalled()
})
it('should fall back to the Agent icon tuple when WebApp site icon data is missing', async () => {
const user = userEvent.setup()
const agent = createAgent({
icon: 'agent-image-file-id',
icon_background: null,
icon_type: 'image',
icon_url: 'https://files.example.test/agent-icon.png',
site: {
...createAgent().site!,
icon: null,
icon_background: null,
icon_type: null,
icon_url: null,
},
})
mocks.siteMutation.mockResolvedValueOnce({
app_id: 'app-1',
code: 'site-token',
copyright: '',
custom_disclaimer: '',
customize_domain: null,
customize_token_strategy: 'allow',
default_language: 'en-US',
description: 'Support Agent',
icon: 'agent-image-file-id',
icon_background: null,
privacy_policy: '',
prompt_public: false,
show_workflow_steps: false,
title: 'Support Agent',
use_icon_as_answer_icon: false,
})
renderWithQueryClient(<WebAppAccessCard agent={agent} agentId="agent-1" isLoading={false} />)
await user.click(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.settings' }),
)
const dialog = await screen.findByRole('dialog', {
name: 'appOverview.overview.appInfo.settings.title',
})
const iconTrigger = within(dialog).getByRole('button', { name: 'app.iconPicker.title' })
expect(iconTrigger.querySelector('img')).toHaveAttribute(
'src',
'https://files.example.test/agent-icon.png',
)
await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => {
expect(mocks.siteMutation.mock.calls[0]?.[0].body).toEqual(
expect.objectContaining({
icon: 'agent-image-file-id',
icon_background: undefined,
icon_type: 'image',
}),
)
})
})
it('should keep embedded disabled until the backing app id and web app token are available', () => {
renderWithQueryClient(
<WebAppAccessCard
agent={createAgent({
app_id: null,
site: {
...createAgent().site!,
access_token: null,
code: null,
},
})}
agentId="agent-1"
isLoading={false}
/>,
)
expect(
screen.getByRole('button', {
name: 'agentV2.agentDetail.access.webApp.actions.embedIntoSite',
}),
).toBeDisabled()
})
it('should keep settings disabled until the backing app id and site data are available', () => {
const agentWithoutApp = createAgent({
app_id: null,
})
const agentWithoutSite = createAgent({
site: null,
})
const queryClient = createConsoleQueryClient()
const { rerender } = render(
<WebAppAccessCard agent={agentWithoutApp} agentId="agent-1" isLoading={false} />,
{ wrapper: createAccessCardWrapper(queryClient) },
)
expect(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.settings' }),
).toBeDisabled()
rerender(<WebAppAccessCard agent={agentWithoutSite} agentId="agent-1" isLoading={false} />)
expect(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.settings' }),
).toBeDisabled()
})
it('should keep customize disabled when the app base URL is empty', () => {
renderWithQueryClient(
<WebAppAccessCard
agent={createAgent({ api_base_url: '' })}
agentId="agent-1"
isLoading={false}
/>,
)
expect(
screen.getByRole('button', {
name: 'agentV2.agentDetail.access.webApp.actions.customFrontend',
}),
).toBeDisabled()
})
it('should explain that publishing enables the Web App switch and open action', async () => {
const user = userEvent.setup()
renderWithQueryClient(
<WebAppAccessCard
agent={createAgent({ access_ready: false, enable_site: false })}
agentId="agent-1"
isLoading={false}
/>,
)
const accessSwitch = screen.getByRole('switch', {
name: 'agentV2.agentDetail.access.toggleSurface:{"name":"agentV2.agentDetail.access.webApp.title"}',
})
expect(accessSwitch).toHaveAttribute('aria-disabled', 'true')
await user.tab()
expect(accessSwitch).toHaveFocus()
expect(
await screen.findByText('agentV2.agentDetail.access.publishRequired', {
selector: '[data-open]',
}),
).toBeVisible()
await user.tab()
await waitFor(() => {
expect(
screen.queryByText('agentV2.agentDetail.access.publishRequired', {
selector: '[data-open]',
}),
).not.toBeInTheDocument()
})
await user.hover(
screen.getByRole('button', {
name: 'agentV2.agentDetail.access.webApp.actions.open',
}),
)
expect(
await screen.findByText('agentV2.agentDetail.access.publishRequired', {
selector: '[data-open]',
}),
).toBeVisible()
})
})
describe('Service API access', () => {
it('should render service API data and toggle Agent API status through the generated Agent endpoint', async () => {
const user = userEvent.setup()
const toggle = createDeferredPromise<AgentApiAccessResponse>()
mocks.apiAccessQueryFn.mockResolvedValueOnce(createAgentApiAccessResponse())
mocks.apiEnableMutation.mockReturnValueOnce(toggle.promise)
renderWithQueryClient(<ServiceApiAccessCard agentId="agent-1" />)
expect(await screen.findByText('https://api.example.test/v1')).toBeInTheDocument()
expect(
screen.getByRole('heading', {
name: 'agentV2.agentDetail.access.serviceApi.title',
level: 3,
}),
).toBeInTheDocument()
expect(
screen.getByText('agentV2.agentDetail.access.serviceApi.description'),
).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.copyServiceEndpoint' }),
).toBeInTheDocument()
expect(
screen.getByRole('link', {
name: 'agentV2.agentDetail.access.serviceApi.actions.apiReference',
}),
).toHaveAttribute('href', 'https://docs.example.test/api-reference/guides/agent')
expect(screen.getByText('2')).toBeInTheDocument()
const accessSwitch = screen.getByRole('switch', {
name: 'agentV2.agentDetail.access.toggleSurface:{"name":"agentV2.agentDetail.access.serviceApi.title"}',
})
const apiKeyButton = screen.getByRole('button', {
name: /agentV2\.agentDetail\.access\.serviceApi\.actions\.apiKey/,
})
await user.click(accessSwitch)
expect(accessSwitch).toHaveAttribute('aria-checked', 'false')
expect(accessSwitch).toBeEnabled()
expect(apiKeyButton).toBeEnabled()
expect(mocks.apiEnableMutation).toHaveBeenNthCalledWith(1, {
params: {
agent_id: 'agent-1',
},
body: {
enable_api: false,
},
})
toggle.reject(new Error('request failed'))
await waitFor(() => {
expect(accessSwitch).toHaveAttribute('aria-checked', 'true')
})
expect(toast.error).toHaveBeenCalledWith('request failed')
expect(toast.success).not.toHaveBeenCalled()
})
it('should keep raw API enablement separate from effective API access status', async () => {
const user = userEvent.setup()
const initialApiAccess = createAgentApiAccessResponse({ enabled: false })
const updatedApiAccess = createAgentApiAccessResponse({ access_ready: false, enabled: false })
mocks.apiAccessQueryFn.mockResolvedValueOnce(initialApiAccess)
mocks.apiEnableMutation.mockResolvedValueOnce(updatedApiAccess)
const agent = createAgent({ enable_api: false })
const queryClient = renderWithQueryClient(<ServiceApiAccessCard agentId="agent-1" />, {
agent,
})
await screen.findByText(initialApiAccess.service_api_base_url)
await user.click(
screen.getByRole('switch', {
name: 'agentV2.agentDetail.access.toggleSurface:{"name":"agentV2.agentDetail.access.serviceApi.title"}',
}),
)
await waitFor(() => {
expect(
queryClient.getQueryData(
consoleQuery.agent.byAgentId.apiAccess.get.queryKey({
input: { params: { agent_id: 'agent-1' } },
}),
),
).toEqual(updatedApiAccess)
expect(
queryClient.getQueryData(
consoleQuery.agent.byAgentId.get.queryKey({
input: { params: { agent_id: 'agent-1' } },
}),
),
).toMatchObject({
enable_api: true,
})
})
expect(toast.success).not.toHaveBeenCalled()
})
it('should manage API keys with the Agent API key endpoints', async () => {
const user = userEvent.setup()
mocks.apiAccessQueryFn.mockResolvedValue(createAgentApiAccessResponse({ api_key_count: 1 }))
mocks.apiKeysQueryFn.mockResolvedValue({
data: [
{
created_at: 1781660000,
id: 'key-1',
last_used_at: null,
token: 'app-existing-secret-key-token',
type: 'app',
},
],
})
mocks.createApiKeyMutation.mockResolvedValueOnce({
created_at: 1781660100,
id: 'key-2',
last_used_at: null,
token: 'app-new-secret-key-token',
type: 'app',
})
mocks.deleteApiKeyMutation.mockResolvedValueOnce(undefined)
renderWithQueryClient(<ServiceApiAccessCard agentId="agent-1" />)
await user.click(
await screen.findByRole('button', {
name: /agentV2\.agentDetail\.access\.serviceApi\.actions\.apiKey/,
}),
)
const dialog = await screen.findByRole('dialog', { name: 'appApi.apiKeyModal.apiSecretKey' })
const keyTable = await within(dialog).findByRole('table', {
name: 'appApi.apiKeyModal.apiSecretKey',
})
expect(
within(keyTable).getByRole('columnheader', { name: 'appApi.apiKeyModal.secretKey' }),
).toBeInTheDocument()
expect(
within(keyTable).getByRole('columnheader', { name: 'appApi.apiKeyModal.created' }),
).toBeInTheDocument()
expect(
within(keyTable).getByRole('columnheader', { name: 'appApi.apiKeyModal.lastUsed' }),
).toBeInTheDocument()
expect(
await within(keyTable).findByRole('cell', { name: 'app-e...oken' }),
).toBeInTheDocument()
await user.click(
within(dialog).getByRole('button', { name: 'appApi.apiKeyModal.createNewSecretKey' }),
)
await waitFor(() => {
expect(mocks.createApiKeyMutation).toHaveBeenNthCalledWith(1, {
params: {
agent_id: 'agent-1',
},
})
})
expect(await screen.findByText('appApi.apiKeyModal.generateTips')).toBeInTheDocument()
expect(screen.getByRole('textbox', { name: 'appApi.apiKeyModal.secretKey' })).toHaveValue(
'app-new-secret-key-token',
)
const result = screen.getByRole('dialog', { name: 'appApi.apiKeyModal.createdTitle' })
await user.click(within(result).getByRole('button', { name: 'appApi.apiKeyModal.saved' }))
await user.click(
within(dialog).getByRole('button', { name: 'common.operation.delete app-e...oken' }),
)
await user.click(await screen.findByRole('button', { name: 'common.operation.delete' }))
await waitFor(() => {
expect(mocks.deleteApiKeyMutation).toHaveBeenNthCalledWith(1, {
params: {
agent_id: 'agent-1',
api_key_id: 'key-1',
},
})
})
await waitFor(() =>
expect(
within(dialog).getByRole('button', { name: 'appApi.apiKeyModal.createNewSecretKey' }),
).toHaveFocus(),
)
})
it('should explain that publishing enables the Service API switch', async () => {
const user = userEvent.setup()
mocks.apiAccessQueryFn.mockResolvedValueOnce(
createAgentApiAccessResponse({
access_ready: false,
api_key_count: 0,
enabled: false,
}),
)
renderWithQueryClient(<ServiceApiAccessCard agentId="agent-1" />)
await screen.findByText('https://api.example.test/v1')
const accessSwitch = screen.getByRole('switch', {
name: 'agentV2.agentDetail.access.toggleSurface:{"name":"agentV2.agentDetail.access.serviceApi.title"}',
})
expect(accessSwitch).toHaveAttribute('aria-disabled', 'true')
expect(
screen.getByRole('button', {
name: /agentV2\.agentDetail\.access\.serviceApi\.actions\.apiKey/,
}),
).toBeDisabled()
await user.tab()
expect(accessSwitch).toHaveFocus()
expect(
await screen.findByText('agentV2.agentDetail.access.publishRequired', {
selector: '[data-open]',
}),
).toBeVisible()
})
it('recovers Service API access after retrying a failed query', async () => {
const user = userEvent.setup()
mocks.apiAccessQueryFn
.mockRejectedValueOnce(new Error('Service API unavailable'))
.mockResolvedValue(createAgentApiAccessResponse())
renderWithQueryClient(<ServiceApiAccessCard agentId="agent-1" />)
expect(
await screen.findByText('agentV2.agentDetail.access.status.unavailable'),
).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'common.operation.retry' }))
expect(await screen.findByText('https://api.example.test/v1')).toBeInTheDocument()
expect(
screen.queryByText('agentV2.agentDetail.access.status.unavailable'),
).not.toBeInTheDocument()
})
})
describe('App-style Web app access control', () => {
const accessControlAgent = () =>
createAgent({
access_mode: 'private_all',
maintainer: 'user-2',
permission_keys: [AgentPermission.AccessPointManage],
})
const organizationAccessLabel = 'app.accessControlDialog.accessItems.organization'
it('should keep access control interactive before the Agent is published', () => {
renderWithQueryClient(
<WebAppAccessCard
agent={createAgent({
...accessControlAgent(),
access_ready: false,
})}
agentId="agent-1"
isLoading={false}
/>,
)
expect(screen.getByRole('button', { name: organizationAccessLabel })).toBeEnabled()
expect(screen.queryByRole('status', { name: 'common.loading' })).not.toBeInTheDocument()
})
it('should hide the access mode entry when Web app auth is disabled', () => {
renderWithQueryClient(
<WebAppAccessCard agent={accessControlAgent()} agentId="agent-1" isLoading={false} />,
{ webAppAuthEnabled: false },
)
expect(
screen.queryByRole('button', { name: organizationAccessLabel }),
).not.toBeInTheDocument()
})
it('should not grant access control management from release permission', () => {
renderWithQueryClient(
<WebAppAccessCard
agent={createAgent({
access_mode: 'private_all',
maintainer: 'user-2',
permission_keys: [AgentPermission.ReleaseAndVersion],
})}
agentId="agent-1"
isLoading={false}
/>,
)
expect(screen.getByRole('button', { name: organizationAccessLabel })).toBeDisabled()
})
it('should hide the access mode entry when the access mode is unavailable', () => {
renderWithQueryClient(
<WebAppAccessCard
agent={createAgent({ access_mode: null })}
agentId="agent-1"
isLoading={false}
/>,
)
expect(
screen.queryByRole('button', { name: organizationAccessLabel }),
).not.toBeInTheDocument()
})
it('should open the shared App access control dialog for the backing app', async () => {
const user = userEvent.setup()
renderWithQueryClient(
<WebAppAccessCard
agent={createAgent({
access_mode: 'private_all',
app_id: 'source-app-1',
backing_app_id: 'backing-app-1',
maintainer: 'user-2',
permission_keys: [AgentPermission.AccessPointManage],
})}
agentId="agent-1"
isLoading={false}
/>,
)
await user.click(screen.getByRole('button', { name: organizationAccessLabel }))
const dialog = await screen.findByRole('dialog', { name: 'app.accessControlDialog.title' })
expect(within(dialog).getByRole('radio', { name: organizationAccessLabel })).toBeChecked()
await user.click(
within(dialog).getByRole('radio', { name: 'app.accessControlDialog.accessItems.external' }),
)
await user.click(within(dialog).getByRole('button', { name: 'common.operation.confirm' }))
await waitFor(() =>
expect(mocks.updateAccessMutation).toHaveBeenCalledExactlyOnceWith({
body: { appId: 'backing-app-1', accessMode: AccessMode.EXTERNAL_MEMBERS },
}),
)
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
})
it('allows viewers to copy and open WebApp addresses while disabling management actions', async () => {
const user = userEvent.setup()
renderWithQueryClient(
<WebAppAccessCard
agent={createAgent({
permission_keys: [AgentPermission.Preview, AgentPermission.AccessPointView],
})}
agentId="agent-1"
isLoading={false}
/>,
)
expect(
screen.getByRole('link', { name: 'agentV2.agentDetail.access.webApp.actions.open' }),
).toHaveAttribute('href', 'https://chat.example.test/agent/site-token')
expect(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.copyAccessUrl' }),
).toBeEnabled()
expect(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.showQrCode' }),
).toBeEnabled()
for (const action of ['embedIntoSite', 'customFrontend', 'settings']) {
expect(
screen.getByRole('button', { name: `agentV2.agentDetail.access.webApp.actions.${action}` }),
).toBeDisabled()
}
expect(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.refreshUrl' }),
).toHaveAttribute('aria-disabled', 'true')
const toggle = screen.getByRole('switch')
await user.click(toggle)
expect(mocks.siteEnableMutation).not.toHaveBeenCalled()
expect(mocks.accessSubjectsQueryFn).not.toHaveBeenCalled()
})
it('allows API viewers to copy the endpoint and read documentation without fetching API keys', async () => {
const user = userEvent.setup()
mocks.apiAccessQueryFn.mockResolvedValue(createAgentApiAccessResponse())
const client = createConsoleQueryClient()
client.setQueryData(
consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: 'agent-1' } } }),
createAgent({ permission_keys: [AgentPermission.AccessPointView] }),
)
render(<ServiceApiAccessCard agentId="agent-1" />, {
wrapper: createAccessCardWrapper(client),
})
await waitFor(() => {
expect(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.copyServiceEndpoint' }),
).toBeEnabled()
})
expect(
screen.getByRole('link', {
name: 'agentV2.agentDetail.access.serviceApi.actions.apiReference',
}),
).toHaveAttribute('href', 'https://docs.example.test/api-reference/guides/agent')
const apiKeys = screen.getByRole('button', { name: /serviceApi.actions.apiKey/ })
expect(apiKeys).toBeDisabled()
await user.click(apiKeys)
await user.click(screen.getByRole('switch'))
expect(mocks.apiKeysQueryFn).not.toHaveBeenCalled()
expect(mocks.apiEnableMutation).not.toHaveBeenCalled()
})
it('closes the settings dialog when Agent access point management is revoked', async () => {
const user = userEvent.setup()
const queryClient = createConsoleQueryClient()
const { rerender } = render(
<WebAppAccessCard agent={createAgent()} agentId="agent-1" isLoading={false} />,
{ wrapper: createAccessCardWrapper(queryClient) },
)
await user.click(
screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.settings' }),
)
expect(screen.getByRole('dialog')).toBeInTheDocument()
rerender(
<WebAppAccessCard
agent={createAgent({ permission_keys: [AgentPermission.AccessPointView] })}
agentId="agent-1"
isLoading={false}
/>,
)
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(mocks.siteMutation).not.toHaveBeenCalled()
})
})