Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

6.4 KB
Raw Blame
import type { Step } from 'react-joyride';
import type { NavigateFunction } from 'react-router-dom';

import { TOUR_WELCOME_MESSAGE } from '../../constants/onboardingChat';
import { store } from '../../store';
import { addMessageLocal, createNewThread, setSelectedThread } from '../../store/threadSlice';
import type { ThreadMessage } from '../../types/thread';

type Translator = (key: string, fallback?: string) => string;

/**
 * Polls via setTimeout until `[data-walkthrough="<selector>"]` appears in the
 * DOM, then resolves. Rejects after `timeout` ms (default 3000).
 *
 * Uses setTimeout (not rAF) so tests can advance time with fake timers.
 */
export function waitForTarget(selector: string, timeout = 3000): Promise<void> {
  const POLL_INTERVAL = 50;

  return new Promise<void>((resolve, reject) => {
    let elapsed = 0;

    function check() {
      if (document.querySelector(`[data-walkthrough="${selector}"]`)) {
        resolve();
        return;
      }
      elapsed += POLL_INTERVAL;
      if (elapsed >= timeout) {
        reject(
          new Error(`[walkthrough] waitForTarget timed out: [data-walkthrough="${selector}"]`)
        );
        return;
      }
      setTimeout(check, POLL_INTERVAL);
    }

    // Initial check — element may already be present.
    if (document.querySelector(`[data-walkthrough="${selector}"]`)) {
      resolve();
      return;
    }
    setTimeout(check, POLL_INTERVAL);
  });
}

/**
 * Factory that produces the post-onboarding walkthrough sequence.
 *
 * Steps that navigate to a different page receive a `before` async hook that
 * calls `navigate(path)` and then waits for the target element to appear in
 * the DOM via `waitForTarget`.
 *
 * All targets follow the `[data-walkthrough="<name>"]` convention — add the
 * attribute to the corresponding DOM element in the page/component.
 */
export function createWalkthroughSteps(
  navigate: NavigateFunction,
  t: Translator = (_key, fallback) => fallback ?? _key
): Step[] {
  return [
    // ── Step 1 — /chat ────────────────────────────────────────────────────
    {
      target: '[data-walkthrough="chat-agent-panel"]',
      title: t('walkthrough.steps.meetAi.title'),
      content: t('walkthrough.steps.meetAi.content'),
      placement: 'bottom',
      skipBeacon: true,
      before: async () => {
        navigate('/chat');
        await waitForTarget('chat-agent-panel');
      },
    },

    // ── Step 2 — /connections (Apps tab) ──────────────────────────────────
    {
      target: '[data-walkthrough="skills-grid"]',
      title: t('walkthrough.steps.connectWorld.title'),
      content: t('walkthrough.steps.connectWorld.content'),
      placement: 'top',
      skipBeacon: true,
      before: async () => {
        navigate('/connections?tab=composio');
        await waitForTarget('skills-grid');
      },
    },

    // ── Step 3 — /connections (Messaging tab) ────────────────────────────
    {
      target: '[data-walkthrough="skills-channels"]',
      title: t('walkthrough.steps.messagingApps.title'),
      content: t('walkthrough.steps.messagingApps.content'),
      placement: 'bottom',
      skipBeacon: true,
      before: async () => {
        navigate('/connections?tab=channels');
        await waitForTarget('skills-channels');
      },
    },

    // ── Step 4 — /settings ────────────────────────────────────────────────
    {
      target: '[data-walkthrough="settings-menu"]',
      title: t('walkthrough.steps.settings.title'),
      content: t('walkthrough.steps.settings.content'),
      placement: 'top',
      skipBeacon: true,
      before: async () => {
        navigate('/settings');
        await waitForTarget('settings-menu');
      },
    },

    // ── Step 5 — primary nav: Chat ────────────────────────────────────────
    {
      target: '[data-walkthrough="tab-chat"]',
      title: t('walkthrough.steps.chatTab.title'),
      content: t('walkthrough.steps.chatTab.content'),
      placement: 'top',
      skipBeacon: true,
      before: async () => {
        navigate('/chat');
        await waitForTarget('tab-chat');
      },
    },

    // ── Step 6 — primary nav: Connections ────────────────────────────────
    {
      target: '[data-walkthrough="tab-connections"]',
      title: t('walkthrough.steps.connectionsTab.title'),
      content: t('walkthrough.steps.connectionsTab.content'),
      placement: 'top',
      skipBeacon: true,
    },

    // Step 10 was the sidebar's Feedback icon. That slot is the ⌘K command
    // palette now and the feedback board moved to `/settings/feedback`, so the
    // step's target element no longer exists — a step pointing at a missing
    // selector is a stall in the middle of onboarding, not a skipped frame.
    // Removed rather than re-pointed: nothing else in the header is the same
    // subject, and `walkthrough.steps.feedbackTab.*` went with it.

    // ── Step 7 — /chat (pre-seeded welcome message) ──────────────────────
    {
      target: '[data-walkthrough="chat-agent-panel"]',
      title: t('walkthrough.steps.allSet.title'),
      content: t('walkthrough.steps.allSet.content'),
      placement: 'bottom',
      skipBeacon: true,
      before: async () => {
        try {
          const thread = await store.dispatch(createNewThread()).unwrap();
          const welcomeMessage: ThreadMessage = {
            id: `msg_${crypto.randomUUID()}`,
            content: TOUR_WELCOME_MESSAGE,
            type: 'text',
            sender: 'agent',
            createdAt: new Date().toISOString(),
            extraMetadata: {},
          };
          await store
            .dispatch(addMessageLocal({ threadId: thread.id, message: welcomeMessage }))
            .unwrap();
          store.dispatch(setSelectedThread(thread.id));
          navigate('/chat');
        } catch (err) {
          console.debug('[walkthrough] step-9 before hook failed, falling back to /chat', err);
          navigate('/chat');
        }
        await waitForTarget('chat-agent-panel');
      },
    },
  ];
}