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.

36.5 KB
Raw Blame
'use client'

import type { RefObject } from 'react'
import type { StepByStepTourGuide } from './target-registry'
import type {
  StepByStepTourGuideGroup,
  StepByStepTourTaskId,
  StepByStepTourTaskView,
} from './types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import {
  Popover,
  PopoverArrow,
  PopoverClose,
  PopoverDescription,
  PopoverPopup,
  PopoverPortal,
  PopoverPositioner,
  PopoverTitle,
  PopoverTrigger,
} from '@langgenius/dify-ui/popover'
import { useSuspenseQuery } from '@tanstack/react-query'
import { useAtom, useAtomValue, useSetAtom } from 'jotai'
import { useQueryState } from 'nuqs'
import { Suspense, useEffect, useRef } from 'react'
import { Translation } from 'react-i18next'
import {
  pricingQueryParamName,
  pricingQueryParser,
} from '@/app/components/billing/pricing/query-params'
import {
  settingsQueryParamName,
  settingsQueryParser,
} from '@/app/components/header/account-setting/query-params'
import { buildIntegrationPath } from '@/app/components/integrations/routes'
import { useEducationExpireNotice } from '@/app/education/expire-notice/use-expire-notice'
import { useDocLink } from '@/context/i18n'
import { useModalContextSelector } from '@/context/modal-context'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
import { currentWorkspaceAtom, isCurrentWorkspaceManagerAtom } from '@/context/workspace-state'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { usePathname, useRouter } from '@/next/navigation'
import { hasPermission } from '@/utils/permission'
import { basePath } from '@/utils/var'
import { getStepByStepTourPermissionVariant, trackStepByStepTourEvent } from './analytics'
import { StepByStepTourCoachmark } from './coachmark'
import { FloatingChecklist, MinimizedTourPill } from './floating-widget'
import {
  activeStepByStepTourGuideGroupAtom,
  activeStepByStepTourGuideIndexAtom,
  activeStepByStepTourGuideIndexesAtom,
  activeStepByStepTourTaskIdAtom,
  advanceStepByStepTourGuideAtom,
  completedStepByStepTourTaskIdsAtom,
  completeStepByStepTourTaskAtom,
  resetStepByStepTourSessionAtom,
  skipStepByStepTourAtom,
  startStepByStepTourTaskAtom,
  stepByStepTourChecklistMinimizedAtom,
  stepByStepTourEnabledForCurrentWorkspaceAtom,
  stepByStepTourFirstWorkspaceIdAtom,
  stepByStepTourSkippedAtom,
  stepByStepTourSkipRecoveryVisibleAtom,
  uncompleteStepByStepTourTaskAtom,
} from './state'
import {
  getStepByStepTourGuideInteractionPolicy,
  getStepByStepTourGuides,
  getStepByStepTourTargetSelector,
  STEP_BY_STEP_TOUR_TARGETS,
} from './target-registry'
import { STEP_BY_STEP_TOUR_TASKS } from './tasks'
import { useStepByStepTourTarget } from './use-tour-target'

type StepByStepTourTask = (typeof STEP_BY_STEP_TOUR_TASKS)[number]

const hasCompletedAllStepByStepTourTasks = (
  completedTaskIds: StepByStepTourTaskId[],
  tasks: readonly StepByStepTourTask[],
) => tasks.every((task) => completedTaskIds.includes(task.id))

const isPermissionFallbackGuideGroup = (
  guideGroup: StepByStepTourGuideGroup | undefined,
): guideGroup is Extract<
  StepByStepTourGuideGroup,
  'homeNoCreate' | 'integrationLimitedAccess' | 'studioNoCreateEmpty' | 'studioNoCreateWithApps'
> =>
  guideGroup === 'homeNoCreate' ||
  guideGroup === 'integrationLimitedAccess' ||
  guideGroup === 'studioNoCreateEmpty' ||
  guideGroup === 'studioNoCreateWithApps'

const shouldHideOnPathname = (pathname: string) =>
  pathname.startsWith('/app/') || pathname.includes('/installed/')

const isGuideEligibleForPlan = (guide: StepByStepTourGuide, canSetPluginPreferences: boolean) =>
  guide.target !== STEP_BY_STEP_TOUR_TARGETS.integrationUpdateSettings || canSetPluginPreferences

const isOptionalGuideTargetAvailable = (guide: StepByStepTourGuide, pathname: string) => {
  if (!guide.optional) return true

  if (guide.integrationSection && pathname !== buildIntegrationPath(guide.integrationSection))
    return true

  if (typeof document === 'undefined') return true

  return Boolean(document.querySelector(getStepByStepTourTargetSelector(guide.target)))
}

