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
fix(web): preserve Studio list filters across navigation (#44429)
Wu Tianwei7106ba8a5a90
diff --git a/web/app/components/app-sidebar/__tests__/app-detail-top.spec.tsx b/web/app/components/app-sidebar/__tests__/app-detail-top.spec.tsxindex 5c211911b31..65479e816e1 100644--- a/web/app/components/app-sidebar/__tests__/app-detail-top.spec.tsx+++ b/web/app/components/app-sidebar/__tests__/app-detail-top.spec.tsx@@ -1,7 +1,8 @@import { Dialog, DialogPopup, DialogPortal, DialogTitle } from '@langgenius/dify-ui/dialog'-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { gotoAnythingDialogHandle } from '@/app/components/goto-anything/dialog-handle'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { AppDetailTop } from '../app-detail-top'function TestGotoAnythingDialog() {diff --git a/web/app/components/app-sidebar/app-detail-top.tsx b/web/app/components/app-sidebar/app-detail-top.tsxindex f30f6b6085a..b91824a2f53 100644--- a/web/app/components/app-sidebar/app-detail-top.tsx+++ b/web/app/components/app-sidebar/app-detail-top.tsx@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next'import { DetailSidebarToggleButton } from '@/app/components/detail-sidebar/toggle-button'import { gotoAnythingDialogHandle } from '@/app/components/goto-anything/dialog-handle'import { GOTO_ANYTHING_HOTKEY } from '@/app/components/goto-anything/hotkeys'+import { useStudioListHref } from '@/features/studio-list-navigation'import Link from '@/next/link'type AppDetailTopProps = {@@ -24,6 +25,7 @@ type AppDetailTopProps = {export function AppDetailTop({ expand = true, onToggle }: AppDetailTopProps) {const { t } = useTranslation(['app', 'navigation'])+ const appsHref = useStudioListHref('/apps')if (!expand) {return (@@ -60,7 +62,7 @@ export function AppDetailTop({ expand = true, onToggle }: AppDetailTopProps) {<BreadcrumbSeparator className="system-md-regular" /><BreadcrumbItem className="shrink-0"><BreadcrumbLink- render={<Link href="/apps" />}+ render={<Link href={appsHref} />}className="rounded-lg px-1.5 py-2 system-sm-semibold-uppercase text-text-secondary hover:bg-background-default-hover hover:text-text-primary">{t(($) => $['menus.apps'], { ns: 'navigation' })}diff --git a/web/app/components/apps/__tests__/list.spec.tsx b/web/app/components/apps/__tests__/list.spec.tsxindex 347618bf75d..c2b7e143677 100644--- a/web/app/components/apps/__tests__/list.spec.tsx+++ b/web/app/components/apps/__tests__/list.spec.tsx@@ -1,5 +1,6 @@import type { AppPartial } from '@dify/contracts/api/console/apps/types.gen'import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'+import type { ReactNode } from 'react'import type { StepByStepTourSessionState } from '@/app/components/step-by-step-tour/types'import type { consoleClient } from '@/service/console'import type { ConsoleQueryTestOptions } from '@/test/console/query-data'@@ -9,6 +10,7 @@ import userEvent from '@testing-library/user-event'import { createStore, Provider as JotaiProvider } from 'jotai'import { queryClientAtom } from 'jotai-tanstack-query'import { NuqsTestingAdapter } from 'nuqs/adapters/testing'+import { AppDetailTop } from '@/app/components/app-sidebar/app-detail-top'import { stepByStepTourSessionAtom } from '@/app/components/step-by-step-tour/state'import { consoleQuery } from '@/service/console'import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'@@ -124,32 +126,47 @@ async function setup(const onUrlUpdate = vi.fn()const onCreateLearnDify = vi.fn()const onTryLearnDify = vi.fn()- await act(async () =>- renderWithConsoleQuery(- <NuqsTestingAdapter hasMemory searchParams={searchParams} onUrlUpdate={onUrlUpdate}>- <JotaiProvider store={store}>- <List onCreateLearnDify={onCreateLearnDify} onTryLearnDify={onTryLearnDify} />- </JotaiProvider>- </NuqsTestingAdapter>,- {- queryClient,- accountProfile: { id: 'creator-1' },- features: {},- workspacePermissionKeys: ['app.create_and_management', 'app.tag.manage'],- systemFeatures: {- rbac_enabled: true,- enable_learn_app: false,- enable_collaboration_mode: false,- },- ...options,- },- ),+ const list = <List onCreateLearnDify={onCreateLearnDify} onTryLearnDify={onTryLearnDify} />+ const route = (path: string, params: string, content: ReactNode) => (+ <JotaiProvider store={store}>+ <NuqsTestingAdapter key={path} hasMemory searchParams={params} onUrlUpdate={onUrlUpdate}>+ {content}+ </NuqsTestingAdapter>+ </JotaiProvider>)+ let rendered!: ReturnType<typeof renderWithConsoleQuery>+ await act(async () => {+ rendered = renderWithConsoleQuery(route('/apps', searchParams, list), {+ queryClient,+ accountProfile: { id: 'creator-1' },+ features: {},+ workspacePermissionKeys: ['app.create_and_management', 'app.tag.manage'],+ systemFeatures: {+ rbac_enabled: true,+ enable_learn_app: false,+ enable_collaboration_mode: false,+ },+ ...options,+ })+ })if (waitForResults)await waitFor(() =>expect(screen.queryByRole('status', { name: 'common.loading' })).not.toBeInTheDocument(),)- return { user: userEvent.setup(), onUrlUpdate, queryClient, onCreateLearnDify, onTryLearnDify }+ const navigate = async (href: string, content: ReactNode) => {+ const [path, params = ''] = href.split('?')+ api.searchParams = new URLSearchParams(params)+ await act(async () => rendered.rerender(route(path!, params, content)))+ }+ return {+ user: userEvent.setup(),+ onUrlUpdate,+ queryClient,+ onCreateLearnDify,+ onTryLearnDify,+ showDetail: () => navigate('/app/app-2/workflow', <AppDetailTop />),+ showList: (href: string) => navigate(href, list),+ }}beforeEach(() => {@@ -254,6 +271,79 @@ it('combines real creator and tag selections with URL filters for both catalogs'expect(scrollTo).toHaveBeenCalledWith({ top: 0 })})+it('restores creator and tag filters from the URL for both catalogs', async () => {+ await setup(+ '?creatorIDs=creator-1&tagIDs=tag-1&category=workflow&keywords=sales&sort_by=earliest_created',+ )+ const filters = {+ page: 1,+ name: 'sales',+ sort_by: 'earliest_created',+ creator_ids: ['creator-1'],+ tag_ids: ['tag-1'],+ mode: 'workflow',+ }+ expect(api.apps).toHaveBeenLastCalledWith({ query: { ...filters, limit: 30 } })+ expect(api.starred).toHaveBeenLastCalledWith({ query: { ...filters, limit: 100 } })+ expect(screen.getByRole('combobox', { name: 'Research' })).toHaveTextContent('Research')+})++it('retains selected creators and tags through the workflow return link', async () => {+ const { user, onUrlUpdate, showDetail, showList } = await setup('?category=workflow')+ await user.click(screen.getByRole('combobox', { name: 'app.studio.filters.creators' }))+ await user.click(await screen.findByRole('option', { name: /Alice/ }))+ await user.keyboard('{Escape}')+ await openTagFilter(user)+ await waitFor(() =>+ expect(onUrlUpdate.mock.lastCall?.[0].searchParams.get('tagIDs')).toBe('tag-1'),+ )++ await showDetail()+ const href = screen.getByRole('link', { name: 'navigation.menus.apps' }).getAttribute('href')!+ const params = new URLSearchParams(href.split('?')[1])+ expect(params.get('creatorIDs')).toBe('creator-1')+ expect(params.get('tagIDs')).toBe('tag-1')+ expect(params.get('category')).toBe('workflow')++ await showList(href)+ expect(screen.getByRole('combobox', { name: 'Research' })).toBeInTheDocument()+ await user.click(screen.getByRole('combobox', { name: 'app.studio.filters.creators' }))+ expect(await screen.findByRole('option', { name: /Alice/ })).toHaveAttribute(+ 'aria-selected',+ 'true',+ )+ expect(api.apps).toHaveBeenLastCalledWith({+ query: expect.objectContaining({+ creator_ids: ['creator-1'],+ tag_ids: ['tag-1'],+ mode: 'workflow',+ }),+ })+})++it('does not restore cleared creator and tag filters when returning from a workflow', async () => {+ const { user, onUrlUpdate, showDetail, showList } = await setup(+ '?creatorIDs=creator-1&tagIDs=tag-1',+ )+ await user.click(screen.getByRole('button', { name: 'app.studio.filters.reset' }))+ await user.click(screen.getByRole('button', { name: 'common.operation.clear' }))+ await waitFor(() => expect(onUrlUpdate.mock.lastCall?.[0].searchParams.toString()).toBe(''))+ await showDetail()+ expect(screen.getByRole('link', { name: 'navigation.menus.apps' })).toHaveAttribute(+ 'href',+ '/apps',+ )+ await showList('/apps')+ expect(screen.queryByRole('button', { name: 'app.studio.filters.reset' })).not.toBeInTheDocument()+ expect(screen.getByRole('combobox', { name: 'common.tag.placeholder' })).toBeInTheDocument()+ expect(api.apps).toHaveBeenLastCalledWith({+ query: expect.not.objectContaining({+ creator_ids: expect.anything(),+ tag_ids: expect.anything(),+ }),+ })+})+it('keeps previous main and starred cards while search resolves and announces empty results afterwards', async () => {api.starred.mockResolvedValue(page([app({ id: 'starred', name: 'Starred app' })]))const { user } = await setup()diff --git a/web/app/components/apps/app-card/index.tsx b/web/app/components/apps/app-card/index.tsxindex 56e1248efbc..83755519bb9 100644--- a/web/app/components/apps/app-card/index.tsx+++ b/web/app/components/apps/app-card/index.tsx@@ -13,9 +13,9 @@ import { UserAvatarList } from '@/app/components/base/user-avatar-list'import { toast } from '@/app/notifications'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { userProfileQueryOptions } from '@/features/account-profile/client'+import { StudioListLink } from '@/features/studio-list-navigation/navigation'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { AppCardTags } from '@/features/tag-management/components/app-card-tags'-import Link from '@/next/link'import { getRedirectionPath } from '@/utils/app-redirection'import {getAppACLCapabilities,@@ -201,7 +201,7 @@ export const AppCard = memo(stepByStepTourActionMenuOpen={stepByStepTourActionMenuOpen}stepByStepTourActionMenuHighlightPart={stepByStepTourActionMenuHighlightPart}>- <Link+ <StudioListLinkhref={appHref}aria-labelledby={appNameId}aria-describedby={app.description ? appDescriptionId : undefined}@@ -210,7 +210,7 @@ export const AppCard = memo(className={appCardClassName}>{appCardContent}- </Link>+ </StudioListLink></AppCardInteractions>)}<div className="absolute top-26 right-3 left-3 flex h-6.5 min-w-0 items-start">diff --git a/web/app/components/apps/app-list-header.tsx b/web/app/components/apps/app-list-header.tsxindex 167dc4f7ca1..671fd3a93d5 100644--- a/web/app/components/apps/app-list-header.tsx+++ b/web/app/components/apps/app-list-header.tsx@@ -15,8 +15,9 @@ import {getStepByStepTourGuides,STEP_BY_STEP_TOUR_TARGETS,} from '@/app/components/step-by-step-tour/target-registry'+import { useStudioListHref } from '@/features/studio-list-navigation'+import { StudioListLink } from '@/features/studio-list-navigation/navigation'import { TagFilter } from '@/features/tag-management/components/tag-filter'-import Link from '@/next/link'import { AppSortFilter } from './app-sort-filter'import { AppTypeFilter } from './app-type-filter'import CreatorsFilter from './creators-filter'@@ -64,6 +65,7 @@ export function AppListHeader({showCreateButton,}: AppListHeaderProps) {const { t } = useTranslation(['app', 'navigation'])+ const snippetsHref = useStudioListHref('/snippets')const activeStepByStepTourTaskId = useAtomValue(activeStepByStepTourTaskIdAtom)const activeStepByStepTourGuideIndex = useAtomValue(activeStepByStepTourGuideIndexAtom)const activeStepByStepTourGuideGroup = useAtomValue(activeStepByStepTourGuideGroupAtom)@@ -106,13 +108,13 @@ export function AppListHeader({/></div><div className="ml-auto flex max-w-full min-w-0 flex-wrap items-center justify-end gap-2">- <Link- href="/snippets"+ <StudioListLink+ href={snippetsHref}className="inline-flex h-8 cursor-pointer items-center justify-center gap-1 rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-3.5 text-[13px] leading-4 font-medium whitespace-nowrap text-components-button-secondary-text shadow-xs outline-hidden backdrop-blur-[5px] hover:border-components-button-secondary-border-hover hover:bg-components-button-secondary-bg-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid"><span aria-hidden className="i-ri-braces-line size-4 shrink-0" />{t(($) => $['studio.viewSnippets'], { ns: 'app' })}- </Link>+ </StudioListLink>{showCreateButton && (<CreateAppDropdownonCreateBlank={onCreateBlank}diff --git a/web/app/components/apps/list.tsx b/web/app/components/apps/list.tsxindex e13fa155177..24f2f064797 100644--- a/web/app/components/apps/list.tsx+++ b/web/app/components/apps/list.tsx@@ -13,9 +13,10 @@ import {} from '@langgenius/dify-ui/scroll-area'import { useDebounce } from 'ahooks'import { useAtomValue } from 'jotai'-import { useQueryStates } from 'nuqs'+import { throttle, useQueryStates } from 'nuqs'import { useCallback, useId, useMemo, useRef, useState } from 'react'import { workspacePermissionKeysAtom } from '@/context/permission-state'+import { StudioListNavigation } from '@/features/studio-list-navigation/navigation'import { CheckResultToast } from '@/hooks/use-pay'import { hasPermission } from '@/utils/permission'import { AppListCatalog } from './app-list-catalog'@@ -24,7 +25,7 @@ import { AppListHeader } from './app-list-header'import { AppListTagManagementModal } from './app-list-tag-management-modal'import { APP_LIST_SEARCH_DEBOUNCE_MS } from './constants'import { useDSLDragDrop } from './hooks/use-dsl-drag-drop'-import { appListQueryParsers } from './query-params'+import { appListQueryParsers, serializeAppListQuery } from './query-params'type AppListQuery = NonNullable<GetAppsData['query']>type AppListSortBy = NonNullable<AppListQuery['sort_by']>@@ -39,9 +40,7 @@ export function List({ onCreateLearnDify, onTryLearnDify }: Props) {const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)const [urlQuery, setUrlQuery] = useQueryStates(appListQueryParsers)- const { category, keywords, sort_by: sortBy } = urlQuery- const [creatorIDs, setCreatorIDs] = useState<string[]>([])- const [tagIDs, setTagIDs] = useState<string[]>([])+ const { category, keywords, creatorIDs, tagIDs, sort_by: sortBy } = urlQueryconst debouncedKeywords = useDebounce(keywords, { wait: APP_LIST_SEARCH_DEBOUNCE_MS })const dropZoneRef = useRef<HTMLDivElement>(null)const scrollViewportRef = useRef<HTMLDivElement>(null)@@ -93,7 +92,7 @@ export function List({ onCreateLearnDify, onTryLearnDify }: Props) {}const changeTagIDs = (nextTagIDs: string[]) => {resetCatalogScroll()- setTagIDs(nextTagIDs)+ void setUrlQuery({ tagIDs: nextTagIDs })}const changeKeywords = (nextKeywords: string) => {resetCatalogScroll()@@ -101,7 +100,7 @@ export function List({ onCreateLearnDify, onTryLearnDify }: Props) {}const changeCreatorIDs = (nextCreatorIDs: string[]) => {resetCatalogScroll()- setCreatorIDs(nextCreatorIDs)+ void setUrlQuery({ creatorIDs: nextCreatorIDs })}const changeSortBy = (nextSortBy: AppListSortBy) => {resetCatalogScroll()@@ -120,7 +119,11 @@ export function List({ onCreateLearnDify, onTryLearnDify }: Props) {const openTagManagement = useCallback(() => setShowTagManagementModal(true), [])return (- <>+ <StudioListNavigation+ path="/apps"+ href={serializeAppListQuery('/apps', urlQuery)}+ flush={() => setUrlQuery(urlQuery, { history: 'replace', limitUrlUpdates: throttle(0) })}+ ><divref={dropZoneRef}className="relative flex h-0 min-h-0 shrink-0 grow flex-col bg-background-body"@@ -197,6 +200,6 @@ export function List({ onCreateLearnDify, onTryLearnDify }: Props) {onOpenBlank={openCreateBlankModal}onOpenTemplate={openCreateTemplateDialog}/>- </>+ </StudioListNavigation>)}diff --git a/web/app/components/apps/query-params.ts b/web/app/components/apps/query-params.tsindex afadfedb428..a123b39cf6d 100644--- a/web/app/components/apps/query-params.ts+++ b/web/app/components/apps/query-params.ts@@ -1,7 +1,14 @@import type { GetAppsData } from '@dify/contracts/api/console/apps/types.gen'import type { inferParserType } from 'nuqs'import { zGetAppsQuery } from '@dify/contracts/api/console/apps/zod.gen'-import { createParser, debounce, parseAsString, parseAsStringLiteral } from 'nuqs'+import {+ createParser,+ createSerializer,+ debounce,+ parseAsArrayOf,+ parseAsString,+ parseAsStringLiteral,+} from 'nuqs'import { APP_TYPES } from './app-type'import { APP_LIST_SEARCH_DEBOUNCE_MS } from './constants'@@ -29,6 +36,8 @@ const parseAsAppListCategory = createParser({export const appListQueryParsers = {category: parseAsAppListCategory,+ creatorIDs: parseAsArrayOf(parseAsString, ';').withDefault([]),+ tagIDs: parseAsArrayOf(parseAsString, ';').withDefault([]),sort_by: parseAsStringLiteral(zGetAppsQuery.shape.sort_by.unwrap().unwrap().options).withDefault(zGetAppsQuery.shape.sort_by.parse(undefined),),@@ -37,4 +46,6 @@ export const appListQueryParsers = {}),}+export const serializeAppListQuery = createSerializer(appListQueryParsers)+export type AppListUrlQuery = inferParserType<typeof appListQueryParsers>diff --git a/web/app/components/apps/starred-app-card.tsx b/web/app/components/apps/starred-app-card.tsxindex 3d43c79e30f..8b98dcc636b 100644--- a/web/app/components/apps/starred-app-card.tsx+++ b/web/app/components/apps/starred-app-card.tsx@@ -11,8 +11,8 @@ import AppIcon from '@/app/components/base/app-icon'import { toast } from '@/app/notifications'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { userProfileQueryOptions } from '@/features/account-profile/client'+import { StudioListLink } from '@/features/studio-list-navigation/navigation'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import Link from '@/next/link'import { getRedirectionPath } from '@/utils/app-redirection'import { hasOnlyAppPreviewPermission } from '@/utils/permission'import { formatTime } from '@/utils/time'@@ -104,7 +104,7 @@ export const StarredAppCard = memo(</button>) : (<AppCardInteractions app={app}>- <Link+ <StudioListLinkhref={href}aria-labelledby={appNameId}data-step-by-step-tour-target={stepByStepTourCardTarget}@@ -112,7 +112,7 @@ export const StarredAppCard = memo(className={cardClassName}>{cardContent}- </Link>+ </StudioListLink></AppCardInteractions>)}</li>diff --git a/web/app/components/goto-anything/__tests__/index.spec.tsx b/web/app/components/goto-anything/__tests__/index.spec.tsxindex 23ed656677f..12511247653 100644--- a/web/app/components/goto-anything/__tests__/index.spec.tsx+++ b/web/app/components/goto-anything/__tests__/index.spec.tsx@@ -154,7 +154,9 @@ function setup({ datasetOperator = false, enableSkill = true, canInstall = true}async function openSearch() {triggerSearchShortcut()- return screen.findByRole('combobox', { name: 'app.gotoAnything.searchTitle' })+ const input = await screen.findByRole('combobox', { name: 'app.gotoAnything.searchTitle' })+ await waitFor(() => expect(input).toHaveFocus())+ return input}beforeEach(() => {diff --git a/web/app/components/main-nav/components/nav-link.tsx b/web/app/components/main-nav/components/nav-link.tsxindex 328437933db..f6f1d29831d 100644--- a/web/app/components/main-nav/components/nav-link.tsx+++ b/web/app/components/main-nav/components/nav-link.tsx@@ -3,6 +3,7 @@import type { ReactNode } from 'react'import type { MainNavItem } from '../types'import { cn } from '@langgenius/dify-ui/cn'+import { useStudioListHref } from '@/features/studio-list-navigation'import Link from '@/next/link'const NavIcon = ({ icon, className }: { icon: string; className?: string }) => (@@ -17,10 +18,11 @@ type MainNavLinkProps = {const MainNavLink = ({ item, pathname, children }: MainNavLinkProps) => {const activated = item.active(pathname)+ const appsHref = useStudioListHref('/apps')return (<Link- href={item.href}+ href={item.href === '/apps' ? appsHref : item.href}aria-current={activated ? 'page' : undefined}title={item.label}className={cn(diff --git a/web/app/components/snippet-list/__tests__/index.spec.tsx b/web/app/components/snippet-list/__tests__/index.spec.tsxindex a74708b85d0..8ba29bdf64a 100644--- a/web/app/components/snippet-list/__tests__/index.spec.tsx+++ b/web/app/components/snippet-list/__tests__/index.spec.tsx@@ -1,8 +1,10 @@-import { screen, waitFor, within } from '@testing-library/react'+import type { ReactNode } from 'react'+import { render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'import * as React from 'react'+import { SnippetDetailTop } from '@/app/components/snippets/components/snippet-detail-top'import { createConsoleQueryWrapper } from '@/test/console/query-data'-import { renderWithNuqs } from '@/test/nuqs-testing'import SnippetList from '..'const mockUseInfiniteSnippetList = vi.hoisted(() => vi.fn())@@ -160,16 +162,25 @@ const renderList = ({const { wrapper: ConsoleQueryWrapper } = createConsoleQueryWrapper({accountProfile: { id: 'creator-1' },})- const createList = () => (+ const onUrlUpdate = vi.fn()+ const createRoute = (path: string, params: string, content: ReactNode) => (<ConsoleQueryWrapper>- <SnippetList />+ <NuqsTestingAdapter key={path} searchParams={params} hasMemory onUrlUpdate={onUrlUpdate}>+ {content}+ </NuqsTestingAdapter></ConsoleQueryWrapper>)- const rendered = renderWithNuqs(createList(), { searchParams, hasMemory: true })+ const createList = () => createRoute('/snippets', searchParams, <SnippetList />)+ const rendered = render(createList())return {...rendered,+ onUrlUpdate,rerenderList: () => rendered.rerender(createList()),+ showDetail: () =>+ rendered.rerender(createRoute('/snippets/snippet-1/orchestrate', '', <SnippetDetailTop />)),+ showList: (href: string) =>+ rendered.rerender(createRoute('/snippets', href.split('?')[1] ?? '', <SnippetList />)),}}@@ -233,6 +244,94 @@ describe('SnippetList', () => {)})+ it('restores creator, tag and publication filters from the URL', () => {+ renderList({+ searchParams:+ '?creatorIDs=creator-1;creator-2&tagIDs=tag-1;tag-2&keywords=sales&publishStatus=draft',+ })+ expect(mockUseInfiniteSnippetList).toHaveBeenLastCalledWith(+ {+ page: 1,+ limit: 30,+ keyword: 'sales',+ creator_ids: ['creator-1', 'creator-2'],+ tag_ids: ['tag-1', 'tag-2'],+ is_published: false,+ },+ { enabled: true },+ )+ expect(screen.getByRole('button', { name: 'snippet.draft' })).toBeInTheDocument()+ })++ it('retains creator, tag and publication selections through the snippet return link', async () => {+ const user = userEvent.setup()+ const { onUrlUpdate, showDetail, showList } = renderList()+ await user.click(screen.getByRole('combobox', { name: 'app.studio.filters.creators' }))+ await user.click(await screen.findByRole('option', { name: /Alice/ }))+ await user.click(screen.getByRole('option', { name: /Bob/ }))+ await user.keyboard('{Escape}')+ await user.click(screen.getByRole('combobox', { name: 'common.tag.placeholder' }))+ await user.click(await screen.findByRole('option', { name: 'Sales' }))+ await user.keyboard('{Escape}')+ await user.click(+ screen.getByRole('button', { name: 'workflow.common.published / snippet.draft' }),+ )+ await user.click(await screen.findByRole('menuitemradio', { name: 'snippet.draft' }))+ await waitFor(() =>+ expect(onUrlUpdate.mock.lastCall?.[0].searchParams.get('publishStatus')).toBe('draft'),+ )++ showDetail()+ const href = screen.getByRole('link', { name: 'workflow.tabs.snippets' }).getAttribute('href')!+ const params = new URLSearchParams(href.split('?')[1])+ expect(params.get('creatorIDs')).toBe('creator-1;creator-2')+ expect(params.get('tagIDs')).toBe('tag-1')+ expect(params.get('publishStatus')).toBe('draft')+ showList(href)+ expect(screen.getByRole('button', { name: 'snippet.draft' })).toBeInTheDocument()+ expect(await screen.findByRole('combobox', { name: 'Sales' })).toBeInTheDocument()+ await user.click(screen.getByRole('combobox', { name: 'app.studio.filters.creators' }))+ expect(await screen.findByRole('option', { name: /Alice/ })).toHaveAttribute(+ 'aria-selected',+ 'true',+ )+ expect(screen.getByRole('option', { name: /Bob/ })).toHaveAttribute('aria-selected', 'true')+ expect(mockUseInfiniteSnippetList).toHaveBeenLastCalledWith(+ expect.objectContaining({+ creator_ids: ['creator-1', 'creator-2'],+ tag_ids: ['tag-1'],+ is_published: false,+ }),+ { enabled: true },+ )+ })++ it('does not restore cleared creators, tags or publication status', async () => {+ const user = userEvent.setup()+ const { onUrlUpdate, showDetail, showList } = renderList({+ searchParams: '?creatorIDs=creator-1&tagIDs=tag-1&publishStatus=published',+ })+ await user.click(screen.getByRole('button', { name: 'app.studio.filters.reset' }))+ await user.click(screen.getByRole('button', { name: 'common.operation.clear' }))+ await user.click(screen.getByRole('button', { name: 'workflow.common.published' }))+ await user.click(await screen.findByRole('menuitemradio', { name: 'app.types.all' }))+ await waitFor(() => expect(onUrlUpdate.mock.lastCall?.[0].searchParams.toString()).toBe(''))+ showDetail()+ expect(screen.getByRole('link', { name: 'workflow.tabs.snippets' })).toHaveAttribute(+ 'href',+ '/snippets',+ )+ showList('/snippets')+ expect(+ screen.queryByRole('button', { name: 'app.studio.filters.reset' }),+ ).not.toBeInTheDocument()+ expect(screen.getByRole('combobox', { name: 'common.tag.placeholder' })).toBeInTheDocument()+ expect(mockUseInfiniteSnippetList).toHaveBeenLastCalledWith(+ { page: 1, limit: 30, keyword: '' },+ { enabled: true },+ )+ })+it.each([{ label: 'workflow.common.published', published: true },{ label: 'snippet.draft', published: false },diff --git a/web/app/components/snippet-list/__tests__/reflow.browser.spec.tsx b/web/app/components/snippet-list/__tests__/reflow.browser.spec.tsxindex cd0896e9688..61f3fbfc20a 100644--- a/web/app/components/snippet-list/__tests__/reflow.browser.spec.tsx+++ b/web/app/components/snippet-list/__tests__/reflow.browser.spec.tsx@@ -12,6 +12,7 @@ const mockQueryState = vi.hoisted(() => ({creatorIDs: [] as string[],keywords: '',tagIDs: [] as string[],+ publishStatus: 'all' as const,}))vi.mock('@/service/use-snippets', async (importOriginal) => ({@@ -26,6 +27,8 @@ vi.mock('../hooks/use-snippets-query-state', () => ({setCreatorIDs: vi.fn(),setKeywords: vi.fn(),setTagIDs: vi.fn(),+ setPublishStatus: vi.fn(),+ flush: vi.fn().mockResolvedValue(new URLSearchParams()),}),}))diff --git a/web/app/components/snippet-list/components/snippet-card.tsx b/web/app/components/snippet-list/components/snippet-card.tsxindex b7df42b039e..244011cff75 100644--- a/web/app/components/snippet-list/components/snippet-card.tsx+++ b/web/app/components/snippet-list/components/snippet-card.tsx@@ -28,8 +28,8 @@ import {} from '@/app/components/snippets/utils/permission'import { toast } from '@/app/notifications'import { workspacePermissionKeysAtom } from '@/context/permission-state'+import { StudioListLink } from '@/features/studio-list-navigation/navigation'import { TagSelector } from '@/features/tag-management/components/tag-selector'-import Link from '@/next/link'import { consoleQuery } from '@/service/console'import {useDeleteSnippetMutation,@@ -146,7 +146,10 @@ const SnippetCard = ({return (<><article className="group relative col-span-1 inline-flex h-40 w-full cursor-pointer flex-col rounded-xl border border-solid border-components-card-border bg-components-card-bg shadow-sm transition-shadow duration-200 ease-in-out hover:shadow-lg">- <Link href={`/snippets/${snippet.id}/orchestrate`} className="flex min-h-0 flex-1 flex-col">+ <StudioListLink+ href={`/snippets/${snippet.id}/orchestrate`}+ className="flex min-h-0 flex-1 flex-col"+ ><div className="flex h-16.5 shrink-0 grow-0 flex-col justify-center px-3.5 pt-3.5 pb-3"><div className="flex items-center text-sm/5 font-semibold text-text-secondary"><div className="truncate" title={snippet.name}>@@ -168,7 +171,7 @@ const SnippetCard = ({{snippet.description}</div></div>- </Link>+ </StudioListLink><div className="absolute right-0 bottom-1 left-0 flex h-10.5 shrink-0 items-center pt-1 pr-1.5 pb-1.5 pl-3.5"><div className="flex w-0 grow items-center gap-1">diff --git a/web/app/components/snippet-list/components/snippet-publish-status-filter.tsx b/web/app/components/snippet-list/components/snippet-publish-status-filter.tsxindex 0a4484aff46..0e26f50dd2b 100644--- a/web/app/components/snippet-list/components/snippet-publish-status-filter.tsx+++ b/web/app/components/snippet-list/components/snippet-publish-status-filter.tsx@@ -1,5 +1,6 @@'use client'+import type { SnippetPublishStatus } from '../query-params'import { cn } from '@langgenius/dify-ui/cn'import {DropdownMenu,@@ -12,8 +13,6 @@ import {import { useMemo } from 'react'import { useTranslation } from 'react-i18next'-export type SnippetPublishStatus = 'all' | 'published' | 'draft'-type SnippetPublishStatusFilterProps = {value: SnippetPublishStatusonChange: (value: SnippetPublishStatus) => voiddiff --git a/web/app/components/snippet-list/hooks/__tests__/use-snippets-query-state.spec.tsx b/web/app/components/snippet-list/hooks/__tests__/use-snippets-query-state.spec.tsxindex de7ce130074..1fbb86695e9 100644--- a/web/app/components/snippet-list/hooks/__tests__/use-snippets-query-state.spec.tsx+++ b/web/app/components/snippet-list/hooks/__tests__/use-snippets-query-state.spec.tsx@@ -12,19 +12,27 @@ describe('useSnippetsQueryState', () => {vi.clearAllMocks()})- it('should parse URL filters without creator state', () => {- const { result } = renderWithAdapter('?tagIDs=tag1;tag2&keywords=search+term')+ it('parses all list filters from the URL', () => {+ const { result } = renderWithAdapter(+ '?tagIDs=tag1;tag2&keywords=search+term&creatorIDs=creator-1;creator-2&publishStatus=draft',+ )expect(result.current.query).toEqual({tagIDs: ['tag1', 'tag2'],keywords: 'search term',- creatorIDs: [],+ creatorIDs: ['creator-1', 'creator-2'],+ publishStatus: 'draft',})})it('should update tag IDs URL state', async () => {const { result, onUrlUpdate } = renderWithAdapter()- expect(result.current.query).toEqual({ tagIDs: [], keywords: '', creatorIDs: [] })+ expect(result.current.query).toEqual({+ tagIDs: [],+ keywords: '',+ creatorIDs: [],+ publishStatus: 'all',+ })act(() => {result.current.setTagIDs(['tag1', 'tag2'])@@ -60,7 +68,7 @@ describe('useSnippetsQueryState', () => {}})- it('should update creator IDs in local state without writing to the URL', () => {+ it('writes creator IDs to the URL and removes them when cleared', async () => {const { result, onUrlUpdate } = renderWithAdapter()act(() => {@@ -68,6 +76,52 @@ describe('useSnippetsQueryState', () => {})expect(result.current.query.creatorIDs).toEqual(['creator-1', 'creator-2'])- expect(onUrlUpdate).not.toHaveBeenCalled()+ await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled())+ expect(onUrlUpdate.mock.lastCall?.[0].searchParams.get('creatorIDs')).toBe(+ 'creator-1;creator-2',+ )+ await act(async () => result.current.setCreatorIDs([]))+ await waitFor(() =>+ expect(onUrlUpdate.mock.lastCall?.[0].searchParams.has('creatorIDs')).toBe(false),+ )+ })++ it('writes publication status to the URL and removes the default', async () => {+ const { result, onUrlUpdate } = renderWithAdapter()+ await act(async () => result.current.setPublishStatus('draft'))+ await waitFor(() =>+ expect(onUrlUpdate.mock.lastCall?.[0].searchParams.get('publishStatus')).toBe('draft'),+ )+ await act(async () => result.current.setPublishStatus('all'))+ await waitFor(() =>+ expect(onUrlUpdate.mock.lastCall?.[0].searchParams.has('publishStatus')).toBe(false),+ )+ })++ it('ignores an invalid publication status', () => {+ const { result } = renderWithAdapter('?publishStatus=invalid')+ expect(result.current.query.publishStatus).toBe('all')+ })++ it('commits pending search before navigation and cancels the delayed write', async () => {+ vi.useFakeTimers()+ try {+ const { result, onUrlUpdate } = renderWithAdapter()+ act(() => result.current.setKeywords('sales'))+ expect(onUrlUpdate).not.toHaveBeenCalled()+ await act(async () => {+ const pending = result.current.flush()+ await vi.runAllTimersAsync()+ await pending+ })+ expect(onUrlUpdate).toHaveBeenCalledOnce()+ expect(onUrlUpdate.mock.lastCall?.[0].searchParams.get('keywords')).toBe('sales')+ await act(async () => {+ await vi.advanceTimersByTimeAsync(SNIPPET_LIST_SEARCH_DEBOUNCE_MS + 100)+ })+ expect(onUrlUpdate).toHaveBeenCalledOnce()+ } finally {+ vi.useRealTimers()+ }})})diff --git a/web/app/components/snippet-list/hooks/use-snippets-query-state.ts b/web/app/components/snippet-list/hooks/use-snippets-query-state.tsindex a39a8f39335..1ffd29d8bd1 100644--- a/web/app/components/snippet-list/hooks/use-snippets-query-state.ts+++ b/web/app/components/snippet-list/hooks/use-snippets-query-state.ts@@ -1,42 +1,41 @@-import { debounce, parseAsArrayOf, parseAsString, useQueryStates } from 'nuqs'-import { useCallback, useMemo, useState } from 'react'-import { SNIPPET_LIST_SEARCH_DEBOUNCE_MS } from '../constants'--const snippetListQueryParsers = {- tagIDs: parseAsArrayOf(parseAsString, ';').withDefault([]).withOptions({ history: 'push' }),- keywords: parseAsString.withDefault('').withOptions({- limitUrlUpdates: debounce(SNIPPET_LIST_SEARCH_DEBOUNCE_MS),- }),-}+import type { SnippetPublishStatus } from '../query-params'+import { throttle, useQueryStates } from 'nuqs'+import { useCallback, useMemo } from 'react'+import { snippetListQueryParsers } from '../query-params'export function useSnippetsQueryState() {- const [urlQuery, setUrlQuery] = useQueryStates(snippetListQueryParsers)- const [creatorIDs, setCreatorIDs] = useState<string[]>([])+ const [query, setQuery] = useQueryStates(snippetListQueryParsers)const setKeywords = useCallback((keywords: string) => {- setUrlQuery({ keywords })+ void setQuery({ keywords })},- [setUrlQuery],+ [setQuery],)const setTagIDs = useCallback((tagIDs: string[]) => {- setUrlQuery({ tagIDs })+ void setQuery({ tagIDs })},- [setUrlQuery],+ [setQuery],)- const handleSetCreatorIDs = useCallback((creatorIDs: string[]) => {- setCreatorIDs(creatorIDs)- }, [])+ const setCreatorIDs = useCallback(+ (creatorIDs: string[]) => {+ void setQuery({ creatorIDs })+ },+ [setQuery],+ )- const query = useMemo(- () => ({- ...urlQuery,- creatorIDs,- }),- [creatorIDs, urlQuery],+ const setPublishStatus = useCallback(+ (publishStatus: SnippetPublishStatus) => {+ void setQuery({ publishStatus })+ },+ [setQuery],+ )+ const flush = useCallback(+ () => setQuery(query, { history: 'replace', limitUrlUpdates: throttle(0) }),+ [query, setQuery],)return useMemo(@@ -44,8 +43,10 @@ export function useSnippetsQueryState() {query,setKeywords,setTagIDs,- setCreatorIDs: handleSetCreatorIDs,+ setCreatorIDs,+ setPublishStatus,+ flush,}),- [handleSetCreatorIDs, query, setKeywords, setTagIDs],+ [flush, query, setCreatorIDs, setKeywords, setPublishStatus, setTagIDs],)}diff --git a/web/app/components/snippet-list/index.tsx b/web/app/components/snippet-list/index.tsxindex e8eea34b430..9c078e2e861 100644--- a/web/app/components/snippet-list/index.tsx+++ b/web/app/components/snippet-list/index.tsx@@ -1,6 +1,6 @@'use client'-import type { SnippetPublishStatus } from './components/snippet-publish-status-filter'+import type { SnippetPublishStatus } from './query-params'import type { SnippetListItem } from '@/types/snippet'import {Breadcrumb,@@ -20,9 +20,10 @@ import { useTranslation } from 'react-i18next'import { SearchInput } from '@/app/components/base/search-input'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { currentWorkspaceLoadingAtom } from '@/context/workspace-state'+import { useStudioListHref } from '@/features/studio-list-navigation'+import { StudioListLink, StudioListNavigation } from '@/features/studio-list-navigation/navigation'import { TagFilter } from '@/features/tag-management/components/tag-filter'import useDocumentTitle from '@/hooks/use-document-title'-import Link from '@/next/link'import { useInfiniteSnippetList } from '@/service/use-snippets'import CreatorsFilter from '../apps/creators-filter'import Empty from '../apps/empty'@@ -33,6 +34,7 @@ import SnippetCreateButton from './components/snippet-create-button'import SnippetPublishStatusFilter from './components/snippet-publish-status-filter'import { SNIPPET_LIST_SEARCH_DEBOUNCE_MS } from './constants'import { useSnippetsQueryState } from './hooks/use-snippets-query-state'+import { serializeSnippetListQuery } from './query-params'const TagManagementModal = dynamic(() =>@@ -73,18 +75,15 @@ const SnippetList = () => {const { t } = useTranslation(['common', 'workflow', 'navigation'])const isLoadingCurrentWorkspace = useAtomValue(currentWorkspaceLoadingAtom)const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)- // oxlint-disable-next-line eslint-react/use-state -- custom URL query hook, not React.useState- const {- query: { tagIDs, keywords, creatorIDs },- setKeywords,- setTagIDs,- setCreatorIDs,- } = useSnippetsQueryState()+ // oxlint-disable-next-line eslint-react/use-state -- the URL query hook returns named filter commands rather than a React state tuple+ const { query, setKeywords, setTagIDs, setCreatorIDs, setPublishStatus, flush } =+ useSnippetsQueryState()+ const { tagIDs, keywords, creatorIDs, publishStatus } = query+ const appsHref = useStudioListHref('/apps')const debouncedKeywords = useDebounce(keywords, { wait: SNIPPET_LIST_SEARCH_DEBOUNCE_MS })const containerRef = useRef<HTMLDivElement>(null)const anchorRef = useRef<HTMLDivElement>(null)const [showTagManagementModal, setShowTagManagementModal] = useState(false)- const [publishStatus, setPublishStatus] = useState<SnippetPublishStatus>('all')useDocumentTitle(t(($) => $['tabs.snippets'], { ns: 'workflow' }))@@ -182,97 +181,106 @@ const SnippetList = () => {: t(($) => $['tabs.noSnippetsFound'], { ns: 'workflow' })return (- <div- ref={containerRef}- className="relative flex h-0 shrink-0 grow flex-col overflow-y-auto bg-background-body"+ <StudioListNavigation+ path="/snippets"+ href={serializeSnippetListQuery('/snippets', query)}+ flush={flush}>- <StudioListHeader- title={- <Breadcrumb aria-label={t(($) => $['tabs.snippets'], { ns: 'workflow' })}>- <BreadcrumbList className="text-[18px]/[21.6px] font-semibold">- <BreadcrumbItem>- <BreadcrumbLink render={<Link href="/apps" />} className="block truncate">- {t(($) => $['menus.apps'], { ns: 'navigation' })}- </BreadcrumbLink>- </BreadcrumbItem>- <BreadcrumbSeparator className="text-base/6 font-light text-divider-deep" />- <BreadcrumbItem>- <h1 className="min-w-0 truncate">- <BreadcrumbPage>- {t(($) => $['tabs.snippets'], { ns: 'workflow' })}- </BreadcrumbPage>- </h1>- </BreadcrumbItem>- </BreadcrumbList>- </Breadcrumb>- }- >- <div className="flex flex-wrap items-center justify-between gap-2">- <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">- <CreatorsFilter value={creatorIDs} onChange={setCreatorIDs} />- <SnippetPublishStatusFilter value={publishStatus} onChange={setPublishStatus} />- <TagFilter- type="snippet"- value={tagIDs}- onChange={setTagIDs}- onOpenTagManagement={() => setShowTagManagementModal(true)}- />- <SearchInput- name="snippet-query"- className="w-full sm:w-50"- value={keywords}- onValueChange={setKeywords}- placeholder={t(($) => $['tabs.searchSnippets'], { ns: 'workflow' })}- aria-label={t(($) => $['tabs.searchSnippets'], { ns: 'workflow' })}- />- </div>- <SnippetCreateButton />- </div>- </StudioListHeader>- <div className="sr-only" role="status" aria-live="polite" aria-atomic="true">- {listStatus}- </div><div- aria-busy={isListBusy}- className={cn(- 'relative grid grow grid-cols-1 content-start gap-4 px-4 pt-2 sm:grid-cols-[repeat(auto-fill,minmax(296px,1fr))] sm:px-8',- !hasAnySnippet && 'overflow-hidden',- )}+ ref={containerRef}+ className="relative flex h-0 shrink-0 grow flex-col overflow-y-auto bg-background-body">- {showSkeleton ? (- <SnippetCardSkeleton count={6} />- ) : hasInitialQueryError ? (- <div className="col-span-full flex min-h-55 flex-col items-center justify-center gap-3 text-center">- <p className="system-md-medium text-text-secondary">{initialQueryErrorMessage}</p>- <Button variant="secondary" loading={isFetching} onClick={() => refetch()}>- {t(($) => $['operation.retry'], { ns: 'common' })}- </Button>+ <StudioListHeader+ title={+ <Breadcrumb aria-label={t(($) => $['tabs.snippets'], { ns: 'workflow' })}>+ <BreadcrumbList className="text-[18px]/[21.6px] font-semibold">+ <BreadcrumbItem>+ <BreadcrumbLink+ render={<StudioListLink href={appsHref} />}+ className="block truncate"+ >+ {t(($) => $['menus.apps'], { ns: 'navigation' })}+ </BreadcrumbLink>+ </BreadcrumbItem>+ <BreadcrumbSeparator className="text-base/6 font-light text-divider-deep" />+ <BreadcrumbItem>+ <h1 className="min-w-0 truncate">+ <BreadcrumbPage>+ {t(($) => $['tabs.snippets'], { ns: 'workflow' })}+ </BreadcrumbPage>+ </h1>+ </BreadcrumbItem>+ </BreadcrumbList>+ </Breadcrumb>+ }+ >+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">+ <CreatorsFilter value={creatorIDs} onChange={setCreatorIDs} />+ <SnippetPublishStatusFilter value={publishStatus} onChange={setPublishStatus} />+ <TagFilter+ type="snippet"+ value={tagIDs}+ onChange={setTagIDs}+ onOpenTagManagement={() => setShowTagManagementModal(true)}+ />+ <SearchInput+ name="snippet-query"+ className="w-full sm:w-50"+ value={keywords}+ onValueChange={setKeywords}+ placeholder={t(($) => $['tabs.searchSnippets'], { ns: 'workflow' })}+ aria-label={t(($) => $['tabs.searchSnippets'], { ns: 'workflow' })}+ />+ </div>+ <SnippetCreateButton /></div>- ) : hasAnySnippet ? (- snippets.map((snippet) => (- <SnippetCard- key={snippet.id}- snippet={snippet}- onOpenTagManagement={() => setShowTagManagementModal(true)}- onRefresh={refetch}- onTagsChange={refetch}- />- ))- ) : (- <Empty message={t(($) => $['tabs.noSnippetsFound'], { ns: 'workflow' })} />- )}- {isFetchingNextPage && <SnippetCardSkeleton count={3} />}- </div>- <div ref={anchorRef} className="h-0">- {' '}+ </StudioListHeader>+ <div className="sr-only" role="status" aria-live="polite" aria-atomic="true">+ {listStatus}+ </div>+ <div+ aria-busy={isListBusy}+ className={cn(+ 'relative grid grow grid-cols-1 content-start gap-4 px-4 pt-2 sm:grid-cols-[repeat(auto-fill,minmax(296px,1fr))] sm:px-8',+ !hasAnySnippet && 'overflow-hidden',+ )}+ >+ {showSkeleton ? (+ <SnippetCardSkeleton count={6} />+ ) : hasInitialQueryError ? (+ <div className="col-span-full flex min-h-55 flex-col items-center justify-center gap-3 text-center">+ <p className="system-md-medium text-text-secondary">{initialQueryErrorMessage}</p>+ <Button variant="secondary" loading={isFetching} onClick={() => refetch()}>+ {t(($) => $['operation.retry'], { ns: 'common' })}+ </Button>+ </div>+ ) : hasAnySnippet ? (+ snippets.map((snippet) => (+ <SnippetCard+ key={snippet.id}+ snippet={snippet}+ onOpenTagManagement={() => setShowTagManagementModal(true)}+ onRefresh={refetch}+ onTagsChange={refetch}+ />+ ))+ ) : (+ <Empty message={t(($) => $['tabs.noSnippetsFound'], { ns: 'workflow' })} />+ )}+ {isFetchingNextPage && <SnippetCardSkeleton count={3} />}+ </div>+ <div ref={anchorRef} className="h-0">+ {' '}+ </div>+ <TagManagementModal+ type="snippet"+ show={showTagManagementModal}+ onClose={() => setShowTagManagementModal(false)}+ onTagsChange={refetch}+ /></div>- <TagManagementModal- type="snippet"- show={showTagManagementModal}- onClose={() => setShowTagManagementModal(false)}- onTagsChange={refetch}- />- </div>+ </StudioListNavigation>)}diff --git a/web/app/components/snippet-list/query-params.ts b/web/app/components/snippet-list/query-params.tsnew file mode 100644index 00000000000..d6dc28f082d--- /dev/null+++ b/web/app/components/snippet-list/query-params.ts@@ -0,0 +1,21 @@+import type { inferParserType } from 'nuqs'+import {+ createSerializer,+ debounce,+ parseAsArrayOf,+ parseAsString,+ parseAsStringLiteral,+} from 'nuqs'+import { SNIPPET_LIST_SEARCH_DEBOUNCE_MS } from './constants'++export const snippetListQueryParsers = {+ creatorIDs: parseAsArrayOf(parseAsString, ';').withDefault([]),+ tagIDs: parseAsArrayOf(parseAsString, ';').withDefault([]).withOptions({ history: 'push' }),+ publishStatus: parseAsStringLiteral(['all', 'published', 'draft']).withDefault('all'),+ keywords: parseAsString.withDefault('').withOptions({+ limitUrlUpdates: debounce(SNIPPET_LIST_SEARCH_DEBOUNCE_MS),+ }),+}++export const serializeSnippetListQuery = createSerializer(snippetListQueryParsers)+export type SnippetPublishStatus = inferParserType<typeof snippetListQueryParsers>['publishStatus']diff --git a/web/app/components/snippets/components/__tests__/snippet-detail-top.spec.tsx b/web/app/components/snippets/components/__tests__/snippet-detail-top.spec.tsxindex c6a39b6b679..7843e3a626e 100644--- a/web/app/components/snippets/components/__tests__/snippet-detail-top.spec.tsx+++ b/web/app/components/snippets/components/__tests__/snippet-detail-top.spec.tsx@@ -1,5 +1,6 @@-import { render, screen, within } from '@testing-library/react'+import { screen, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { SnippetDetailTop } from '../snippet-detail-top'const back = vi.fn()diff --git a/web/app/components/snippets/components/snippet-detail-top.tsx b/web/app/components/snippets/components/snippet-detail-top.tsxindex 96791b28189..3bee4d6d67f 100644--- a/web/app/components/snippets/components/snippet-detail-top.tsx+++ b/web/app/components/snippets/components/snippet-detail-top.tsx@@ -16,6 +16,7 @@ import { useTranslation } from 'react-i18next'import { DetailSidebarToggleButton } from '@/app/components/detail-sidebar/toggle-button'import { gotoAnythingDialogHandle } from '@/app/components/goto-anything/dialog-handle'import { GOTO_ANYTHING_HOTKEY } from '@/app/components/goto-anything/hotkeys'+import { useStudioListHref } from '@/features/studio-list-navigation'import Link from '@/next/link'import { useRouter } from '@/next/navigation'@@ -27,6 +28,7 @@ type SnippetDetailTopProps = {export function SnippetDetailTop({ expand = true, onToggle }: SnippetDetailTopProps) {const { t } = useTranslation(['app', 'common', 'workflow', 'navigation'])const router = useRouter()+ const snippetsHref = useStudioListHref('/snippets')if (!expand) {return (@@ -67,7 +69,7 @@ export function SnippetDetailTop({ expand = true, onToggle }: SnippetDetailTopPr<BreadcrumbSeparator className="system-md-regular" /><BreadcrumbItem className="shrink-0"><BreadcrumbLink- render={<Link href="/snippets" />}+ render={<Link href={snippetsHref} />}className="rounded-lg px-1.5 py-2 system-sm-semibold-uppercase text-text-secondary hover:bg-background-default-hover hover:text-text-primary">{t(($) => $['tabs.snippets'], { ns: 'workflow' })}diff --git a/web/features/studio-list-navigation/__tests__/index.spec.tsx b/web/features/studio-list-navigation/__tests__/index.spec.tsxnew file mode 100644index 00000000000..13dcd8a6452--- /dev/null+++ b/web/features/studio-list-navigation/__tests__/index.spec.tsx@@ -0,0 +1,121 @@+import type { ContextType } from 'react'+import { act, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { RouterContext } from 'next/dist/shared/lib/router-context.shared-runtime'+import { AppDetailTop } from '@/app/components/app-sidebar/app-detail-top'+import MainNavLink from '@/app/components/main-nav/components/nav-link'+import { SnippetDetailTop } from '@/app/components/snippets/components/snippet-detail-top'+import { seedCurrentWorkspaceQuery } from '@/test/console/current-workspace'+import { renderWithConsoleQuery } from '@/test/console/query-data'+import { createDeferred } from '@/test/deferred'+import { StudioListLink, StudioListNavigation } from '../navigation'++const router = vi.hoisted(() => ({ push: vi.fn(), replace: vi.fn(), back: vi.fn() }))+vi.mock('@/next/navigation', () => ({ useRouter: () => router }))++const studioItem = {+ href: '/apps',+ label: 'Studio',+ icon: 'i-ri-apps-line',+ activeIcon: 'i-ri-apps-fill',+ active: () => false,+}++function Destinations() {+ return (+ <>+ <AppDetailTop />+ <SnippetDetailTop />+ <MainNavLink item={studioItem} pathname="/" />+ </>+ )+}++const flush = () => Promise.resolve(new URLSearchParams())+const remember = (path: '/apps' | '/snippets', href: string) => (+ <StudioListNavigation path={path} href={href} flush={flush}>+ <Destinations />+ </StudioListNavigation>+)+const appsLink = () => screen.getByRole('link', { name: 'navigation.menus.apps' })+const snippetsLink = () => screen.getByRole('link', { name: 'workflow.tabs.snippets' })++it('uses default destinations when there is no list history', () => {+ renderWithConsoleQuery(<Destinations />)+ expect(appsLink()).toHaveAttribute('href', '/apps')+ expect(snippetsLink()).toHaveAttribute('href', '/snippets')+ expect(screen.getByRole('link', { name: 'Studio' })).toHaveAttribute('href', '/apps')+})++it('retains independent apps and snippets destinations after leaving both lists', () => {+ const appsHref = '/apps?creatorIDs=alice&tagIDs=research&category=workflow'+ const snippetsHref = '/snippets?creatorIDs=bob&publishStatus=draft'+ const { rerender } = renderWithConsoleQuery(remember('/apps', appsHref))+ rerender(remember('/snippets', snippetsHref))+ rerender(<Destinations />)+ expect(appsLink()).toHaveAttribute('href', appsHref)+ expect(snippetsLink()).toHaveAttribute('href', snippetsHref)+ expect(screen.getByRole('link', { name: 'Studio' })).toHaveAttribute('href', appsHref)+})++it('keeps list destinations isolated by workspace', async () => {+ const { rerender, queryClient } = renderWithConsoleQuery(+ remember('/apps', '/apps?creatorIDs=alice'),+ )+ rerender(<Destinations />)+ await act(async () => seedCurrentWorkspaceQuery(queryClient, { id: 'workspace-2' }))+ await waitFor(() => expect(appsLink()).toHaveAttribute('href', '/apps'))+ expect(snippetsLink()).toHaveAttribute('href', '/snippets')+ rerender(remember('/apps', '/apps?creatorIDs=bob'))+ rerender(<Destinations />)+ await act(async () => seedCurrentWorkspaceQuery(queryClient, { id: 'workspace-1' }))+ await waitFor(() => expect(appsLink()).toHaveAttribute('href', '/apps?creatorIDs=alice'))+})++it.each(['/apps', '/snippets'] as const)(+ 'replaces the saved %s destination when filters are cleared',+ (path) => {+ const { rerender } = renderWithConsoleQuery(remember(path, `${path}?creatorIDs=alice`))+ rerender(remember(path, path))+ rerender(<Destinations />)+ expect(path === '/apps' ? appsLink() : snippetsLink()).toHaveAttribute('href', path)+ },+)++it('finishes pending URL writes before navigating to the editor', async () => {+ const user = userEvent.setup()+ const pending = createDeferred<URLSearchParams>()+ const flushPending = vi.fn(() => pending.promise)+ const linkRouter: NonNullable<ContextType<typeof RouterContext>> = {+ basePath: '',+ route: '/apps',+ pathname: '/apps',+ query: {},+ asPath: '/apps',+ isFallback: false,+ isLocaleDomain: false,+ isReady: true,+ isPreview: false,+ push: vi.fn().mockResolvedValue(true),+ replace: vi.fn().mockResolvedValue(true),+ reload: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn().mockResolvedValue(undefined),+ beforePopState: vi.fn(),+ events: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ }+ renderWithConsoleQuery(+ <RouterContext value={linkRouter}>+ <StudioListNavigation path="/apps" href="/apps?keywords=sales" flush={flushPending}>+ <StudioListLink href="/app/app-1/workflow">Edit workflow</StudioListLink>+ </StudioListNavigation>+ </RouterContext>,+ )+ await user.click(screen.getByRole('link', { name: 'Edit workflow' }))+ expect(flushPending).toHaveBeenCalledOnce()+ expect(router.push).not.toHaveBeenCalled()+ expect(linkRouter.push).not.toHaveBeenCalled()+ await act(async () => pending.resolve(new URLSearchParams('keywords=sales')))+ expect(router.push).toHaveBeenCalledExactlyOnceWith('/app/app-1/workflow', { scroll: undefined })+})diff --git a/web/features/studio-list-navigation/index.ts b/web/features/studio-list-navigation/index.tsnew file mode 100644index 00000000000..a1d0a41c255--- /dev/null+++ b/web/features/studio-list-navigation/index.ts@@ -0,0 +1,18 @@+'use client'++import { atom, useAtomValue } from 'jotai'+import { currentWorkspaceIdAtom } from '@/context/workspace-state'++export type StudioListPath = '/apps' | '/snippets'++export const listHrefsAtom = atom<Record<string, Partial<Record<StudioListPath, string>>>>({})+const appListHrefAtom = atom(+ (get) => get(listHrefsAtom)[get(currentWorkspaceIdAtom)]?.['/apps'] ?? '/apps',+)+const snippetListHrefAtom = atom(+ (get) => get(listHrefsAtom)[get(currentWorkspaceIdAtom)]?.['/snippets'] ?? '/snippets',+)++export function useStudioListHref(path: StudioListPath) {+ return useAtomValue(path === '/apps' ? appListHrefAtom : snippetListHrefAtom)+}diff --git a/web/features/studio-list-navigation/navigation.tsx b/web/features/studio-list-navigation/navigation.tsxnew file mode 100644index 00000000000..ccfc18b84a5--- /dev/null+++ b/web/features/studio-list-navigation/navigation.tsx@@ -0,0 +1,75 @@+'use client'++import type { ComponentProps, ReactNode } from 'react'+import type { StudioListPath } from '.'+import { useAtomValue, useSetAtom } from 'jotai'+import { createContext, use, useEffect } from 'react'+import { currentWorkspaceIdAtom } from '@/context/workspace-state'+import Link from '@/next/link'+import { useRouter } from '@/next/navigation'+import { listHrefsAtom } from '.'++type LinkProps = ComponentProps<typeof Link>+type NavigationEvent = Parameters<NonNullable<LinkProps['onNavigate']>>[0]+type NavigationOptions = Pick<LinkProps, 'replace' | 'scroll'>++const NavigationContext = createContext<+ ((event: NavigationEvent, href: string, options: NavigationOptions) => void) | null+>(null)++export function StudioListNavigation({+ path,+ href,+ flush,+ children,+}: {+ path: StudioListPath+ href: string+ flush: () => Promise<URLSearchParams>+ children: ReactNode+}) {+ const workspaceId = useAtomValue(currentWorkspaceIdAtom)+ const setListHrefs = useSetAtom(listHrefsAtom)+ const router = useRouter()++ // Retain this route's destination after it unmounts; filters are always read from the URL.+ useEffect(() => {+ if (!workspaceId) return++ setListHrefs((previous) => {+ if (previous[workspaceId]?.[path] === href) return previous++ return { ...previous, [workspaceId]: { ...previous[workspaceId], [path]: href } }+ })+ }, [href, path, setListHrefs, workspaceId])++ const navigate = (event: NavigationEvent, destination: string, options: NavigationOptions) => {+ event.preventDefault()+ // Finish debounced URL writes before creating the detail page's history entry.+ void flush().then(() => {+ const navigateTo = options.replace ? router.replace : router.push+ navigateTo(destination, { scroll: options.scroll })+ })+ }++ return <NavigationContext value={navigate}>{children}</NavigationContext>+}++export function StudioListLink({+ href,+ replace,+ scroll,+ ...props+}: Omit<LinkProps, 'href' | 'onNavigate'> & { href: string }) {+ const navigate = use(NavigationContext)++ return (+ <Link+ {...props}+ href={href}+ replace={replace}+ scroll={scroll}+ onNavigate={navigate ? (event) => navigate(event, href, { replace, scroll }) : undefined}+ />+ )+}