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(web): gray preview-only agent cards (#42809)

Wu Tianwei2fa4c57026e5
diff --git a/web/context/__tests__/console-bootstrap.spec.tsx b/web/context/__tests__/console-bootstrap.spec.tsx
index 5e0ee0deace..90848b6e48c 100644
--- a/web/context/__tests__/console-bootstrap.spec.tsx
+++ b/web/context/__tests__/console-bootstrap.spec.tsx
@@ -2,6 +2,7 @@ import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/syst
import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { Provider as JotaiProvider, useAtomValue, useSetAtom } from 'jotai'
import { queryClientAtom } from 'jotai-tanstack-query'
import { useHydrateAtoms } from 'jotai/react/utils'
@@ -12,6 +13,8 @@ import { flushRegistrationSuccess } from '@/app/components/base/amplitude/regist
import { setAnalyticsConsent } from '@/app/components/base/analytics-consent/consent-store'
import { zendeskRuntime } from '@/app/components/base/zendesk/runtime'
import { ZENDESK_FIELD_IDS } from '@/config'
+import { consoleQuery } from '@/service/console'
+import { useLogout } from '@/service/use-common'
import { createSystemFeaturesFixture } from '@/test/console/system-features'
import { initialWorkspaceSummary } from '../app-context-defaults'
import {
@@ -29,6 +32,7 @@ import {
} from '../workspace-state'
const mockGetRequest = vi.hoisted(() => vi.fn())
+const mockPostRequest = vi.hoisted(() => vi.fn())
const mockGetPermissionKeys = vi.hoisted(() => vi.fn())
const mockPermissionKeysState = vi.hoisted(() => ({
datasetPermissionKeys: ['dataset.acl.edit'],
@@ -151,6 +155,7 @@ vi.mock('@/service/console', () => ({
rbac: {
myPermissions: {
get: {
+ key: () => ['current-permissions'],
queryOptions: () => ({
queryKey: ['current-permissions'],
queryFn: mockGetPermissionKeys,
@@ -181,7 +186,7 @@ vi.mock('@/service/console', () => ({
vi.mock('@/service/base', () => ({
get: mockGetRequest,
- post: vi.fn(),
+ post: mockPostRequest,
}))
vi.mock('@/app/components/base/amplitude', () => ({
@@ -263,6 +268,15 @@ function ConsoleBootstrapProbe() {
)
}
+function LogoutButton() {
+ const { isSuccess, mutateAsync: logout } = useLogout()
+ return (
+ <button type="button" onClick={() => void logout()}>
+ {isSuccess ? 'Logged out' : 'Log out'}
+ </button>
+ )
+}
+
function TestQueryClientHydrator({
children,
queryClient,
@@ -365,6 +379,52 @@ describe('Console bootstrap', () => {
})
describe('Bootstrap atoms', () => {
+ it('replaces account-scoped atom results after logout and the next account hydration', async () => {
+ const user = userEvent.setup()
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: 5 * 60 * 1000 } },
+ })
+ const permissionQueryKey = consoleQuery.workspaces.current.rbac.myPermissions.get.key()
+ const workspaceQueryKey = consoleQuery.workspaces.current.summary.get.key()
+ queryClient.setQueryData(permissionQueryKey, {
+ workspace: { permission_keys: ['agent.create'] },
+ })
+ queryClient.setQueryData(workspaceQueryKey, mockCurrentWorkspaceResponse)
+ mockPostRequest.mockResolvedValueOnce({ result: 'success' })
+ const tree = (showConsole: boolean) => (
+ <JotaiProvider>
+ <QueryClientProvider client={queryClient}>
+ <TestQueryClientHydrator queryClient={queryClient}>
+ <Suspense fallback={<span>loading</span>}>
+ {showConsole && <ConsoleBootstrapProbe />}
+ <LogoutButton />
+ </Suspense>
+ </TestQueryClientHydrator>
+ </QueryClientProvider>
+ </JotaiProvider>
+ )
+ const view = render(tree(true))
+ expect(await screen.findByText('keys:agent.create')).toBeInTheDocument()
+
+ await user.click(screen.getByRole('button', { name: 'Log out' }))
+ await screen.findByRole('button', { name: 'Logged out' })
+ view.rerender(tree(false))
+ mockPermissionKeysState.permissionKeys = []
+ act(() => {
+ queryClient.setQueryData(permissionQueryKey, {
+ workspace: { permission_keys: [] },
+ })
+ queryClient.setQueryData(workspaceQueryKey, {
+ ...mockCurrentWorkspaceResponse,
+ name: 'Next Workspace',
+ })
+ })
+ view.rerender(tree(true))
+
+ expect(await screen.findByText('keys:')).toBeInTheDocument()
+ expect(await screen.findByText('workspace:Next Workspace')).toBeInTheDocument()
+ })
+
it('should provide workspace, permissions, and loading state', async () => {
renderConsoleBootstrap()
diff --git a/web/context/auth-session-state.ts b/web/context/auth-session-state.ts
new file mode 100644
index 00000000000..98d76d27f98
--- /dev/null
+++ b/web/context/auth-session-state.ts
@@ -0,0 +1,6 @@
+'use client'
+
+import { atom } from 'jotai'
+
+// A QueryClient.clear() does not discard observers cached by atomWithQuery.
+export const authSessionRevisionAtom = atom(0)
diff --git a/web/context/permission-state.ts b/web/context/permission-state.ts
index c96eb49056b..ec42d88f843 100644
--- a/web/context/permission-state.ts
+++ b/web/context/permission-state.ts
@@ -4,10 +4,12 @@ import { atom } from 'jotai'
import { atomWithQuery } from 'jotai-tanstack-query'
import { consoleQuery } from '@/service/console'
import { emptyWorkspacePermissionKeys } from './app-context-normalizers'
+import { authSessionRevisionAtom } from './auth-session-state'
-const workspacePermissionKeysQueryAtom = atomWithQuery(() =>
- consoleQuery.workspaces.current.rbac.myPermissions.get.queryOptions(),
-)
+const workspacePermissionKeysQueryAtom = atomWithQuery((get) => {
+ get(authSessionRevisionAtom)
+ return consoleQuery.workspaces.current.rbac.myPermissions.get.queryOptions()
+})
export const workspacePermissionKeysAtom = atom((get) => {
return (
diff --git a/web/context/workspace-state.ts b/web/context/workspace-state.ts
index bc66d1897ca..ccd1db0dd52 100644
--- a/web/context/workspace-state.ts
+++ b/web/context/workspace-state.ts
@@ -5,8 +5,10 @@ import { atomWithQuery } from 'jotai-tanstack-query'
import { consoleQuery } from '@/service/console'
import { initialWorkspaceSummary } from './app-context-defaults'
import { getWorkspaceRoleFlags, normalizeCurrentWorkspaceSummary } from './app-context-normalizers'
+import { authSessionRevisionAtom } from './auth-session-state'
-const currentWorkspaceQueryAtom = atomWithQuery(() => {
+const currentWorkspaceQueryAtom = atomWithQuery((get) => {
+ get(authSessionRevisionAtom)
return consoleQuery.workspaces.current.summary.get.queryOptions({
select: normalizeCurrentWorkspaceSummary,
})
diff --git a/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsx b/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsx
index b470d6286b3..5ee7bacc2e4 100644
--- a/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsx
+++ b/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsx
@@ -114,6 +114,7 @@ describe('AgentRosterList', () => {
workspacePermissions.canCreate = true
vi.spyOn(toast, 'error').mockReturnValue('toast-id')
vi.spyOn(toast, 'success').mockReturnValue('toast-id')
+ vi.spyOn(toast, 'warning').mockReturnValue('toast-id')
duplicateAgentMutationFn.mockResolvedValue(
createAgent({
id: 'agent-copy',
@@ -613,15 +614,25 @@ describe('AgentRosterList', () => {
).toBeDisabled()
})
- it('renders preview-only agent cards without navigation', () => {
+ it('explains preview-only access through the card without navigating', async () => {
+ const user = userEvent.setup()
workspacePermissions.canCreate = false
renderList([createAgent({ permission_keys: [AgentPermission.Preview] })])
const card = screen.getByRole('listitem', { name: 'Research Agent' })
+ const entry = within(card).getByRole('button', { name: 'Research Agent' })
expect(within(card).queryByRole('link', { name: 'Research Agent' })).not.toBeInTheDocument()
- expect(card).toHaveAccessibleDescription(
+ expect(entry).toHaveAccessibleDescription(
'agentV2.roster.usageStatus.draft Find and summarize market materials.',
)
+
+ await user.tab()
+ expect(entry).toHaveFocus()
+ await user.keyboard('{Enter}')
+ expect(toast.warning).toHaveBeenCalledWith('app.noAccessResourcePermission')
+
+ await user.click(entry)
+ expect(toast.warning).toHaveBeenCalledTimes(2)
})
it('links viewers to access points and hides mutation menus including the context menu', async () => {
diff --git a/web/features/agent-v2/roster/components/agent-roster-list.tsx b/web/features/agent-v2/roster/components/agent-roster-list.tsx
index 311fc27620b..1143a828b84 100644
--- a/web/features/agent-v2/roster/components/agent-roster-list.tsx
+++ b/web/features/agent-v2/roster/components/agent-roster-list.tsx
@@ -218,6 +218,7 @@ function AgentRosterItem({ agent }: { agent: AgentAppPartial }) {
const [activeDialog, setActiveDialog] = useState<'delete' | 'duplicate' | 'edit' | null>(null)
const { exportAppDsl, isExporting } = useExportAppDsl()
const capabilities = getAgentACLCapabilities(agent.permission_keys)
+ const isPreviewOnly = agent.permission_keys?.length === 1 && capabilities.canPreview
const canDuplicate = useCanCreateAgents() && capabilities.canPreview
const hasActions =
capabilities.canEdit ||
@@ -281,6 +282,10 @@ function AgentRosterItem({ agent }: { agent: AgentAppPartial }) {
})
}
+ const showPreviewOnlyAccessWarning = () => {
+ toast.warning(tApp(($) => $.noAccessResourcePermission))
+ }
+
const cardContent = (
<>
<div className="flex items-center gap-3 pt-3.5 pr-4 pb-2 pl-3.5">
@@ -325,7 +330,12 @@ function AgentRosterItem({ agent }: { agent: AgentAppPartial }) {
<li
aria-labelledby={nameId}
aria-describedby={defaultSection ? undefined : accessibleDescriptionIds || undefined}
- className="group relative isolate col-span-1 h-36.5 min-w-0 overflow-hidden rounded-xl border-[0.5px] border-solid border-components-card-border bg-components-card-bg shadow-xs shadow-shadow-shadow-3 transition-shadow duration-200 ease-in-out after:pointer-events-none after:absolute after:inset-0 after:z-1 after:rounded-xl after:content-[''] focus-within:bg-components-card-bg-alt hover:bg-components-card-bg-alt hover:shadow-md hover:shadow-shadow-shadow-5 has-data-popup-open:bg-components-card-bg-alt has-data-popup-open:shadow-md has-data-popup-open:shadow-shadow-shadow-5 has-[>a:focus-visible]:after:inset-ring-2 has-[>a:focus-visible]:after:inset-ring-state-accent-solid motion-reduce:transition-none [@media(hover:none)]:bg-components-card-bg-alt"
+ className={cn(
+ "group relative isolate col-span-1 h-36.5 min-w-0 overflow-hidden rounded-xl border-[0.5px] border-solid border-components-card-border bg-components-card-bg shadow-xs shadow-shadow-shadow-3 transition-shadow duration-200 ease-in-out after:pointer-events-none after:absolute after:inset-0 after:z-1 after:rounded-xl after:content-[''] focus-within:bg-components-card-bg-alt has-[>a:focus-visible]:after:inset-ring-2 has-[>a:focus-visible]:after:inset-ring-state-accent-solid has-[>button:focus-visible]:after:inset-ring-2 has-[>button:focus-visible]:after:inset-ring-state-accent-solid motion-reduce:transition-none",
+ isPreviewOnly
+ ? 'opacity-60'
+ : 'hover:bg-components-card-bg-alt hover:shadow-md hover:shadow-shadow-shadow-5 has-data-popup-open:bg-components-card-bg-alt has-data-popup-open:shadow-md has-data-popup-open:shadow-shadow-shadow-5 [@media(hover:none)]:bg-components-card-bg-alt',
+ )}
>
<ContextMenu>
<ContextMenuTrigger
@@ -339,6 +349,16 @@ function AgentRosterItem({ agent }: { agent: AgentAppPartial }) {
>
{cardContent}
</Link>
+ ) : isPreviewOnly ? (
+ <button
+ type="button"
+ aria-labelledby={nameId}
+ aria-describedby={accessibleDescriptionIds || undefined}
+ className={cn(cardClassName, 'w-full cursor-not-allowed text-left')}
+ onClick={showPreviewOnlyAccessWarning}
+ >
+ {cardContent}
+ </button>
) : (
<div className={cardClassName}>{cardContent}</div>
)
diff --git a/web/service/use-common.ts b/web/service/use-common.ts
index 21fd6748c07..5f779ecd7c4 100644
--- a/web/service/use-common.ts
+++ b/web/service/use-common.ts
@@ -13,7 +13,9 @@ import type {
StructuredOutputRulesResponse,
} from '@/models/common'
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useSetAtom } from 'jotai'
import { discardRegistrationSessionState } from '@/app/components/base/amplitude/registration-session-state'
+import { authSessionRevisionAtom } from '@/context/auth-session-state'
// oxlint-disable-next-line no-restricted-imports
import { get, post } from './base'
@@ -146,6 +148,7 @@ export const useSchemaTypeDefinitions = () => {
export const useLogout = () => {
const queryClient = useQueryClient()
+ const advanceAuthSession = useSetAtom(authSessionRevisionAtom)
return useMutation({
mutationKey: [NAME_SPACE, 'logout'],
mutationFn: () => post('/logout'),
@@ -159,6 +162,8 @@ export const useLogout = () => {
// need to be remembered here. systemFeatures (user-agnostic) just
// refetches once on the way to /signin, which is cheap.
queryClient.clear()
+ // Rebind account-scoped Jotai queries to the cleared cache.
+ advanceAuthSession((revision) => revision + 1)
},
})
}