const isElementVerticallyVisible = (element: HTMLElement) => {
  const rect = element.getBoundingClientRect()
  const viewportHeight = window.innerHeight || document.documentElement.clientHeight

  return rect.top >= 0 && rect.bottom <= viewportHeight
}

const scrollTourTargetIntoView = (element: HTMLElement) => {
  if (isElementVerticallyVisible(element)) return

  element.scrollIntoView({
    block: 'nearest',
    behavior: 'auto',
  })
}

const createGuideIndexes = (guides: StepByStepTourGuide[]) => guides.map((_, index) => index)

const getActiveGuideIndexes = (
  guides: StepByStepTourGuide[],
  guideIndexes: number[] | undefined,
) => {
  const fallbackGuideIndexes = createGuideIndexes(guides)

  if (!guideIndexes?.length) return fallbackGuideIndexes

  const validGuideIndexes = guideIndexes.filter((index) => index >= 0 && index < guides.length)
  return validGuideIndexes.length > 0 ? validGuideIndexes : fallbackGuideIndexes
}

type StepByStepTourMountProps = {
  className?: string
  recoveryAnchorRef?: RefObject<HTMLButtonElement | null>
}

export default function StepByStepTourMount({
  className,
  recoveryAnchorRef,
}: StepByStepTourMountProps) {
  const [pricing] = useQueryState(pricingQueryParamName, pricingQueryParser)
  const router = useRouter()
  const pathname = usePathname()
  const docLink = useDocLink()
  const currentWorkspace = useAtomValue(currentWorkspaceAtom)
  const 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)
  const skipped = useAtomValue(stepByStepTourSkippedAtom)
  const firstWorkspaceId = useAtomValue(stepByStepTourFirstWorkspaceIdAtom)
  const enabledForCurrentWorkspace = useAtomValue(stepByStepTourEnabledForCurrentWorkspaceAtom)
  const activeTaskId = useAtomValue(activeStepByStepTourTaskIdAtom)
  const sessionGuideIndex = useAtomValue(activeStepByStepTourGuideIndexAtom)
  const sessionGuideGroup = useAtomValue(activeStepByStepTourGuideGroupAtom)
  const sessionGuideIndexes = useAtomValue(activeStepByStepTourGuideIndexesAtom)
  const skipRecoveryVisible = useAtomValue(stepByStepTourSkipRecoveryVisibleAtom)
  const setSkipRecoveryVisible = useSetAtom(stepByStepTourSkipRecoveryVisibleAtom)
  const advanceGuide = useSetAtom(advanceStepByStepTourGuideAtom)
  const completeTask = useSetAtom(completeStepByStepTourTaskAtom)
  const resetSession = useSetAtom(resetStepByStepTourSessionAtom)
  const patchSkipTour = useSetAtom(skipStepByStepTourAtom)
  const startTask = useSetAtom(startStepByStepTourTaskAtom)
  const uncompleteTask = useSetAtom(uncompleteStepByStepTourTaskAtom)
  const [checklistMinimized, setChecklistMinimized] = useAtom(stepByStepTourChecklistMinimizedAtom)
  const checklistCloseButtonRef = useRef<HTMLButtonElement>(null)
  const restoreTriggerRef = useRef<HTMLButtonElement>(null)
  const checklistPopupRef = useRef<HTMLDivElement>(null)
  const lastRequestedIntegrationRouteRef = useRef<string | undefined>(undefined)
  const previousSkippedRef = useRef(skipped)
  const permissionFallbackAnalyticsKeyRef = useRef<string | undefined>(undefined)
  const shownAnalyticsKeyRef = useRef<string | undefined>(undefined)
  const stepShownAnalyticsKeyRef = useRef<string | undefined>(undefined)
  const currentWorkspaceId = currentWorkspace.id
  const canCreateApp = hasPermission(workspacePermissionKeys, 'app.create_and_management')
  const homeGuideGroup: Extract<StepByStepTourGuideGroup, 'homeNoCreate'> | undefined = canCreateApp
    ? undefined
    : 'homeNoCreate'
  const hasKnowledgeWalkthroughPermissions =
    hasPermission(workspacePermissionKeys, 'dataset.create_and_management') &&
    hasPermission(workspacePermissionKeys, 'dataset.external.connect')
  const canSetPluginPreferences = hasPermission(
    workspacePermissionKeys,
    'plugin.plugin_preferences',
  )
  const integrationGuideGroup:
    | Extract<StepByStepTourGuideGroup, 'integrationLimitedAccess'>
    | undefined = isCurrentWorkspaceManager ? undefined : 'integrationLimitedAccess'
  const hasIntegrationWalkthroughPermissions = !integrationGuideGroup

  const learnDifyEnabled = systemFeatures.enable_learn_app
  const stepByStepTourFeatureEnabled = systemFeatures.enable_step_by_step_tour
  const availableTasks = learnDifyEnabled
    ? STEP_BY_STEP_TOUR_TASKS
    : STEP_BY_STEP_TOUR_TASKS.filter((task) => task.id !== 'home')
  const availableTaskIds = availableTasks.map((task) => task.id)
  const completedAvailableTaskIds = completedTaskIds.filter((taskId) =>
    availableTaskIds.includes(taskId),
  )
  const allTasksCompleted = hasCompletedAllStepByStepTourTasks(completedTaskIds, availableTasks)
  const currentTask = availableTasks.find((task) => !completedTaskIds.includes(task.id))
  const activeTask = activeTaskId
    ? availableTasks.find((task) => task.id === activeTaskId)
    : undefined
  const activeGuideGroup: StepByStepTourGuideGroup | undefined =
    activeTask?.id === 'home'
      ? homeGuideGroup
      : activeTask?.id === 'integration'
        ? integrationGuideGroup
        : sessionGuideGroup
  const activeGuides = activeTask ? getStepByStepTourGuides(activeTask.id, activeGuideGroup) : []
  const activeGuideIndex = sessionGuideIndex ?? 0
  const activeGuide = activeGuides[activeGuideIndex]
  const hasActiveGuide = Boolean(activeTask && activeGuide)
  const minimized = Boolean(activeTask) || checklistMinimized
  const activeGuideIndexes =
    activeGuides.length > 0
      ? getActiveGuideIndexes(activeGuides, sessionGuideIndexes).filter((index) =>
          isGuideEligibleForPlan(activeGuides[index]!, canSetPluginPreferences),
        )
      : []
  const activeGuidePlanIndex = activeGuideIndexes.findIndex((index) => index === activeGuideIndex)
  const activeStepIndex =
    activeGuideIndexes.length > 0
      ? activeGuidePlanIndex === -1
        ? activeGuideIndexes.filter((index) => index < activeGuideIndex).length
        : activeGuidePlanIndex
      : activeGuideIndex
  const activeStepTotal = activeGuideIndexes.length || activeGuides.length
  const activeGuideAnalyticsProperties =
    activeTask && activeGuide
      ? {
          task_id: activeTask.id,
          guide_id: activeGuide.id,
        }
      : undefined
  const visible =
    systemFeatures.deployment_edition === 'CLOUD' &&
    stepByStepTourFeatureEnabled &&
    enabledForCurrentWorkspace &&
    (hasActiveGuide || !shouldHideOnPathname(pathname))
  const overlayVisible =
    visible &&
    !hasBlockingModalOpen &&
    pricing !== 'open' &&
    !settingsDestination &&
    !(pathname === '/apps' && educationExpireNotice)
  const completionPromptVisible = visible && allTasksCompleted && !activeTask
  const expanded = completionPromptVisible || !minimized
  const activeTargetElement = useStepByStepTourTarget(activeGuide?.target)
  const activeGuidePlacement =
    activeGuide?.target === STEP_BY_STEP_TOUR_TARGETS.studioEmptyLearnDify
      ? 'top'
      : activeGuide?.target === STEP_BY_STEP_TOUR_TARGETS.integration
        ? 'inline-end'
        : 'bottom'
  const getPermissionVariant = (taskId: StepByStepTourTaskId) =>
    getStepByStepTourPermissionVariant({
      canCreateApp,
      hasIntegrationWalkthroughPermissions,
      hasKnowledgeWalkthroughPermissions,
      taskId,
    })

  const trackTaskCompleted = (
    completedTaskIds: StepByStepTourTaskId[],
    taskId: StepByStepTourTaskId,
  ) => {
    const completedAvailableTaskIds = completedTaskIds.filter((completedTaskId) =>
      availableTaskIds.includes(completedTaskId),
    )

    trackStepByStepTourEvent({
      action: 'task_completed',
      task_id: taskId,
      completed_task_count: completedAvailableTaskIds.length,
      permission_variant: getPermissionVariant(taskId),
      task_total: availableTasks.length,
    })

    if (hasCompletedAllStepByStepTourTasks(completedTaskIds, availableTasks)) {
      trackStepByStepTourEvent({
        action: 'tour_completed',
        completed_task_count: completedAvailableTaskIds.length,
        task_total: availableTasks.length,
      })
    }
  }

  const trackTourSkipped = (completedTaskIds: StepByStepTourTaskId[]) => {
    trackStepByStepTourEvent({
      action: 'tour_skipped',
      task_id: activeTask?.id,
      completed_task_count: completedTaskIds.filter((taskId) => availableTaskIds.includes(taskId))
        .length,
    })
  }

  useEffect(() => {
    if (activeTask?.id !== 'integration' || !activeGuide?.integrationSection) return

    const activeGuideRoute = buildIntegrationPath(activeGuide.integrationSection)
    if (pathname === activeGuideRoute) {
      lastRequestedIntegrationRouteRef.current = undefined
      return
    }

    if (lastRequestedIntegrationRouteRef.current === activeGuideRoute) return

    lastRequestedIntegrationRouteRef.current = activeGuideRoute
    router.replace(activeGuideRoute)
  }, [activeGuide?.integrationSection, activeTask?.id, pathname, router])

  useEffect(() => {
    if (!activeTargetElement) return

    scrollTourTargetIntoView(activeTargetElement)
  }, [activeGuide?.target, activeTargetElement])

  useEffect(() => {
    if (!visible) return

    const entryPoint = previousSkippedRef.current
      ? 'reenabled_after_skip'
      : firstWorkspaceId === currentWorkspaceId
        ? 'first_workspace'
        : 'help_menu_enabled'
    const shownAnalyticsKey = `${currentWorkspaceId}:${entryPoint}`
    if (shownAnalyticsKeyRef.current === shownAnalyticsKey) return

    shownAnalyticsKeyRef.current = shownAnalyticsKey
    trackStepByStepTourEvent({
      action: 'tour_shown',
      completed_task_count: completedAvailableTaskIds.length,
      entry_point: entryPoint,
      task_total: availableTasks.length,
    })
  }, [
    availableTasks.length,
    completedAvailableTaskIds.length,
    currentWorkspaceId,
    firstWorkspaceId,
    visible,
  ])

  useEffect(() => {
    if (!visible || !activeTask || !activeGuide || !activeTargetElement) return

    const guideAnalyticsProperties = { task_id: activeTask.id, guide_id: activeGuide.id }

    const stepShownAnalyticsKey = [
      currentWorkspaceId,
      guideAnalyticsProperties.task_id,
      guideAnalyticsProperties.guide_id,
    ].join(':')
    if (stepShownAnalyticsKeyRef.current === stepShownAnalyticsKey) return

    stepShownAnalyticsKeyRef.current = stepShownAnalyticsKey
    trackStepByStepTourEvent({
      action: 'guide_shown',
      task_id: guideAnalyticsProperties.task_id,
      guide_id: guideAnalyticsProperties.guide_id,
    })
  }, [
    activeGuide,
    activeGuideGroup,
    activeStepIndex,
    activeStepTotal,
    activeTargetElement,
    activeTask,
    currentWorkspaceId,
    visible,
  ])

  useEffect(() => {
    if (!visible) return

    if (currentTask?.id === 'knowledge' && !hasKnowledgeWalkthroughPermissions) {
      const fallbackAnalyticsKey = `${currentWorkspaceId}:knowledge:no_knowledge_permission`
      if (permissionFallbackAnalyticsKeyRef.current === fallbackAnalyticsKey) return

      permissionFallbackAnalyticsKeyRef.current = fallbackAnalyticsKey
      trackStepByStepTourEvent({
        action: 'permission_fallback_shown',
        task_id: 'knowledge',
        permission_variant: 'no_knowledge_permission',
      })
      return
    }

    if (!activeTask) return

    if (!isPermissionFallbackGuideGroup(activeGuideGroup)) return

    const fallbackAnalyticsKey = `${currentWorkspaceId}:${activeTask.id}:${activeGuideGroup}`
    if (permissionFallbackAnalyticsKeyRef.current === fallbackAnalyticsKey) return

    permissionFallbackAnalyticsKeyRef.current = fallbackAnalyticsKey
    trackStepByStepTourEvent({
      action: 'permission_fallback_shown',
      task_id: activeTask.id,
      permission_variant:
        activeTask.id === 'integration' ? 'no_integration_permission' : 'no_create',
    })
  }, [
    activeGuideGroup,
    activeTask,
    currentTask?.id,
    currentWorkspaceId,
    hasKnowledgeWalkthroughPermissions,
    visible,
  ])

  useEffect(() => {
    previousSkippedRef.current = skipped
  }, [skipped])

  const recoveryVisible = Boolean(recoveryAnchorRef) && skipRecoveryVisible

  if (!visible && !recoveryVisible) return null
  return (
    <Suspense fallback={null}>
      <Translation ns={['onboarding']}>
        {(t) => {
          const title = t(($) => $['stepByStepTour.title'], { ns: 'onboarding' })
          const taskCopy: Record<
            StepByStepTourTaskId,
            Pick<StepByStepTourTaskView, 'title' | 'description' | 'primaryActionLabel'>
          > = {
            home: {
              title: canCreateApp
                ? t(($) => $['stepByStepTour.tasks.home.title'], { ns: 'onboarding' })
                : t(($) => $['stepByStepTour.tasks.home.noCreate.title'], { ns: 'onboarding' }),
              description: canCreateApp
                ? t(($) => $['stepByStepTour.tasks.home.description'], { ns: 'onboarding' })
                : t(($) => $['stepByStepTour.tasks.home.noCreate.description'], {
                    ns: 'onboarding',
                  }),
              primaryActionLabel: t(($) => $['stepByStepTour.tasks.home.primaryActionLabel'], {
                ns: 'onboarding',
              }),
            },
            studio: {
              title: canCreateApp
                ? t(($) => $['stepByStepTour.tasks.studio.title'], { ns: 'onboarding' })
                : t(($) => $['stepByStepTour.tasks.studio.noCreate.title'], { ns: 'onboarding' }),
              description: canCreateApp
                ? t(($) => $['stepByStepTour.tasks.studio.description'], { ns: 'onboarding' })
                : t(($) => $['stepByStepTour.tasks.studio.noCreate.description'], {
                    ns: 'onboarding',
                  }),
              primaryActionLabel: t(($) => $['stepByStepTour.tasks.studio.primaryActionLabel'], {
                ns: 'onboarding',
              }),
            },
            knowledge: {
              title: hasKnowledgeWalkthroughPermissions
                ? t(($) => $['stepByStepTour.tasks.knowledge.title'], { ns: 'onboarding' })
                : t(($) => $['stepByStepTour.tasks.knowledge.noPermission.title'], {
                    ns: 'onboarding',
                  }),
              description: hasKnowledgeWalkthroughPermissions
                ? t(($) => $['stepByStepTour.tasks.knowledge.description'], { ns: 'onboarding' })
                : t(($) => $['stepByStepTour.tasks.knowledge.noPermission.description'], {
                    ns: 'onboarding',
                  }),
              primaryActionLabel: hasKnowledgeWalkthroughPermissions
                ? t(($) => $['stepByStepTour.tasks.knowledge.primaryActionLabel'], {
                    ns: 'onboarding',
                  })
                : t(($) => $['stepByStepTour.tasks.knowledge.noPermission.primaryActionLabel'], {
                    ns: 'onboarding',
                  }),
            },
            integration: {
              title: hasIntegrationWalkthroughPermissions
                ? t(($) => $['stepByStepTour.tasks.integration.title'], { ns: 'onboarding' })
                : t(($) => $['stepByStepTour.tasks.integration.noPermission.title'], {
                    ns: 'onboarding',
                  }),
              description: hasIntegrationWalkthroughPermissions
                ? t(($) => $['stepByStepTour.tasks.integration.description'], { ns: 'onboarding' })
                : t(($) => $['stepByStepTour.tasks.integration.noPermission.description'], {
                    ns: 'onboarding',
                  }),
              primaryActionLabel: t(
                ($) => $['stepByStepTour.tasks.integration.primaryActionLabel'],
                {
                  ns: 'onboarding',
                },
              ),
            },
          }
          const tasks = availableTasks.map((task): StepByStepTourTaskView => {
            const completed = completedTaskIds.includes(task.id)
            const knowledgeUnavailable =
              task.id === 'knowledge' && !hasKnowledgeWalkthroughPermissions

            return {
              ...taskCopy[task.id],
              id: task.id,
              iconClassName: knowledgeUnavailable ? 'i-ri-lock-line' : task.iconClassName,
              status: completed ? 'completed' : task.id === currentTask?.id ? 'current' : 'pending',
            }
          })

          const skipTour = () => {
            patchSkipTour({
              onSuccess: trackTourSkipped,
              onError: () => setSkipRecoveryVisible(false),
            })
            if (recoveryAnchorRef) setSkipRecoveryVisible(true)
          }

          const skipActiveGuide = () => {
            const guideAnalyticsProperties = activeGuideAnalyticsProperties
            if (guideAnalyticsProperties) {
              trackStepByStepTourEvent({
                action: 'guide_skipped',
                task_id: guideAnalyticsProperties.task_id,
                guide_id: guideAnalyticsProperties.guide_id,
              })
            }

            resetSession()
            setChecklistMinimized(false)
          }

          const getNextVisibleActiveGuideIndex = (startIndex: number) => {
            if (activeGuideIndexes.length > 0) {
              let nextGuideIndexes = activeGuideIndexes
              let nextGuideIndex = nextGuideIndexes.find((index) => index >= startIndex)

              while (nextGuideIndex !== undefined) {
                if (
                  isGuideEligibleForPlan(activeGuides[nextGuideIndex]!, canSetPluginPreferences) &&
                  isOptionalGuideTargetAvailable(activeGuides[nextGuideIndex]!, pathname)
                ) {
                  return { activeGuideIndex: nextGuideIndex, activeGuideIndexes: nextGuideIndexes }
                }

                nextGuideIndexes = nextGuideIndexes.filter((index) => index !== nextGuideIndex)
                nextGuideIndex = nextGuideIndexes.find((index) => index >= startIndex)
              }

              return { activeGuideIndex: -1, activeGuideIndexes: nextGuideIndexes }
            }

            for (let index = startIndex; index < activeGuides.length; index += 1) {
              if (
                isGuideEligibleForPlan(activeGuides[index]!, canSetPluginPreferences) &&
                isOptionalGuideTargetAvailable(activeGuides[index]!, pathname)
              ) {
                return { activeGuideIndex: index, activeGuideIndexes: undefined }
              }
            }

            return { activeGuideIndex: -1, activeGuideIndexes: undefined }
          }

          const completeActiveGuide = () => {
            if (!activeTask || !activeGuide) return

            if (activeGuide.completionMode === 'external') return

            const guideAnalyticsProperties = activeGuideAnalyticsProperties
            if (guideAnalyticsProperties) {
              trackStepByStepTourEvent({
                action: 'guide_completed',
                task_id: guideAnalyticsProperties.task_id,
                guide_id: guideAnalyticsProperties.guide_id,
              })
            }

            if (activeGuideIndex < activeGuides.length - 1) {
              const nextActiveGuide = getNextVisibleActiveGuideIndex(activeGuideIndex + 1)

              if (nextActiveGuide.activeGuideIndex === -1) {
                completeTask({
                  taskId: activeTask.id,
                  onSuccess: (completedTaskIds) =>
                    trackTaskCompleted(completedTaskIds, activeTask.id),
                })
                resetSession()
                setChecklistMinimized(false)
                return
              }

              const nextGuideSection =
                activeTask.id === 'integration'
                  ? activeGuides[nextActiveGuide.activeGuideIndex]?.integrationSection
                  : undefined
              const nextGuideRoute = nextGuideSection && buildIntegrationPath(nextGuideSection)
              // The Integrations page stays mounted across sections, so the step only needs the URL.
              if (nextGuideRoute && nextGuideRoute !== pathname) {
                lastRequestedIntegrationRouteRef.current = nextGuideRoute
                window.history.replaceState(null, '', `${basePath}${nextGuideRoute}`)
              }
              advanceGuide({
                guideIndex: nextActiveGuide.activeGuideIndex,
                guideIndexes: nextActiveGuide.activeGuideIndexes,
              })
              return
            }

            completeTask({
              taskId: activeTask.id,
              onSuccess: (completedTaskIds) => trackTaskCompleted(completedTaskIds, activeTask.id),
            })
            resetSession()
            setChecklistMinimized(false)
          }

          const dismissCompletedTour = () => {
            patchSkipTour({
              onSuccess: trackTourSkipped,
            })
            resetSession()
            setChecklistMinimized(false)
          }

          const progress = {
            ariaValueText: t(($) => $['stepByStepTour.progressAriaValueText'], {
              ns: 'onboarding',
              completed: completedAvailableTaskIds.length,
              total: availableTasks.length,
            }),
            completed: completedAvailableTaskIds.length,
            total: availableTasks.length,
          }
          const floatingChecklist = (
            <FloatingChecklist
              title={title}
              duration={t(($) => $['stepByStepTour.duration'], { ns: 'onboarding' })}
              progress={progress}
              completionPrompt={
                completionPromptVisible
                  ? {
                      label: t(($) => $['stepByStepTour.completion.label'], { ns: 'onboarding' }),
                      title: t(($) => $['stepByStepTour.completion.title'], { ns: 'onboarding' }),
                      description: t(($) => $['stepByStepTour.completion.description'], {
                        ns: 'onboarding',
                      }),
                      dismissLabel: t(($) => $['stepByStepTour.completion.dismiss'], {
                        ns: 'onboarding',
                      }),
                      onDismiss: dismissCompletedTour,
                    }
                  : undefined
              }
              tasks={tasks}
              closeButtonRef={checklistCloseButtonRef}
              skipLabel={t(($) => $['stepByStepTour.skip'], { ns: 'onboarding' })}
              minimizeLabel={t(($) => $['stepByStepTour.minimize'], { ns: 'onboarding' })}
              getTaskCompleteLabel={(taskTitle) =>
                t(($) => $['stepByStepTour.markTaskComplete'], {
                  ns: 'onboarding',
                  title: taskTitle,
                })
              }
              getTaskIncompleteLabel={(taskTitle) =>
                t(($) => $['stepByStepTour.markTaskIncomplete'], {
                  ns: 'onboarding',
                  title: taskTitle,
                })
              }
              onMinimize={() => {
                setChecklistMinimized(true)
              }}
              onSkip={skipTour}
              onStartTask={(taskId) => {
                const task = availableTasks.find((item) => item.id === taskId)

                if (!task) return

                const guideGroup =
                  taskId === 'home'
                    ? homeGuideGroup
                    : taskId === 'integration'
                      ? integrationGuideGroup
                      : undefined
                trackStepByStepTourEvent({
                  action: 'task_started',
                  task_id: taskId,
                  permission_variant: getPermissionVariant(taskId),
                })

                if (taskId === 'knowledge' && !hasKnowledgeWalkthroughPermissions) {
                  completeTask({
                    taskId,
                    onSuccess: (completedTaskIds) => trackTaskCompleted(completedTaskIds, taskId),
                  })
                  resetSession()
                  setChecklistMinimized(false)
                  return
                }

                startTask({ taskId, guideGroup })
                router.push(task.route)
              }}
              onUncompleteTask={(taskId) => {
                uncompleteTask({
                  taskId,
                  onSuccess: (completedTaskIds) => {
                    trackStepByStepTourEvent({
                      action: 'task_reopened',
                      task_id: taskId,
                      completed_task_count: completedTaskIds.filter((completedTaskId) =>
                        availableTaskIds.includes(completedTaskId),
                      ).length,
                    })
                  },
                })
              }}
            />
          )

          return (
            <div className={cn('relative', className)}>
              {overlayVisible && !allTasksCompleted && activeTask && activeGuide && (
                <StepByStepTourCoachmark
                  guide={{
                    ...activeGuide,
                    description: t(($) => $[activeGuide.description]),
                    learnMoreHref: activeGuide.learnMoreDocPath
                      ? docLink(activeGuide.learnMoreDocPath)
                      : undefined,
                    learnMoreLabel: t(($) => $[activeGuide.learnMoreLabel]),
                    primaryActionLabel: t(($) => $[activeGuide.primaryActionLabel]),
                    title: t(($) => $[activeGuide.title]),
                  }}
                  targetElement={activeTargetElement}
                  placement={activeGuidePlacement}
                  stepLabel={t(($) => $['stepByStepTour.stepLabel'], {
                    ns: 'onboarding',
                    current: activeStepIndex + 1,
                    total: activeStepTotal,
                  })}
                  skipLabel={t(($) => $['stepByStepTour.skip'], { ns: 'onboarding' })}
                  interactionPolicy={getStepByStepTourGuideInteractionPolicy(
                    activeGuide,
                    activeTask.canClickThrough,
                  )}
                  onSkip={skipActiveGuide}
                  onComplete={completeActiveGuide}
                />
              )}
              {visible && (!allTasksCompleted || completionPromptVisible) && (
                <Popover
                  open={overlayVisible && expanded}
                  onOpenChange={(open, { event, reason }) => {
                    if (open) {
                      setChecklistMinimized(false)
                      return
                    }
                    // Only the checklist's own keyboard exits minimize it: Escape from inside it or
                    // its trigger, and Tab past it through a focus guard. Outside presses keep it.
                    const target = event.target instanceof Element ? event.target : null
                    const escapedFromChecklist =
                      reason === 'escape-key' &&
                      Boolean(
                        target &&
                        (checklistPopupRef.current?.contains(target) ||
                          restoreTriggerRef.current?.contains(target)),
                      )
                    const tabbedOut =
                      reason === 'focus-out' &&
                      Boolean(target?.hasAttribute('data-base-ui-focus-guard'))
                    if (reason === 'trigger-press' || escapedFromChecklist || tabbedOut)
                      setChecklistMinimized(true)
                  }}
                >
                  {(!expanded || overlayVisible) && (
                    <PopoverTrigger
                      ref={restoreTriggerRef}
                      render={(props) => (
                        <MinimizedTourPill
                          {...props}
                          className={cn(props.className, 'data-popup-open:opacity-0')}
                          title={title}
                          progress={progress}
                        />
                      )}
                    />
                  )}
                  {overlayVisible && (
                    <PopoverPortal>
                      <PopoverPositioner
                        side="top"
                        align="start"
                        // The expanded checklist covers its pill.
                        sideOffset={({ anchor }) => -anchor.height}
                        collisionPadding={8}
                        collisionAvoidance={{
                          side: 'shift',
                          align: 'shift',
                          fallbackAxisSide: 'none',
                        }}
                      >
                        <PopoverPopup
                          ref={checklistPopupRef}
                          initialFocus={checklistCloseButtonRef}
                          finalFocus={() =>
                            hasActiveGuide && activeTargetElement
                              ? false
                              : restoreTriggerRef.current
                          }
                        >
                          {floatingChecklist}
                        </PopoverPopup>
                      </PopoverPositioner>
                    </PopoverPortal>
                  )}
                </Popover>
              )}
              {recoveryAnchorRef && (
                <SkipRecoveryPrompt
                  open={recoveryVisible}
                  anchorRef={recoveryAnchorRef}
                  label={t(($) => $['stepByStepTour.skipRecovery.label'], { ns: 'onboarding' })}
                  message={t(($) => $['stepByStepTour.skipRecovery.message'], { ns: 'onboarding' })}
                  dismissLabel={t(($) => $['stepByStepTour.skipRecovery.dismiss'], {
                    ns: 'onboarding',
                  })}
                  onOpenChange={setSkipRecoveryVisible}
                />
              )}
            </div>
          )
        }}
      </Translation>
    </Suspense>
  )
}

