Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

21.3 KB
Raw Blame
'use client'

import type { UpdateAppPayload } from '@dify/contracts/api/console/apps/types.gen'
import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'
import type { StepByStepTourTaskId } from '@/app/components/step-by-step-tour/types'
import type { TrackCreateAppParams } from '@/utils/create-app-tracking'
import { zIconType } from '@dify/contracts/api/console/apps/zod.gen'
import { cn } from '@langgenius/dify-ui/cn'
import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import {
  noop,
  useMutation,
  useQueryClient,
  useSuspenseQueries,
  useSuspenseQuery,
} from '@tanstack/react-query'
import { useAtomValue, useSetAtom } from 'jotai'
import dynamic from 'next/dynamic'
import { useQueryState } from 'nuqs'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
import { AppMetadataForm } from '@/app/components/app/app-metadata'
import { getTemplateImportSource } from '@/app/components/explore/template-import'
import { MAIN_NAV_APP_CARD_GRID_CLASS_NAME } from '@/app/components/main-nav/app-card-grid'
import {
  getStepByStepTourPermissionVariant,
  trackStepByStepTourEvent,
} from '@/app/components/step-by-step-tour/analytics'
import {
  activeStepByStepTourGuideIndexAtom,
  activeStepByStepTourTaskIdAtom,
  advanceStepByStepTourGuideAtom,
  completedStepByStepTourTaskIdsAtom,
  completeStepByStepTourTaskAtom,
  resetStepByStepTourSessionAtom,
} from '@/app/components/step-by-step-tour/state'
import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'
import { STEP_BY_STEP_TOUR_TASKS } from '@/app/components/step-by-step-tour/tasks'
import { toast } from '@/app/notifications'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
import { useCanImportAgents } from '@/features/agent-v2/permissions'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { useImportDSL } from '@/hooks/use-import-dsl'
import { consoleQuery } from '@/service/console'
import { trackCreateApp } from '@/utils/create-app-tracking'
import { getErrorMessage } from '@/utils/error-message'
import { hasPermission } from '@/utils/permission'
import { HomeBanner } from '../banner/home-banner'
import { HomeIntro } from '../home-intro'
import { HomeShell } from '../home-shell'
import { TemplateCard } from '../template-card'
import { HomeRecommendations } from './recommendations'
import { HomeTemplatesHeader } from './templates-header'

const TryApp = dynamic(() => import('@/app/components/explore/try-app'), { ssr: false })
const DSLConfirmModal = dynamic(
  () => import('@/app/components/app/create-from-dsl-modal/dsl-confirm-modal'),
  { ssr: false },
)

const HOME_STEP_BY_STEP_TOUR_TASK_ID = 'home' satisfies StepByStepTourTaskId

