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
refactor(web): clarify education state ownership (#39748)
yyh3ad925a66a9a
diff --git a/web/app/components/app/overview/settings/__tests__/index.spec.tsx b/web/app/components/app/overview/settings/__tests__/index.spec.tsxindex e25acc23c6c..0096191f425 100644--- a/web/app/components/app/overview/settings/__tests__/index.spec.tsx+++ b/web/app/components/app/overview/settings/__tests__/index.spec.tsx@@ -72,7 +72,6 @@ const buildModalContext = (): ModalContextState => ({setShowModelLoadBalancingModal: vi.fn(),setShowOpeningModal: vi.fn(),setShowUpdatePluginModal: vi.fn(),- setShowEducationExpireNoticeModal: vi.fn(),setShowTriggerEventsLimitModal: vi.fn(),})diff --git a/web/app/components/apps/__tests__/index.spec.tsx b/web/app/components/apps/__tests__/index.spec.tsxindex a3142b53882..272bba9d9cc 100644--- a/web/app/components/apps/__tests__/index.spec.tsx+++ b/web/app/components/apps/__tests__/index.spec.tsx@@ -26,7 +26,6 @@ vi.mock('@/next/dynamic', () => ({}))let documentTitleCalls: string[] = []-let educationInitCalls: number = 0const mockHandleImportDSL = vi.fn()const mockHandleImportDSLConfirm = vi.fn()const mockTrackCreateApp = vi.fn()@@ -66,10 +65,12 @@ vi.mock('@/hooks/use-document-title', () => ({},}))-vi.mock('@/app/education-apply/hooks', () => ({- useEducationInit: () => {- educationInitCalls++- },+vi.mock('@/app/education-apply/expire-notice', () => ({+ EducationExpireNotice: () => null,+}))++vi.mock('@/app/education-apply/external-action-boundary', () => ({+ EducationExternalActionBoundary: ({ children }: { children: ReactNode }) => children,}))vi.mock('@/context/permission-state', async () => {@@ -255,7 +256,6 @@ describe('Apps', () => {beforeEach(() => {vi.clearAllMocks()documentTitleCalls = []- educationInitCalls = 0mockWorkspacePermissionKeys = ['app.create_and_management']mockSearchParams = new URLSearchParams()mockReplace.mockClear()diff --git a/web/app/components/apps/index.tsx b/web/app/components/apps/index.tsxindex c593b97ca90..6c0b3b89c07 100644--- a/web/app/components/apps/index.tsx+++ b/web/app/components/apps/index.tsx@@ -6,7 +6,8 @@ import type { TrackCreateAppParams } from '@/utils/create-app-tracking'import { useAtomValue } from 'jotai'import { useCallback, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useEducationInit } from '@/app/education-apply/hooks'+import { EducationExpireNotice } from '@/app/education-apply/expire-notice'+import { EducationExternalActionBoundary } from '@/app/education-apply/external-action-boundary'import AppListContext from '@/context/app-list-context'import { workspacePermissionKeysAtom } from '@/context/permission-state'import useDocumentTitle from '@/hooks/use-document-title'@@ -29,7 +30,7 @@ const ImportFromMarketplaceTemplateModal = dynamic({ ssr: false },)-const Apps = () => {+const AppsContent = () => {const { t } = useTranslation()const searchParams = useSearchParams()const { replace } = useRouter()@@ -39,7 +40,6 @@ const Apps = () => {const templateDismissedRef = useRef(false)useDocumentTitle(t(($) => $['menus.apps'], { ns: 'common' }))- useEducationInit()const [currentTryAppParams, setCurrentTryAppParams] = useState<TryAppSelection | undefined>(undefined,@@ -192,64 +192,73 @@ const Apps = () => {)return (- <AppListContext.Provider- value={{- currentApp: currentTryAppParams,- isShowTryAppPanel,- setShowTryAppPanel,- controlHideCreateFromTemplatePanel,- }}- >- <div className="relative flex h-0 shrink-0 grow flex-col overflow-y-auto bg-background-body">- <List- controlRefreshList={controlRefreshList}- onCreateLearnDify={handleCreateLearnDify}- onTryLearnDify={handleTryLearnDify}- />- {isShowTryAppPanel && currentTryAppParams && (- <TryApp- appId={currentTryAppParams.appId}- app={currentTryAppParams.app}- categories={currentTryAppParams.app.categories}- onClose={hideTryAppPanel}- onCreate={handleShowFromTryApp}+ <>+ <EducationExpireNotice />+ <AppListContext.Provider+ value={{+ currentApp: currentTryAppParams,+ isShowTryAppPanel,+ setShowTryAppPanel,+ controlHideCreateFromTemplatePanel,+ }}+ >+ <div className="relative flex h-0 shrink-0 grow flex-col overflow-y-auto bg-background-body">+ <List+ controlRefreshList={controlRefreshList}+ onCreateLearnDify={handleCreateLearnDify}+ onTryLearnDify={handleTryLearnDify}/>- )}-- {showDSLConfirmModal && (- <DSLConfirmModal- versions={versions}- onCancel={() => setShowDSLConfirmModal(false)}- onConfirm={onConfirmDSL}- confirmDisabled={isFetching}- />- )}-- {isShowCreateModal && (- <CreateAppModal- appIconType={currApp?.app.icon_type || 'emoji'}- appIcon={currApp?.app.icon || ''}- appIconBackground={currApp?.app.icon_background || ''}- appIconUrl={currApp?.app.icon_url}- appName={currApp?.app.name || ''}- appDescription={currApp?.app.description || ''}- show- onConfirm={onCreate}- confirmDisabled={isFetching}- onHide={() => setIsShowCreateModal(false)}- />- )}+ {isShowTryAppPanel && currentTryAppParams && (+ <TryApp+ appId={currentTryAppParams.appId}+ app={currentTryAppParams.app}+ categories={currentTryAppParams.app.categories}+ onClose={hideTryAppPanel}+ onCreate={handleShowFromTryApp}+ />+ )}- {canCreateApp && templateId && !templateDismissedRef.current && (- <ImportFromMarketplaceTemplateModal- templateId={templateId}- onClose={handleCloseTemplateModal}- onConfirm={handleMarketplaceTemplateConfirm}- />- )}- </div>- </AppListContext.Provider>+ {showDSLConfirmModal && (+ <DSLConfirmModal+ versions={versions}+ onCancel={() => setShowDSLConfirmModal(false)}+ onConfirm={onConfirmDSL}+ confirmDisabled={isFetching}+ />+ )}++ {isShowCreateModal && (+ <CreateAppModal+ appIconType={currApp?.app.icon_type || 'emoji'}+ appIcon={currApp?.app.icon || ''}+ appIconBackground={currApp?.app.icon_background || ''}+ appIconUrl={currApp?.app.icon_url}+ appName={currApp?.app.name || ''}+ appDescription={currApp?.app.description || ''}+ show+ onConfirm={onCreate}+ confirmDisabled={isFetching}+ onHide={() => setIsShowCreateModal(false)}+ />+ )}++ {canCreateApp && templateId && !templateDismissedRef.current && (+ <ImportFromMarketplaceTemplateModal+ templateId={templateId}+ onClose={handleCloseTemplateModal}+ onConfirm={handleMarketplaceTemplateConfirm}+ />+ )}+ </div>+ </AppListContext.Provider>+ </>)}+const Apps = () => (+ <EducationExternalActionBoundary>+ <AppsContent />+ </EducationExternalActionBoundary>+)+export default Appsdiff --git a/web/app/components/header/account-dropdown/index.tsx b/web/app/components/header/account-dropdown/index.tsxindex d9c81a13b04..c98e696ef06 100644--- a/web/app/components/header/account-dropdown/index.tsx+++ b/web/app/components/header/account-dropdown/index.tsx@@ -12,11 +12,6 @@ import { useAtomValue } from 'jotai'import { useState, useSyncExternalStore } from 'react'import { useTranslation } from 'react-i18next'import { resetUser } from '@/app/components/base/amplitude/utils'-import {- useSetEducationExpiredHasNoticed,- useSetEducationReverifyHasNoticed,- useSetEducationReverifyPrevExpireAt,-} from '@/app/education-apply/storage'import { userProfileAtom } from '@/context/account-state'import { langGeniusVersionInfoAtom } from '@/context/version-state'import { useRouter } from '@/next/navigation'@@ -49,9 +44,6 @@ export default function AppSelector({ trigger, variant = 'default' }: AccountDroconst { t } = useTranslation()const userProfile = useAtomValue(userProfileAtom)const langGeniusVersionInfo = useAtomValue(langGeniusVersionInfoAtom)- const clearEducationReverifyPrevExpireAt = useSetEducationReverifyPrevExpireAt()- const clearEducationReverifyHasNoticed = useSetEducationReverifyHasNoticed()- const clearEducationExpiredHasNoticed = useSetEducationExpiredHasNoticed()const { mutateAsync: logout } = useLogout()@@ -60,11 +52,6 @@ export default function AppSelector({ trigger, variant = 'default' }: AccountDroresetUser()// Tokens are now stored in cookies and cleared by backend- // To avoid use other account's education notice info- clearEducationReverifyPrevExpireAt(null)- clearEducationReverifyHasNoticed(null)- clearEducationExpiredHasNoticed(null)-router.push('/signin')}diff --git a/web/app/components/step-by-step-tour/__tests__/mount.spec.tsx b/web/app/components/step-by-step-tour/__tests__/mount.spec.tsxindex c9d09999467..f8b9624db1f 100644--- a/web/app/components/step-by-step-tour/__tests__/mount.spec.tsx+++ b/web/app/components/step-by-step-tour/__tests__/mount.spec.tsx@@ -65,6 +65,9 @@ const mockEnableStepByStepTour = vi.hoisted(() => ({const mockHasBlockingModalOpen = vi.hoisted(() => ({value: false,}))+const mockEducationExpireNotice = vi.hoisted(() => ({+ value: false,+}))const mockStepByStepTour = vi.hoisted(() => {const stateQueryKey = ['console', 'onboarding', 'step-by-step-tour', 'state'] as constconst createState = (@@ -211,6 +214,15 @@ vi.mock('@/context/modal-context', () => ({}),}))+vi.mock('@/app/education-apply/use-expire-notice', () => ({+ useEducationExpireNotice: () => [+ mockEducationExpireNotice.value+ ? { accountId: 'user-1', expireAt: 1, expired: false, phase: 'expiring' }+ : null,+ vi.fn(),+ ],+}))+vi.mock('@/next/navigation', () => ({usePathname: () => mockPathname,useRouter: () => ({ push: mockRouterPush }),@@ -535,6 +547,7 @@ describe('StepByStepTourMount', () => {mockEnableLearnApp.value = truemockEnableStepByStepTour.value = truemockHasBlockingModalOpen.value = false+ mockEducationExpireNotice.value = falsemockPathname = '/apps'localStorage.clear()mockStepByStepTour.reset()@@ -802,6 +815,40 @@ describe('StepByStepTourMount', () => {expect(document.body.querySelector('[data-base-ui-portal]')).not.toBeInTheDocument()})+ it('hides expanded tour overlays while the Education expiration notice is open', async () => {+ setStepByStepTourTestState({+ manuallyEnabledWorkspaceIds: ['workspace-1'],+ manuallyDisabledWorkspaceIds: [],+ minimized: false,+ completedTaskIds: [],+ skipped: false,+ })++ mockEducationExpireNotice.value = true+ renderStepByStepTourMount()++ await waitFor(() => {+ expect(screen.queryByRole('region', { name: 'Get to know Dify' })).not.toBeInTheDocument()+ })+ expect(document.body.querySelector('[data-base-ui-portal]')).not.toBeInTheDocument()+ })++ it('does not block the tour outside the Apps route for an unmounted Education notice', async () => {+ mockPathname = '/datasets'+ mockEducationExpireNotice.value = true+ setStepByStepTourTestState({+ manuallyEnabledWorkspaceIds: ['workspace-1'],+ manuallyDisabledWorkspaceIds: [],+ minimized: false,+ completedTaskIds: [],+ skipped: false,+ })++ renderStepByStepTourMount()++ expect(await screen.findByRole('region', { name: 'Get to know Dify' })).toBeInTheDocument()+ })+it('keeps the minimized tour entry available while a blocking modal is open', async () => {mockHasBlockingModalOpen.value = truelocalStorage.setItem(STEP_BY_STEP_TOUR_SHELL_MODE_STORAGE_KEY, 'collapsed')diff --git a/web/app/components/step-by-step-tour/mount.tsx b/web/app/components/step-by-step-tour/mount.tsxindex de604958905..e173c1e7997 100644--- a/web/app/components/step-by-step-tour/mount.tsx+++ b/web/app/components/step-by-step-tour/mount.tsx@@ -19,6 +19,7 @@ import {settingsQueryParser,} from '@/app/components/header/account-setting/query-params'import { buildIntegrationPath } from '@/app/components/integrations/routes'+import { useEducationExpireNotice } from '@/app/education-apply/use-expire-notice'import { useDocLink } from '@/context/i18n'import { useModalContextSelector } from '@/context/modal-context'import { workspacePermissionKeysAtom } from '@/context/permission-state'@@ -135,6 +136,7 @@ export default function StepByStepTourMount({ className }: StepByStepTourMountPrconst isCurrentWorkspaceManager = useAtomValue(isCurrentWorkspaceManagerAtom)const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)const hasBlockingModalOpen = useModalContextSelector((state) => state.hasBlockingModalOpen)+ const [educationExpireNotice] = useEducationExpireNotice()const [settingsDestination] = useQueryState(settingsQueryParamName, settingsQueryParser)const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const completedTaskIds = useAtomValue(completedStepByStepTourTaskIdsAtom)@@ -238,7 +240,11 @@ export default function StepByStepTourMount({ className }: StepByStepTourMountPrstepByStepTourFeatureEnabled &&enabledForCurrentWorkspace &&(hasActiveGuide || !shouldHideOnPathname(pathname))- const overlayVisible = visible && !hasBlockingModalOpen && !settingsDestination+ const overlayVisible =+ visible &&+ !hasBlockingModalOpen &&+ !settingsDestination &&+ !(pathname === '/apps' && educationExpireNotice)const completionPromptVisible = visible && allTasksCompleted && !activeTaskconst checklistMinimized = completionPromptVisible ? false : minimizedconst expanded = !checklistMinimizeddiff --git a/web/app/components/tools/edit-custom-collection-modal/__tests__/index.spec.tsx b/web/app/components/tools/edit-custom-collection-modal/__tests__/index.spec.tsxindex 021d0ee57b7..39505b3b2c0 100644--- a/web/app/components/tools/edit-custom-collection-modal/__tests__/index.spec.tsx+++ b/web/app/components/tools/edit-custom-collection-modal/__tests__/index.spec.tsx@@ -34,7 +34,6 @@ vi.mock('@/context/modal-context', () => ({setShowModelLoadBalancingModal: vi.fn(),setShowOpeningModal: vi.fn(),setShowUpdatePluginModal: vi.fn(),- setShowEducationExpireNoticeModal: vi.fn(),setShowTriggerEventsLimitModal: vi.fn(),}),}))diff --git a/web/app/education-apply/__tests__/expire-notice.spec.tsx b/web/app/education-apply/__tests__/expire-notice.spec.tsxnew file mode 100644index 00000000000..329dbd51552--- /dev/null+++ b/web/app/education-apply/__tests__/expire-notice.spec.tsx@@ -0,0 +1,161 @@+import { screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { createConsoleQueryWrapper } from '@/test/console/query-data'+import { render } from '@/test/console/render'+import { EducationExpireNotice } from '../expire-notice'+import { resolveEducationExpireNotice } from '../use-expire-notice'++const mockEducationStatus = vi.hoisted(() => ({+ allowRefresh: true,+ expireAt: Date.UTC(2099, 0, 1) / 1000,+ isLoading: false,+}))+const mockPricingModal = vi.hoisted(() => ({ isOpen: false }))++vi.mock('@/context/provider-context', () => ({+ useProviderContext: () => ({+ allowRefreshEducationVerify: mockEducationStatus.allowRefresh,+ educationAccountExpireAt: mockEducationStatus.expireAt,+ isLoadingEducationAccountInfo: mockEducationStatus.isLoading,+ }),+}))++vi.mock('@/hooks/use-query-params', () => ({+ usePricingModal: () => [mockPricingModal.isOpen, vi.fn()],+}))++vi.mock('@/next/dynamic', () => ({+ default:+ () =>+ ({ expired, onClose }: { expired: boolean; onClose: () => void }) => (+ <div role="dialog">+ <span>{expired ? 'Expired' : 'Expiring'}</span>+ <button type="button" onClick={onClose}>+ Close+ </button>+ </div>+ ),+}))++const renderNotice = (accountId = 'user-1') => {+ const { wrapper } = createConsoleQueryWrapper({+ accountProfile: { id: accountId, timezone: 'UTC' },+ })++ return render(<EducationExpireNotice />, { wrapper })+}++describe('EducationExpireNotice', () => {+ beforeEach(() => {+ localStorage.clear()+ mockEducationStatus.allowRefresh = true+ mockEducationStatus.expireAt = Date.UTC(2099, 0, 1) / 1000+ mockEducationStatus.isLoading = false+ mockPricingModal.isOpen = false+ })++ it('persists dismissal for the same account, expiration date, and phase', async () => {+ const user = userEvent.setup()+ const firstRender = renderNotice()++ expect(await screen.findByRole('dialog')).toHaveTextContent('Expiring')+ await user.click(screen.getByRole('button', { name: 'Close' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())++ firstRender.unmount()+ renderNotice()++ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ })++ it('shows a new notice when the expiration identity changes', async () => {+ const user = userEvent.setup()+ const firstRender = renderNotice()++ await user.click(await screen.findByRole('button', { name: 'Close' }))+ firstRender.unmount()+ mockEducationStatus.expireAt = Date.UTC(2020, 0, 1) / 1000+ renderNotice()++ expect(await screen.findByRole('dialog')).toHaveTextContent('Expired')+ })++ it('does not show while education status is unavailable', async () => {+ mockEducationStatus.isLoading = true++ renderNotice()++ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ })++ it('defers the notice while the URL-driven pricing modal is open', async () => {+ mockPricingModal.isOpen = true++ renderNotice()++ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ })+})++describe('resolveEducationExpireNotice', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-07-29T12:00:00Z'))+ })++ afterEach(() => {+ vi.useRealTimers()+ })++ it('treats expiring and expired reminders as distinct dismissal identities', () => {+ const expireAt = Date.parse('2026-07-30T00:00:00Z') / 1000+ const dismissedNotice = {+ accountId: 'user-1',+ expireAt,+ phase: 'expiring' as const,+ }++ expect(+ resolveEducationExpireNotice({+ accountId: 'user-1',+ allowRefresh: true,+ dismissedNotice,+ expireAt,+ isLoading: false,+ userTimezone: 'UTC',+ }),+ ).toBeNull()++ vi.setSystemTime(new Date('2026-07-30T12:00:00Z'))++ expect(+ resolveEducationExpireNotice({+ accountId: 'user-1',+ allowRefresh: true,+ dismissedNotice,+ expireAt,+ isLoading: false,+ userTimezone: 'UTC',+ }),+ ).toMatchObject({ expired: true, phase: 'expired' })+ })++ it('scopes a dismissed reminder to the account that dismissed it', () => {+ const expireAt = Date.parse('2026-08-01T00:00:00Z') / 1000++ expect(+ resolveEducationExpireNotice({+ accountId: 'user-2',+ allowRefresh: true,+ dismissedNotice: {+ accountId: 'user-1',+ expireAt,+ phase: 'expiring',+ },+ expireAt,+ isLoading: false,+ userTimezone: 'UTC',+ }),+ ).toMatchObject({ accountId: 'user-2', phase: 'expiring' })+ })+})diff --git a/web/app/education-apply/__tests__/external-action-boundary.spec.tsx b/web/app/education-apply/__tests__/external-action-boundary.spec.tsxnew file mode 100644index 00000000000..6dafc4f9980--- /dev/null+++ b/web/app/education-apply/__tests__/external-action-boundary.spec.tsx@@ -0,0 +1,142 @@+import type { ComponentType } from 'react'+import { screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { lazy, StrictMode, Suspense } from 'react'+import { render } from '@/test/console/render'+import { EducationExternalActionBoundary } from '../external-action-boundary'++const mockMutate = vi.fn()+const mockReplace = vi.fn()+const mockMutationState = vi.hoisted(() => ({ isError: false }))+const mockSearchParams = vi.hoisted(() => ({+ value: new URLSearchParams('action=educationReVerify'),+}))++vi.mock('@/next/navigation', () => ({+ useRouter: () => ({ replace: mockReplace }),+ useSearchParams: () => mockSearchParams.value,+}))++vi.mock('@/next/dynamic', () => ({+ default: (loader: () => Promise<ComponentType>, options: { loading?: ComponentType }) => {+ const LazyComponent = lazy(async () => ({ default: await loader() }))+ const Loading = options.loading++ return function DynamicComponent(props: Record<string, unknown>) {+ return (+ <Suspense fallback={Loading ? <Loading /> : null}>+ <LazyComponent {...props} />+ </Suspense>+ )+ }+ },+}))++vi.mock('@/service/use-education', () => ({+ useEducationVerify: () => ({+ isError: mockMutationState.isError,+ mutate: mockMutate,+ }),+}))++vi.mock('@/app/components/full-screen-loading', () => ({+ FullScreenLoading: () => <div>Loading</div>,+}))++vi.mock('../verify-state-modal', () => ({+ default: ({+ confirmText,+ isShow,+ onCancel,+ onConfirm,+ }: {+ confirmText: string+ isShow: boolean+ onCancel: () => void+ onConfirm: () => void+ }) =>+ isShow ? (+ <div role="dialog">+ <button type="button" onClick={onConfirm}>+ {confirmText}+ </button>+ <button type="button" onClick={onCancel}>+ Cancel+ </button>+ </div>+ ) : null,+}))++describe('EducationExternalActionBoundary', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockMutationState.isError = false+ mockSearchParams.value = new URLSearchParams('action=educationReVerify')+ })++ it('ignores unsupported actions', () => {+ mockSearchParams.value = new URLSearchParams('action=unknown')++ render(<EducationExternalActionBoundary>Apps</EducationExternalActionBoundary>)++ expect(screen.getByText('Apps')).toBeInTheDocument()+ expect(mockMutate).not.toHaveBeenCalled()+ })++ it('starts re-verification once and replaces the command URL with the token page', async () => {+ mockMutate.mockImplementation(+ (_variables: undefined, options: { onSuccess: (result: { token: string }) => void }) =>+ options.onSuccess({ token: 'education-token' }),+ )++ render(+ <StrictMode>+ <EducationExternalActionBoundary>Apps</EducationExternalActionBoundary>+ </StrictMode>,+ )++ await waitFor(() => {+ expect(mockMutate).toHaveBeenCalledTimes(1)+ expect(mockReplace).toHaveBeenCalledWith('/education-apply?token=education-token')+ })+ })++ it('retries a failed verification only after explicit confirmation', async () => {+ mockMutationState.isError = true+ const user = userEvent.setup()++ render(<EducationExternalActionBoundary>Apps</EducationExternalActionBoundary>)++ await waitFor(() => expect(mockMutate).toHaveBeenCalledTimes(1))+ await user.click(await screen.findByRole('button', { name: 'common.errorBoundary.tryAgain' }))++ expect(mockMutate).toHaveBeenCalledTimes(2)+ })++ it('returns to Apps when the verification error is dismissed', async () => {+ mockMutationState.isError = true+ const user = userEvent.setup()++ render(<EducationExternalActionBoundary>Apps</EducationExternalActionBoundary>)++ await user.click(await screen.findByRole('button', { name: 'Cancel' }))++ expect(mockReplace).toHaveBeenCalledWith('/apps')+ })++ it('canonicalizes the active Education pricing link', async () => {+ mockSearchParams.value = new URLSearchParams('action=educationPricing&utm_source=email')++ render(+ <StrictMode>+ <EducationExternalActionBoundary>Apps</EducationExternalActionBoundary>+ </StrictMode>,+ )++ await waitFor(() => {+ expect(mockReplace).toHaveBeenCalledTimes(1)+ expect(mockReplace).toHaveBeenCalledWith('/apps?utm_source=email&pricing=open')+ })+ expect(mockMutate).not.toHaveBeenCalled()+ })+})diff --git a/web/app/education-apply/expire-notice.tsx b/web/app/education-apply/expire-notice.tsxnew file mode 100644index 00000000000..c0a6de1ad52--- /dev/null+++ b/web/app/education-apply/expire-notice.tsx@@ -0,0 +1,22 @@+'use client'++import { usePricingModal } from '@/hooks/use-query-params'+import dynamic from '@/next/dynamic'+import { useEducationExpireNotice } from './use-expire-notice'++const ExpireNoticeModal = dynamic(() => import('./expire-notice-modal'), { ssr: false })++export function EducationExpireNotice() {+ const [isPricingModalOpen] = usePricingModal()+ const [notice, dismissNotice] = useEducationExpireNotice()++ if (!notice || isPricingModalOpen) return null++ return (+ <ExpireNoticeModal+ expireAt={notice.expireAt}+ expired={notice.expired}+ onClose={dismissNotice}+ />+ )+}diff --git a/web/app/education-apply/external-action-boundary.tsx b/web/app/education-apply/external-action-boundary.tsxnew file mode 100644index 00000000000..067422c9a01--- /dev/null+++ b/web/app/education-apply/external-action-boundary.tsx@@ -0,0 +1,46 @@+'use client'++import type { ReactNode } from 'react'+import { useEffect, useRef } from 'react'+import { FullScreenLoading } from '@/app/components/full-screen-loading'+import dynamic from '@/next/dynamic'+import { useRouter, useSearchParams } from '@/next/navigation'++const EDUCATION_REVERIFY_ACTION = 'educationReVerify'+const EDUCATION_PRICING_ACTION = 'educationPricing'++const EducationReverifyFlow = dynamic(+ () => import('./reverify-flow').then((module) => module.EducationReverifyFlow),+ {+ ssr: false,+ loading: FullScreenLoading,+ },+)++function EducationPricingRedirect({ searchParamsString }: { searchParamsString: string }) {+ const router = useRouter()+ const redirectedRef = useRef(false)++ useEffect(() => {+ if (redirectedRef.current) return++ redirectedRef.current = true+ const searchParams = new URLSearchParams(searchParamsString)+ searchParams.delete('action')+ searchParams.set('pricing', 'open')+ router.replace(`/apps?${searchParams.toString()}`)+ }, [router, searchParamsString])++ return <FullScreenLoading />+}++export function EducationExternalActionBoundary({ children }: { children: ReactNode }) {+ const searchParams = useSearchParams()+ const action = searchParams.get('action')++ if (action === EDUCATION_REVERIFY_ACTION) return <EducationReverifyFlow />+ if (action === EDUCATION_PRICING_ACTION)+ return <EducationPricingRedirect searchParamsString={searchParams.toString()} />++ return children+}diff --git a/web/app/education-apply/hooks.ts b/web/app/education-apply/hooks.tsindex abb91ea6930..45631b61b6e 100644--- a/web/app/education-apply/hooks.ts+++ b/web/app/education-apply/hooks.ts@@ -1,22 +1,8 @@import type { SearchParams } from './types'-import { useQuery } from '@tanstack/react-query'import { useDebounceFn } from 'ahooks'-import dayjs from 'dayjs'-import timezone from 'dayjs/plugin/timezone'-import utc from 'dayjs/plugin/utc'-import { useCallback, useEffect, useState } from 'react'-import {- useEducationExpiredHasNoticed,- useEducationReverifyHasNoticed,- useEducationReverifyPrevExpireAt,-} from '@/app/education-apply/storage'-import { useModalContextSelector } from '@/context/modal-context'-import { useProviderContext } from '@/context/provider-context'-import { userProfileQueryOptions } from '@/features/account-profile/client'+import { useCallback, useState } from 'react'import { useEducationAutocomplete } from '@/service/use-education'-dayjs.extend(utc)-dayjs.extend(timezone)export const useEducation = () => {const { mutateAsync, isPending, data } = useEducationAutocomplete()@@ -54,74 +40,3 @@ export const useEducation = () => {hasNext: data?.has_next,}}--type useEducationReverifyNoticeParams = {- onNotice: ({ expireAt, expired }: { expireAt: number; expired: boolean }) => void-}--const isExpired = (expireAt?: number, timezone?: string) => {- if (!expireAt || !timezone) return false- const today = dayjs().tz(timezone).startOf('day')- const expiredDay = dayjs.unix(expireAt).tz(timezone).startOf('day')- return today.isSame(expiredDay) || today.isAfter(expiredDay)-}--const useEducationReverifyNotice = ({ onNotice }: useEducationReverifyNoticeParams) => {- const { data: timezone } = useQuery({- ...userProfileQueryOptions(),- select: (data) => data.profile.timezone ?? undefined,- })- // const [educationInfo, setEducationInfo] = useState<{ is_student: boolean, allow_refresh: boolean, expire_at: number | null } | null>(null)- // const isLoading = !educationInfo- const {- educationAccountExpireAt,- allowRefreshEducationVerify,- isLoadingEducationAccountInfo: isLoading,- } = useProviderContext()- const [prevExpireAt, setPrevExpireAt] = useEducationReverifyPrevExpireAt()- const [reverifyHasNoticed, setReverifyHasNoticed] = useEducationReverifyHasNoticed()- const [expiredHasNoticed, setExpiredHasNoticed] = useEducationExpiredHasNoticed()-- useEffect(() => {- if (isLoading || !timezone) return- if (allowRefreshEducationVerify) {- const expired = isExpired(educationAccountExpireAt!, timezone)- const isExpireAtChanged = prevExpireAt !== educationAccountExpireAt- if (isExpireAtChanged) {- setPrevExpireAt(educationAccountExpireAt!)- setReverifyHasNoticed(false)- setExpiredHasNoticed(false)- }- const shouldNotice = (() => {- if (isExpireAtChanged) return true- return expired ? !expiredHasNoticed : !reverifyHasNoticed- })()- if (shouldNotice) {- onNotice({- expireAt: educationAccountExpireAt!,- expired,- })- if (expired) setExpiredHasNoticed(true)- else setReverifyHasNoticed(true)- }- }- }, [allowRefreshEducationVerify, timezone])-- return {- isLoading,- expireAt: educationAccountExpireAt!,- expired: isExpired(educationAccountExpireAt!, timezone),- }-}--export const useEducationInit = () => {- const setShowEducationExpireNoticeModal = useModalContextSelector(- (s) => s.setShowEducationExpireNoticeModal,- )-- useEducationReverifyNotice({- onNotice: (payload) => {- setShowEducationExpireNoticeModal({ payload })- },- })-}diff --git a/web/app/education-apply/reverify-flow.tsx b/web/app/education-apply/reverify-flow.tsxnew file mode 100644index 00000000000..45a95ac79ec--- /dev/null+++ b/web/app/education-apply/reverify-flow.tsx@@ -0,0 +1,45 @@+'use client'++import { useCallback, useEffect, useRef } from 'react'+import { useTranslation } from 'react-i18next'+import { FullScreenLoading } from '@/app/components/full-screen-loading'+import { useRouter } from '@/next/navigation'+import { useEducationVerify } from '@/service/use-education'+import VerifyStateModal from './verify-state-modal'++export function EducationReverifyFlow() {+ const { t } = useTranslation()+ const router = useRouter()+ const verificationStartedRef = useRef(false)+ const { isError, mutate } = useEducationVerify()++ const startVerification = useCallback(() => {+ if (verificationStartedRef.current) return++ verificationStartedRef.current = true+ mutate(undefined, {+ onSuccess: ({ token }) => {+ router.replace(`/education-apply?token=${token}`)+ },+ })+ }, [mutate, router])++ useEffect(() => {+ startVerification()+ }, [startVerification])++ if (!isError) return <FullScreenLoading />++ return (+ <VerifyStateModal+ isShow+ title={t(($) => $['errorBoundary.title'], { ns: 'common' })}+ confirmText={t(($) => $['errorBoundary.tryAgain'], { ns: 'common' })}+ onConfirm={() => {+ verificationStartedRef.current = false+ startVerification()+ }}+ onCancel={() => router.replace('/apps')}+ />+ )+}diff --git a/web/app/education-apply/storage.ts b/web/app/education-apply/storage.tsindex fc7e764d62a..5172a533761 100644--- a/web/app/education-apply/storage.ts+++ b/web/app/education-apply/storage.ts@@ -1,28 +1,17 @@import { createLocalStorageState } from 'foxact/create-local-storage-state'-const [- useEducationReverifyPrevExpireAt,- _useEducationReverifyPrevExpireAtValue,- useSetEducationReverifyPrevExpireAt,-] = createLocalStorageState<number>('education-reverify-prev-expire-at', 0)+export type EducationExpireNoticePhase = 'expiring' | 'expired'-const [- useEducationReverifyHasNoticed,- _useEducationReverifyHasNoticedValue,- useSetEducationReverifyHasNoticed,-] = createLocalStorageState<boolean>('education-reverify-has-noticed', false)+export type DismissedEducationExpireNotice = {+ accountId: string+ expireAt: number+ phase: EducationExpireNoticePhase+}-const [- useEducationExpiredHasNoticed,- _useEducationExpiredHasNoticedValue,- useSetEducationExpiredHasNoticed,-] = createLocalStorageState<boolean>('education-expired-has-noticed', false)+const [useDismissedEducationExpireNotice] =+ createLocalStorageState<DismissedEducationExpireNotice | null>(+ 'dismissed-education-expire-notice',+ null,+ )-export {- useEducationExpiredHasNoticed,- useEducationReverifyHasNoticed,- useEducationReverifyPrevExpireAt,- useSetEducationExpiredHasNoticed,- useSetEducationReverifyHasNoticed,- useSetEducationReverifyPrevExpireAt,-}+export { useDismissedEducationExpireNotice }diff --git a/web/app/education-apply/use-expire-notice.ts b/web/app/education-apply/use-expire-notice.tsnew file mode 100644index 00000000000..f109ea9c3bf--- /dev/null+++ b/web/app/education-apply/use-expire-notice.ts@@ -0,0 +1,93 @@+'use client'++import type { DismissedEducationExpireNotice, EducationExpireNoticePhase } from './storage'+import { useQuery } from '@tanstack/react-query'+import dayjs from 'dayjs'+import timezone from 'dayjs/plugin/timezone'+import utc from 'dayjs/plugin/utc'+import { useProviderContext } from '@/context/provider-context'+import { userProfileQueryOptions } from '@/features/account-profile/client'+import { useDismissedEducationExpireNotice } from './storage'++dayjs.extend(utc)+dayjs.extend(timezone)++export type EducationExpireNotice = {+ accountId: string+ expireAt: number+ expired: boolean+ phase: EducationExpireNoticePhase+}++type ResolveEducationExpireNoticeParams = {+ accountId?: string+ allowRefresh: boolean+ dismissedNotice: DismissedEducationExpireNotice | null+ expireAt: number | null+ isLoading: boolean+ userTimezone?: string+}++const isSameNotice = (+ dismissedNotice: DismissedEducationExpireNotice | null,+ notice: EducationExpireNotice,+) =>+ dismissedNotice?.accountId === notice.accountId &&+ dismissedNotice.expireAt === notice.expireAt &&+ dismissedNotice.phase === notice.phase++export const resolveEducationExpireNotice = ({+ accountId,+ allowRefresh,+ dismissedNotice,+ expireAt,+ isLoading,+ userTimezone,+}: ResolveEducationExpireNoticeParams): EducationExpireNotice | null => {+ if (isLoading || !accountId || !userTimezone || !allowRefresh || expireAt === null) return null++ const today = dayjs().tz(userTimezone).startOf('day')+ const expireDay = dayjs.unix(expireAt).tz(userTimezone).startOf('day')+ const expired = today.isSame(expireDay) || today.isAfter(expireDay)+ const notice: EducationExpireNotice = {+ accountId,+ expireAt,+ expired,+ phase: expired ? 'expired' : 'expiring',+ }++ return isSameNotice(dismissedNotice, notice) ? null : notice+}++export function useEducationExpireNotice() {+ const { data: profile } = useQuery({+ ...userProfileQueryOptions(),+ select: ({ profile }) => ({+ accountId: profile.id,+ timezone: profile.timezone ?? undefined,+ }),+ })+ const { educationAccountExpireAt, allowRefreshEducationVerify, isLoadingEducationAccountInfo } =+ useProviderContext()+ const [dismissedNotice, setDismissedNotice] = useDismissedEducationExpireNotice()+ const notice = resolveEducationExpireNotice({+ accountId: profile?.accountId,+ allowRefresh: allowRefreshEducationVerify,+ dismissedNotice,+ expireAt: educationAccountExpireAt,+ isLoading: isLoadingEducationAccountInfo,+ userTimezone: profile?.timezone,+ })++ const dismissNotice = () => {+ if (!notice) return++ setDismissedNotice({+ accountId: notice.accountId,+ expireAt: notice.expireAt,+ phase: notice.phase,+ })+ }++ return [notice, dismissNotice] as const+}diff --git a/web/context/modal-context-provider.tsx b/web/context/modal-context-provider.tsxindex 760a9325f2a..fcd67b49892 100644--- a/web/context/modal-context-provider.tsx+++ b/web/context/modal-context-provider.tsx@@ -7,7 +7,6 @@ import type { CreateExternalAPIReq } from '@/app/components/datasets/external-apimport type { ModelLoadBalancingModalProps } from '@/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-modal'import type { UpdatePluginPayload } from '@/app/components/plugins/types'import type { InputVar } from '@/app/components/workflow/types'-import type { ExpireNoticeModalPayloadProps } from '@/app/education-apply/expire-notice-modal'import type { ExternalDataTool } from '@/models/common'import type { ModerationConfig, PromptVariable } from '@/models/debug'import { useAtomValue } from 'jotai'@@ -70,9 +69,6 @@ const UpdatePlugin = dynamic(() => import('@/app/components/plugins/update-plugissr: false,})-const ExpireNoticeModal = dynamic(() => import('@/app/education-apply/expire-notice-modal'), {- ssr: false,-})const TriggerEventsLimitModal = dynamic(() => import('@/app/components/billing/trigger-events-limit-modal'),{@@ -103,8 +99,6 @@ export const ModalContextProvider = ({ children }: ModalContextProviderProps) =>> | null>(null)const [showUpdatePluginModal, setShowUpdatePluginModal] =useState<ModalState<UpdatePluginPayload> | null>(null)- const [showEducationExpireNoticeModal, setShowEducationExpireNoticeModal] =- useState<ModalState<ExpireNoticeModalPayloadProps> | null>(null)const currentWorkspaceId = useAtomValue(currentWorkspaceIdAtom)const [showAnnotationFullModal, setShowAnnotationFullModal] = useState(false)@@ -221,7 +215,6 @@ export const ModalContextProvider = ({ children }: ModalContextProviderProps) =>showModelLoadBalancingModal ||showOpeningModal ||showUpdatePluginModal ||- showEducationExpireNoticeModal ||showTriggerEventsLimitModal,)@@ -238,7 +231,6 @@ export const ModalContextProvider = ({ children }: ModalContextProviderProps) =>setShowModelLoadBalancingModal,setShowOpeningModal,setShowUpdatePluginModal,- setShowEducationExpireNoticeModal,setShowTriggerEventsLimitModal,}}>@@ -321,12 +313,6 @@ export const ModalContextProvider = ({ children }: ModalContextProviderProps) =>}}/>)}- {!!showEducationExpireNoticeModal && (- <ExpireNoticeModal- {...showEducationExpireNoticeModal.payload}- onClose={() => setShowEducationExpireNoticeModal(null)}- />- )}{!!showTriggerEventsLimitModal && (<TriggerEventsLimitModalshowdiff --git a/web/context/modal-context.ts b/web/context/modal-context.tsindex 04ce47f3198..bd8aa00c096 100644--- a/web/context/modal-context.ts+++ b/web/context/modal-context.ts@@ -15,7 +15,6 @@ import type {import type { ModelLoadBalancingModalProps } from '@/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-modal'import type { UpdatePluginPayload } from '@/app/components/plugins/types'import type { InputVar } from '@/app/components/workflow/types'-import type { ExpireNoticeModalPayloadProps } from '@/app/education-apply/expire-notice-modal'import type { ExternalDataTool } from '@/models/common'import type { ModerationConfig, PromptVariable } from '@/models/debug'import { noop } from 'es-toolkit/function'@@ -63,9 +62,6 @@ export type ModalContextState = {> | null>>setShowUpdatePluginModal: Dispatch<SetStateAction<ModalState<UpdatePluginPayload> | null>>- setShowEducationExpireNoticeModal: Dispatch<- SetStateAction<ModalState<ExpireNoticeModalPayloadProps> | null>- >setShowTriggerEventsLimitModal: Dispatch<SetStateAction<ModalState<TriggerEventsLimitModalPayload> | null>>@@ -82,7 +78,6 @@ export const ModalContext = createContext<ModalContextState>({setShowModelLoadBalancingModal: noop,setShowOpeningModal: noop,setShowUpdatePluginModal: noop,- setShowEducationExpireNoticeModal: noop,setShowTriggerEventsLimitModal: noop,})diff --git a/web/service/__tests__/use-education.spec.tsx b/web/service/__tests__/use-education.spec.tsxnew file mode 100644index 00000000000..a064eaa5da6--- /dev/null+++ b/web/service/__tests__/use-education.spec.tsx@@ -0,0 +1,59 @@+import type { ReactNode } from 'react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, renderHook } from '@testing-library/react'+import { useEducationVerify } from '../use-education'++const mockVerifyEducation = vi.hoisted(() => vi.fn())++vi.mock('../client', () => ({+ consoleClient: {+ account: {+ education: {+ verify: {+ get: mockVerifyEducation,+ },+ },+ },+ },+}))++const createWrapper = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ mutations: { retry: false },+ queries: { retry: false },+ },+ })++ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ )+}++describe('useEducationVerify', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it('requests a verification token silently through the generated client', async () => {+ mockVerifyEducation.mockResolvedValue({ token: 'education-token' })+ const { result } = renderHook(() => useEducationVerify(), { wrapper: createWrapper() })++ await act(async () => {+ await expect(result.current.mutateAsync()).resolves.toEqual({ token: 'education-token' })+ })++ expect(mockVerifyEducation).toHaveBeenCalledWith({}, { context: { silent: true } })+ })++ it('rejects an invalid successful response without a token', async () => {+ mockVerifyEducation.mockResolvedValue({ token: null })+ const { result } = renderHook(() => useEducationVerify(), { wrapper: createWrapper() })++ await act(async () => {+ await expect(result.current.mutateAsync()).rejects.toThrow(+ 'Education verification token is missing',+ )+ })+ })+})diff --git a/web/service/use-education.ts b/web/service/use-education.tsindex ca204cffa13..010893f8e88 100644--- a/web/service/use-education.ts+++ b/web/service/use-education.ts@@ -1,6 +1,7 @@import type { EducationAddParams } from '@/app/education-apply/types'import { useMutation, useQuery } from '@tanstack/react-query'import { get, post } from './base'+import { consoleClient } from './client'import { useInvalid } from './use-base'const NAME_SPACE = 'education'@@ -8,8 +9,14 @@ const NAME_SPACE = 'education'export const useEducationVerify = () => {return useMutation({mutationKey: [NAME_SPACE, 'education-verify'],- mutationFn: () => {- return get<{ token: string }>('/account/education/verify', {}, { silent: true })+ mutationFn: async () => {+ const response = await consoleClient.account.education.verify.get(+ {},+ { context: { silent: true } },+ )+ if (!response.token) throw new Error('Education verification token is missing')++ return { token: response.token }},})}