function SkipRecoveryPrompt({
  anchorRef,
  dismissLabel,
  label,
  message,
  onOpenChange,
  open,
}: {
  anchorRef: RefObject<HTMLButtonElement | null>
  dismissLabel: string
  label: string
  message: string
  onOpenChange: (open: boolean) => void
  open: boolean
}) {
  const dismissRef = useRef<HTMLButtonElement>(null)
  const shouldRestoreFocusRef = useRef(false)

  return (
    <Popover
      open={open}
      onOpenChange={(nextOpen, eventDetails) => {
        shouldRestoreFocusRef.current =
          !nextOpen &&
          (eventDetails.reason === 'close-press' || eventDetails.reason === 'escape-key')
        onOpenChange(nextOpen)
      }}
    >
      <PopoverPortal>
        <PopoverPositioner
          side="top"
          align="end"
          sideOffset={28}
          anchor={anchorRef}
          arrowPadding={8}
          collisionPadding={6}
          collisionAvoidance={{
            side: 'shift',
            align: 'shift',
            fallbackAxisSide: 'none',
          }}
        >
          <PopoverPopup
            initialFocus={dismissRef}
            finalFocus={() => {
              const shouldRestoreFocus = shouldRestoreFocusRef.current
              shouldRestoreFocusRef.current = false
              return shouldRestoreFocus ? anchorRef.current : false
            }}
            className="w-65 max-w-[calc(100vw-12px)] rounded-2xl border-[0.5px] border-state-accent-hover-alt bg-state-accent-hover p-4 shadow-[0_20px_24px_-4px_var(--color-shadow-shadow-5),0_8px_8px_-4px_var(--color-shadow-shadow-1)] backdrop-blur-[10px]"
          >
            <div className="flex flex-col gap-1">
              <PopoverTitle className="sr-only">{label}</PopoverTitle>
              <PopoverDescription className="system-sm-regular text-text-secondary">
                {message}
              </PopoverDescription>
              <div className="flex h-12 items-end justify-end pt-4">
                <PopoverClose
                  ref={dismissRef}
                  render={<Button variant="primary" size="medium" className="w-20" />}
                >
                  {dismissLabel}
                </PopoverClose>
              </div>
            </div>
            <PopoverArrow className="pointer-events-none -bottom-7 h-7 w-3">
              <span
                aria-hidden
                className="absolute top-0 left-1/2 h-7 w-0.5 -translate-x-1/2 bg-state-accent-hover-alt"
              />
              <span
                aria-hidden
                className="absolute top-5.5 left-1/2 size-3 -translate-x-1/2 rounded-full border-2 border-state-accent-hover bg-state-accent-solid shadow-xs"
              />
            </PopoverArrow>
          </PopoverPopup>
        </PopoverPositioner>
      </PopoverPortal>
    </Popover>
  )
}