export function HomeContent() {
  const { t } = useTranslation(['explore', 'app'])
  const locale = useLocale()
  const queryClient = useQueryClient()
  const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
  const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
  const [templatesQuery, recentAppsQuery] = useSuspenseQueries({
    queries: [
      consoleQuery.explore.apps.get.queryOptions({
        input: { query: { language: locale } },
      }),
      consoleQuery.apps.recent.get.queryOptions({
        input: { query: { limit: 8 } },
      }),
    ],
  })
  const templatesData = templatesQuery.data
  const continueWorkApps = recentAppsQuery.data.data
  const allCategoriesEn = t(($) => $['apps.allCategories'], { ns: 'explore', lng: 'en' })
  const canCreateApp = hasPermission(workspacePermissionKeys, 'app.create_and_management')
  const canImportAgents = useCanImportAgents()
  const canCreateTemplate = useCallback(
    (mode?: string | null) => (mode === 'agent' ? canImportAgents : canCreateApp),
    [canCreateApp, canImportAgents],
  )
  const activeStepByStepTourTaskId = useAtomValue(activeStepByStepTourTaskIdAtom)
  const activeStepByStepTourGuideIndex = useAtomValue(activeStepByStepTourGuideIndexAtom)
  const completedStepByStepTourTaskIds = useAtomValue(completedStepByStepTourTaskIdsAtom)
  const advanceStepByStepTourGuide = useSetAtom(advanceStepByStepTourGuideAtom)
  const completeStepByStepTourTask = useSetAtom(completeStepByStepTourTaskAtom)
  const resetStepByStepTourSession = useSetAtom(resetStepByStepTourSessionAtom)
  const trackHomeTourCompleted = useCallback(
    (
      completedTaskIds: StepByStepTourTaskId[],
      homeOutcome: 'lesson_app_created' | 'lesson_opened',
    ) => {
      trackStepByStepTourEvent({
        action: 'task_completed',
        task_id: HOME_STEP_BY_STEP_TOUR_TASK_ID,
        completed_task_count: completedTaskIds.length,
        home_outcome: homeOutcome,
        permission_variant: getStepByStepTourPermissionVariant({
          canCreateApp,
          hasIntegrationWalkthroughPermissions: true,
          hasKnowledgeWalkthroughPermissions: true,
          taskId: HOME_STEP_BY_STEP_TOUR_TASK_ID,
        }),
        task_total: STEP_BY_STEP_TOUR_TASKS.length,
      })

      if (STEP_BY_STEP_TOUR_TASKS.every((task) => completedTaskIds.includes(task.id))) {
        trackStepByStepTourEvent({
          action: 'tour_completed',
          completed_task_count: completedTaskIds.length,
          task_total: STEP_BY_STEP_TOUR_TASKS.length,
        })
      }
    },
    [canCreateApp],
  )

  const [keywords, setKeywords] = useState('')

  const [currCategory, setCurrCategory] = useQueryState('category', {
    defaultValue: allCategoriesEn,
  })

  const visibleCategories = useMemo(() => {
    const categoriesWithApps = new Set<string>()
    templatesData.recommended_apps.forEach((app) => {
      app.categories?.forEach((category) => categoriesWithApps.add(category))
    })

    return templatesData.categories.filter((category) => categoriesWithApps.has(category))
  }, [templatesData])

  const activeCategory = visibleCategories.includes(currCategory) ? currCategory : allCategoriesEn

  const filteredList = useMemo(() => {
    return [...templatesData.recommended_apps]
      .sort((a, b) => (a.position ?? 0) - (b.position ?? 0))
      .filter(
        (item) => activeCategory === allCategoriesEn || item.categories?.includes(activeCategory),
      )
  }, [templatesData, activeCategory, allCategoriesEn])

  const searchFilteredList = useMemo(() => {
    const searchKeywords = keywords.trim().toLowerCase()
    if (!searchKeywords) return filteredList

    return filteredList.filter(
      (item) =>
        item.app?.name?.toLowerCase().includes(searchKeywords) ||
        item.description?.toLowerCase().includes(searchKeywords),
    )
  }, [keywords, filteredList])

  const [currApp, setCurrApp] = useState<RecommendedAppResponse | null>(null)
  const [isShowCreateModal, setIsShowCreateModal] = useState(false)
  const createNameRef = useRef<HTMLInputElement>(null)

  const { handleImportDSL, handleImportDSLConfirm, versions, isFetching } = useImportDSL()
  const [showDSLConfirmModal, setShowDSLConfirmModal] = useState(false)

  const [currentTryApp, setCurrentTryApp] = useState<RecommendedAppResponse | undefined>(undefined)
  const currentCreateAppModeRef = useRef<string | null>(null)
  const currentCreateAppTrackingRef = useRef<Pick<
    TrackCreateAppParams,
    'source' | 'templateId'
  > | null>(null)
  const isCurrentTryAppFromLearnDifyRef = useRef(false)
  const shouldCompleteHomeTourOnCreateRef = useRef(false)
  const isSubmittingHomeTourCreateRef = useRef(false)
  const wasHomeTryAppCreateGuideActiveRef = useRef(false)
  const shouldForceShowLearnDifyForTour =
    activeStepByStepTourTaskId === HOME_STEP_BY_STEP_TOUR_TASK_ID &&
    !completedStepByStepTourTaskIds.includes(HOME_STEP_BY_STEP_TOUR_TASK_ID) &&
    (activeStepByStepTourGuideIndex ?? 0) === 0
  const abandonHomeTour = useCallback(() => {
    if (
      activeStepByStepTourTaskId !== HOME_STEP_BY_STEP_TOUR_TASK_ID ||
      completedStepByStepTourTaskIds.includes(HOME_STEP_BY_STEP_TOUR_TASK_ID)
    ) {
      return
    }

    resetStepByStepTourSession()
  }, [activeStepByStepTourTaskId, completedStepByStepTourTaskIds, resetStepByStepTourSession])

  const completeHomeTourAfterCreate = useCallback(() => {
    if (!shouldCompleteHomeTourOnCreateRef.current) return

    resetStepByStepTourSession()
    isCurrentTryAppFromLearnDifyRef.current = false
    shouldCompleteHomeTourOnCreateRef.current = false
    isSubmittingHomeTourCreateRef.current = false
    completeStepByStepTourTask({
      taskId: HOME_STEP_BY_STEP_TOUR_TASK_ID,
      onSuccess: (completedTaskIds) => {
        trackHomeTourCompleted(completedTaskIds, 'lesson_app_created')
      },
    })
  }, [completeStepByStepTourTask, resetStepByStepTourSession, trackHomeTourCompleted])

  const completeHomeTourAfterOpenDetails = useCallback(() => {
    if (
      activeStepByStepTourTaskId !== HOME_STEP_BY_STEP_TOUR_TASK_ID ||
      completedStepByStepTourTaskIds.includes(HOME_STEP_BY_STEP_TOUR_TASK_ID) ||
      (activeStepByStepTourGuideIndex ?? 0) !== 0
    ) {
      return
    }

    resetStepByStepTourSession()
    completeStepByStepTourTask({
      taskId: HOME_STEP_BY_STEP_TOUR_TASK_ID,
      onSuccess: (completedTaskIds) => trackHomeTourCompleted(completedTaskIds, 'lesson_opened'),
    })
  }, [
    activeStepByStepTourGuideIndex,
    activeStepByStepTourTaskId,
    completedStepByStepTourTaskIds,
    completeStepByStepTourTask,
    resetStepByStepTourSession,
    trackHomeTourCompleted,
  ])

  const abandonHomeTourCreate = useCallback(() => {
    if (!isCurrentTryAppFromLearnDifyRef.current || isSubmittingHomeTourCreateRef.current) return

    abandonHomeTour()
    setCurrentTryApp(undefined)
    setIsShowCreateModal(false)
    currentCreateAppTrackingRef.current = null
    currentCreateAppModeRef.current = null
    isCurrentTryAppFromLearnDifyRef.current = false
    shouldCompleteHomeTourOnCreateRef.current = false
  }, [abandonHomeTour])

  const hideTryAppPanel = useCallback(() => {
    abandonHomeTourCreate()
    setCurrentTryApp(undefined)
  }, [abandonHomeTourCreate])
  const homeTryAppCreateGuideActive =
    activeStepByStepTourTaskId === HOME_STEP_BY_STEP_TOUR_TASK_ID &&
    activeStepByStepTourGuideIndex === 1 &&
    !completedStepByStepTourTaskIds.includes(HOME_STEP_BY_STEP_TOUR_TASK_ID)
  useEffect(() => {
    if (!isCurrentTryAppFromLearnDifyRef.current || !currentTryApp || isShowCreateModal) {
      wasHomeTryAppCreateGuideActiveRef.current = false
      return
    }

    if (homeTryAppCreateGuideActive) {
      wasHomeTryAppCreateGuideActiveRef.current = true
      return
    }

    if (wasHomeTryAppCreateGuideActiveRef.current) {
      wasHomeTryAppCreateGuideActiveRef.current = false
      hideTryAppPanel()
    }
  }, [currentTryApp, hideTryAppPanel, homeTryAppCreateGuideActive, isShowCreateModal])
  const handleTryApp = useCallback(
    (app: RecommendedAppResponse, fromLearnDify = false) => {
      // Start the workflow request while the preview dialog's code and app details load.
      if (app.app?.mode === 'workflow' || app.app?.mode === 'advanced-chat') {
        void queryClient
          .query(
            consoleQuery.trialApps.byAppId.workflows.get.queryOptions({
              input: { params: { app_id: app.app_id } },
            }),
          )
          .catch(noop)
      }
      isCurrentTryAppFromLearnDifyRef.current = fromLearnDify
      setCurrentTryApp(app)
    },
    [queryClient],
  )
  const handleTryAppFromLearnDify = useCallback(
    (app: RecommendedAppResponse) => {
      handleTryApp(app, true)

      if (
        activeStepByStepTourTaskId === HOME_STEP_BY_STEP_TOUR_TASK_ID &&
        !completedStepByStepTourTaskIds.includes(HOME_STEP_BY_STEP_TOUR_TASK_ID) &&
        (activeStepByStepTourGuideIndex ?? 0) === 0
      ) {
        if (!canCreateApp) {
          completeHomeTourAfterOpenDetails()
          isCurrentTryAppFromLearnDifyRef.current = false
          return
        }

        advanceStepByStepTourGuide({
          guideIndex: 1,
        })
      }
    },
    [
      activeStepByStepTourGuideIndex,
      activeStepByStepTourTaskId,
      advanceStepByStepTourGuide,
      canCreateApp,
      completedStepByStepTourTaskIds,
      completeHomeTourAfterOpenDetails,
      handleTryApp,
    ],
  )
  const handleShowFromTryApp = useCallback(() => {
    if (!canCreateTemplate(currentTryApp?.app?.mode)) return
    setCurrApp(currentTryApp || null)
    currentCreateAppTrackingRef.current = {
      source: 'explore_template_preview',
      templateId: currentTryApp?.app_id,
    }
    shouldCompleteHomeTourOnCreateRef.current =
      isCurrentTryAppFromLearnDifyRef.current &&
      activeStepByStepTourTaskId === HOME_STEP_BY_STEP_TOUR_TASK_ID &&
      !completedStepByStepTourTaskIds.includes(HOME_STEP_BY_STEP_TOUR_TASK_ID) &&
      activeStepByStepTourGuideIndex === 1

    setIsShowCreateModal(true)
  }, [
    activeStepByStepTourGuideIndex,
    activeStepByStepTourTaskId,
    canCreateTemplate,
    completedStepByStepTourTaskIds,
    currentTryApp,
  ])
  const handleCreateFromLearnDify = useCallback((app: RecommendedAppResponse) => {
    setCurrApp(app)

    setIsShowCreateModal(true)
  }, [])
  const handleCreateFromTemplate = useCallback(
    (app: RecommendedAppResponse) => {
      if (!canCreateTemplate(app.app?.mode)) return
      currentCreateAppTrackingRef.current = {
        source: 'explore_template_list',
        templateId: app.app_id,
      }
      setCurrApp(app)

      setIsShowCreateModal(true)
    },
    [canCreateTemplate],
  )
  const trackCurrentCreateApp = useCallback((appMode?: string | null) => {
    const currentCreateAppTracking = currentCreateAppTrackingRef.current
    const resolvedAppMode = appMode ?? currentCreateAppModeRef.current
    if (!resolvedAppMode || !currentCreateAppTracking) return

    trackCreateApp({
      ...currentCreateAppTracking,
      appMode: resolvedAppMode,
    })
    currentCreateAppTrackingRef.current = null
    currentCreateAppModeRef.current = null
  }, [])
  const handleCreateModalHide = useCallback(() => {
    if (!isSubmittingHomeTourCreateRef.current) abandonHomeTourCreate()

    setIsShowCreateModal(false)
  }, [abandonHomeTourCreate])

  const onCreate = useCallback(
    async ({ name, icon_type, icon, icon_background, description }: UpdateAppPayload) => {
      const appId = currApp?.app_id
      if (!appId || !canCreateTemplate(currApp.app?.mode)) return
      isSubmittingHomeTourCreateRef.current = shouldCompleteHomeTourOnCreateRef.current
      hideTryAppPanel()

      let appMode: string
      let importSource: ReturnType<typeof getTemplateImportSource>
      try {
        const appDetail = await queryClient.query({
          ...consoleQuery.explore.apps.byAppId.get.queryOptions({
            context: { silent: true },
            input: { params: { app_id: appId } },
          }),
          staleTime: 0,
        })
        if (!canCreateTemplate(appDetail.mode))
          throw new Error('Template creation is not permitted')
        appMode = appDetail.mode
        importSource = getTemplateImportSource(appDetail)
      } catch (error) {
        toast.error(getErrorMessage(error) ?? t(($) => $['newApp.appCreateFailed'], { ns: 'app' }))
        isSubmittingHomeTourCreateRef.current = false
        abandonHomeTourCreate()
        return
      }

      currentCreateAppModeRef.current = appMode
      const payload = {
        ...importSource,
        name,
        icon_type,
        icon,
        icon_background,
        description,
      }
      let didTransitionCreateFlow = false
      await handleImportDSL(payload, {
        onSuccess: (response) => {
          didTransitionCreateFlow = true
          trackCurrentCreateApp(response.app_mode)
          completeHomeTourAfterCreate()
          setIsShowCreateModal(false)
        },
        onPending: () => {
          didTransitionCreateFlow = true
          setIsShowCreateModal(false)
          setShowDSLConfirmModal(true)
        },
        skipRedirectOnSuccess: shouldCompleteHomeTourOnCreateRef.current,
      })
      if (!didTransitionCreateFlow && shouldCompleteHomeTourOnCreateRef.current) {
        isSubmittingHomeTourCreateRef.current = false
        abandonHomeTourCreate()
      }
    },
    [
      abandonHomeTourCreate,
      completeHomeTourAfterCreate,
      canCreateTemplate,
      currApp?.app?.mode,
      currApp?.app_id,
      handleImportDSL,
      hideTryAppPanel,
      queryClient,
      t,
      trackCurrentCreateApp,
    ],
  )

  const submission = useMutation({ mutationFn: onCreate })
  const isCreatePending = submission.isPending || isFetching

  const onConfirmDSL = useCallback(async () => {
    await handleImportDSLConfirm({
      onSuccess: (response) => {
        trackCurrentCreateApp(response.app_mode)
        completeHomeTourAfterCreate()
      },
      skipRedirectOnSuccess: shouldCompleteHomeTourOnCreateRef.current,
    })
  }, [completeHomeTourAfterCreate, handleImportDSLConfirm, trackCurrentCreateApp])

  const handleCancelDSLConfirm = useCallback(() => {
    setShowDSLConfirmModal(false)
    isSubmittingHomeTourCreateRef.current = false
    abandonHomeTourCreate()
  }, [abandonHomeTourCreate])

  return (
    <HomeShell>
      <div className="flex flex-1 flex-col overflow-y-auto">
        <HomeIntro />
        {systemFeatures.enable_explore_banner && <HomeBanner />}
        <HomeRecommendations
          canCreate={canCreateApp}
          continueWorkApps={continueWorkApps}
          forceShowLearnDify={shouldForceShowLearnDifyForTour}
          onCreate={handleCreateFromLearnDify}
          onTry={handleTryAppFromLearnDify}
        />

        <HomeTemplatesHeader
          allCategoriesEn={allCategoriesEn}
          categories={visibleCategories}
          currCategory={activeCategory}
          keywords={keywords}
          onCategoryChange={setCurrCategory}
          onKeywordsChange={setKeywords}
        />

        <div className={cn('relative flex flex-1 shrink-0 grow flex-col pb-6')}>
          <section aria-labelledby="home-templates-title" className="shrink-0 px-8">
            {searchFilteredList.length > 0 ? (
              <ul
                // Safari drops list semantics from grid lists after preflight removes markers.
                // oxlint-disable-next-line jsx-a11y/no-redundant-roles -- Restore Safari list semantics.
                role="list"
                className={cn('content-start gap-2.5', MAIN_NAV_APP_CARD_GRID_CLASS_NAME)}
              >
                {searchFilteredList.map((app) => (
                  <TemplateCard
                    key={app.app_id}
                    app={app}
                    canCreate={canCreateTemplate(app.app?.mode)}
                    onCreate={() => handleCreateFromTemplate(app)}
                    onTry={handleTryApp}
                  />
                ))}
              </ul>
            ) : (
              <div role="status" className="rounded-lg bg-workflow-process-bg p-4">
                <p className="title-md-semi-bold text-text-primary">
                  {t(($) => $['newApp.noTemplateFound'], { ns: 'app' })}
                </p>
                {keywords.trim() && (
                  <p className="mt-2 system-sm-regular text-text-tertiary">
                    {t(($) => $['newApp.noTemplateFoundTip'], { ns: 'app' })}
                  </p>
                )}
              </div>
            )}
          </section>
        </div>
      </div>
      <Dialog
        open={isShowCreateModal}
        disablePointerDismissal
        onOpenChange={(open, details) => {
          if (!open && isCreatePending) details.cancel()
          else if (!open) handleCreateModalHide()
        }}
        onOpenChangeComplete={(open) => {
          if (!open) {
            if (!submission.isPending) submission.reset()
            setCurrApp(null)
          }
        }}
      >
        <DialogContent initialFocus={createNameRef}>
          {currApp && (
            <AppMetadataForm
              operation="create"
              appDetail={{
                name: currApp.app?.name ?? '',
                description: currApp.description ?? '',
                icon_type: zIconType.safeParse(currApp.app?.icon_type).data ?? 'emoji',
                icon: currApp.app?.icon ?? null,
                icon_background: currApp.app?.icon_background,
                icon_url: currApp.app?.icon_url ?? null,
              }}
              nameInputRef={createNameRef}
              isPending={isCreatePending}
              error={submission.error?.message}
              onSubmit={(body) => {
                if (!isCreatePending) submission.mutate(body)
              }}
            />
          )}
        </DialogContent>
      </Dialog>
      {showDSLConfirmModal && (
        <DSLConfirmModal
          versions={versions}
          onCancel={handleCancelDSLConfirm}
          onConfirm={onConfirmDSL}
          confirmLoading={isFetching}
        />
      )}

      {currentTryApp && (
        <TryApp
          appId={currentTryApp.app_id}
          canTrial={currentTryApp.can_trial}
          categories={currentTryApp.categories}
          templateName={currentTryApp.app?.name}
          templateMode={currentTryApp.app?.mode}
          canCreate={canCreateTemplate(currentTryApp.app?.mode)}
          createButtonStepByStepTourTarget={
            canCreateApp && isCurrentTryAppFromLearnDifyRef.current && !isShowCreateModal
              ? STEP_BY_STEP_TOUR_TARGETS.homeTryAppCreate
              : undefined
          }
          onClose={hideTryAppPanel}
          onCreate={handleShowFromTryApp}
        />
      )}
    </HomeShell>
  )
}