@posthog/wizard 2.19.0 → 2.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -0
- package/dist/{slides-mT2s9wM_.js → OutroScreen-CqF6SdBo.js} +614 -122
- package/dist/OutroScreen-CqF6SdBo.js.map +1 -0
- package/dist/{add-mcp-server-to-clients-CjnvTVj0.js → add-mcp-server-to-clients-DQHGhzt6.js} +4 -4
- package/dist/{add-mcp-server-to-clients-CjnvTVj0.js.map → add-mcp-server-to-clients-DQHGhzt6.js.map} +1 -1
- package/dist/{agent-interface-CQU6x4Hj.js → agent-interface-DE7txTqh.js} +163 -52
- package/dist/agent-interface-DE7txTqh.js.map +1 -0
- package/dist/{agent-runner-Cj7saDkL.js → agent-runner-DUZ5OD6e.js} +10 -9
- package/dist/{agent-runner-Cj7saDkL.js.map → agent-runner-DUZ5OD6e.js.map} +1 -1
- package/dist/{analytics-Df-Xb81i.js → analytics-Bl5DPj_0.js} +2 -2
- package/dist/{analytics-Df-Xb81i.js.map → analytics-Bl5DPj_0.js.map} +1 -1
- package/dist/{api-Dw6_orDE.js → api-DuA0_88V.js} +25 -4
- package/dist/{api-Dw6_orDE.js.map → api-DuA0_88V.js.map} +1 -1
- package/dist/bin.js +74 -47
- package/dist/bin.js.map +1 -1
- package/dist/check-screens.tsx +124 -0
- package/dist/{ci-install-BKAvFfK6.js → ci-install-BnOYI4mZ.js} +4 -4
- package/dist/{ci-install-BKAvFfK6.js.map → ci-install-BnOYI4mZ.js.map} +1 -1
- package/dist/{debug-Cp_wNn8i.js → debug-BVC48wlb.js} +1 -1
- package/dist/{debug-DnMO6O8O.js → debug-h7Z9zEbD.js} +2 -2
- package/dist/{debug-DnMO6O8O.js.map → debug-h7Z9zEbD.js.map} +1 -1
- package/dist/{environment-Ls0H9ljT.js → environment-uaLmtlH_.js} +3 -3
- package/dist/{environment-Ls0H9ljT.js.map → environment-uaLmtlH_.js.map} +1 -1
- package/dist/{interactive-D15byhpc.js → interactive-CW5gjyDd.js} +2 -2
- package/dist/{interactive-D15byhpc.js.map → interactive-CW5gjyDd.js.map} +1 -1
- package/dist/{mcp-prompt-streaming-DQOTQfW1.js → mcp-prompt-streaming-DMDwaark.js} +4 -4
- package/dist/{mcp-prompt-streaming-DQOTQfW1.js.map → mcp-prompt-streaming-DMDwaark.js.map} +1 -1
- package/dist/{non-interactive-DcFLJtl_.js → non-interactive-DJrVQ4nS.js} +2 -2
- package/dist/{non-interactive-DcFLJtl_.js.map → non-interactive-DJrVQ4nS.js.map} +1 -1
- package/dist/{package-manager-DUPgLGpQ.js → package-manager-DCUBRbr-.js} +2 -2
- package/dist/{package-manager-DUPgLGpQ.js.map → package-manager-DCUBRbr-.js.map} +1 -1
- package/dist/{playground-BZ0hGjbL.js → playground-DCVaVeVD.js} +138 -9
- package/dist/playground-DCVaVeVD.js.map +1 -0
- package/dist/{posthog-integration-C8qhJnI3.js → posthog-integration-ChdwFPMj.js} +17 -11
- package/dist/posthog-integration-ChdwFPMj.js.map +1 -0
- package/dist/{provisioning-C-2ExcqY.js → provisioning-GeMkBMSR.js} +3 -3
- package/dist/{provisioning-C-2ExcqY.js.map → provisioning-GeMkBMSR.js.map} +1 -1
- package/dist/{registry-hBUgaWFx.js → registry-VSSRH3sU.js} +4 -4
- package/dist/{registry-hBUgaWFx.js.map → registry-VSSRH3sU.js.map} +1 -1
- package/dist/{setup-utils-DetnhXo0.js → setup-utils-BfV4pydt.js} +12 -10
- package/dist/setup-utils-BfV4pydt.js.map +1 -0
- package/dist/{start-tui-BfXoErKg.js → start-tui-BRvm5VP9.js} +93 -228
- package/dist/start-tui-BRvm5VP9.js.map +1 -0
- package/dist/{steps-SoDXSUxe.js → steps-DA4uvSbg.js} +6 -6
- package/dist/{steps-SoDXSUxe.js.map → steps-DA4uvSbg.js.map} +1 -1
- package/dist/{task-stream-CZRj6auI.js → task-stream-CZawuzlz.js} +2 -2
- package/dist/{task-stream-CZRj6auI.js.map → task-stream-CZawuzlz.js.map} +1 -1
- package/dist/{telemetry-CPcMFxcO.js → telemetry-BRAonUea.js} +2 -2
- package/dist/{telemetry-CPcMFxcO.js.map → telemetry-BRAonUea.js.map} +1 -1
- package/dist/{urls-BO7doNJG.js → urls-B66Ib2jT.js} +2 -2
- package/dist/{urls-BO7doNJG.js.map → urls-B66Ib2jT.js.map} +1 -1
- package/dist/{wizard-abort-CDXufkqJ.js → wizard-abort-D1_DnFjm.js} +12 -7
- package/dist/wizard-abort-D1_DnFjm.js.map +1 -0
- package/dist/wizard-abort-gMB1eV6T.js +2 -0
- package/dist/{wizard-session-d27JGRGi.js → wizard-session-G3VWD6hv.js} +3 -1
- package/dist/{wizard-session-d27JGRGi.js.map → wizard-session-G3VWD6hv.js.map} +1 -1
- package/dist/{wizard-session-y304gEEI.js → wizard-session-wPJtNl4c.js} +1 -1
- package/dist/wizard-ui-YdGFRyu_.js.map +1 -1
- package/package.json +4 -2
- package/dist/agent-interface-CQU6x4Hj.js.map +0 -1
- package/dist/playground-BZ0hGjbL.js.map +0 -1
- package/dist/posthog-integration-C8qhJnI3.js.map +0 -1
- package/dist/setup-utils-DetnhXo0.js.map +0 -1
- package/dist/slides-mT2s9wM_.js.map +0 -1
- package/dist/start-tui-BfXoErKg.js.map +0 -1
- package/dist/wizard-abort-CDXufkqJ.js.map +0 -1
- package/dist/wizard-abort-CtMY57ZE.js +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"OutroScreen-CqF6SdBo.js","names":["CHROME_ROWS","fs","copyData.pinnedFirstPrompt","copyData.defaultKit","copyData.roleKits","copyData.roleFamilyOverrides","copyData.roleGreetings","copyData.neutralGreeting","copyData.toolFollowUps","copyData.roleFollowUps","copyData.genericFollowUps","copyData.deepDiveFollowUps","copyData.crossSellByRole","copyData.neutralCrossSell","copyData.slackApp","ChoiceValue"],"sources":["../src/lib/programs/program-step.ts","../src/ui/tui/screen-sequences.ts","../src/ui/tui/router.ts","../src/ui/tui/store.ts","../src/ui/tui/primitives/CardLayout.tsx","../src/ui/tui/primitives/SplitView.tsx","../src/ui/tui/primitives/LoadingBox.tsx","../src/ui/tui/primitives/ProgressList.tsx","../src/ui/tui/primitives/PromptLabel.tsx","../src/ui/tui/hooks/keyboard-hints-utils.ts","../src/ui/tui/hooks/useKeyboardHints.tsx","../src/ui/tui/hooks/useKeyBindings.ts","../src/ui/tui/primitives/PickerMenu.tsx","../src/ui/tui/hooks/useStdoutDimensions.ts","../src/ui/tui/primitives/GroupedPickerMenu.tsx","../src/ui/tui/primitives/ConfirmationInput.tsx","../src/ui/tui/primitives/Divider.tsx","../src/ui/tui/primitives/ModalOverlay.tsx","../src/ui/tui/primitives/LogViewer.tsx","../src/ui/tui/primitives/EventPlanViewer.tsx","../src/ui/tui/components/TitleBar.tsx","../src/ui/tui/primitives/DissolveTransition.tsx","../src/ui/tui/primitives/KeyboardHintsBar.tsx","../src/ui/tui/primitives/ScreenErrorBoundary.tsx","../src/ui/tui/primitives/ScreenContainer.tsx","../src/ui/tui/primitives/TabContainer.tsx","../src/ui/tui/primitives/HNViewer.tsx","../src/ui/tui/primitives/LinesBlock.tsx","../src/ui/tui/primitives/NodeBlock.tsx","../src/ui/tui/primitives/ContentSequencer.tsx","../src/ui/tui/components/LearnCard.tsx","../src/ui/tui/components/TipsCard.tsx","../src/ui/tui/components/ServiceHealthList.tsx","../src/ui/tui/screens/doctor/IssueTable.tsx","../src/ui/tui/screens/McpScreen.tsx","../src/lib/mcp-role-prompts.copy.json","../src/lib/mcp-role-prompts.ts","../src/ui/tui/screens/McpSuggestedPromptsScreen.tsx","../src/ui/tui/screens/audit/AuditChecksViewer/AreaHeaderRow.tsx","../src/ui/tui/screens/audit/AuditChecksViewer/layout.ts","../src/ui/tui/screens/audit/AuditChecksViewer/CheckRow.tsx","../src/ui/tui/screens/audit/AuditChecksViewer/DetailRow.tsx","../src/ui/tui/screens/audit/AuditChecksViewer/Legend.tsx","../src/ui/tui/screens/audit/AuditChecksViewer/Header.tsx","../src/ui/tui/screens/audit/AuditChecksViewer/Footer.tsx","../src/ui/tui/screens/audit/AuditChecksViewer/sort.ts","../src/ui/tui/screens/audit/AuditChecksViewer/AuditChecksViewer.tsx","../src/ui/tui/screens/audit/slides/shared.tsx","../src/ui/tui/screens/audit/slides/installation.tsx","../src/ui/tui/screens/audit/slides/identification.tsx","../src/ui/tui/screens/audit/slides/eventCapture.tsx","../src/ui/tui/screens/audit/slides/writeReport.tsx","../src/ui/tui/screens/audit/slides/uploadNotebook.tsx","../src/ui/tui/screens/audit/slides/index.ts","../src/ui/tui/screens/audit-3000/slides/eventQuality.tsx","../src/ui/tui/screens/audit-3000/slides/featureFlags.tsx","../src/ui/tui/screens/audit-3000/slides/expansion.tsx","../src/ui/tui/screens/audit-3000/slides/index.ts","../src/ui/tui/screens/SlackConnectScreen.tsx","../src/ui/tui/screens/OutroScreen.tsx"],"sourcesContent":["import type { WizardSession, DiscoveredFeature } from '@lib/wizard-session';\nimport type { WizardReadinessResult } from '@lib/health-checks/readiness';\nimport type { ProgramRun } from '@lib/agent/agent-runner';\nimport type { Integration } from '@lib/constants';\nimport type { FrameworkConfig } from '@lib/framework-config';\nimport type { ContentBlock } from '@ui/tui/primitives/index';\nimport type { WizardStore } from '@ui/tui/store';\n\n/**\n * A program step is the primary unit of the wizard's execution model.\n *\n * It can own:\n * - a screen in the TUI (optional — some steps are headless)\n * - agent work via a program reference (optional — some steps are UI-only)\n * - completion and visibility predicates\n *\n * The PostHog integration program is one ordered list of steps.\n * Other programs (e.g. revenue analytics) register a different step list.\n */\n/**\n * Context passed to onInit callbacks — fires when the TUI starts\n * rendering, before bin.ts has assigned the real session.\n */\nexport interface StoreInitContext {\n readonly session: WizardSession;\n readonly setReadinessResult: (result: WizardReadinessResult | null) => void;\n readonly setFrameworkContext: (key: string, value: unknown) => void;\n readonly emitChange: () => void;\n}\n\n/**\n * Context passed to onReady callbacks — fires after bin.ts has assigned\n * the real session, so reading `session.installDir` returns the target\n * project. Use for async pre-program work like prerequisite detection.\n */\nexport interface ProgramReadyContext {\n readonly session: WizardSession;\n readonly setFrameworkContext: (key: string, value: unknown) => void;\n\n // Detection-specific methods — used by core-integration's detect step\n readonly setFrameworkConfig: (\n integration: Integration,\n config: FrameworkConfig,\n ) => void;\n readonly setDetectedFramework: (label: string) => void;\n readonly setUnsupportedVersion: (info: {\n current: string;\n minimum: string;\n docsUrl: string;\n }) => void;\n readonly addDiscoveredFeature: (feature: DiscoveredFeature) => void;\n readonly setDetectionComplete: () => void;\n}\n\nexport interface ProgramStep {\n /** Unique identifier for this step */\n id: string;\n\n /** Human-readable label for progress display */\n label: string;\n\n /**\n * TUI screen this step owns, if any.\n * Matches the ScreenId enum values (e.g. 'intro', 'run', 'outro').\n */\n screenId?: string;\n\n /**\n * Whether this step should be visible in the current program.\n * If omitted, the step is always visible.\n */\n show?: (session: WizardSession) => boolean;\n\n /**\n * Exit condition for the screen. Router advances when true.\n * Defaults to `gate` if unset.\n */\n isComplete?: (session: WizardSession) => boolean;\n\n /**\n * Define a gate if your screen needs to await user interactions.\n * bin.ts can `await store.getGate(stepId)` to pause until the\n * predicate becomes true.\n */\n gate?: (session: WizardSession) => boolean;\n\n /**\n * Called once when the TUI starts rendering, with the default\n * session. Use for session-independent fire-and-forget work that\n * should start as early as possible (e.g. health check kicked off\n * while the user is still reading the intro screen). Never fires for\n * a store that isn't rendering screens (tests, playground).\n */\n onInit?: (ctx: StoreInitContext) => void;\n\n /**\n * Called once after bin.ts has assigned the real session to the store,\n * before any gate is awaited. Awaited in sequence with other steps'\n * onReady callbacks. Use for session-dependent pre-program work like\n * scanning the installDir for prerequisites. May be sync or async.\n */\n onReady?: (ctx: ProgramReadyContext) => void | Promise<void>;\n}\n\n/**\n * Uniform configuration for a wizard program.\n *\n * Each program directory exports one of these. The system uses it\n * for CLI registration, sequence/step wiring, and skill bootstrap.\n */\nexport interface ProgramConfig {\n /** CLI command name (e.g. 'revenue'). Omit for the default program. */\n command?: string;\n /**\n * Parent CLI command to nest this program under. When set, the program is\n * registered as `<parentCommand> <command>` instead of as a top-level\n * command. The parent must itself be a registered subcommand program. Omit\n * for top-level programs.\n */\n parentCommand?: string;\n /** CLI description shown in --help */\n description: string;\n /** Unique program id — matches the Program enum value */\n id: string;\n /**\n * Context-mill skill ID this program installs and runs. When present,\n * bin.ts seeds `session.skillId` with this value before the TUI renders\n * so intro screens can resolve skill metadata without waiting for the\n * agent run.\n */\n skillId?: string;\n /** The ordered step list */\n steps: ProgramStep[];\n /** Agent run config. Static object or async function for dynamic config. */\n run?: ProgramRun | ((session: WizardSession) => Promise<ProgramRun>);\n /**\n * CI-mode pre-run strategy. When set, runWizardCI awaits this after building\n * the ci:true session and before the agent runs, instead of walking step\n * onReady hooks. Use for headless prerequisite work (e.g. framework\n * detection) that the TUI performs via step onReady callbacks.\n */\n ciPreRun?: (session: WizardSession) => Promise<void>;\n /** Prerequisites: other program ids that must have run first */\n requires?: string[];\n /**\n * Path (relative to installDir) of the report file the program writes.\n * Mirrors `run.reportFile` but lifted to the top level so UI screens can\n * read it synchronously without resolving a deferred `run` function.\n */\n reportFile?: string;\n /**\n * LearnCard deck rendered in the shared `RunScreen` while the agent\n * runs. Lives at `<program>/content/index.tsx` by convention.\n * Programs that ship a custom RunScreen variant (audit, audit-3000)\n * or skip the run step (posthog-doctor) leave this unset.\n */\n getContentBlocks?: (store?: WizardStore) => ContentBlock[];\n /**\n * Subcommand-specific CLI options. Spread into yargs `.options(...)` when the\n * program's subcommand is registered. Program-specific knowledge stays in\n * the program config, not in bin.ts. Typed as `unknown` to avoid pulling a\n * yargs dependency into this module.\n */\n cliOptions?: Record<string, unknown>;\n /**\n * Translate parsed CLI argv into extra options the runner consumes. Runs\n * after yargs validation, before runWizard/runWizardCI. Use this when a flag\n * needs to derive another field (e.g. `--product=statsig` → `skillId:\n * 'migrate-statsig'`).\n */\n mapCliOptions?: (argv: Record<string, unknown>) => Record<string, unknown>;\n /**\n * Extra tool names added on top of BASE_ALLOWED_TOOLS for this program's\n * agent run. Use for tools that only this program needs.\n */\n allowedTools?: readonly string[];\n /**\n * Tool names removed from BASE_ALLOWED_TOOLS for this program's agent\n * run. Use to forbid a base tool — e.g. `['Agent']` to block subagent\n * dispatch in a program whose steps are explicitly single-agent.\n */\n disallowedTools?: readonly string[];\n}\n\n/**\n * Project program steps into the narrower Screen shape the router consumes.\n *\n * Two things happen here:\n * 1. Headless steps (no `screenId`) are filtered out. The router walks\n * visible screens; gate-only steps like `detect` are store concerns.\n * 2. The step is narrowed to just { id, show, isComplete } — the\n * router has no business touching gate, onInit, or label.\n *\n * This intentional separation keeps the router focused on one question:\n * \"Which screen should be rendered right now?\"\n */\nexport function createProgramSequence(steps: ProgramStep[]): Array<{\n id: string;\n show?: (session: WizardSession) => boolean;\n isComplete?: (session: WizardSession) => boolean;\n}> {\n const entries = steps\n .filter((step) => step.screenId != null)\n .map((step) => ({\n id: step.screenId!,\n show: step.show,\n // `isComplete` defaults to `gate` — for most steps they're the same\n // predicate (e.g. intro: setupConfirmed unblocks bin.ts AND finishes\n // the screen). Only override when the two conditions diverge.\n isComplete: step.isComplete ?? step.gate,\n }));\n\n // Every program ends with the exit screen.\n entries.push({ id: 'exit', show: undefined, isComplete: undefined });\n\n return entries;\n}\n","/**\n * Screen taxonomy + per-program screen sequences.\n *\n * Owns the ScreenId enum and projects each registered program's steps\n * into the router-shaped screen sequence (filtering headless steps and\n * appending the exit screen). Pure leaf module — no store, no React.\n */\n\nimport type { WizardSession } from '@lib/wizard-session';\nimport {\n PROGRAM_REGISTRY,\n type ProgramId,\n} from '@lib/programs/program-registry';\nimport { createProgramSequence } from '@lib/programs/program-step';\n\n/** Screens that participate in linear programs. */\nexport enum ScreenId {\n Intro = 'intro',\n RevenueIntro = 'revenue-intro',\n SourceMapsIntro = 'source-maps-intro',\n SourceMapsOutro = 'source-maps-outro',\n MigrationIntro = 'migration-intro',\n AgentSkillIntro = 'agent-skill-intro',\n AuditIntro = 'audit-intro',\n AuditRun = 'audit-run',\n AuditOutro = 'audit-outro',\n Audit3000Intro = 'audit-3000-intro',\n Audit3000Run = 'audit-3000-run',\n Audit3000Outro = 'audit-3000-outro',\n HealthCheck = 'health-check',\n DoctorIntro = 'doctor-intro',\n DoctorReport = 'doctor-report',\n Setup = 'setup',\n Auth = 'auth',\n Run = 'run',\n Mcp = 'mcp',\n McpSuggestedPrompts = 'mcp-suggested-prompts',\n SlackConnect = 'slack-connect',\n KeepSkills = 'keep-skills',\n Outro = 'outro',\n Exit = 'exit',\n McpAdd = 'mcp-add',\n McpRemove = 'mcp-remove',\n}\n\nexport interface Screen {\n /** ScreenId to show */\n id: ScreenId;\n /** If provided, screen is skipped when this returns false. Omit = always show. */\n show?: (session: WizardSession) => boolean;\n /** If provided, screen is considered complete when this returns true. */\n isComplete?: (session: WizardSession) => boolean;\n}\n\n/** An ordered list of screens — a program's screen journey. */\nexport type Sequence = Screen[];\n\n/** All program screen sequences keyed by program id. */\nexport const PROGRAM_SEQUENCES: Record<ProgramId, Sequence> =\n Object.fromEntries(\n PROGRAM_REGISTRY.map((c) => [\n c.id,\n createProgramSequence(c.steps) as Sequence,\n ]),\n ) as Record<ProgramId, Sequence>;\n","/**\n * WizardRouter — declarative program pipelines + overlay stack.\n *\n * Two layers:\n * Program cursor — linear sequence of screens, advanced with next()\n * Overlay stack — interrupts (outage, auth-expired, etc.) that push/pop\n *\n * The visible screen is: top of overlay stack if non-empty, otherwise the program cursor.\n *\n * Adding a program screen = append to a sequence array.\n * Adding an overlay = call pushOverlay() from anywhere.\n * No switch statements, no hardcoded transitions in business logic.\n */\n\nimport type { WizardSession } from '@lib/wizard-session';\nimport { Program, type ProgramId } from '@lib/programs/program-registry';\nimport {\n PROGRAM_SEQUENCES,\n ScreenId,\n type Screen,\n type Sequence,\n} from './screen-sequences.js';\n\n// Re-export so existing imports from './router.js' keep working\nexport { ScreenId, Program };\nexport type { Screen, Sequence, ProgramId };\n\n// ── ScreenId name taxonomy ──────────────────────────────────────────────\n\n/** Screens that interrupt programs as overlays */\nexport enum Overlay {\n SettingsOverride = 'settings-override',\n ManagedSettings = 'managed-settings',\n PortConflict = 'port-conflict',\n ManualAuthCode = 'manual-auth-code',\n AuthError = 'auth-error',\n WizardAsk = 'wizard-ask',\n}\n\n/** Union of all screen names */\nexport type ScreenName = ScreenId | Overlay;\n\n// ── Router ────────────────────────────────────────────────────────────\n\nexport class WizardRouter {\n private sequence: Sequence;\n private programId: ProgramId;\n private overlays: Overlay[] = [];\n\n constructor(programId: ProgramId = Program.PostHogIntegration) {\n this.programId = programId;\n this.sequence = PROGRAM_SEQUENCES[programId];\n }\n\n /**\n * Resolve which screen should be active based on session state.\n * Walks the program sequence, skipping hidden entries and completed entries,\n * returns the first incomplete screen.\n */\n resolve(session: WizardSession): ScreenName {\n if (this.overlays.length > 0) {\n return this.overlays[this.overlays.length - 1];\n }\n\n for (const entry of this.sequence) {\n if (entry.show && !entry.show(session)) continue;\n if (entry.isComplete && entry.isComplete(session)) continue;\n return entry.id;\n }\n\n // All entries complete — show the last screen (outro)\n return this.sequence[this.sequence.length - 1].id;\n }\n\n /** The screen that should be rendered right now. */\n get activeScreen(): ScreenName {\n // Overlays take priority — resolve() handles this too,\n // but activeScreen is called before session is available in some paths\n if (this.overlays.length > 0) {\n return this.overlays[this.overlays.length - 1];\n }\n return this.sequence[0].id;\n }\n\n /** The id of the active program. */\n get activeProgram(): ProgramId {\n return this.programId;\n }\n\n /** Whether an overlay is currently active. */\n get hasOverlay(): boolean {\n return this.overlays.length > 0;\n }\n\n /**\n * Push an overlay that interrupts the current program.\n * The program resumes when the overlay is dismissed via popOverlay().\n */\n pushOverlay(overlay: Overlay): void {\n this.overlays.push(overlay);\n }\n\n /**\n * Dismiss the topmost overlay. The program screen underneath resumes.\n */\n popOverlay(): void {\n this.overlays.pop();\n }\n\n /**\n * Direction hint for screen transitions.\n */\n private _lastDirection: 'push' | 'pop' | null = null;\n\n get lastNavDirection(): 'push' | 'pop' | null {\n return this._lastDirection;\n }\n\n /** @internal — called by store wrapper to track direction */\n _setDirection(dir: 'push' | 'pop' | null): void {\n this._lastDirection = dir;\n }\n}\n","/**\n * WizardStore — Nanostore-backed reactive store for the TUI.\n * React components subscribe via useSyncExternalStore.\n *\n * The active screen is derived from session state — WizardRouter walks\n * the flow and shows the first step whose `isComplete` is still false.\n *\n * Define a step `gate` if your screen needs to await user interactions.\n * bin.ts calls `await store.getGate(stepId)` to pause until the gate\n * predicate becomes true.\n *\n * All session mutations that affect screen resolution go through\n * explicit setters so emitChange() is always called.\n */\n\nimport { atom, map } from 'nanostores';\nimport { logToFile } from '@utils/debug';\nimport { TaskStatus, isTaskStatus, type AuthErrorDetail } from '@ui/wizard-ui';\nimport {\n type WizardSession,\n type OutroData,\n type DiscoveredFeature,\n type PendingQuestion,\n type AskAnswers,\n AdditionalFeature,\n McpOutcome,\n RunPhase,\n buildSession,\n} from '@lib/wizard-session';\nimport type { SettingsConflict } from '@lib/agent/claude-settings';\nimport type { WizardReadinessResult } from '@lib/health-checks/readiness';\nimport {\n WizardRouter,\n type ScreenName,\n ScreenId,\n Overlay,\n Program,\n type ProgramId,\n} from './router.js';\nimport { analytics, sessionProperties } from '@utils/analytics';\nimport type {\n StoreInitContext,\n ProgramReadyContext,\n} from '@lib/programs/program-step';\nimport { getProgramConfig } from '@lib/programs/program-registry';\nimport { EXPANDED_COUNT } from '@ui/tui/constants';\n\nexport { TaskStatus, ScreenId, Overlay, Program, RunPhase, McpOutcome };\nexport type { ScreenName, OutroData, WizardSession, ProgramId };\n\nexport interface TaskItem {\n label: string;\n activeForm?: string;\n status: TaskStatus;\n /** Legacy compat */\n done: boolean;\n}\n\nexport interface PlannedEvent {\n name: string;\n description: string;\n}\n\ninterface GateEntry {\n predicate: (session: WizardSession) => boolean;\n promise: Promise<void>;\n resolve: () => void;\n resolved: boolean;\n}\n\n/**\n * FIFO cap on retained status lines. The status bar is the only consumer and\n * renders at most EXPANDED_COUNT lines, so there is no reason to retain more —\n * the cap is tied to the window it feeds.\n */\nconst MAX_STATUS_MESSAGES = EXPANDED_COUNT;\n\nexport class WizardStore {\n // ── Internal nanostore atoms ─────────────────────────────────────\n private $session = map<WizardSession>(buildSession({}));\n private $statusMessages = atom<string[]>([]);\n private $statusExpanded = atom(false);\n private $tasks = atom<TaskItem[]>([]);\n private $eventPlan = atom<PlannedEvent[]>([]);\n private $learnCardBlockIdx = atom(0);\n private $learnCardComplete = atom(false);\n private $version = atom(0);\n\n private _onTasksChanged: (() => void) | null = null;\n /** Last screen seen — used to detect screen transitions for analytics. */\n private _lastScreen: ScreenName | null = null;\n\n /** Hooks run when transitioning onto a screen. */\n private _enterScreenHooks = new Map<ScreenName, (() => void)[]>();\n\n /** Gate promises derived from program step definitions. */\n private _gates = new Map<string, GateEntry>();\n\n version = '';\n\n /** Navigation router — resolves active screen from session state. */\n readonly router: WizardRouter;\n\n /** Blocks agent execution until the settings-override overlay is dismissed. */\n private _resolveSettingsOverride: (() => void) | null = null;\n private _backupAndFixSettings: (() => boolean) | null = null;\n\n /** Blocks OAuth flow until the port-conflict overlay is dismissed. */\n private _resolvePortConflict: (() => void) | null = null;\n\n /** Resolves the OAuth flow with a manually-entered authorization code. */\n private _resolveManualAuthCode: ((code: string) => void) | null = null;\n\n /** Resolves the in-flight wizard_ask request. */\n private _resolvePendingQuestion: ((answers: AskAnswers) => void) | null =\n null;\n\n constructor(program: ProgramId = Program.PostHogIntegration) {\n this.router = new WizardRouter(program);\n this._initFromProgram(program);\n }\n\n /**\n * Scan program steps for gate predicates and create gate promises.\n */\n private _initFromProgram(program: ProgramId): void {\n const steps = getProgramConfig(program).steps;\n\n // Create gate promises from steps that define them\n for (const step of steps) {\n if (step.gate) {\n let resolve!: () => void;\n const promise = new Promise<void>((r) => {\n resolve = r;\n });\n this._gates.set(step.id, {\n predicate: step.gate,\n promise,\n resolve,\n resolved: false,\n });\n }\n }\n }\n\n /**\n * Run the program steps' onInit callbacks. startTUI calls this once\n * the screens are actually rendering — constructing a store alone\n * (tests, playground) must not fire init work like the health-check\n * pre-flight, whose probes belong only to flows that show its screen.\n */\n runInitHooks(): void {\n const steps = getProgramConfig(this.router.activeProgram).steps;\n const getSession = (): WizardSession => this.session;\n const ctx: StoreInitContext = {\n get session() {\n return getSession();\n },\n setReadinessResult: (r) => this.setReadinessResult(r),\n setFrameworkContext: (k, v) => this.setFrameworkContext(k, v),\n emitChange: () => this.emitChange(),\n };\n for (const step of steps) {\n step.onInit?.(ctx);\n }\n }\n\n /**\n * Run all `onReady` hooks declared by the current flow's steps, in\n * order. Must be called after `store.session = session` so hooks see\n * the real installDir. bin.ts calls this generically — it doesn't\n * need to know which program has which pre-flow work.\n */\n async runReadyHooks(): Promise<void> {\n const steps = getProgramConfig(this.router.activeProgram).steps;\n const ctx: ProgramReadyContext = {\n session: this.session,\n setFrameworkContext: (k, v) => this.setFrameworkContext(k, v),\n setFrameworkConfig: (i, c) => this.setFrameworkConfig(i, c),\n setDetectedFramework: (l) => this.setDetectedFramework(l),\n setUnsupportedVersion: (info) => this.setUnsupportedVersion(info),\n addDiscoveredFeature: (f) => this.addDiscoveredFeature(f),\n setDetectionComplete: () => this.setDetectionComplete(),\n };\n for (const step of steps) {\n if (step.onReady) {\n await step.onReady(ctx);\n }\n }\n }\n\n // ── Gate API ────────────────────────────────────────────────────\n\n /**\n * Get a gate promise by step ID — the primary blocking checkpoint API\n * for bin.ts. `await store.getGate('...')` parks the caller until the\n * corresponding program step's gate predicate flips to true (if the\n * predicate stays false, the caller stays parked indefinitely — the\n * TUI keeps rendering so the user can resolve whatever is blocking).\n *\n * If the program doesn't define a step with this ID, or the step\n * has no `gate` predicate, this returns an already-resolved promise\n * so bin.ts flows straight through. This lets programs opt in to\n * gates on a per-step basis without bin.ts needing to know which\n * gates exist in which flow.\n */\n getGate(stepId: string): Promise<void> {\n return this._gates.get(stepId)?.promise ?? Promise.resolve();\n }\n\n /**\n * Re-evaluate every gate predicate against the current session and\n * resolve any whose predicate now returns true. Called after every\n * emitChange(), so gates unblock as soon as the session mutation\n * that satisfies them lands. Gates only resolve once — a predicate\n * that goes true → false → true will NOT re-block a caller that\n * already awaited through.\n */\n private _checkGates(): void {\n for (const [, gate] of this._gates) {\n if (!gate.resolved && gate.predicate(this.session)) {\n gate.resolved = true;\n gate.resolve();\n }\n }\n }\n\n // ── State accessors (read from atoms) ────────────────────────────\n\n get session(): WizardSession {\n return this.$session.get();\n }\n\n set session(value: WizardSession) {\n this.$session.set(value);\n this.emitChange();\n }\n\n get statusMessages(): string[] {\n return this.$statusMessages.get();\n }\n\n get tasks(): TaskItem[] {\n return this.$tasks.get();\n }\n\n get eventPlan(): PlannedEvent[] {\n return this.$eventPlan.get();\n }\n\n get statusExpanded(): boolean {\n return this.$statusExpanded.get();\n }\n\n toggleStatusExpanded(): void {\n this.$statusExpanded.set(!this.$statusExpanded.get());\n this.emitChange();\n }\n\n setStatusExpanded(expanded: boolean): void {\n if (this.$statusExpanded.get() !== expanded) {\n this.$statusExpanded.set(expanded);\n this.emitChange();\n }\n }\n\n // ── Session setters ─────────────────────────────────────────────\n // Every setter that affects screen resolution calls emitChange().\n // Business logic calls these instead of mutating session directly.\n\n /** Sets setupConfirmed. Gate resolves via _checkGates(). */\n completeSetup(): void {\n this.$session.setKey('setupConfirmed', true);\n analytics.wizardCapture('setup confirmed', sessionProperties(this.session));\n this.emitChange();\n }\n\n setRunPhase(phase: RunPhase): void {\n this.$session.setKey('runPhase', phase);\n this.emitChange();\n }\n\n setCredentials(credentials: WizardSession['credentials']): void {\n this.$session.setKey('credentials', credentials);\n analytics.wizardCapture('auth complete', {\n project_id: credentials?.projectId,\n });\n this.emitChange();\n }\n\n setRoleAtOrganization(role: string | null): void {\n this.$session.setKey('roleAtOrganization', role);\n this.emitChange();\n }\n\n setApiUser(user: WizardSession['apiUser']): void {\n this.$session.setKey('apiUser', user);\n this.emitChange();\n }\n\n setFrameworkConfig(\n integration: WizardSession['integration'],\n config: WizardSession['frameworkConfig'],\n ): void {\n this.$session.setKey('integration', integration);\n this.$session.setKey('frameworkConfig', config);\n this.$session.setKey('unsupportedVersion', null);\n this.emitChange();\n }\n\n setDetectionComplete(): void {\n this.$session.setKey('detectionComplete', true);\n this.emitChange();\n }\n\n setDetectedFramework(label: string): void {\n this.$session.setKey('detectedFrameworkLabel', label);\n this.emitChange();\n }\n\n setUnsupportedVersion(info: {\n current: string;\n minimum: string;\n docsUrl: string;\n }): void {\n this.$session.setKey('unsupportedVersion', info);\n this.emitChange();\n }\n\n setLoginUrl(url: string | null): void {\n this.$session.setKey('loginUrl', url);\n this.emitChange();\n }\n\n setAuthorizeUrl(url: string | null): void {\n this.$session.setKey('authorizeUrl', url);\n this.emitChange();\n }\n\n setReadinessResult(result: WizardReadinessResult | null): void {\n this.$session.setKey('readinessResult', result);\n this.emitChange();\n }\n\n /** User dismissed the blocking outage screen. Gate resolves via _checkGates(). */\n dismissOutage(): void {\n logToFile('[health-checks] user dismissed outage screen, continuing');\n this.$session.setKey('outageDismissed', true);\n this.emitChange();\n }\n\n /**\n * Push the settings-override overlay and return a promise that blocks\n * until the user dismisses it via backupAndFixSettingsOverride().\n */\n showSettingsOverride(\n conflicts: SettingsConflict[],\n backupAndFix: () => boolean,\n ): Promise<void> {\n const allKeys = conflicts.flatMap((c) => c.keys);\n this.$session.setKey('settingsOverrideKeys', allKeys);\n this.$session.setKey('settingsConflicts', conflicts);\n this._backupAndFixSettings = backupAndFix;\n\n const hasReadOnly = conflicts.some((c) => !c.writable);\n if (hasReadOnly) {\n this.pushOverlay(Overlay.ManagedSettings);\n } else {\n this.pushOverlay(Overlay.SettingsOverride);\n }\n\n return new Promise((resolve) => {\n this._resolveSettingsOverride = resolve;\n });\n }\n\n /**\n * Push the port-conflict overlay and return a promise that blocks\n * until the user frees the ports and retries, or exits.\n */\n showPortConflict(processInfo: {\n command: string;\n pid: string;\n port: number;\n user: string;\n }): Promise<void> {\n this.$session.setKey('portConflictProcess', processInfo);\n this.pushOverlay(Overlay.PortConflict);\n return new Promise((resolve) => {\n this._resolvePortConflict = resolve;\n });\n }\n\n /** Dismiss the port-conflict overlay and retry the OAuth port loop. */\n resolvePortConflict(): void {\n this.$session.setKey('portConflictProcess', null);\n this.popOverlay();\n this._resolvePortConflict?.();\n this._resolvePortConflict = null;\n }\n\n /**\n * Return a promise that resolves when the user submits a manually-entered\n * OAuth code via the paste modal. The OAuth flow races this against the\n * local callback server — see `performOAuthFlow`.\n */\n waitForManualAuthCode(): Promise<string> {\n return new Promise<string>((resolve) => {\n this._resolveManualAuthCode = resolve;\n });\n }\n\n /** Open the manual OAuth code-entry overlay over the auth screen. */\n showManualAuthCode(): void {\n this.pushOverlay(Overlay.ManualAuthCode);\n }\n\n /** Dismiss the manual OAuth code overlay without submitting. */\n dismissManualAuthCode(): void {\n this.popOverlay();\n }\n\n /**\n * Submit a manually-entered authorization code: dismiss the overlay and\n * resolve the in-flight OAuth flow so it can exchange the code for a token.\n */\n submitManualAuthCode(code: string): void {\n this.popOverlay();\n this._resolveManualAuthCode?.(code);\n this._resolveManualAuthCode = null;\n }\n\n /**\n * Open the WizardAsk overlay with a set of questions and return a promise\n * that resolves once the user submits answers (or the request is cancelled).\n *\n * Only one request is in flight at a time — calling this while a request\n * is already pending throws.\n */\n requestQuestion(question: PendingQuestion): Promise<AskAnswers> {\n if (this._resolvePendingQuestion) {\n throw new Error(\n 'requestQuestion called while another wizard_ask request is pending',\n );\n }\n this.$session.setKey('pendingQuestion', question);\n this.pushOverlay(Overlay.WizardAsk);\n analytics.wizardCapture('wizard_ask shown', {\n source: question.source,\n question_count: question.questions.length,\n kinds: question.questions.map((q) => q.kind),\n });\n return new Promise<AskAnswers>((resolve) => {\n this._resolvePendingQuestion = resolve;\n });\n }\n\n /**\n * Resolve the in-flight wizard_ask request with the user's answers and\n * dismiss the overlay. Answers flow back to the agent as the tool result.\n */\n resolvePendingQuestion(answers: AskAnswers): void {\n const resolve = this._resolvePendingQuestion;\n this._resolvePendingQuestion = null;\n this.$session.setKey('pendingQuestion', null);\n this.popOverlay();\n resolve?.(answers);\n }\n\n /**\n * Cancel the in-flight wizard_ask request — the bridge sends a sentinel\n * answer (\"__cancelled__\") so the skill can decide how to handle it.\n */\n cancelPendingQuestion(): void {\n const pending = this.session.pendingQuestion;\n if (!pending) return;\n const cancelled: AskAnswers = {};\n for (const q of pending.questions) {\n cancelled[q.id] = '__cancelled__';\n }\n this.resolvePendingQuestion(cancelled);\n }\n\n /**\n * Back up .claude/settings.json. Dismisses the overlay on success.\n */\n backupAndFixSettingsOverride(): boolean {\n const ok = this._backupAndFixSettings?.() ?? false;\n if (ok) {\n this.$session.setKey('settingsOverrideKeys', null);\n this.$session.setKey('settingsConflicts', null);\n this.popOverlay();\n this._resolveSettingsOverride?.();\n this._resolveSettingsOverride = null;\n this._backupAndFixSettings = null;\n }\n return ok;\n }\n\n /** Push the auth-error overlay (no dismiss — user must exit). */\n showAuthError(detail?: AuthErrorDetail): void {\n this.$session.setKey('authErrorDetail', detail ?? null);\n this.pushOverlay(Overlay.AuthError);\n }\n\n addDiscoveredFeature(feature: DiscoveredFeature): void {\n if (!this.session.discoveredFeatures.includes(feature)) {\n this.session.discoveredFeatures.push(feature);\n this.emitChange();\n }\n }\n\n /**\n * Enable an additional feature: enqueue it for the stop hook\n * and set any feature-specific session flags.\n */\n enableFeature(feature: AdditionalFeature): void {\n if (!this.session.additionalFeatureQueue.includes(feature)) {\n this.session.additionalFeatureQueue.push(feature);\n }\n // Feature-specific flags\n if (feature === AdditionalFeature.LLM) {\n this.session.llmOptIn = true;\n }\n analytics.wizardCapture('feature enabled', { feature });\n this.emitChange();\n }\n\n setMcpComplete(\n outcome: McpOutcome = McpOutcome.Skipped,\n installedClients: string[] = [],\n featuresSelected?: 'all' | string[],\n ): void {\n this.$session.setKey('mcpComplete', true);\n this.$session.setKey('mcpOutcome', outcome);\n this.$session.setKey('mcpInstalledClients', installedClients);\n const featuresPayload =\n outcome === McpOutcome.Installed && featuresSelected !== undefined\n ? { mcp_features_selected: featuresSelected }\n : {};\n analytics.wizardCapture('mcp complete', {\n mcp_outcome: outcome,\n mcp_installed_clients: installedClients,\n ...featuresPayload,\n ...sessionProperties(this.session),\n });\n this.emitChange();\n }\n\n setSkillsComplete(kept: boolean): void {\n this.$session.setKey('skillsComplete', true);\n analytics.wizardCapture('skills complete', {\n skills_kept: kept,\n ...sessionProperties(this.session),\n });\n this.emitChange();\n }\n\n setMcpSuggestedPromptsDismissed(): void {\n this.$session.setKey('mcpSuggestedPromptsDismissed', true);\n this.emitChange();\n }\n\n setSlackStepDismissed(): void {\n this.$session.setKey('slackStepDismissed', true);\n this.emitChange();\n }\n\n setSlackConnected(connected: boolean): void {\n this.$session.setKey('slackConnected', connected);\n this.emitChange();\n }\n\n setOutroDismissed(): void {\n this.$session.setKey('outroDismissed', true);\n this.emitChange();\n }\n\n setOutroData(data: OutroData): void {\n this.$session.setKey('outroData', data);\n this.emitChange();\n }\n\n setDashboardUrl(url: string): void {\n logToFile(`store.setDashboardUrl: ${url}`);\n this.$session.setKey('dashboardUrl', url);\n this.emitChange();\n }\n\n setNotebookUrl(url: string): void {\n logToFile(`store.setNotebookUrl: ${url}`);\n this.$session.setKey('notebookUrl', url);\n this.emitChange();\n }\n\n setFrameworkContext(key: string, value: unknown): void {\n const ctx = { ...this.$session.get().frameworkContext, [key]: value };\n this.$session.setKey('frameworkContext', ctx);\n this.emitChange();\n }\n\n // ── Derived state ───────────────────────────────────────────────\n\n /**\n * The screen that should be rendered right now.\n * Derived from session state via the router.\n */\n get currentScreen(): ScreenName {\n return this.router.resolve(this.session);\n }\n\n /** Direction hint for screen transitions. */\n get lastNavDirection(): 'push' | 'pop' | null {\n return this.router.lastNavDirection;\n }\n\n // ── Change notification ─────────────────────────────────────────\n\n getVersion(): number {\n return this.$version.get();\n }\n\n /**\n * Notify React that state has changed.\n * The router re-resolves the active screen on next render.\n * Gate predicates are checked and resolved if ready.\n */\n emitChange(): void {\n this.router._setDirection('push');\n this.$version.set(this.$version.get() + 1);\n this._checkGates();\n this._detectTransition();\n }\n\n // ── Overlay navigation ──────────────────────────────────────────\n\n pushOverlay(overlay: Overlay): void {\n this.router._setDirection('push');\n this.router.pushOverlay(overlay);\n this.$version.set(this.$version.get() + 1);\n this._detectTransition();\n }\n\n popOverlay(): void {\n this.router._setDirection('pop');\n this.router.popOverlay();\n this.$version.set(this.$version.get() + 1);\n this._detectTransition();\n }\n\n // ── ScreenId transition analytics ─────────────────────────────────\n\n /**\n * Register a callback to run when transitioning onto the given screen.\n * Fires after every transition that lands on this screen.\n */\n onEnterScreen(screen: ScreenName, fn: () => void): void {\n const list = this._enterScreenHooks.get(screen) ?? [];\n list.push(fn);\n this._enterScreenHooks.set(screen, list);\n }\n\n /**\n * Detect screen transitions, run enter-screen hooks, and fire analytics.\n * Called at the end of emitChange/pushOverlay/popOverlay.\n */\n private _detectTransition(): void {\n const next = this.router.resolve(this.session);\n const prev = this._lastScreen;\n if (prev !== null && next !== prev) {\n const hooks = this._enterScreenHooks.get(next);\n if (hooks) {\n for (const fn of hooks) fn();\n }\n analytics.wizardCapture(`screen ${next}`, {\n from_screen: prev,\n program_id: this.router.activeProgram,\n ...sessionProperties(this.session),\n });\n }\n this._lastScreen = next;\n }\n\n // ── Agent observation state ─────────────────────────────────────\n\n pushStatus(message: string): void {\n const msgs = this.$statusMessages.get();\n // Skip consecutive duplicate messages (no allocation on the hot path)\n if (msgs.length > 0 && msgs[msgs.length - 1] === message) return;\n // Nanostore detects change by reference equality, so a new array is\n // required. At the cap, allocate exactly once at the final size (dropping\n // the oldest entry) rather than push-then-truncate.\n const next =\n msgs.length >= MAX_STATUS_MESSAGES\n ? [...msgs.slice(msgs.length - MAX_STATUS_MESSAGES + 1), message]\n : [...msgs, message];\n this.$statusMessages.set(next);\n this.emitChange();\n }\n\n setTasks(tasks: TaskItem[]): void {\n this.$tasks.set(tasks);\n this.emitChange();\n }\n\n updateTask(index: number, done: boolean): void {\n const tasks = this.$tasks.get();\n if (tasks[index]) {\n const updated = [...tasks];\n updated[index] = {\n ...updated[index],\n done,\n status: done ? TaskStatus.Completed : TaskStatus.Pending,\n };\n this.$tasks.set(updated);\n this.emitChange();\n }\n }\n\n setEventPlan(events: PlannedEvent[]): void {\n this.$eventPlan.set(events);\n this.emitChange();\n }\n\n get learnCardBlockIdx(): number {\n return this.$learnCardBlockIdx.get();\n }\n\n setLearnCardBlockIdx(idx: number): void {\n this.$learnCardBlockIdx.set(idx);\n }\n\n get learnCardComplete(): boolean {\n return this.$learnCardComplete.get();\n }\n\n setLearnCardComplete(): void {\n this.$learnCardComplete.set(true);\n this.emitChange();\n }\n\n syncTodos(\n todos: Array<{ content: string; status: string; activeForm?: string }>,\n ): void {\n const incoming = todos.map((t) => {\n const status = isTaskStatus(t.status) ? t.status : TaskStatus.Pending;\n return {\n label: t.content,\n activeForm: t.activeForm,\n status,\n done: status === TaskStatus.Completed,\n };\n });\n\n const incomingLabels = new Set(incoming.map((t) => t.label));\n\n const retained = this.$tasks\n .get()\n .filter((t) => t.done && !incomingLabels.has(t.label));\n\n this.$tasks.set([...retained, ...incoming]);\n this.emitChange();\n this._onTasksChanged?.();\n }\n\n /** Register a listener for task state changes (e.g. task stream push). */\n set onTasksChanged(fn: () => void) {\n this._onTasksChanged = fn;\n }\n\n // ── React integration ───────────────────────────────────────────\n\n subscribe(callback: () => void): () => void {\n return this.$version.listen(() => callback());\n }\n\n getSnapshot(): number {\n return this.$version.get();\n }\n}\n","/**\n * CardLayout — Aligns a single child within available space.\n */\n\nimport { Box } from 'ink';\nimport type { ReactNode } from 'react';\nimport { HAlign, VAlign } from '@ui/tui/styles';\n\ninterface CardLayoutProps {\n hAlign?: HAlign;\n vAlign?: VAlign;\n children: ReactNode;\n}\n\nexport const CardLayout = ({\n hAlign = HAlign.Left,\n vAlign = VAlign.Top,\n children,\n}: CardLayoutProps) => {\n return (\n <Box\n flexDirection=\"column\"\n flexGrow={1}\n justifyContent={vAlign}\n alignItems={hAlign}\n >\n {children}\n </Box>\n );\n};\n","/**\n * SplitView — Two-pane horizontal layout: 50/50.\n */\n\nimport { Box } from 'ink';\nimport type { ReactNode } from 'react';\n\ninterface SplitViewProps {\n left: ReactNode;\n right: ReactNode;\n gap?: number;\n}\n\nexport const SplitView = ({ left, right, gap = 2 }: SplitViewProps) => {\n return (\n <Box flexDirection=\"row\" flexGrow={1} flexShrink={1} gap={gap}>\n <Box width=\"50%\" flexDirection=\"column\" overflow=\"hidden\">\n {left}\n </Box>\n <Box width=\"50%\" flexDirection=\"column\" overflow=\"hidden\">\n {right}\n </Box>\n </Box>\n );\n};\n","/**\n * LoadingBox — Spinner with message.\n */\n\nimport { Box, Text } from 'ink';\nimport { Spinner } from '@inkjs/ui';\n\ninterface LoadingBoxProps {\n message: string;\n}\n\nexport const LoadingBox = ({ message }: LoadingBoxProps) => {\n return (\n <Box gap={1}>\n <Spinner />\n <Text>{message}</Text>\n </Box>\n );\n};\n","/**\n * ProgressList — Reusable task checklist with status icons.\n * Extracted from StatusTab logic.\n */\n\nimport { Box, Text } from 'ink';\nimport { Spinner } from '@inkjs/ui';\nimport { Colors, Icons } from '@ui/tui/styles';\nimport { LoadingBox } from './LoadingBox.js';\n\nexport interface ProgressItem {\n label: string;\n activeForm?: string;\n status: 'pending' | 'in_progress' | 'completed';\n}\n\ninterface ProgressListProps {\n items: ProgressItem[];\n title?: string;\n}\n\nexport const ProgressList = ({ items, title }: ProgressListProps) => {\n const completed = items.filter((t) => t.status === 'completed').length;\n const total = items.length;\n\n return (\n <Box flexDirection=\"column\">\n {title && (\n <>\n <Text bold>{title}</Text>\n <Text> </Text>\n </>\n )}\n {items.length === 0 && <LoadingBox message=\"Analyzing project...\" />}\n {items.map((item, i) => {\n const icon =\n item.status === 'completed'\n ? Icons.squareFilled\n : item.status === 'in_progress'\n ? Icons.triangleRight\n : Icons.squareOpen;\n const color =\n item.status === 'completed'\n ? Colors.success\n : item.status === 'in_progress'\n ? Colors.primary\n : Colors.muted;\n const label =\n item.status === 'in_progress' && item.activeForm\n ? item.activeForm\n : item.label;\n\n return (\n <Text key={i}>\n <Text color={color}>{icon}</Text>\n <Text dimColor={item.status === 'pending'}> {label}</Text>\n </Text>\n );\n })}\n {total > 0 && (\n <Box marginTop={1} gap={1}>\n <Spinner />\n <Text dimColor>\n {completed < total\n ? `Progress: ${completed}/${total} completed`\n : 'Cleaning up...'}\n </Text>\n </Box>\n )}\n </Box>\n );\n};\n","/**\n * PromptLabel — Compact inline label for input prompts.\n *\n * Renders: [!] message\n * where [!] is black text on accent background.\n */\n\nimport { Box, Text } from 'ink';\nimport { Colors } from '@ui/tui/styles';\n\ninterface PromptLabelProps {\n message?: string;\n}\n\nexport const PromptLabel = ({ message }: PromptLabelProps) => {\n return (\n <Box>\n <Text bold color={Colors.accent}>\n {' '}\n {message}\n </Text>\n </Box>\n );\n};\n","/**\n * Pure utility functions for keyboard hints — no React or Ink dependencies.\n * Extracted for testability in a node Jest environment.\n */\n\nexport interface KeyboardHint {\n label: string;\n action: string;\n priority: number;\n}\n\n/** Well-known key matches corresponding to Ink's key.* properties. */\nexport enum KeyMatch {\n UpArrow = 'upArrow',\n DownArrow = 'downArrow',\n LeftArrow = 'leftArrow',\n RightArrow = 'rightArrow',\n Return = 'return',\n Escape = 'escape',\n Space = 'space',\n}\n\n/** A key match: either a KeyMatch enum value or a literal character string (e.g. 'a', 's'). */\nexport type KeyMatchOrChar = KeyMatch | (string & NonNullable<unknown>);\n\n/** Default priorities by key type. */\nconst DEFAULT_PRIORITY: Record<string, number> = {\n [KeyMatch.UpArrow]: 0,\n [KeyMatch.DownArrow]: 0,\n [KeyMatch.LeftArrow]: 1,\n [KeyMatch.RightArrow]: 1,\n [KeyMatch.Space]: 10,\n [KeyMatch.Escape]: 20,\n [KeyMatch.Return]: 21,\n};\n\n/** Get the default display priority for a key match. */\nexport function getDefaultPriority(\n match: KeyMatchOrChar | KeyMatchOrChar[],\n): number {\n const first = Array.isArray(match) ? match[0] : match;\n return DEFAULT_PRIORITY[first] ?? 15;\n}\n\n/** Check if a KeyMatchOrChar matches the given input string and key flags. */\nexport function matchesKey(\n m: KeyMatchOrChar,\n input: string,\n key: { [k: string]: unknown },\n): boolean {\n switch (m) {\n case KeyMatch.UpArrow:\n return !!key.upArrow;\n case KeyMatch.DownArrow:\n return !!key.downArrow;\n case KeyMatch.LeftArrow:\n return !!key.leftArrow;\n case KeyMatch.RightArrow:\n return !!key.rightArrow;\n case KeyMatch.Return:\n return !!key.return;\n case KeyMatch.Escape:\n return !!key.escape;\n case KeyMatch.Space:\n return input === ' ';\n default:\n return input === m;\n }\n}\n\n/** Serialize hints for comparison. */\nexport function hintsKey(hints: KeyboardHint[]): string {\n return hints.map((h) => `${h.label}:${h.action}`).join('|');\n}\n\n/** Deduplicate hints by label+action and sort by priority. */\nexport function deduplicateAndSort(hints: KeyboardHint[]): KeyboardHint[] {\n const seen = new Set<string>();\n const deduped: KeyboardHint[] = [];\n for (const hint of hints) {\n const k = `${hint.label}:${hint.action}`;\n if (!seen.has(k)) {\n seen.add(k);\n deduped.push(hint);\n }\n }\n deduped.sort((a, b) => a.priority - b.priority);\n return deduped;\n}\n","/**\n * KeyboardHintsProvider — Context for collecting and displaying keyboard hints.\n *\n * Input components register their hints via useKeyBindings. The provider\n * flattens, deduplicates, and sorts them. The hints bar stays visible for as\n * long as a screen has registered hints — it never auto-dismisses.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport {\n hintsKey,\n deduplicateAndSort,\n type KeyboardHint,\n} from './keyboard-hints-utils.js';\n\nexport type { KeyboardHint } from './keyboard-hints-utils.js';\n\ninterface KeyboardHintsContextValue {\n register(id: string, hints: KeyboardHint[]): void;\n unregister(id: string): void;\n hints: KeyboardHint[];\n}\n\nconst KeyboardHintsContext = createContext<KeyboardHintsContextValue>({\n register: () => undefined,\n unregister: () => undefined,\n hints: [],\n});\n\nexport const useKeyboardHintsContext = () => useContext(KeyboardHintsContext);\n\nexport const KeyboardHintsProvider = ({\n children,\n}: {\n children: ReactNode;\n}) => {\n const registrationsRef = useRef(new Map<string, KeyboardHint[]>());\n const [hints, setHints] = useState<KeyboardHint[]>([]);\n const prevHintsKeyRef = useRef('');\n\n const recompute = useCallback(() => {\n const all: KeyboardHint[] = [];\n for (const h of registrationsRef.current.values()) {\n all.push(...h);\n }\n const deduped = deduplicateAndSort(all);\n\n const newKey = hintsKey(deduped);\n if (newKey !== prevHintsKeyRef.current) {\n prevHintsKeyRef.current = newKey;\n setHints(deduped);\n }\n }, []);\n\n const register = useCallback(\n (id: string, h: KeyboardHint[]) => {\n registrationsRef.current.set(id, h);\n recompute();\n },\n [recompute],\n );\n\n const unregister = useCallback(\n (id: string) => {\n registrationsRef.current.delete(id);\n recompute();\n },\n [recompute],\n );\n\n return (\n <KeyboardHintsContext.Provider value={{ register, unregister, hints }}>\n {children}\n </KeyboardHintsContext.Provider>\n );\n};\n","/**\n * useKeyBindings — Declarative keyboard input + automatic hint registration.\n *\n * Replaces raw `useInput` in input components. Define bindings as data;\n * the hook wires up the Ink input handler AND registers hints in the\n * KeyboardHintsProvider. One source of truth for keys and their labels.\n */\n\nimport { useInput, type Key } from 'ink';\nimport { useEffect, useRef } from 'react';\nimport { useKeyboardHintsContext } from './useKeyboardHints.js';\nimport {\n matchesKey,\n getDefaultPriority,\n KeyMatch,\n type KeyboardHint,\n type KeyMatchOrChar,\n} from './keyboard-hints-utils.js';\n\nexport { KeyMatch };\nexport type { KeyMatchOrChar } from './keyboard-hints-utils.js';\n\nexport interface KeyBinding {\n /** Which key(s) trigger this binding. Array = multiple keys, one hint. */\n match: KeyMatchOrChar | KeyMatchOrChar[];\n /** Display label in hints bar (e.g. \"↑↓\", \"space\", \"enter\") */\n label: string;\n /** Description in hints bar (e.g. \"navigate\", \"toggle\") */\n action: string;\n /** Ordering priority (lower = further left). Defaults based on key type. */\n priority?: number;\n /** Handler called when the key matches. */\n handler: (input: string, key: Key) => void;\n}\n\n/**\n * Declarative key bindings hook. Replaces `useInput` in input components.\n * Registers hints automatically with the KeyboardHintsProvider.\n *\n * @param id Unique identifier for this component's hints registration\n * @param bindings Array of key binding definitions\n */\nexport function useKeyBindings(id: string, bindings: KeyBinding[]): void {\n const ctx = useKeyboardHintsContext();\n\n // Extract hints and register. Use a serialized key to avoid unnecessary updates.\n const hintsRef = useRef<string>('');\n const hints: KeyboardHint[] = bindings.map((b) => ({\n label: b.label,\n action: b.action,\n priority: b.priority ?? getDefaultPriority(b.match),\n }));\n const serialized = hints\n .map((h) => `${h.label}:${h.action}:${h.priority}`)\n .join('|');\n\n useEffect(() => {\n if (serialized !== hintsRef.current) {\n hintsRef.current = serialized;\n ctx.register(id, hints);\n }\n return () => ctx.unregister(id);\n // eslint-disable-next-line\n }, [id, serialized]);\n\n // Wire up input handling\n useInput((input, key) => {\n for (const binding of bindings) {\n const matches = Array.isArray(binding.match)\n ? binding.match\n : [binding.match];\n if (matches.some((m) => matchesKey(m, input, key))) {\n binding.handler(input, key);\n return;\n }\n }\n });\n}\n","/**\n * PickerMenu — Single and multi select.\n * Single mode: custom renderer with small triangle indicator.\n * Multi mode: checkbox glyphs with space to toggle.\n *\n * Key bindings are declared via useKeyBindings, which auto-registers\n * hints in the KeyboardHintsBar.\n */\n\nimport { Box, Text } from 'ink';\nimport { useEffect, useState } from 'react';\nimport { Icons, Colors } from '@ui/tui/styles';\nimport { PromptLabel } from './PromptLabel.js';\nimport {\n useKeyBindings,\n KeyMatch,\n type KeyBinding,\n} from '@ui/tui/hooks/useKeyBindings';\n\ninterface PickerOption<T> {\n label: string;\n value: T;\n hint?: string;\n /** Glyph rendered before the label, in its own color — unaffected by\n * focus and disabled styling. */\n icon?: { glyph: string; color?: string };\n /** Dimmed and unselectable; navigation skips over it. */\n disabled?: boolean;\n /**\n * Multi-select only: marks this option mutually exclusive with every other\n * option. Selecting it clears all other picks; selecting any non-exclusive\n * option clears it. Used e.g. for a browser connector that can't be\n * installed alongside local editors.\n */\n exclusive?: boolean;\n}\n\n/**\n * Step through a column's options in `dir`, wrapping, until an enabled\n * option is found. Returns `from` unchanged if the column is entirely\n * disabled.\n */\nfunction stepEnabled<T>(\n options: PickerOption<T>[],\n rows: number,\n from: number,\n dir: 1 | -1,\n): number {\n const col = Math.floor(from / rows);\n const colStart = col * rows;\n const colLen = Math.min(rows, options.length - colStart);\n let row = from % rows;\n for (let i = 0; i < colLen; i++) {\n row = (row + dir + colLen) % colLen;\n const idx = colStart + row;\n if (!options[idx]?.disabled) return idx;\n }\n return from;\n}\n\n/** Index of the first enabled option, for the initial focus. */\nfunction firstEnabled<T>(options: PickerOption<T>[]): number {\n const idx = options.findIndex((o) => !o.disabled);\n return idx === -1 ? 0 : idx;\n}\n\ninterface PickerMenuProps<T> {\n message?: string;\n options: PickerOption<T>[];\n mode?: 'single' | 'multi';\n centered?: boolean;\n columns?: 1 | 2 | 3 | 4;\n /**\n * Vertical space between options, in TUI rows. Defaults to 0 — i.e.\n * options stack tightly. Set to 1+ when the option labels are long\n * (wrap across multiple lines) or for visual breathing room.\n */\n optionMarginBottom?: number;\n onSelect: (value: T | T[]) => void;\n}\n\nexport const PickerMenu = <T,>({\n message,\n options,\n mode = 'single',\n centered = false,\n columns = 1,\n optionMarginBottom = 0,\n onSelect,\n}: PickerMenuProps<T>) => {\n if (mode === 'multi') {\n return (\n <MultiPickerMenu\n message={message}\n options={options}\n centered={centered}\n columns={columns}\n optionMarginBottom={optionMarginBottom}\n onSelect={onSelect}\n />\n );\n }\n\n return (\n <SinglePickerMenu\n message={message}\n options={options}\n centered={centered}\n columns={columns}\n optionMarginBottom={optionMarginBottom}\n onSelect={onSelect}\n />\n );\n};\n\n/** Custom single-select with triangle indicator and accent highlight. */\nconst SinglePickerMenu = <T,>({\n message,\n options,\n centered = false,\n columns = 1,\n optionMarginBottom = 0,\n onSelect,\n}: {\n message?: string;\n options: PickerOption<T>[];\n centered?: boolean;\n columns?: number;\n optionMarginBottom?: number;\n onSelect: (value: T | T[]) => void;\n}) => {\n const [focused, setFocused] = useState(() => firstEnabled(options));\n const rows = Math.ceil(options.length / columns);\n\n // Re-validate focus when the options change while mounted \\u2014 a list\n // that shrinks or disables entries can leave `focused` pointing at a\n // missing or disabled option, which would make enter a no-op.\n useEffect(() => {\n if (focused >= options.length || options[focused]?.disabled) {\n setFocused(firstEnabled(options));\n }\n }, [options, focused]);\n\n const bindings: KeyBinding[] = [\n {\n match: [KeyMatch.UpArrow, KeyMatch.DownArrow],\n label: '\\u2191\\u2193',\n action: 'navigate',\n handler: (_input, key) => {\n if (key.upArrow) {\n setFocused(stepEnabled(options, rows, focused, -1));\n }\n if (key.downArrow) {\n setFocused(stepEnabled(options, rows, focused, 1));\n }\n },\n },\n {\n match: KeyMatch.Return,\n label: 'enter',\n action: 'select',\n handler: () => {\n const selected = options[focused];\n if (selected && !selected.disabled) {\n onSelect(selected.value);\n }\n },\n },\n ];\n\n if (columns > 1) {\n bindings.splice(1, 0, {\n match: [KeyMatch.LeftArrow, KeyMatch.RightArrow],\n label: '\\u2190\\u2192',\n action: 'navigate',\n handler: (_input, key) => {\n const col = Math.floor(focused / rows);\n const row = focused % rows;\n\n let next = focused;\n if (key.leftArrow) {\n const prevCol = col > 0 ? col - 1 : columns - 1;\n next = Math.min(prevCol * rows + row, options.length - 1);\n }\n if (key.rightArrow) {\n const nextCol = col < columns - 1 ? col + 1 : 0;\n next = Math.min(nextCol * rows + row, options.length - 1);\n }\n // Landing on a disabled option slides to the column's nearest\n // enabled one.\n if (options[next]?.disabled) {\n next = stepEnabled(options, rows, next, 1);\n }\n setFocused(next);\n },\n });\n }\n\n useKeyBindings('single-picker', bindings);\n\n // Chunk options into columns (column-first ordering)\n const columnArrays: PickerOption<T>[][] = [];\n for (let c = 0; c < columns; c++) {\n columnArrays.push(options.slice(c * rows, c * rows + rows));\n }\n\n const align = centered ? 'center' : undefined;\n\n return (\n <Box flexDirection=\"column\" alignItems={align}>\n <PromptLabel message={message} />\n <Box flexDirection=\"row\" gap={4}>\n {columnArrays.map((colOpts, colIdx) => (\n <Box key={colIdx} flexDirection=\"column\">\n {colOpts.map((opt, rowIdx) => {\n const flatIdx = colIdx * rows + rowIdx;\n const isFocused = flatIdx === focused;\n const label = opt.hint ? `${opt.label} (${opt.hint})` : opt.label;\n return (\n <Box key={flatIdx} gap={1} marginBottom={optionMarginBottom}>\n <Text\n color={isFocused ? Colors.accent : undefined}\n dimColor={!isFocused}\n >\n {isFocused ? Icons.triangleSmallRight : ' '}\n </Text>\n {opt.icon && (\n <Text color={opt.icon.color}>{opt.icon.glyph}</Text>\n )}\n <Text\n color={\n opt.disabled\n ? Colors.muted\n : isFocused\n ? Colors.accent\n : undefined\n }\n bold={isFocused && !opt.disabled}\n dimColor={!isFocused || opt.disabled}\n >\n {label}\n </Text>\n </Box>\n );\n })}\n </Box>\n ))}\n </Box>\n </Box>\n );\n};\n\n/** Custom multi-select with checkbox glyphs and accent highlight. */\nconst MultiPickerMenu = <T,>({\n message,\n options,\n centered = false,\n columns = 1,\n optionMarginBottom = 0,\n onSelect,\n}: {\n message?: string;\n options: PickerOption<T>[];\n centered?: boolean;\n columns?: number;\n optionMarginBottom?: number;\n onSelect: (value: T | T[]) => void;\n}) => {\n const [focused, setFocused] = useState(() => firstEnabled(options));\n const [selected, setSelected] = useState<Set<number>>(new Set());\n const rows = Math.ceil(options.length / columns);\n\n // Re-validate focus when the options change while mounted — a list\n // that shrinks or disables entries can leave `focused` pointing at a\n // missing or disabled option, which would make enter a no-op.\n useEffect(() => {\n if (focused >= options.length || options[focused]?.disabled) {\n setFocused(firstEnabled(options));\n }\n }, [options, focused]);\n\n const bindings: KeyBinding[] = [\n {\n match: [KeyMatch.UpArrow, KeyMatch.DownArrow],\n label: '\\u2191\\u2193',\n action: 'navigate',\n handler: (_input, key) => {\n if (key.upArrow) {\n setFocused(stepEnabled(options, rows, focused, -1));\n }\n if (key.downArrow) {\n setFocused(stepEnabled(options, rows, focused, 1));\n }\n },\n },\n {\n match: KeyMatch.Space,\n label: 'space',\n action: 'toggle',\n handler: () => {\n if (options[focused]?.disabled) return;\n setSelected((prev) => {\n const next = new Set(prev);\n if (next.has(focused)) {\n next.delete(focused);\n return next;\n }\n // Enforce mutual exclusivity: an exclusive option clears every other\n // pick; any other option clears previously-picked exclusive ones.\n if (options[focused]?.exclusive) {\n return new Set([focused]);\n }\n for (const i of next) {\n if (options[i]?.exclusive) {\n next.delete(i);\n }\n }\n next.add(focused);\n return next;\n });\n },\n },\n {\n match: KeyMatch.Return,\n label: 'enter',\n action: 'confirm',\n handler: () => {\n if (selected.size === 0) {\n const hovered = options[focused];\n if (hovered && !hovered.disabled) {\n onSelect(hovered.value);\n }\n } else {\n const values = [...selected].sort().map((i) => options[i].value);\n onSelect(values);\n }\n },\n },\n ];\n\n if (columns > 1) {\n bindings.splice(1, 0, {\n match: [KeyMatch.LeftArrow, KeyMatch.RightArrow],\n label: '\\u2190\\u2192',\n action: 'navigate',\n handler: (_input, key) => {\n const col = Math.floor(focused / rows);\n const row = focused % rows;\n\n let next = focused;\n if (key.leftArrow) {\n const prevCol = col > 0 ? col - 1 : columns - 1;\n next = Math.min(prevCol * rows + row, options.length - 1);\n }\n if (key.rightArrow) {\n const nextCol = col < columns - 1 ? col + 1 : 0;\n next = Math.min(nextCol * rows + row, options.length - 1);\n }\n // Landing on a disabled option slides to the column's nearest\n // enabled one.\n if (options[next]?.disabled) {\n next = stepEnabled(options, rows, next, 1);\n }\n setFocused(next);\n },\n });\n }\n\n useKeyBindings('multi-picker', bindings);\n\n const columnArrays: PickerOption<T>[][] = [];\n for (let c = 0; c < columns; c++) {\n columnArrays.push(options.slice(c * rows, c * rows + rows));\n }\n\n return (\n <Box flexDirection=\"column\" alignItems={centered ? 'center' : undefined}>\n <PromptLabel message={message} />\n <Box\n flexDirection=\"row\"\n gap={4}\n marginLeft={centered ? 0 : 2}\n marginTop={1}\n >\n {columnArrays.map((colOpts, colIdx) => (\n <Box key={colIdx} flexDirection=\"column\">\n {colOpts.map((opt, rowIdx) => {\n const flatIdx = colIdx * rows + rowIdx;\n const isFocused = flatIdx === focused;\n const isSelected = selected.has(flatIdx);\n const label = opt.hint ? `${opt.label} (${opt.hint})` : opt.label;\n const checkbox = isSelected\n ? Icons.squareFilled\n : Icons.squareOpen;\n return (\n <Box key={flatIdx} gap={1} marginBottom={optionMarginBottom}>\n <Text\n color={isSelected ? 'white' : Colors.muted}\n dimColor={!isFocused && !isSelected}\n >\n {checkbox}\n </Text>\n {opt.icon && (\n <Text color={opt.icon.color}>{opt.icon.glyph}</Text>\n )}\n <Text\n color={\n opt.disabled\n ? Colors.muted\n : isFocused\n ? Colors.accent\n : undefined\n }\n bold={isFocused && !opt.disabled}\n dimColor={!isFocused || opt.disabled}\n >\n {label}\n </Text>\n </Box>\n );\n })}\n </Box>\n ))}\n </Box>\n </Box>\n );\n};\n","/**\n * useStdoutDimensions — Returns [columns, rows] and re-renders on terminal resize.\n *\n * Ink's useStdout() does not subscribe to resize events, so layout only updates\n * when something else causes a re-render. This hook listens to the stream's\n * 'resize' event (Node TTY) and updates state so the component re-renders\n * with the new dimensions.\n */\n\nimport { useStdout } from 'ink';\nimport { useState, useEffect } from 'react';\n\nexport function useStdoutDimensions(): [number, number] {\n const { stdout } = useStdout();\n const [size, setSize] = useState<[number, number]>(() => [\n stdout.columns || 80,\n stdout.rows || 24,\n ]);\n\n useEffect(() => {\n const cols = stdout.columns || 80;\n const rows = stdout.rows || 24;\n setSize([cols, rows]);\n\n const stream = stdout as NodeJS.WriteStream & {\n on?(event: string, fn: () => void): void;\n };\n if (typeof stream.on !== 'function') return;\n\n const onResize = () => {\n const c = stdout.columns || 80;\n const r = stdout.rows || 24;\n if (c > 0 && r > 0) setSize([c, r]);\n };\n stream.on('resize', onResize);\n return () => {\n stream.off?.('resize', onResize);\n };\n }, [stdout]);\n\n return size;\n}\n","/**\n * GroupedPickerMenu — Multi-select with category headers.\n *\n * Renders groups of options with bold category labels.\n * Arrow keys navigate selectable items (headers are skipped),\n * space toggles, \"a\" toggles all, enter submits.\n *\n * When content exceeds available terminal height, the list scrolls\n * to keep the focused item visible with up/down indicators.\n *\n * Key bindings are declared via useKeyBindings, which auto-registers\n * hints in the KeyboardHintsBar.\n */\n\nimport { Box, Text } from 'ink';\nimport { useState, useMemo } from 'react';\nimport { Icons, Colors } from '@ui/tui/styles';\nimport { PromptLabel } from './PromptLabel.js';\nimport { useStdoutDimensions } from '@ui/tui/hooks/useStdoutDimensions';\nimport { useKeyBindings, KeyMatch } from '@ui/tui/hooks/useKeyBindings';\n\ninterface GroupOption {\n value: string;\n label: string;\n hint?: string;\n}\n\ninterface GroupedPickerMenuProps {\n message?: string;\n groups: Record<string, GroupOption[]>;\n initialSelected?: string[];\n onSelect: (values: string[]) => void;\n}\n\ntype Row =\n | { kind: 'header'; label: string }\n | { kind: 'option'; value: string; label: string; hint?: string };\n\n/** Truncate text with \"\\u2026\" if it exceeds maxWidth. */\nfunction truncateWithEllipsis(text: string, maxWidth: number): string {\n if (text.length <= maxWidth) return text;\n return text.slice(0, maxWidth - 1) + '\\u2026';\n}\n\n/** Rows consumed by chrome outside this component (title bar, screen padding, etc.) */\nconst CHROME_OVERHEAD = 10;\n/** Rows used by the prompt label + marginTop before content (hint text moved to KeyboardHintsBar). */\nconst MENU_CHROME = 2;\n\n/** Count the visual rows occupied by rows[start..end), accounting for header margins. */\nfunction countVisualRows(rows: Row[], start: number, end: number): number {\n let count = 0;\n for (let i = start; i < end && i < rows.length; i++) {\n if (rows[i].kind === 'header' && i > start) count += 1; // marginTop gap\n count += 1;\n }\n return count;\n}\n\n/** From scrollOffset, find how many flat rows fit in the visual budget. */\nfunction computeVisibleEnd(\n rows: Row[],\n scrollOffset: number,\n budget: number,\n): number {\n let visualCount = 0;\n let i = scrollOffset;\n while (i < rows.length) {\n const cost = rows[i].kind === 'header' && i > scrollOffset ? 2 : 1;\n if (visualCount + cost > budget) break;\n visualCount += cost;\n i++;\n }\n return i;\n}\n\n/** Adjust scroll offset to keep focusedRowIdx visible within the viewport. */\nfunction adjustScrollOffset(\n currentOffset: number,\n focusedRowIdx: number,\n rows: Row[],\n viewportBudget: number,\n): number {\n const visibleEnd = computeVisibleEnd(rows, currentOffset, viewportBudget);\n\n // Already visible\n if (focusedRowIdx >= currentOffset && focusedRowIdx < visibleEnd) {\n return currentOffset;\n }\n\n // Focus moved above viewport — scroll up, including group header if adjacent\n if (focusedRowIdx < currentOffset) {\n let newOffset = focusedRowIdx;\n if (newOffset > 0 && rows[newOffset - 1]?.kind === 'header') {\n newOffset--;\n }\n return Math.max(0, newOffset);\n }\n\n // Focus moved below viewport — scroll down minimally\n let newOffset = currentOffset + 1;\n while (newOffset < rows.length) {\n const end = computeVisibleEnd(rows, newOffset, viewportBudget);\n if (focusedRowIdx < end) break;\n newOffset++;\n }\n return Math.min(newOffset, Math.max(0, rows.length - 1));\n}\n\nexport const GroupedPickerMenu = ({\n message,\n groups,\n initialSelected,\n onSelect,\n}: GroupedPickerMenuProps) => {\n const [termCols, termRows] = useStdoutDimensions();\n\n // Available width for option labels, after subtracting layout chrome:\n // paddingX(2) + marginLeft(2) + option marginLeft(1) + gap(1) + checkbox(2) = 8\n const labelWidth = Math.max(10, Math.min(termCols, 120) - 8);\n\n // Build a flat row list with headers interleaved\n const rows = useMemo<Row[]>(() => {\n const result: Row[] = [];\n for (const [groupName, options] of Object.entries(groups)) {\n result.push({ kind: 'header', label: groupName });\n for (const opt of options) {\n result.push({ kind: 'option', ...opt });\n }\n }\n return result;\n }, [groups]);\n\n // Indices of selectable (non-header) rows\n const selectableIndices = useMemo(\n () =>\n rows.map((r, i) => (r.kind === 'option' ? i : -1)).filter((i) => i >= 0),\n [rows],\n );\n\n // All option values for toggle-all\n const allValues = useMemo(\n () =>\n rows\n .filter((r): r is Row & { kind: 'option' } => r.kind === 'option')\n .map((r) => r.value),\n [rows],\n );\n\n const [focusedSelectable, setFocusedSelectable] = useState(0);\n const [selected, setSelected] = useState<Set<string>>(\n () => new Set(initialSelected ?? allValues),\n );\n const [scrollOffset, setScrollOffset] = useState(0);\n\n const focusedRowIdx = selectableIndices[focusedSelectable] ?? 0;\n\n // Viewport budget: how many visual rows can be shown\n const viewportBudget = Math.max(5, termRows - CHROME_OVERHEAD - MENU_CHROME);\n const totalVisual = countVisualRows(rows, 0, rows.length);\n const needsScroll = totalVisual > viewportBudget;\n const effectiveBudget = needsScroll ? viewportBudget - 2 : viewportBudget;\n\n useKeyBindings('grouped-picker', [\n {\n match: [KeyMatch.UpArrow, KeyMatch.DownArrow],\n label: '\\u2191\\u2193',\n action: 'navigate',\n handler: (_input, key) => {\n let newFocused = focusedSelectable;\n\n if (key.upArrow) {\n newFocused =\n focusedSelectable > 0\n ? focusedSelectable - 1\n : selectableIndices.length - 1;\n }\n if (key.downArrow) {\n newFocused =\n focusedSelectable < selectableIndices.length - 1\n ? focusedSelectable + 1\n : 0;\n }\n\n if (newFocused !== focusedSelectable) {\n setFocusedSelectable(newFocused);\n if (needsScroll) {\n const newFocusedRowIdx = selectableIndices[newFocused] ?? 0;\n setScrollOffset((prev) =>\n adjustScrollOffset(prev, newFocusedRowIdx, rows, effectiveBudget),\n );\n }\n }\n },\n },\n {\n match: KeyMatch.Space,\n label: 'space',\n action: 'toggle',\n handler: () => {\n const targetRowIdx = selectableIndices[focusedSelectable] ?? 0;\n const row = rows[targetRowIdx];\n if (row?.kind === 'option') {\n setSelected((prev) => {\n const next = new Set(prev);\n if (next.has(row.value)) {\n next.delete(row.value);\n } else {\n next.add(row.value);\n }\n return next;\n });\n }\n },\n },\n {\n match: 'a',\n label: 'a',\n action: 'toggle all',\n priority: 11,\n handler: () => {\n setSelected((prev) => {\n if (prev.size === allValues.length) {\n return new Set();\n }\n return new Set(allValues);\n });\n },\n },\n {\n match: KeyMatch.Return,\n label: 'enter',\n action: 'confirm',\n handler: () => {\n onSelect([...selected]);\n },\n },\n ]);\n\n // Determine visible slice\n const visibleStart = needsScroll ? scrollOffset : 0;\n const visibleEnd = needsScroll\n ? computeVisibleEnd(rows, visibleStart, effectiveBudget)\n : rows.length;\n const visibleRows = rows.slice(visibleStart, visibleEnd);\n const hiddenAbove = needsScroll\n ? selectableIndices.filter((s) => s < visibleStart).length\n : 0;\n const hiddenBelow = needsScroll\n ? selectableIndices.filter((s) => s >= visibleEnd).length\n : 0;\n\n return (\n <Box flexDirection=\"column\">\n <PromptLabel message={message} />\n <Box flexDirection=\"column\" marginTop={1} marginLeft={2}>\n {needsScroll && (\n <Text dimColor>\n {hiddenAbove > 0 ? `\\u2191 ${hiddenAbove} more` : ' '}\n </Text>\n )}\n {visibleRows.map((row, relIdx) => {\n const absIdx = visibleStart + relIdx;\n\n if (row.kind === 'header') {\n return (\n <Box\n key={`h-${absIdx}`}\n marginTop={relIdx > 0 && absIdx > 0 ? 1 : 0}\n >\n <Text bold dimColor>\n {row.label}\n </Text>\n </Box>\n );\n }\n\n const isFocused = focusedRowIdx === absIdx;\n const isSelected = selected.has(row.value);\n const checkbox = isSelected ? Icons.squareFilled : Icons.squareOpen;\n const fullLabel = row.hint ? `${row.label} (${row.hint})` : row.label;\n const label = truncateWithEllipsis(fullLabel, labelWidth);\n\n return (\n <Box key={row.value} gap={1} marginLeft={1}>\n <Text\n color={isSelected ? 'white' : Colors.muted}\n dimColor={!isFocused && !isSelected}\n >\n {checkbox}\n </Text>\n <Box flexGrow={1} flexShrink={1} overflow=\"hidden\">\n <Text\n color={isFocused ? Colors.accent : undefined}\n bold={isFocused}\n dimColor={!isFocused}\n wrap=\"truncate\"\n >\n {label}\n </Text>\n </Box>\n </Box>\n );\n })}\n {needsScroll && (\n <Text dimColor>\n {hiddenBelow > 0 ? `\\u2193 ${hiddenBelow} more` : ' '}\n </Text>\n )}\n </Box>\n </Box>\n );\n};\n","/**\n * ConfirmationInput — Continue/cancel prompt.\n * Enter confirms, escape cancels. Arrow keys toggle focus.\n *\n * Key bindings are declared via useKeyBindings, which auto-registers\n * hints in the KeyboardHintsBar.\n */\n\nimport { Box, Text } from 'ink';\nimport { useState } from 'react';\nimport { Icons, Colors } from '@ui/tui/styles';\nimport { PromptLabel } from './PromptLabel.js';\nimport { useKeyBindings, KeyMatch } from '@ui/tui/hooks/useKeyBindings';\n\ninterface ConfirmationInputProps {\n message: string;\n onConfirm: () => void;\n onCancel: () => void;\n confirmLabel?: string;\n cancelLabel?: string;\n}\n\nenum FocusTarget {\n Continue = 'continue',\n Cancel = 'cancel',\n}\n\nexport const ConfirmationInput = ({\n message,\n onConfirm,\n onCancel,\n confirmLabel = 'Continue',\n cancelLabel = 'Cancel',\n}: ConfirmationInputProps) => {\n const [focused, setFocused] = useState<FocusTarget>(FocusTarget.Continue);\n\n useKeyBindings('confirmation', [\n {\n match: [KeyMatch.LeftArrow, KeyMatch.RightArrow],\n label: '\\u2190\\u2192',\n action: 'switch',\n handler: () => {\n setFocused((f) =>\n f === FocusTarget.Continue\n ? FocusTarget.Cancel\n : FocusTarget.Continue,\n );\n },\n },\n {\n match: KeyMatch.Return,\n label: 'enter',\n action: 'confirm',\n handler: () => {\n if (focused === FocusTarget.Continue) {\n onConfirm();\n } else {\n onCancel();\n }\n },\n },\n {\n match: KeyMatch.Escape,\n label: 'esc',\n action: 'cancel',\n handler: () => {\n onCancel();\n },\n },\n ]);\n\n return (\n <Box flexDirection=\"column\">\n <PromptLabel message={message} />\n <Box gap={2} marginTop={1} marginLeft={2}>\n <Text\n bold={focused === FocusTarget.Continue}\n color={\n focused === FocusTarget.Continue ? Colors.accent : Colors.muted\n }\n >\n {focused === FocusTarget.Continue ? Icons.triangleSmallRight : ' '}{' '}\n {confirmLabel}\n </Text>\n <Text\n bold={focused === FocusTarget.Cancel}\n color={focused === FocusTarget.Cancel ? Colors.accent : Colors.muted}\n >\n {focused === FocusTarget.Cancel ? Icons.triangleSmallRight : ' '}{' '}\n {cancelLabel}\n </Text>\n </Box>\n </Box>\n );\n};\n","import { Box, Text, measureElement } from 'ink';\nimport { useRef, useState, useEffect } from 'react';\n\ninterface DividerProps {\n dimColor?: boolean;\n char?: string;\n}\n\nexport const Divider = ({ dimColor = true, char = '─' }: DividerProps) => {\n const ref = useRef(null);\n const [width, setWidth] = useState(0);\n\n useEffect(() => {\n if (ref.current) {\n const { width: measured } = measureElement(ref.current);\n setWidth(measured);\n }\n }, []);\n\n return (\n <Box ref={ref} width=\"100%\">\n <Text dimColor={dimColor}>{width > 0 ? char.repeat(width) : ''}</Text>\n </Box>\n );\n};\n","/**\n * ModalOverlay — Reusable centered card for overlay screens.\n *\n * Shared layout for HealthCheckScreen, SettingsOverrideScreen, PortConflictScreen, etc.\n * Provides: centered card with border, title, body, optional feedback, divider, and actions.\n */\n\nimport type { ReactNode } from 'react';\nimport { Box, Text } from 'ink';\nimport { Divider } from './Divider.js';\n\ninterface ModalOverlayProps {\n /** Card border color */\n borderColor: string;\n /** Title text */\n title: string;\n /** Title text color (defaults to borderColor) */\n titleColor?: string;\n /** Card width (default 68) */\n width?: number;\n /** Body content */\n children: ReactNode;\n /** Optional feedback message (shown in yellow above the divider) */\n feedback?: string | null;\n /** Footer content below the divider (typically ConfirmationInput) */\n footer?: ReactNode;\n}\n\nexport const ModalOverlay = ({\n borderColor,\n title,\n titleColor,\n width = 68,\n children,\n feedback,\n footer,\n}: ModalOverlayProps) => {\n return (\n <Box\n flexDirection=\"column\"\n flexGrow={1}\n alignItems=\"center\"\n justifyContent=\"center\"\n >\n <Box\n flexDirection=\"column\"\n borderStyle=\"round\"\n borderColor={borderColor}\n paddingX={3}\n paddingY={1}\n width={width}\n >\n <Box justifyContent=\"center\" marginBottom={1}>\n <Text color={titleColor ?? borderColor} bold>\n {title}\n </Text>\n </Box>\n\n {children}\n\n {feedback && (\n <Box marginTop={1}>\n <Text color=\"yellow\">{feedback}</Text>\n </Box>\n )}\n\n {footer && (\n <>\n <Box marginY={1}>\n <Divider />\n </Box>\n {footer}\n </>\n )}\n </Box>\n </Box>\n );\n};\n","/**\n * LogViewer — Real-time log tail, pinned to available terminal height.\n * Only renders the last N lines that fit on screen.\n *\n * Reads only the last TAIL_BYTES of the file on each refresh and throttles\n * fs.watch callbacks to one refresh per WATCH_THROTTLE_MS. Without this,\n * fs.readFileSync allocates a string the size of the entire log on every\n * append — during subagent fan-out that's tens of writes per second against\n * a log that grows into the hundreds of MB, producing OOM-grade allocation\n * pressure on V8's heap.\n */\n\nimport { Box, Text } from 'ink';\nimport { useState, useEffect } from 'react';\nimport * as fs from 'fs';\nimport { useStdoutDimensions } from '@ui/tui/hooks/useStdoutDimensions';\n\n/** Rows consumed by TitleBar + spacer + ScreenContainer padding + status bar + tab bar */\nconst CHROME_ROWS = 8;\n\n/** Bytes read from the end of the log per refresh — large enough to contain\n * any practical visible window of lines, small enough to allocate cheaply. */\nconst TAIL_BYTES = 256 * 1024;\n\n/** Minimum gap between watch-triggered refreshes. fs.watch fires on every\n * append */\nconst WATCH_THROTTLE_MS = 250;\n\ninterface LogViewerProps {\n filePath: string;\n /** Fixed visible height. Defaults to terminal rows minus chrome. */\n height?: number;\n}\n\nfunction readTailLines(filePath: string, visibleLines: number): string[] {\n const stat = fs.statSync(filePath);\n if (stat.size === 0) return [];\n const start = Math.max(0, stat.size - TAIL_BYTES);\n const length = stat.size - start;\n const buf = Buffer.alloc(length);\n const fd = fs.openSync(filePath, 'r');\n try {\n fs.readSync(fd, buf, 0, length, start);\n } finally {\n fs.closeSync(fd);\n }\n let text = buf.toString('utf-8');\n if (start > 0) {\n const firstNewline = text.indexOf('\\n');\n if (firstNewline >= 0) text = text.slice(firstNewline + 1);\n }\n return text.split('\\n').slice(-visibleLines);\n}\n\nexport const LogViewer = ({ filePath, height }: LogViewerProps) => {\n const [, rows] = useStdoutDimensions();\n const visibleLines = height ?? Math.max(5, rows - CHROME_ROWS);\n\n const [lines, setLines] = useState<string[]>([]);\n\n useEffect(() => {\n let lastReadAt = 0;\n let pendingTimer: ReturnType<typeof setTimeout> | undefined;\n\n const readTail = () => {\n try {\n setLines(readTailLines(filePath, visibleLines));\n } catch {\n setLines(['(No log file found)']);\n }\n };\n\n const scheduleRead = () => {\n const now = Date.now();\n const elapsed = now - lastReadAt;\n if (elapsed >= WATCH_THROTTLE_MS) {\n lastReadAt = now;\n readTail();\n return;\n }\n if (pendingTimer) return;\n pendingTimer = setTimeout(() => {\n pendingTimer = undefined;\n lastReadAt = Date.now();\n readTail();\n }, WATCH_THROTTLE_MS - elapsed);\n };\n\n readTail();\n lastReadAt = Date.now();\n\n let watcher: fs.FSWatcher | undefined;\n try {\n watcher = fs.watch(filePath, () => scheduleRead());\n } catch {\n const interval = setInterval(() => {\n try {\n fs.accessSync(filePath);\n readTail();\n clearInterval(interval);\n watcher = fs.watch(filePath, () => scheduleRead());\n } catch {\n // Still waiting for the file to appear\n }\n }, 1000);\n\n return () => {\n clearInterval(interval);\n if (pendingTimer) clearTimeout(pendingTimer);\n };\n }\n\n return () => {\n watcher?.close();\n if (pendingTimer) clearTimeout(pendingTimer);\n };\n }, [filePath, visibleLines]);\n\n return (\n <Box flexDirection=\"column\" height={visibleLines}>\n {lines.map((line, i) => (\n <Text key={i} dimColor wrap=\"truncate\">\n {line}\n </Text>\n ))}\n </Box>\n );\n};\n","/**\n * EventPlanViewer — Renders a table of planned analytics events.\n */\n\nimport { Box, Text } from 'ink';\nimport type { PlannedEvent } from '@ui/tui/store';\n\ninterface EventPlanViewerProps {\n events: PlannedEvent[];\n}\n\nexport const EventPlanViewer = ({ events }: EventPlanViewerProps) => {\n return (\n <Box flexDirection=\"column\" paddingX={1}>\n <Text bold>Event plan</Text>\n <Box height={1} />\n {events.map((event) => (\n <Box key={event.name}>\n <Text bold>{event.name}</Text>\n <Text dimColor> {event.description}</Text>\n </Box>\n ))}\n </Box>\n );\n};\n","import { Box, Text } from 'ink';\nimport { Colors } from '@ui/tui/styles';\n\nconst FEEDBACK = 'Feedback: wizard@posthog.com ';\nconst FEEDBACK_SHORT = ' wizard@posthog.com ';\n\ninterface TitleBarProps {\n version: string;\n width: number;\n}\n\nexport const TitleBar = ({ version, width }: TitleBarProps) => {\n const fullTitle = ` PostHog Wizard v${version}`;\n const needShort = width < fullTitle.length + FEEDBACK.length;\n const feedback = needShort ? FEEDBACK_SHORT : FEEDBACK;\n const title =\n needShort && fullTitle.length + feedback.length > width\n ? ` Wizard v${version}`\n : fullTitle;\n const gap = Math.max(0, width - title.length - feedback.length);\n const padding = ' '.repeat(gap);\n\n return (\n <Box width={width} overflow=\"hidden\">\n <Text backgroundColor={Colors.accent} color={Colors.titleColor}>\n {title}\n {padding}\n {feedback}\n </Text>\n </Box>\n );\n};\n","/**\n * DissolveTransition — Column-sweep inspired by TTE's Sweep effect.\n *\n * Uses a SequenceEaser (in_out_circ) to activate columns with eased pacing.\n * Each activated column cycles through shade characters (░▒▓█) independently.\n *\n * Out phase: columns sweep, building up shade chars until solid █ (covers old content).\n * In phase: columns sweep in reverse, dissolving █ back through shades to empty (reveals new content).\n */\n\nimport { Box, Text } from 'ink';\nimport { useState, useEffect, useRef, type ReactNode } from 'react';\n\n/** Shade characters in build-up order (light → solid). */\nconst SHADES = ['░', '▒', '▓', '█'] as const;\n/** How many ticks each shade character displays before advancing. */\nconst TICKS_PER_SHADE = 2;\n/** Total ticks a column needs to complete its shade cycle. */\nconst SHADE_CYCLE_TICKS = SHADES.length * TICKS_PER_SHADE;\n\nexport type WipeDirection = 'left' | 'right';\n\ninterface DissolveTransitionProps {\n transitionKey: string;\n width: number;\n height: number;\n children: ReactNode;\n direction?: WipeDirection;\n duration?: number;\n}\n\nfunction easeInOutCirc(t: number): number {\n if (t < 0.5) {\n return (1 - Math.sqrt(1 - 4 * t * t)) / 2;\n }\n return (Math.sqrt(1 - (2 * t - 2) ** 2) + 1) / 2;\n}\n\nenum TransitionPhase {\n Idle = 'idle',\n Out = 'out',\n In = 'in',\n}\n\nexport const DissolveTransition = ({\n transitionKey,\n width,\n height,\n children,\n direction = 'left',\n duration = 2,\n}: DissolveTransitionProps) => {\n const [phase, setPhase] = useState<TransitionPhase>(TransitionPhase.Idle);\n const [tick, setTick] = useState(0);\n const [activeDir, setActiveDir] = useState<WipeDirection>(direction);\n const prevKey = useRef(transitionKey);\n const pendingChildren = useRef<ReactNode>(children);\n const [displayChildren, setDisplayChildren] = useState<ReactNode>(children);\n\n // Track when each column was activated (tick number), -1 means not yet.\n const columnActivationTick = useRef<number[]>([]);\n\n useEffect(() => {\n if (transitionKey !== prevKey.current) {\n prevKey.current = transitionKey;\n pendingChildren.current = children;\n setActiveDir(direction);\n setPhase(TransitionPhase.Out);\n setTick(0);\n columnActivationTick.current = new Array(width).fill(-1);\n } else if (phase !== TransitionPhase.Idle) {\n // Terminal resized mid-transition — abort and show new content immediately\n setPhase(TransitionPhase.Idle);\n setDisplayChildren(children);\n } else {\n setDisplayChildren(children);\n }\n }, [transitionKey, children, width, height, phase, direction]);\n\n useEffect(() => {\n if (phase === TransitionPhase.Idle) return;\n\n const timer = setInterval(() => {\n setTick((prev) => prev + 1);\n }, duration);\n\n return () => clearInterval(timer);\n }, [phase, duration]);\n\n // Easer steps = width: roughly one column activates per tick.\n // This keeps the sweep front tight (only a few columns in-flight at once).\n const easerSteps = width;\n\n // A phase ends when the easer has completed AND all columns have finished their shade cycle.\n const maxTicks = easerSteps + SHADE_CYCLE_TICKS;\n\n useEffect(() => {\n if (phase === TransitionPhase.Idle) return;\n if (tick >= maxTicks) {\n if (phase === TransitionPhase.Out) {\n setDisplayChildren(pendingChildren.current);\n setPhase(TransitionPhase.In);\n setTick(0);\n columnActivationTick.current = new Array(width).fill(-1);\n } else {\n setPhase(TransitionPhase.Idle);\n }\n }\n }, [tick, phase, maxTicks, width]);\n\n if (phase === TransitionPhase.Idle) {\n return <>{displayChildren}</>;\n }\n\n // --- SequenceEaser logic ---\n // Map current tick to easer progress (0..1), apply easing,\n // then determine how many columns should be activated.\n const easerProgress = Math.min(tick / easerSteps, 1);\n const easedValue = easeInOutCirc(easerProgress);\n const activatedCount = Math.floor(easedValue * width);\n\n // Build column order based on direction.\n // \"left\" means sweep moves left-to-right; \"right\" means right-to-left.\n // TTE's COLUMN_RIGHT_TO_LEFT activates rightmost first.\n const columnOrder: number[] = [];\n if (activeDir === 'left') {\n for (let c = width - 1; c >= 0; c--) columnOrder.push(c);\n } else {\n for (let c = 0; c < width; c++) columnOrder.push(c);\n }\n\n // Activate columns that should be active but aren't yet.\n for (let i = 0; i < activatedCount && i < columnOrder.length; i++) {\n const col = columnOrder[i];\n if (columnActivationTick.current[col] === -1) {\n columnActivationTick.current[col] = tick;\n }\n }\n\n // --- Render frame ---\n const rows: string[] = [];\n for (let r = 0; r < height; r++) {\n let row = '';\n for (let c = 0; c < width; c++) {\n const activatedAt = columnActivationTick.current[c];\n\n let char: string;\n if (activatedAt === -1) {\n // Not yet activated\n char = phase === TransitionPhase.Out ? ' ' : '█';\n } else {\n // Column is activated — determine shade based on ticks since activation\n const age = tick - activatedAt;\n const shadeIndex = Math.min(\n Math.floor(age / TICKS_PER_SHADE),\n SHADES.length - 1,\n );\n\n if (phase === TransitionPhase.Out) {\n // Building up: ░ → ▒ → ▓ → █\n char = SHADES[shadeIndex];\n } else {\n // Dissolving: █ → ▓ → ▒ → ░ → space\n if (shadeIndex >= SHADES.length - 1 && age >= SHADE_CYCLE_TICKS) {\n char = ' ';\n } else {\n char = SHADES[SHADES.length - 1 - shadeIndex];\n }\n }\n }\n\n row += char;\n }\n rows.push(row);\n }\n\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n {rows.map((row, i) => (\n <Text key={i} dimColor>\n {row}\n </Text>\n ))}\n </Box>\n );\n};\n","/**\n * KeyboardHintsBar — Row showing active keyboard shortcuts.\n *\n * Always reserves its row to prevent layout shift, and always renders the\n * active hints (in dimmed grey text) while a screen has registered them.\n */\n\nimport { Box, Text } from 'ink';\nimport { useKeyboardHintsContext } from '@ui/tui/hooks/useKeyboardHints';\nimport { Colors } from '@ui/tui/styles';\n\nexport const KeyboardHintsBar = () => {\n const { hints } = useKeyboardHintsContext();\n\n return (\n <Box height={1} paddingX={1}>\n {hints.map((hint, i) => (\n <Box\n key={`${hint.label}-${hint.action}`}\n marginRight={i < hints.length - 1 ? 2 : 0}\n >\n <Text bold color={Colors.muted}>\n {hint.label}\n </Text>\n <Text dimColor> {hint.action}</Text>\n </Box>\n ))}\n </Box>\n );\n};\n","/**\n * ScreenErrorBoundary — catches React render errors in screens\n * and routes to the outro screen with an error message.\n *\n * Without this, a screen crash silently hangs the TUI.\n */\n\nimport { Box, Text } from 'ink';\nimport { Component, type ReactNode } from 'react';\nimport type { WizardStore } from '@ui/tui/store';\nimport { OutroKind, RunPhase } from '@lib/wizard-session';\nimport { logToFile } from '@utils/debug';\n\ninterface Props {\n store: WizardStore;\n children: ReactNode;\n}\n\ninterface State {\n error: Error | null;\n}\n\nexport class ScreenErrorBoundary extends Component<Props, State> {\n state: State = { error: null };\n\n static getDerivedStateFromError(error: Error): State {\n return { error };\n }\n\n componentDidCatch(error: Error): void {\n const { store } = this.props;\n\n // The console.error below is wiped with the alt screen; this survives.\n logToFile('[screen-error-boundary]', error);\n // eslint-disable-next-line no-console\n console.error('[ScreenErrorBoundary]', error.message, error.stack);\n\n // Set error state — the router will resolve to outro\n store.setOutroData({\n kind: OutroKind.Error,\n message: `A screen crashed: ${error.message}`,\n });\n store.setRunPhase(RunPhase.Error);\n }\n\n render(): ReactNode {\n if (this.state.error) {\n // Fallback while the store transition fires\n return (\n <Box flexDirection=\"column\">\n <Text color=\"red\" bold>\n Something went wrong.\n </Text>\n <Text dimColor>{this.state.error.message}</Text>\n </Box>\n );\n }\n\n return this.props.children;\n }\n}\n","/**\n * ScreenContainer — Renders TitleBar + routes between screens with transitions.\n * Takes a screens map and renders the one matching store.currentScreen.\n * Horizontal wipe plays on push (left) or pop (right).\n *\n * Each screen is wrapped in a ScreenErrorBoundary so that render crashes\n * route to the outro screen with an error message instead of hanging.\n *\n * Provides KeyboardHintsProvider context. The hints bar is rendered below\n * screen content (inside the transition area) so all screens get it.\n */\n\nimport { Box } from 'ink';\nimport { useSyncExternalStore, type ReactNode } from 'react';\nimport { TitleBar } from '@ui/tui/components/TitleBar';\nimport { useStdoutDimensions } from '@ui/tui/hooks/useStdoutDimensions';\nimport { KeyboardHintsProvider } from '@ui/tui/hooks/useKeyboardHints';\nimport { DissolveTransition } from './DissolveTransition.js';\nimport { KeyboardHintsBar } from './KeyboardHintsBar.js';\nimport { ScreenErrorBoundary } from './ScreenErrorBoundary.js';\nimport type { WizardStore } from '@ui/tui/store';\n\nconst MIN_WIDTH = 80;\nexport const MAX_WIDTH = 120;\n\n/** Use terminal width when small so we don't overflow; otherwise clamp to [MIN_WIDTH, MAX_WIDTH]. */\nfunction getContentWidth(terminalColumns: number): number {\n if (terminalColumns < MIN_WIDTH) return terminalColumns;\n return Math.min(MAX_WIDTH, terminalColumns);\n}\n\ninterface ScreenContainerProps {\n store: WizardStore;\n screens: Record<string, ReactNode>;\n}\n\nexport const ScreenContainer = ({ store, screens }: ScreenContainerProps) => {\n const [columns, rows] = useStdoutDimensions();\n useSyncExternalStore(\n (cb) => store.subscribe(cb),\n () => store.getSnapshot(),\n );\n\n const terminalWidth = columns;\n const width = getContentWidth(terminalWidth);\n const contentHeight = Math.max(5, rows - 3);\n const contentAreaWidth = Math.max(10, width - 2);\n const direction = store.lastNavDirection === 'pop' ? 'right' : 'left';\n const activeScreen = screens[store.currentScreen] ?? null;\n\n const inner = (\n <Box flexDirection=\"column\" height={rows} width={width}>\n <TitleBar version={store.version} width={width} />\n <Box height={1} />\n <Box flexDirection=\"column\" flexGrow={1} paddingX={1}>\n <DissolveTransition\n transitionKey={store.currentScreen}\n width={contentAreaWidth}\n height={contentHeight}\n direction={direction}\n >\n <ScreenErrorBoundary store={store}>\n <Box flexDirection=\"column\" height={contentHeight}>\n <Box\n flexDirection=\"column\"\n flexGrow={1}\n flexShrink={1}\n overflow=\"hidden\"\n >\n {activeScreen}\n </Box>\n <Box height={1} />\n <KeyboardHintsBar />\n </Box>\n </ScreenErrorBoundary>\n </DissolveTransition>\n </Box>\n </Box>\n );\n\n return (\n <Box\n flexDirection=\"column\"\n height={rows}\n width={terminalWidth}\n alignItems=\"center\"\n justifyContent=\"flex-start\"\n >\n <KeyboardHintsProvider>{inner}</KeyboardHintsProvider>\n </Box>\n );\n};\n","/**\n * TabContainer — Self-contained tabbed interface.\n * Absorbs BottomTabBar + StatusPanel functionality.\n *\n * Key bindings are declared via useKeyBindings, which auto-registers\n * hints in the KeyboardHintsBar (rendered by ScreenContainer).\n */\n\nimport { Box, Text } from 'ink';\nimport { useState, useMemo, type ReactNode } from 'react';\nimport { Colors, Icons } from '@ui/tui/styles';\nimport {\n useKeyBindings,\n KeyMatch,\n type KeyBinding,\n} from '@ui/tui/hooks/useKeyBindings';\nimport type { WizardStore } from '@ui/tui/store';\nimport { COLLAPSED_COUNT, EXPANDED_COUNT } from '@ui/tui/constants';\n\n// Re-exported so existing importers (e.g. LearnCard) keep their path.\nexport { COLLAPSED_COUNT, EXPANDED_COUNT };\n\nexport interface TabDefinition {\n id: string;\n label: string;\n component: ReactNode;\n}\n\ninterface TabContainerProps {\n tabs: TabDefinition[];\n statusMessage?: string | string[];\n /** Enable expand/collapse on the status box via 's' key */\n expandableStatus?: boolean;\n /** Store reference — required when expandableStatus is true so status state is shared. */\n store?: WizardStore;\n}\n\nexport const TabContainer = ({\n tabs,\n statusMessage,\n expandableStatus = false,\n store,\n}: TabContainerProps) => {\n const [activeTab, setActiveTab] = useState(0);\n // Fallback to local state when no store is provided\n const [localExpanded, setLocalExpanded] = useState(false);\n\n const statusExpanded = store ? store.statusExpanded : localExpanded;\n\n const bindings = useMemo<KeyBinding[]>(() => {\n const b: KeyBinding[] = [\n {\n match: [KeyMatch.LeftArrow, KeyMatch.RightArrow],\n label: '\\u2190\\u2192',\n action: 'switch tab',\n handler: (_input, key) => {\n if (key.leftArrow) {\n setActiveTab((prev) => Math.max(0, prev - 1));\n }\n if (key.rightArrow) {\n setActiveTab((prev) => Math.min(tabs.length - 1, prev + 1));\n }\n },\n },\n ];\n if (expandableStatus) {\n b.push({\n match: 's',\n label: 's',\n action: 'toggle status',\n priority: 12,\n handler: () => {\n if (store) {\n store.toggleStatusExpanded();\n } else {\n setLocalExpanded((prev) => !prev);\n }\n },\n });\n }\n return b;\n }, [tabs.length, expandableStatus, store]);\n\n useKeyBindings('tab-container', bindings);\n\n const current = tabs[activeTab];\n\n const allMessages = statusMessage\n ? Array.isArray(statusMessage)\n ? statusMessage\n : [statusMessage]\n : [];\n const visibleCount =\n expandableStatus && statusExpanded ? EXPANDED_COUNT : COLLAPSED_COUNT;\n const visibleMessages = allMessages.slice(-visibleCount);\n\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n {/* Active tab content — overflow hidden so expanded status eats into this area */}\n <Box flexDirection=\"column\" flexGrow={1} flexShrink={1} overflow=\"hidden\">\n {current?.component}\n </Box>\n\n {/* Status bar */}\n {visibleMessages.length > 0 && (\n <Box\n flexDirection=\"column\"\n borderStyle=\"single\"\n borderTop\n borderBottom={false}\n borderLeft={false}\n borderRight={false}\n borderColor={Colors.muted}\n paddingX={1}\n overflow=\"hidden\"\n >\n {visibleMessages.map((msg, i, arr) => {\n const isCurrent = i === arr.length - 1;\n return (\n <Text key={i} color={Colors.muted} dimColor={!isCurrent}>\n {isCurrent ? Icons.diamond : '\\u250A'} {msg}\n </Text>\n );\n })}\n </Box>\n )}\n\n {/* Tab bar — wraps onto extra rows when there are more tabs than\n fit the terminal width, instead of clipping the overflow. */}\n <Box height={1} />\n <Box gap={1} paddingX={1} flexWrap=\"wrap\" flexShrink={0}>\n {tabs.map((tab, i) => (\n <Text\n key={tab.id}\n inverse={i === activeTab}\n color={i === activeTab ? Colors.accent : Colors.muted}\n bold={i === activeTab}\n >\n {` ${tab.label} `}\n </Text>\n ))}\n </Box>\n </Box>\n );\n};\n","/**\n * HNViewer — Top 10 Hacker News stories.\n *\n * Fetches from the HN Firebase API on mount.\n * Each story has a [1]–[0] numeral; typing it opens the HN comments page.\n */\n\nimport { Box, Text } from 'ink';\nimport { useState, useEffect } from 'react';\nimport { Colors } from '@ui/tui/styles';\nimport { useKeyBindings } from '@ui/tui/hooks/useKeyBindings';\n\nconst HN_API = 'https://hacker-news.firebaseio.com/v0';\n\ninterface HNStory {\n id: number;\n title: string;\n by: string;\n time: number;\n score: number;\n}\n\nexport const HNViewer = () => {\n const [stories, setStories] = useState<HNStory[]>([]);\n const [loading, setLoading] = useState(true);\n\n useEffect(() => {\n void (async () => {\n try {\n const res = await fetch(`${HN_API}/topstories.json`);\n const ids = (await res.json()) as number[];\n const top10 = ids.slice(0, 10);\n\n const items = await Promise.all(\n top10.map(async (id) => {\n const r = await fetch(`${HN_API}/item/${id}.json`);\n return r.json() as Promise<HNStory>;\n }),\n );\n\n setStories(items);\n } catch {\n // Silently fail — tab just stays empty\n }\n setLoading(false);\n })();\n }, []);\n\n useKeyBindings('hn-viewer', [\n {\n match: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'],\n label: 'number keys',\n action: 'open story',\n priority: 5,\n handler: (input) => openStory(input, stories),\n },\n ]);\n\n if (loading) {\n return (\n <Box paddingX={1}>\n <Text dimColor>Loading Hacker News...</Text>\n </Box>\n );\n }\n\n if (stories.length === 0) {\n return (\n <Box paddingX={1}>\n <Text dimColor>Could not load Hacker News.</Text>\n </Box>\n );\n }\n\n return (\n <Box flexDirection=\"column\" paddingX={1}>\n <Text bold color={Colors.accent}>\n Hacker News — Top 10\n </Text>\n <Box height={1} />\n {stories.map((story, i) => {\n const key = i === 9 ? '0' : String(i + 1);\n const date = new Date(story.time * 1000);\n const dateStr = date.toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n });\n\n return (\n <Box key={story.id} flexDirection=\"column\">\n <Box>\n <Text color={Colors.accent} bold>\n [{key}]\n </Text>\n <Text bold> {story.title}</Text>\n </Box>\n <Box marginLeft={4}>\n <Text dimColor>\n {story.score}pts • {story.by}, {dateStr}\n </Text>\n </Box>\n </Box>\n );\n })}\n </Box>\n );\n};\n\nfunction openStory(input: string, stories: HNStory[]): void {\n const num = parseInt(input, 10);\n if (isNaN(num)) return;\n const index = num === 0 ? 9 : num - 1;\n const story = stories[index];\n if (!story) return;\n\n const url = `https://news.ycombinator.com/item?id=${story.id}`;\n void import('child_process').then(({ exec }) => {\n exec(`open \"${url}\" 2>/dev/null || xdg-open \"${url}\" 2>/dev/null`);\n });\n}\n","/**\n * LinesBlock — Reveals ReactNode lines one at a time.\n * Each line can contain colors, bold, ASCII art — any JSX.\n */\n\nimport { Box } from 'ink';\nimport { useState, useEffect, type ReactNode } from 'react';\n\ninterface LinesBlockProps {\n lines: ReactNode[];\n interval: number;\n active: boolean;\n completed: boolean;\n onComplete: () => void;\n /** Max rows this block may occupy. When exceeded, top lines are truncated. */\n maxHeight?: number;\n}\n\nexport const LinesBlock = ({\n lines,\n interval,\n active,\n completed,\n onComplete,\n maxHeight,\n}: LinesBlockProps) => {\n const [revealedCount, setRevealedCount] = useState(0);\n\n // Reveal lines one at a time\n useEffect(() => {\n if (!active || revealedCount >= lines.length) return;\n const timer = setTimeout(\n () => setRevealedCount((c) => c + 1),\n revealedCount === 0 ? 0 : interval,\n );\n return () => clearTimeout(timer);\n }, [active, revealedCount, lines.length, interval]);\n\n // Fire onComplete when all lines revealed\n useEffect(() => {\n if (active && revealedCount >= lines.length) onComplete();\n }, [active, revealedCount, lines.length, onComplete]);\n\n // When maxHeight is set, only show the last maxHeight lines\n const visibleStart =\n maxHeight != null\n ? Math.max(0, (completed ? lines.length : revealedCount) - maxHeight)\n : 0;\n\n return (\n <Box flexDirection=\"column\">\n {lines.map((line, li) => {\n if (completed) {\n if (li < visibleStart) return null;\n return <Box key={li}>{line}</Box>;\n }\n if (li >= revealedCount || li < visibleStart) return null;\n return <Box key={li}>{line}</Box>;\n })}\n </Box>\n );\n};\n","/**\n * NodeBlock — Renders static JSX, fires onComplete immediately.\n * The sequencer's blockInterval handles dwell time.\n */\n\nimport { Text } from 'ink';\nimport { useEffect, type ReactNode } from 'react';\n\ninterface NodeBlockProps {\n content: ReactNode;\n active: boolean;\n completed: boolean;\n onComplete: () => void;\n}\n\nexport const NodeBlock = ({\n content,\n active,\n completed,\n onComplete,\n}: NodeBlockProps) => {\n useEffect(() => {\n if (active) onComplete();\n }, [active, onComplete]);\n\n if (completed) return <Text dimColor>{content}</Text>;\n return <>{content}</>;\n};\n","/**\n * ContentSequencer — Plays content blocks in order.\n *\n * Each block is a self-animating component that fires onComplete() when done.\n * The sequencer waits blockInterval ms between blocks, then advances.\n *\n * Block types:\n * - string → TextBlock (animated text, sugar for { content: '...' })\n * - { content: str } → TextBlock (animated text with per-block overrides)\n * - { content: JSX } → NodeBlock (static JSX)\n * - { type: 'lines' } → LinesBlock (line-by-line reveal)\n * - { type: 'clear' } → ClearBlock (page break — hides all prior blocks)\n */\n\nimport { Box } from 'ink';\nimport {\n useState,\n useCallback,\n useEffect,\n useRef,\n useMemo,\n type ReactNode,\n} from 'react';\nimport { TextBlock, type TextRevealMode } from './TextBlock.js';\nimport { LinesBlock } from './LinesBlock.js';\nimport { NodeBlock } from './NodeBlock.js';\nimport { computeVisibleRange } from './layout-helpers.js';\nimport { isLinesBlock, isClearBlock, isObjectBlock } from './content-types.js';\nexport type {\n ContentBlock,\n ContentObjectBlock,\n ContentLinesBlock,\n ContentClearBlock,\n} from './content-types.js';\nexport { isLinesBlock, isClearBlock, isObjectBlock } from './content-types.js';\n\nimport type { ContentBlock } from './content-types.js';\n\n/** Resolve the pause after a block completes. */\nexport function getBlockPause(\n block: ContentBlock,\n blockInterval: number,\n): number {\n if (typeof block === 'string') return blockInterval;\n return block.pause ?? blockInterval;\n}\n\ninterface ContentSequencerProps {\n blocks: ContentBlock[];\n mode: TextRevealMode;\n /** Row budget for visible content. When set, older blocks are evicted. */\n maxHeight?: number;\n /** Available text width in columns (for height estimation). */\n availableWidth?: number;\n bullet?: ReactNode;\n animationInterval?: number;\n sentenceInterval?: number;\n lineInterval?: number;\n blockInterval?: number;\n /** Delay in ms before the first block appears. */\n startDelay?: number;\n /** Resume from a previously persisted block index. */\n initialBlockIdx?: number;\n /** Called whenever the active block index advances. */\n onBlockChange?: (idx: number) => void;\n /** Called once when the last block completes (after its pause). */\n onSequenceComplete?: () => void;\n}\n\nexport const ContentSequencer = ({\n blocks,\n mode,\n maxHeight,\n availableWidth,\n bullet,\n animationInterval,\n sentenceInterval,\n lineInterval = 200,\n blockInterval = 3200,\n startDelay = 0,\n initialBlockIdx = 0,\n onBlockChange,\n onSequenceComplete,\n}: ContentSequencerProps) => {\n const resuming = initialBlockIdx > 0;\n const [activeIdx, setActiveIdx] = useState(\n resuming ? initialBlockIdx : startDelay > 0 ? -1 : 0,\n );\n const transitionTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n // Initial delay before first block (skip when resuming)\n useEffect(() => {\n if (resuming || startDelay <= 0 || activeIdx !== -1) return;\n const timer = setTimeout(() => setActiveIdx(0), startDelay);\n return () => clearTimeout(timer);\n }, [startDelay, activeIdx]);\n\n // Compute visible range reactively (re-evaluates on resize, block advance, etc.)\n const [visibleStart, visibleEnd] = useMemo(() => {\n if (activeIdx < 0) return [0, -1] as [number, number];\n if (maxHeight == null || availableWidth == null) {\n return [0, activeIdx] as [number, number];\n }\n return computeVisibleRange(blocks, activeIdx, availableWidth, maxHeight);\n }, [blocks, activeIdx, maxHeight, availableWidth]);\n\n const handleComplete = useCallback(\n (blockIndex: number) => {\n // Only the active block can trigger advancement\n if (blockIndex !== activeIdx) return;\n // Last block — fire sequence-complete after its pause, don't advance\n if (activeIdx >= blocks.length - 1) {\n if (onSequenceComplete && !transitionTimer.current) {\n const pause = getBlockPause(blocks[blockIndex], blockInterval);\n transitionTimer.current = setTimeout(() => {\n transitionTimer.current = null;\n onSequenceComplete();\n }, pause);\n }\n return;\n }\n // Don't double-trigger\n if (transitionTimer.current) return;\n\n const pause = getBlockPause(blocks[blockIndex], blockInterval);\n transitionTimer.current = setTimeout(() => {\n transitionTimer.current = null;\n setActiveIdx((i) => {\n const next = i + 1;\n onBlockChange?.(next);\n return next;\n });\n }, pause);\n },\n [activeIdx, blocks, blockInterval, onBlockChange, onSequenceComplete],\n );\n\n // Find the most recent clear block — nothing before it renders.\n // When the active block IS a clear block, immediately hide all prior content\n // so the pause shows a blank screen (not dim prior text).\n const clearFloor = useMemo(() => {\n if (activeIdx >= 0 && isClearBlock(blocks[activeIdx])) return activeIdx;\n for (let i = activeIdx - 1; i >= 0; i--) {\n if (isClearBlock(blocks[i])) return i + 1;\n }\n return 0;\n }, [blocks, activeIdx]);\n\n return (\n <Box flexDirection=\"column\">\n {blocks.map((block, i) => {\n // Not yet reached\n if (i > activeIdx) return null;\n // Hidden by clear block\n if (i < clearFloor) return null;\n // Completed clear blocks don't render (active ones must mount to fire onComplete)\n if (isClearBlock(block) && i < activeIdx) return null;\n // Evicted by viewport\n if (i < visibleStart || i > visibleEnd) return null;\n\n const active = i === activeIdx;\n const completed = i < activeIdx;\n\n // Completed non-text blocks don't persist by default\n if (completed && isObjectBlock(block)) {\n const isText = typeof block.content === 'string';\n const shouldPersist = block.persist ?? isText;\n if (!shouldPersist) return null;\n }\n\n return (\n <Box key={i} flexDirection=\"column\" marginBottom={1}>\n <BlockRenderer\n block={block}\n active={active}\n completed={completed}\n onComplete={() => handleComplete(i)}\n mode={mode}\n bullet={bullet}\n animationInterval={animationInterval}\n sentenceInterval={sentenceInterval}\n lineInterval={lineInterval}\n maxHeight={maxHeight}\n availableWidth={availableWidth}\n />\n </Box>\n );\n })}\n </Box>\n );\n};\n\ninterface BlockRendererProps {\n block: ContentBlock;\n active: boolean;\n completed: boolean;\n onComplete: () => void;\n mode: TextRevealMode;\n bullet?: ReactNode;\n animationInterval?: number;\n sentenceInterval?: number;\n lineInterval: number;\n maxHeight?: number;\n availableWidth?: number;\n}\n\nconst BlockRenderer = ({\n block,\n active,\n completed,\n onComplete,\n mode,\n bullet,\n animationInterval,\n sentenceInterval,\n lineInterval,\n maxHeight,\n availableWidth,\n}: BlockRendererProps) => {\n // Clear block — completes immediately, renders nothing\n if (isClearBlock(block)) {\n useEffect(() => {\n if (active) onComplete();\n }, [active, onComplete]);\n return null;\n }\n\n // Bare string sugar → TextBlock with sequencer defaults\n if (typeof block === 'string') {\n return (\n <TextBlock\n text={block}\n active={active}\n completed={completed}\n onComplete={onComplete}\n mode={mode}\n bullet={bullet}\n animationInterval={animationInterval}\n sentenceInterval={sentenceInterval}\n maxHeight={maxHeight}\n availableWidth={availableWidth}\n // Bare string sugar always uses the default — to override, use\n // the object form: { content: '...', dimWhenComplete: false }.\n />\n );\n }\n\n // Lines block\n if (isLinesBlock(block)) {\n return (\n <LinesBlock\n lines={block.lines}\n interval={block.interval ?? lineInterval}\n active={active}\n completed={completed}\n onComplete={onComplete}\n maxHeight={maxHeight}\n />\n );\n }\n\n // Object block — dispatch on content type\n if (typeof block.content === 'string') {\n return (\n <TextBlock\n text={block.content}\n active={active}\n completed={completed}\n onComplete={onComplete}\n mode={block.mode ?? mode}\n bullet={bullet}\n animationInterval={block.animationInterval ?? animationInterval}\n sentenceInterval={block.sentenceInterval ?? sentenceInterval}\n maxHeight={maxHeight}\n availableWidth={availableWidth}\n dimWhenComplete={block.dimWhenComplete ?? true}\n />\n );\n }\n\n return (\n <NodeBlock\n content={block.content}\n active={active}\n completed={completed}\n onComplete={onComplete}\n />\n );\n};\n","/**\n * LearnCard — Generic render shell for an animated content deck.\n *\n * Program-owned. Callers pass the script via `blocks`. The script lives\n * under `src/lib/programs/<name>/content/`. The shell handles\n * dimension tracking, status-bar height math, and the `display=\"none\"`\n * clamp on narrow terminals.\n */\n\nimport { Box, Text } from 'ink';\nimport { Colors } from '@ui/tui/styles';\nimport type { WizardStore } from '@ui/tui/store';\nimport { ContentSequencer, TextRevealMode } from '@ui/tui/primitives/index';\nimport type { ContentBlock } from '@ui/tui/primitives/index';\nimport { useStdoutDimensions } from '@ui/tui/hooks/useStdoutDimensions';\nimport {\n COLLAPSED_COUNT,\n EXPANDED_COUNT,\n} from '@ui/tui/primitives/TabContainer';\n\n/** Fixed chrome: ScreenContainer (3) + TabContainer tab bar (2) */\nconst FIXED_CHROME = 5;\nconst HEADER_ROWS = 2; // title + spacer\nconst MIN_CONTENT_ROWS = 6;\n\ninterface LearnCardProps {\n store?: WizardStore;\n /** The script to play. Program-owned; see programs/<name>/content/. */\n blocks: ContentBlock[];\n onComplete?: () => void;\n}\n\nexport const LearnCard = ({ store, blocks, onComplete }: LearnCardProps) => {\n const [columns, rows] = useStdoutDimensions();\n\n // Dynamic status bar height: messages + border when present\n const hasStatus = store ? store.statusMessages.length > 0 : false;\n const statusBarRows = hasStatus\n ? (store?.statusExpanded ? EXPANDED_COUNT : COLLAPSED_COUNT) + 1\n : 0;\n\n const contentHeight = rows - FIXED_CHROME - statusBarRows;\n const tooSmall = contentHeight < MIN_CONTENT_ROWS;\n\n const maxHeight = Math.max(1, contentHeight - HEADER_ROWS);\n // Half of clamped content width, minus paddingX on both sides\n const paneWidth = Math.floor((Math.min(120, columns) - 2) / 2) - 2;\n\n // Always render so ContentSequencer stays mounted (preserves activeIdx).\n // When too small, hide visually via display=\"none\".\n return (\n <Box\n flexDirection=\"column\"\n paddingX={1}\n display={tooSmall ? 'none' : 'flex'}\n >\n <Text bold color={Colors.accent}>\n Learn\n </Text>\n <Box height={1} />\n <ContentSequencer\n blocks={blocks}\n mode={TextRevealMode.SentenceBySentence}\n maxHeight={maxHeight}\n availableWidth={paneWidth}\n startDelay={2000}\n initialBlockIdx={store?.learnCardBlockIdx ?? 0}\n onBlockChange={(idx) => store?.setLearnCardBlockIdx(idx)}\n onSequenceComplete={onComplete}\n />\n </Box>\n );\n};\n","/**\n * TipsCard — Shows PostHog tips during the agent run.\n * Reactively shows/hides tips based on discovered features.\n * Supports toggling additional features via key bindings.\n */\n\nimport { Box, Text, useInput } from 'ink';\nimport type { WizardStore } from '@ui/tui/store';\nimport { Colors, Icons } from '@ui/tui/styles';\nimport { DiscoveredFeature, AdditionalFeature } from '@lib/wizard-session';\n\n/** A discrete tip shown in the TipsCard during the agent run. */\ninterface Tip {\n /** Unique identifier */\n id: string;\n /** Title line */\n title: string;\n /** Description shown below the title */\n description: string;\n /** Optional URL shown after the description */\n url?: string;\n /** When provided, the tip is only shown if this returns true */\n visible?: (store: WizardStore) => boolean;\n /** Optional key binding that toggles an AdditionalFeature */\n toggle?: {\n /** The key the user presses (lowercase) */\n key: string;\n /** The additional feature to enqueue */\n feature: AdditionalFeature;\n /** Label shown when toggled on */\n enabledLabel: string;\n /** Prompt shown when not yet toggled */\n prompt: string;\n /** Returns true if already toggled */\n isEnabled: (store: WizardStore) => boolean;\n };\n}\n\nconst TIPS: Tip[] = [\n {\n id: 'persons',\n title: 'You can also track people and groups with PostHog',\n description:\n \"Events can be associated with the humans who generate them, letting you understand a specific user or customer's situation.\",\n },\n {\n id: 'properties',\n title: 'Get way more detail using properties',\n description:\n 'Events and person records can have any properties you want. Track things like how they found your website, what subscription tier they choose, and much more.',\n },\n {\n id: 'slack',\n title: 'Use PostHog in Slack',\n description:\n 'Connect the PostHog Slack app to analyze data and ship product changes — deploy flags, open PRs, run queries — just by tagging @PostHog:',\n url: 'https://posthog.com/slack-app',\n },\n {\n id: 'stripe',\n title: 'You can track Stripe revenue with PostHog',\n description: 'Add Stripe as a data source while you wait:',\n url: 'https://app.posthog.com/project/data-warehouse/new-source?kind=Stripe',\n visible: (store) =>\n store.session.discoveredFeatures.includes(DiscoveredFeature.Stripe),\n },\n {\n id: 'llm',\n title: 'PostHog can also help you track your LLM costs',\n description: '',\n visible: (store) =>\n store.session.discoveredFeatures.includes(DiscoveredFeature.LLM),\n toggle: {\n key: 'l',\n feature: AdditionalFeature.LLM,\n enabledLabel: 'LLM analytics setup queued next',\n prompt: 'We detected LLM dependencies in your project.',\n isEnabled: (store) => store.session.llmOptIn,\n },\n },\n];\n\nexport const TipsCard = ({ store }: { store: WizardStore }) => {\n useInput((input) => {\n for (const tip of TIPS) {\n if (\n tip.toggle &&\n input.toLowerCase() === tip.toggle.key &&\n (!tip.visible || tip.visible(store)) &&\n !tip.toggle.isEnabled(store)\n ) {\n store.enableFeature(tip.toggle.feature);\n }\n }\n });\n\n return (\n <Box flexDirection=\"column\" paddingX={1}>\n <Text bold color={Colors.accent}>\n Tips\n </Text>\n <Box height={1} />\n\n {TIPS.filter((tip) => !tip.visible || tip.visible(store)).map((tip) => (\n <Box key={tip.id} flexDirection=\"column\" marginBottom={1}>\n <Text>\n <Text color={Colors.accent}>{Icons.diamond} </Text>\n <Text bold>{tip.title}</Text>\n </Text>\n\n {tip.toggle ? (\n tip.toggle.isEnabled(store) ? (\n <Text color={Colors.success}>\n {Icons.check} {tip.toggle.enabledLabel}\n </Text>\n ) : (\n <Text dimColor>\n {tip.toggle.prompt} Press{' '}\n <Text bold color={Colors.accent}>\n {tip.toggle.key.toUpperCase()}\n </Text>{' '}\n to enable.\n </Text>\n )\n ) : (\n <Text dimColor>\n {tip.description}\n {tip.url && (\n <>\n {' '}\n <Text color=\"cyan\">{tip.url}</Text>\n </>\n )}\n </Text>\n )}\n </Box>\n ))}\n </Box>\n );\n};\n","/**\n * ServiceHealthList — Shared component for displaying service health status.\n *\n * Used by HealthCheckScreen (blocking services only) and HealthWarningsTab (all services).\n */\n\nimport { Box, Text } from 'ink';\nimport {\n ServiceHealthStatus,\n type AllServicesHealth,\n type ComponentHealthResult,\n type ComponentStatus,\n type HealthCheckKey,\n} from '@lib/health-checks/types';\nimport { SERVICE_LABELS } from '@lib/health-checks/readiness';\nimport { Icons } from '@ui/tui/styles';\n\n/** Keys that are component-level detail — shown inline under their parent. */\nconst COMPONENT_KEYS: HealthCheckKey[] = [\n 'posthogComponents',\n 'npmComponents',\n 'cloudflareComponents',\n];\n\n/** Map component key → its parent \"overall\" key */\nconst COMPONENT_PARENT: Partial<Record<HealthCheckKey, HealthCheckKey>> = {\n posthogComponents: 'posthogOverall',\n npmComponents: 'npmOverall',\n cloudflareComponents: 'cloudflareOverall',\n};\n\nfunction statusIcon(status: ServiceHealthStatus): {\n icon: string;\n color: string;\n} {\n switch (status) {\n case ServiceHealthStatus.Down:\n return { icon: Icons.squareFilled, color: 'red' };\n case ServiceHealthStatus.Degraded:\n return { icon: Icons.squareFilled, color: '#DC9300' };\n case ServiceHealthStatus.Healthy:\n return { icon: Icons.check, color: 'green' };\n }\n}\n\ninterface ServiceHealthListProps {\n health: AllServicesHealth;\n /** If set, only show services with these keys */\n filterKeys?: HealthCheckKey[];\n /** Show healthy services (default true) */\n showHealthy?: boolean;\n}\n\nexport const ServiceHealthList = ({\n health,\n filterKeys,\n showHealthy = true,\n}: ServiceHealthListProps) => {\n const topLevelKeys = (Object.keys(health) as HealthCheckKey[]).filter(\n (k) => !COMPONENT_KEYS.includes(k),\n );\n\n const keysToShow = filterKeys\n ? topLevelKeys.filter((k) => filterKeys.includes(k))\n : topLevelKeys;\n\n return (\n <Box flexDirection=\"column\" paddingLeft={1}>\n {keysToShow.map((key) => {\n const result = health[key];\n if (!showHealthy && result.status === ServiceHealthStatus.Healthy) {\n return null;\n }\n\n const { icon, color } = statusIcon(result.status);\n const label = SERVICE_LABELS[key];\n\n // Find component-level details if this is a parent key\n const componentKey = (\n Object.entries(COMPONENT_PARENT) as [HealthCheckKey, HealthCheckKey][]\n ).find(([, parent]) => parent === key)?.[0];\n const componentResult = componentKey\n ? (health[componentKey] as ComponentHealthResult)\n : undefined;\n const affectedComponents: ComponentStatus[] =\n componentResult?.degradedOrDownComponents ?? [];\n\n return (\n <Box key={key} flexDirection=\"column\">\n <Text>\n <Text color={color}>{icon}</Text>{' '}\n <Text bold={result.status !== ServiceHealthStatus.Healthy}>\n {label}\n </Text>\n </Text>\n {affectedComponents.length > 0 && (\n <Box flexDirection=\"column\" paddingLeft={3}>\n {affectedComponents.slice(0, 5).map((c) => {\n const ci = statusIcon(c.status);\n return (\n <Text key={c.name} dimColor>\n <Text color={ci.color}>{ci.icon}</Text> {c.name}\n </Text>\n );\n })}\n {affectedComponents.length > 5 && (\n <Text dimColor>+{affectedComponents.length - 5} more</Text>\n )}\n </Box>\n )}\n </Box>\n );\n })}\n </Box>\n );\n};\n","import { Box, Text } from 'ink';\nimport { useStdoutDimensions } from '@ui/tui/hooks/useStdoutDimensions';\nimport { Colors, Icons } from '@ui/tui/styles';\nimport {\n getKindMeta,\n type HealthIssue,\n type HealthIssueSeverity,\n} from '@lib/programs/posthog-doctor/index';\n\nexport const SEVERITY_ORDER: HealthIssueSeverity[] = [\n 'critical',\n 'warning',\n 'info',\n];\n\nconst SEVERITY_COLOR: Record<HealthIssueSeverity, string> = {\n critical: Colors.error,\n warning: Colors.accent,\n info: Colors.primary,\n};\n\nexport const SEVERITY_LABEL: Record<HealthIssueSeverity, string> = {\n critical: 'Critical',\n warning: 'Warning',\n info: 'Info',\n};\n\nconst ICON_COL = 2;\nconst ROW_GAP = 2;\nconst NARROW_TERM_THRESHOLD = 90;\nconst MAX_DOCS_WIDTH = 50;\nconst MIN_DOCS_WIDTH = 20;\n\nfunction computeDocsWidth(termCols: number): number {\n if (termCols < NARROW_TERM_THRESHOLD) return 0;\n const inner = termCols - 12;\n return Math.min(\n MAX_DOCS_WIDTH,\n Math.max(MIN_DOCS_WIDTH, Math.floor(inner * 0.45)),\n );\n}\n\ninterface IssueTableProps {\n issues: HealthIssue[];\n}\n\nexport const IssueTable = ({ issues }: IssueTableProps) => {\n const [termCols] = useStdoutDimensions();\n const docsWidth = computeDocsWidth(termCols);\n\n const grouped: Partial<Record<HealthIssueSeverity, HealthIssue[]>> = {};\n for (const issue of issues) {\n (grouped[issue.severity] ??= []).push(issue);\n }\n\n return (\n <Box flexDirection=\"column\">\n {SEVERITY_ORDER.map((sev) => {\n const list = grouped[sev];\n if (!list || list.length === 0) return null;\n return (\n <Box key={sev} flexDirection=\"column\" marginTop={1}>\n <Text bold color={SEVERITY_COLOR[sev]}>\n {SEVERITY_LABEL[sev]} ({list.length})\n </Text>\n {list.map((issue) => (\n <IssueRow key={issue.id} issue={issue} docsWidth={docsWidth} />\n ))}\n </Box>\n );\n })}\n </Box>\n );\n};\n\nconst IssueRow = ({\n issue,\n docsWidth,\n}: {\n issue: HealthIssue;\n docsWidth: number;\n}) => {\n const meta = getKindMeta(issue.kind);\n const sevColor = SEVERITY_COLOR[issue.severity];\n\n if (docsWidth === 0) {\n return (\n <Box flexDirection=\"column\">\n <Box>\n <Box width={ICON_COL}>\n <Text color={sevColor}>{Icons.squareFilled}</Text>\n </Box>\n <Box flexGrow={1} flexShrink={1} overflow=\"hidden\">\n <Text wrap=\"truncate\">{meta.title}</Text>\n </Box>\n </Box>\n <Box paddingLeft={ICON_COL}>\n <Text color={Colors.primary} wrap=\"truncate\">\n {meta.docsUrl}\n </Text>\n </Box>\n </Box>\n );\n }\n\n return (\n <Box>\n <Box width={ICON_COL}>\n <Text color={sevColor}>{Icons.squareFilled}</Text>\n </Box>\n <Box flexGrow={1} flexShrink={1} overflow=\"hidden\" marginRight={ROW_GAP}>\n <Text wrap=\"truncate\">{meta.title}</Text>\n </Box>\n <Box width={docsWidth} flexShrink={0}>\n <Text color={Colors.primary} wrap=\"truncate\">\n {meta.docsUrl}\n </Text>\n </Box>\n </Box>\n );\n};\n","/**\n * McpScreen — MCP server install/remove flow.\n *\n * Uses an McpInstaller service (passed via props) instead of\n * importing business logic directly. Testable, no dynamic imports.\n *\n * Supports two modes via the `mode` prop:\n * - 'install': detect clients → confirm → [pick clients] → pick features → install\n * - 'remove': detect installed clients → confirm → remove\n *\n * When done, calls store.setMcpComplete(). The router resolves to outro.\n */\n\nimport { Box, Text, useInput } from 'ink';\nimport { useState, useEffect } from 'react';\nimport { useSyncExternalStore } from 'react';\nimport { type WizardStore, McpOutcome } from '@ui/tui/store';\nimport {\n ConfirmationInput,\n PickerMenu,\n GroupedPickerMenu,\n} from '@ui/tui/primitives/index';\nimport { Colors, Icons } from '@ui/tui/styles';\nimport type {\n McpInstaller,\n McpClientInfo,\n} from '@ui/tui/services/mcp-installer';\nimport {\n AVAILABLE_FEATURES,\n ALL_FEATURE_VALUES,\n isAllFeaturesSelected,\n} from '@steps/add-mcp-server-to-clients/defaults';\n\nexport type McpMode = 'install' | 'remove';\n\ninterface McpScreenProps {\n store: WizardStore;\n installer: McpInstaller;\n mode?: McpMode;\n}\n\nenum Phase {\n Detecting = 'detecting',\n Ask = 'ask',\n Pick = 'pick',\n FeatureSelect = 'feature-select',\n Connector = 'connector',\n Working = 'working',\n Done = 'done',\n None = 'none',\n}\n\nconst markDone = (\n store: WizardStore,\n outcome: McpOutcome,\n clients: string[] = [],\n featuresSelected?: 'all' | string[],\n) => {\n store.setMcpComplete(outcome, clients, featuresSelected);\n};\n\nconst reportFeatures = (features: string[]): 'all' | string[] =>\n isAllFeaturesSelected(features) ? 'all' : features;\n\n/**\n * Connector step prompt — Enter continues (opens the connector page). There's\n * no skip: picking the connector commits to opening it.\n */\nconst ConnectorContinue = ({ onContinue }: { onContinue: () => void }) => {\n useInput((_input, key) => {\n if (key.return) {\n onContinue();\n }\n });\n return (\n <Text color={Colors.primary}>\n Press enter to continue {Icons.triangleRight}\n </Text>\n );\n};\n\nexport const McpScreen = ({\n store,\n installer,\n mode = 'install',\n}: McpScreenProps) => {\n useSyncExternalStore(\n (cb) => store.subscribe(cb),\n () => store.getSnapshot(),\n );\n\n // Keep stdin active from mount so Windows cmd.exe doesn't drop\n // the first keypress when ConfirmationInput appears after detection.\n useInput(() => undefined);\n\n const isRemove = mode === 'remove';\n\n const [phase, setPhase] = useState<Phase>(Phase.Detecting);\n const [clients, setClients] = useState<McpClientInfo[]>([]);\n const [selectedClientNames, setSelectedClientNames] = useState<string[]>([]);\n const [resultClients, setResultClients] = useState<string[]>([]);\n const [pluginClients, setPluginClients] = useState<string[]>([]);\n const [installMode, setInstallMode] = useState<'all' | 'custom'>('custom');\n\n useEffect(() => {\n void (async () => {\n try {\n const detected = await installer.detectClients();\n if (detected.length === 0) {\n setPhase(Phase.None);\n setTimeout(() => markDone(store, McpOutcome.NoClients), 1500);\n } else {\n setClients(detected);\n setPhase(Phase.Ask);\n }\n } catch {\n setPhase(Phase.None);\n setTimeout(() => markDone(store, McpOutcome.Failed), 1500);\n }\n })();\n }, [installer]); // eslint-disable-line\n\n const proceedAfterClientPick = (\n clientNames: string[],\n chosenMode: 'all' | 'custom',\n ) => {\n setSelectedClientNames(clientNames);\n\n // Recommended flow: install everything straight away. Browser connectors\n // (e.g. Claude Desktop/Web) just open their connector page here, same as\n // before — no extra screen.\n if (chosenMode === 'all') {\n void doInstall(clientNames, [...ALL_FEATURE_VALUES]);\n return;\n }\n if (store.session.mcpFeatures) {\n void doInstall(clientNames, store.session.mcpFeatures);\n return;\n }\n\n // Customize flow: a browser connector configures its tools and features in\n // Claude's UI, not through the wizard's feature picker. The picker keeps it\n // mutually exclusive from local editors, so a connector selection is\n // connector-only — show its own screen instead of the feature picker.\n const isConnector = clientNames.some(\n (name) => clients.find((c) => c.name === name)?.finish,\n );\n if (isConnector) {\n setPhase(Phase.Connector);\n return;\n }\n setPhase(Phase.FeatureSelect);\n };\n\n const handleConfirm = () => {\n if (isRemove) {\n void doRemove();\n } else if (clients.length === 1) {\n proceedAfterClientPick([clients[0]!.name], 'custom');\n } else {\n setPhase(Phase.Pick);\n }\n };\n\n const handleTriStateChoice = (choice: 'all' | 'custom' | 'skip') => {\n if (choice === 'skip') {\n handleSkip();\n return;\n }\n setInstallMode(choice);\n if (clients.length === 1) {\n proceedAfterClientPick([clients[0]!.name], choice);\n } else {\n setPhase(Phase.Pick);\n }\n };\n\n const handleSkip = () => {\n markDone(store, McpOutcome.Skipped);\n };\n\n const doInstall = async (names: string[], features?: string[]) => {\n setPhase(Phase.Working);\n let mcpResult: string[] = [];\n let pluginResult: string[] = [];\n\n const pluginCapableSet = new Set(\n clients.filter((c) => c.supportsPlugin).map((c) => c.name),\n );\n const pluginCapableNames = names.filter((n) => pluginCapableSet.has(n));\n const directNames = names.filter((n) => !pluginCapableSet.has(n));\n\n if (installMode === 'all') {\n // Plugin-capable clients get the plugin (which bundles MCP).\n // Non-plugin-capable clients get a direct MCP config write.\n try {\n mcpResult = await installer.install(\n directNames,\n features,\n store.session.apiKey,\n );\n } catch {\n // mcpResult stays []\n }\n try {\n pluginResult = await installer.installPlugins(pluginCapableNames);\n } catch {\n // best-effort\n }\n } else {\n // 'custom' — MCP-only for every selected client. Plugin install is\n // skipped so the user's feature selection is actually respected.\n try {\n mcpResult = await installer.install(\n names,\n features,\n store.session.apiKey,\n );\n } catch {\n // mcpResult stays []\n }\n }\n\n setResultClients(mcpResult);\n setPluginClients(pluginResult);\n setPhase(Phase.Done);\n const succeeded = mcpResult.length + pluginResult.length > 0;\n const outcome = succeeded ? McpOutcome.Installed : McpOutcome.Failed;\n const featuresReport = reportFeatures(features ?? [...ALL_FEATURE_VALUES]);\n setTimeout(\n () =>\n markDone(\n store,\n outcome,\n [...mcpResult, ...pluginResult],\n featuresReport,\n ),\n 2000,\n );\n };\n\n const doRemove = async () => {\n setPhase(Phase.Working);\n let result: string[] = [];\n try {\n result = await installer.remove();\n setResultClients(result);\n } catch {\n setResultClients([]);\n }\n setPhase(Phase.Done);\n const outcome =\n result.length > 0 ? McpOutcome.Installed : McpOutcome.Failed;\n setTimeout(() => markDone(store, outcome, result), 2000);\n };\n\n // The \"what you get\" preview shown above the install confirmation —\n // installed users have no idea what \"MCP\" means; lead with the value.\n const installValueBullets = [\n 'Ask your agent: \"List my feature flags\" — and it does.',\n 'Run SQL, build dashboards, ship flags, all from your IDE.',\n 'No copy-pasting tokens or context. Your agent has the keys.',\n ];\n\n // Clients connected via a browser page (e.g. Claude Desktop/Web) aren't truly\n // \"installed\" — the user finishes in the browser. Split them out of the\n // \"installed for\" list and render the finish instructions separately.\n const finishNotes = clients.flatMap((c) =>\n c.finish && resultClients.includes(c.name)\n ? [{ name: c.name, url: c.finish.url, instruction: c.finish.instruction }]\n : [],\n );\n const installedNow = resultClients.filter(\n (name) => !finishNotes.some((n) => n.name === name),\n );\n\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n <Text bold color={Colors.accent}>\n {isRemove\n ? 'Remove the PostHog MCP'\n : 'Install the MCP so you can chat to your data'}\n </Text>\n\n <Box marginTop={1} flexDirection=\"column\">\n {phase === Phase.Detecting && (\n <Text dimColor>Detecting supported editors...</Text>\n )}\n\n {phase === Phase.None && (\n <Text dimColor>\n No {isRemove ? 'installed' : 'supported'} MCP clients detected.\n Skipping...\n </Text>\n )}\n\n {phase === Phase.Ask && (\n <>\n {!isRemove && (\n <Box flexDirection=\"column\" marginBottom={1}>\n {installValueBullets.map((bullet) => (\n <Text key={bullet} dimColor>\n {'•'} {bullet}\n </Text>\n ))}\n </Box>\n )}\n <Text dimColor>\n Detected: {clients.map((c) => c.name).join(', ')}\n </Text>\n <Box marginTop={1}>\n {!isRemove && !store.session.mcpFeatures ? (\n <PickerMenu\n message={`Install the PostHog MCP server${\n clients.some((c) => c.supportsPlugin) ? ' and plugin' : ''\n }?`}\n options={[\n {\n label: 'Install with all features',\n value: 'all',\n hint: 'recommended',\n },\n {\n label: 'Customize features',\n value: 'custom',\n },\n { label: 'No thanks', value: 'skip' },\n ]}\n mode=\"single\"\n onSelect={(choice) =>\n handleTriStateChoice(choice as 'all' | 'custom' | 'skip')\n }\n />\n ) : (\n <ConfirmationInput\n message={`${\n isRemove ? 'Remove' : 'Install'\n } the PostHog MCP server${\n clients.some((c) => c.supportsPlugin) ? ' and plugin' : ''\n }?`}\n confirmLabel={isRemove ? 'Remove' : 'Install'}\n cancelLabel=\"No thanks\"\n onConfirm={handleConfirm}\n onCancel={handleSkip}\n />\n )}\n </Box>\n </>\n )}\n\n {phase === Phase.Pick && (\n <PickerMenu\n message={\n installMode === 'all'\n ? 'Select editor to install'\n : 'Select editor to install MCP server'\n }\n options={clients.map((c) => ({\n label: c.name,\n value: c.name,\n // Browser connectors can't be installed alongside local editors\n // and are configured on their own screen, not the feature picker.\n exclusive: Boolean(c.finish),\n // Hints only show in the recommended flow; the customize flow\n // keeps the list clean.\n hint:\n installMode === 'all'\n ? c.finish\n ? 'connector'\n : c.supportsPlugin\n ? 'plugin'\n : 'MCP'\n : undefined,\n }))}\n mode=\"multi\"\n onSelect={(selected) => {\n const names = Array.isArray(selected) ? selected : [selected];\n proceedAfterClientPick(names, installMode);\n }}\n />\n )}\n\n {phase === Phase.FeatureSelect && (\n <GroupedPickerMenu\n message=\"Select features to enable\"\n groups={AVAILABLE_FEATURES}\n initialSelected={[]}\n onSelect={(features) => {\n void doInstall(selectedClientNames, features);\n }}\n />\n )}\n\n {phase === Phase.Connector && (\n <Box flexDirection=\"column\">\n <Box marginBottom={1}>\n <Text dimColor>\n You'll choose which features and tools to enable in\n Claude's UI after connecting.\n </Text>\n </Box>\n <ConnectorContinue\n onContinue={() => void doInstall(selectedClientNames, [])}\n />\n </Box>\n )}\n\n {phase === Phase.Working && (\n <Text dimColor>\n {isRemove ? 'Removing' : 'Installing'} MCP server...\n </Text>\n )}\n\n {phase === Phase.Done && (\n <Box flexDirection=\"column\">\n {installedNow.length + pluginClients.length + finishNotes.length ===\n 0 ? (\n <Text dimColor>\n {isRemove ? 'Removal' : 'Installation'} skipped.\n </Text>\n ) : (\n <>\n {pluginClients.length > 0 && (\n <>\n <Text color=\"green\" bold>\n {'\\u2714'} Plugin installed for:\n </Text>\n {pluginClients.map((name, i) => (\n <Text key={`p-${i}`}>\n {' '}\n {'\\u2022'} {name}\n </Text>\n ))}\n </>\n )}\n {installedNow.length > 0 && (\n <>\n <Text color=\"green\" bold>\n {'\\u2714'} MCP server{' '}\n {isRemove ? 'removed from' : 'installed for'}:\n </Text>\n {installedNow.map((name, i) => (\n <Text key={`m-${i}`}>\n {' '}\n {'\\u2022'} {name}\n </Text>\n ))}\n </>\n )}\n {finishNotes.map((note) => (\n <Box key={note.name} flexDirection=\"column\" marginTop={1}>\n <Text color=\"green\" bold>\n {'\\u2714'} {note.name} {'\\u2014'} installs a PostHog\n connector:\n </Text>\n <Text>\n {' '}Opened <Text color=\"cyan\">{note.url}</Text>\n </Text>\n <Text dimColor>\n {' '}\n {note.instruction}\n </Text>\n <Text dimColor>\n {' '}(If it didn't open, paste the URL above.)\n </Text>\n </Box>\n ))}\n </>\n )}\n </Box>\n )}\n </Box>\n </Box>\n );\n};\n","","/**\n * Role + framework-tailored MCP prompt suggestions.\n *\n * All copy lives in `mcp-role-prompts.copy.json` so prompts can be\n * edited without touching TypeScript. This file holds the types,\n * the lookup functions, and the framework-family mapping.\n *\n * Editing rule for the JSON (which can't carry comments itself): every\n * prompt is either (a) a read query on any PostHog product, or (b) a\n * write on dashboards, insights, notebooks, or annotations — the four\n * \"persistence\" surfaces. No prompt should ask the agent to ship a\n * flag, run an experiment, send a survey, or create an alert. See\n * prompt-tree.md §5 for the scope reality.\n *\n * The wizard surfaces these on the McpSuggestedPromptsScreen after\n * MCP install. Picking strategy for the kit:\n * 1. Known role + known framework → role kit with family overrides.\n * 2. Known role + unknown framework → role kit, no overrides.\n * 3. Unknown role → DEFAULT_KIT.\n */\n\nimport type { Integration } from './constants';\nimport copyData from './mcp-role-prompts.copy.json';\n\n/**\n * Roles that ship from `role_at_organization` on the PostHog user object.\n * `security` isn't in the enum upstream — the engineering kit covers\n * that audience.\n */\nexport const TAILORED_ROLES = [\n 'founder',\n 'product',\n 'leadership',\n 'marketing',\n 'engineering',\n 'data',\n] as const;\n\nexport type TailoredRole = (typeof TAILORED_ROLES)[number];\n\n/**\n * Unified shape for every clickable picker entry the screen renders —\n * initial-picker kit prompts, cross-sell prompts, and follow-up prompts.\n * The three flavors are distinguished by which optional fields they\n * populate, not by separate types:\n *\n * kit prompt → { prompt, description }\n * cross-sell prompt → { prompt, description, product }\n * follow-up prompt → { prompt, label }\n */\nexport interface PromptOption {\n /** Sent to the agent when picked. Also serves as the picker label when `label` is omitted. */\n prompt: string;\n /** Optional picker label override. Follow-ups use this to show a short verb-phrase (\"Save as dashboard\") instead of the full prompt. */\n label?: string;\n /** Optional one-line description shown by the Goodbye sample list. */\n description?: string;\n /** Optional product tag — when present, picker prepends \"Try {product} —\" to the label. */\n product?: string;\n /** Stable identifier used by `roleFamilyOverrides` to target a kit entry by name (reorder-safe). Populated on kit entries; left out on cross-sells and follow-ups. */\n key?: string;\n}\n\nexport type PromptKit = PromptOption[];\n\n/**\n * Buckets `Integration` values into broader framework families so we can\n * write one kit per family instead of per individual integration.\n */\nexport type FrameworkFamily =\n | 'frontend-web'\n | 'mobile'\n | 'backend'\n | 'fullstack'\n | 'unknown';\n\nexport interface RoleGreeting {\n /** 1-line hook — typewrites in. */\n headline: string;\n /** 2-3 lines of value framing — revealed line-by-line. */\n bullets: string[];\n /** Sets up the picker, e.g. \"Pick one to try.\" — fades in. */\n outro: string;\n}\n\n/**\n * The \"Take PostHog to Slack\" card surfaced at the end of the MCP flow\n * (Goodbye phase + dedicated Connect-Slack step). `useCases` is resolved\n * per role; the rest is static. Every string here is presentation copy\n * shown to the user — none of it is sent to the agent, so the picker's\n * read/persistence prompt-scope rule does not apply.\n */\nexport interface SlackAppCard {\n headline: string;\n /** One-line hook covering both analysis and shipping. */\n pitch: string;\n /** posthog.com/slack-app — \"learn more\". */\n learnMoreUrl: string;\n /** settings/project-integrations#integration-slack — where the user connects Slack. */\n setupUrl: string;\n /** The Slack agent's two capabilities (code/PR + data) — fixed, not role-tailored. */\n capabilities: string[];\n}\n\nexport const FOLLOW_UP_EXIT_SENTINEL = '__follow_up_exit__';\n/** How many follow-up suggestions to surface above the exit entry. */\nexport const FOLLOW_UP_COUNT = 3;\n\n// ── Data loaded from JSON ──────────────────────────────────────────────\n// One cast per top-level key. JSON imports lose the precise key\n// constraints (e.g. Record<TailoredRole, ...>), so we re-attach them\n// here. TypeScript can still catch shape mismatches at the call site.\n\n/**\n * Always shown as the picker's first option regardless of role —\n * a safe generic read that works on any project setup. The screen\n * prepends it and dedupes against the role kit so it never appears\n * twice when DEFAULT_KIT happens to include it.\n */\nexport const PINNED_FIRST_PROMPT = copyData.pinnedFirstPrompt as PromptOption;\n\nconst DEFAULT_KIT = copyData.defaultKit as PromptKit;\nconst ROLE_KITS = copyData.roleKits as Record<TailoredRole, PromptKit>;\n// Overrides are keyed by a base-kit entry's `key` (e.g. \"onboarding\",\n// \"top-errors\") so a kit reorder doesn't silently shift overrides to\n// the wrong slot. Each override is a partial PromptOption that gets\n// merged onto the base entry.\nconst ROLE_FAMILY_OVERRIDES = copyData.roleFamilyOverrides as Partial<\n Record<\n TailoredRole,\n Partial<Record<FrameworkFamily, Record<string, PromptOption>>>\n >\n>;\nconst ROLE_GREETINGS = copyData.roleGreetings as Record<\n TailoredRole,\n RoleGreeting\n>;\nconst NEUTRAL_GREETING = copyData.neutralGreeting as RoleGreeting;\nconst TOOL_FOLLOW_UPS = copyData.toolFollowUps as Record<\n string,\n PromptOption[]\n>;\nconst ROLE_FOLLOW_UPS = copyData.roleFollowUps as Record<\n TailoredRole,\n PromptOption[]\n>;\nconst GENERIC_FOLLOW_UPS = copyData.genericFollowUps as PromptOption[];\nconst DEEP_DIVE_FOLLOW_UPS = copyData.deepDiveFollowUps as PromptOption[];\nconst CROSS_SELL_BY_ROLE = copyData.crossSellByRole as Record<\n TailoredRole,\n PromptOption[]\n>;\nconst NEUTRAL_CROSS_SELL = copyData.neutralCrossSell as PromptOption[];\n// Presentation copy for the \"Take PostHog to Slack\" surfaces (Goodbye\n// card + dedicated step). Shown to the user, never sent to the agent —\n// so the read/persistence prompt-scope rule above does not apply. The\n// capabilities describe the Slack agent itself, not role-specific\n// examples. Connecting Slack is a manual OAuth step in the PostHog app,\n// so we link out to `setupUrl` rather than wiring it up.\nconst SLACK_APP = copyData.slackApp as {\n learnMoreUrl: string;\n setupUrl: string;\n headline: string;\n pitch: string;\n capabilities: string[];\n};\n\n// ── Framework family map ───────────────────────────────────────────────\n// Stays in code (not JSON) because it's structural data tied to the\n// `Integration` enum, not user-facing copy.\n\nconst INTEGRATION_FAMILY: Record<string, FrameworkFamily> = {\n nextjs: 'fullstack',\n nuxt: 'fullstack',\n 'tanstack-start': 'fullstack',\n astro: 'fullstack',\n sveltekit: 'fullstack',\n vue: 'frontend-web',\n angular: 'frontend-web',\n 'react-router': 'frontend-web',\n 'tanstack-router': 'frontend-web',\n javascript_web: 'frontend-web',\n 'react-native': 'mobile',\n swift: 'mobile',\n android: 'mobile',\n django: 'backend',\n flask: 'backend',\n fastapi: 'backend',\n python: 'backend',\n laravel: 'backend',\n rails: 'backend',\n ruby: 'backend',\n javascript_node: 'backend',\n};\n\nconst EXIT_FOLLOW_UP: PromptOption = {\n label: \"I'm done — exit\",\n prompt: FOLLOW_UP_EXIT_SENTINEL,\n};\n\n// ── Helpers ────────────────────────────────────────────────────────────\n\nfunction isTailoredRole(role: string | null | undefined): role is TailoredRole {\n return (\n typeof role === 'string' &&\n (TAILORED_ROLES as readonly string[]).includes(role)\n );\n}\n\n/**\n * Strip MCP tool-name prefixes so lookup keys can stay short. Real MCP\n * tool names arrive as `mcp__<server>__<tool>`; the agent SDK also\n * sometimes drops the prefix. We take the substring after the last\n * double-underscore (or the input untouched if there's none).\n */\nfunction normalizeToolName(toolName: string | null): string | null {\n if (!toolName) return null;\n const idx = toolName.lastIndexOf('__');\n return idx >= 0 ? toolName.slice(idx + 2) : toolName;\n}\n\n/** Pick `n` items from a pool starting at a rotation offset. */\nfunction pickRotated<T>(pool: T[], n: number, rotation: number): T[] {\n if (pool.length === 0) return [];\n if (pool.length <= n) return pool;\n const start =\n ((Math.floor(rotation) % pool.length) + pool.length) % pool.length;\n const result: T[] = [];\n for (let i = 0; i < n; i++) {\n result.push(pool[(start + i) % pool.length]);\n }\n return result;\n}\n\n/** Drop duplicates while preserving order (by prompt text). */\nfunction dedupeFollowUps(list: PromptOption[]): PromptOption[] {\n const seen = new Set<string>();\n const out: PromptOption[] = [];\n for (const f of list) {\n if (seen.has(f.prompt)) continue;\n seen.add(f.prompt);\n out.push(f);\n }\n return out;\n}\n\n// ── Public API ─────────────────────────────────────────────────────────\n\nexport function getFrameworkFamily(\n integration: Integration | null | undefined,\n): FrameworkFamily {\n if (!integration) return 'unknown';\n return INTEGRATION_FAMILY[integration] ?? 'unknown';\n}\n\n/**\n * Resolve the right kit given everything we know about the user + project.\n * Always returns at least DEFAULT_KIT; never throws.\n */\nexport function getRolePrompts(\n role: string | null | undefined,\n integration: Integration | null | undefined,\n): PromptKit {\n const family = getFrameworkFamily(integration);\n\n if (!isTailoredRole(role)) {\n // Unknown role — DEFAULT_KIT is already framework-agnostic and broad.\n return DEFAULT_KIT;\n }\n\n const baseKit = ROLE_KITS[role];\n const overridesForRole = ROLE_FAMILY_OVERRIDES[role];\n const overridesForFamily = overridesForRole?.[family];\n\n if (!overridesForFamily) {\n return baseKit;\n }\n\n // Look up overrides by each entry's stable `key` so a kit reorder\n // doesn't shift overrides to the wrong slot. An entry without a key,\n // or a key not present in the override map, passes through unchanged.\n return baseKit.map((entry) => {\n const override = entry.key ? overridesForFamily[entry.key] : undefined;\n return override ?? entry;\n });\n}\n\nexport function getRoleGreeting(role: string | null | undefined): RoleGreeting {\n if (!isTailoredRole(role)) return NEUTRAL_GREETING;\n return ROLE_GREETINGS[role];\n}\n\n/**\n * Resolve `FOLLOW_UP_COUNT` context-aware follow-ups + an always-present\n * exit entry. Pulls from up to four pools — tool-specific, role-specific,\n * deep-dive (only after the user has explored a few steps), and generic —\n * dedupes, filters out anything already in `branchHistory`, then picks\n * `FOLLOW_UP_COUNT` with a rotation offset driven by `branchHistory.length`\n * so successive visits surface different slices.\n */\nexport function getFollowUps(args: {\n lastToolName: string | null;\n lastPrompt: string;\n role: string | null | undefined;\n branchHistory: string[];\n}): PromptOption[] {\n const { lastToolName, role, branchHistory } = args;\n const normalized = normalizeToolName(lastToolName);\n const depth = branchHistory.length;\n\n // Build the candidate pool — order matters because dedup keeps the\n // first occurrence. Tool-specific first (most relevant), then role,\n // then deep-dive (only after the user's been exploring), then generic.\n const candidates: PromptOption[] = [];\n if (normalized && TOOL_FOLLOW_UPS[normalized]) {\n candidates.push(...TOOL_FOLLOW_UPS[normalized]);\n }\n if (isTailoredRole(role)) {\n candidates.push(...ROLE_FOLLOW_UPS[role]);\n }\n if (depth >= 3) {\n candidates.push(...DEEP_DIVE_FOLLOW_UPS);\n }\n candidates.push(...GENERIC_FOLLOW_UPS);\n\n const deduped = dedupeFollowUps(candidates);\n const seen = new Set(branchHistory);\n const fresh = deduped.filter((f) => !seen.has(f.prompt));\n\n // Rotate by depth so repeat visits to the same tool surface different\n // slices of the pool. A user who keeps picking `query-trends` won't\n // see the same three options every time.\n const selected = pickRotated(fresh, FOLLOW_UP_COUNT, depth);\n\n return [...selected, EXIT_FOLLOW_UP];\n}\n\n/**\n * Cross-sell prompts to surface above the role kit in PromptPicker.\n * Filtered by role so the recommendations stay coherent (founders see\n * the \"exec-friendly\" cross-sells, engineers see \"debug-friendly\", etc).\n */\nexport function getCrossSellPrompts(\n role: string | null | undefined,\n): PromptOption[] {\n if (!isTailoredRole(role)) return NEUTRAL_CROSS_SELL;\n return CROSS_SELL_BY_ROLE[role];\n}\n\n/**\n * Resolve the \"Take PostHog to Slack\" card. Role-independent — the Slack\n * agent's two capabilities (code/PR + data) describe the product itself,\n * not role-specific examples.\n */\nexport function getSlackAppCard(): SlackAppCard {\n return {\n headline: SLACK_APP.headline,\n pitch: SLACK_APP.pitch,\n learnMoreUrl: SLACK_APP.learnMoreUrl,\n setupUrl: SLACK_APP.setupUrl,\n capabilities: SLACK_APP.capabilities,\n };\n}\n","/**\n * McpSuggestedPromptsScreen — shown after MCP install succeeds in the\n * standalone `wizard mcp add` program, and as the entry point for\n * `wizard mcp tutorial`.\n *\n * Phases:\n * 1. Choose — opens with a Log in / Exit picker, framed by a\n * teaser of what MCP can do.\n * 2. Authenticating — runs `services.performLogin()` (OAuth in\n * production, canned values in the playground).\n * Renders a spinner + login URL inline while the\n * promise is pending. Errors return to Choose\n * with an inline error line.\n * 3. Greeting — role-tuned welcome via `getRoleGreeting`. A\n * ContentSequencer animates the headline,\n * bullets, and outro, then hands off to\n * PromptPicker. Only fires once per session\n * (returning via `[p]` skips it).\n * 4. PromptPicker — lists the role-tailored kit from\n * `getRolePrompts`; user picks one to run.\n * 5. Running — streams the agent's response inline via\n * `services.runPromptStreaming`. Text chunks\n * typewrite in; tool calls and results render\n * as styled badges. `[esc]` aborts; `[p]`\n * returns to the picker. On `done`/`error`,\n * auto-advances to FollowUp.\n * 6. FollowUp — surfaces 3 context-aware next prompts inferred\n * from the last tool the agent used (via\n * `getFollowUps`), plus an explicit exit.\n * Picking a follow-up re-enters Running; the\n * conversation tree grows as deep as\n * MAX_PROMPT_RUNS allows.\n *\n * Credentials are guaranteed non-null once Greeting / PromptPicker /\n * Running / FollowUp are reached (the Choose → Authenticating gate\n * forces a successful login first). A defensive throw protects the\n * Running useEffect against a state-machine bug.\n */\n\nimport { Box, Text } from 'ink';\nimport { Spinner } from '@inkjs/ui';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { useSyncExternalStore } from 'react';\nimport opn from 'opn';\n\nimport type { WizardStore } from '@ui/tui/store';\nimport { Colors, Icons } from '@ui/tui/styles';\nimport { useKeyBindings, KeyMatch } from '@ui/tui/hooks/useKeyBindings';\nimport {\n ContentSequencer,\n LoadingBox,\n PickerMenu,\n TextRevealMode,\n type ContentBlock,\n} from '@ui/tui/primitives/index';\nimport {\n getRolePrompts,\n getRoleGreeting,\n getFollowUps,\n getCrossSellPrompts,\n getSlackAppCard,\n FOLLOW_UP_EXIT_SENTINEL,\n PINNED_FIRST_PROMPT,\n type PromptOption,\n type RoleGreeting,\n} from '@lib/mcp-role-prompts';\nimport type { Integration } from '@lib/constants';\nimport { analytics } from '@utils/analytics';\nimport { logToFile } from '@utils/debug';\nimport type {\n AgentChunk,\n McpSuggestedPromptsServices,\n} from '@ui/tui/services/mcp-suggested-prompts-services';\n\ninterface McpSuggestedPromptsScreenProps {\n store: WizardStore;\n services: McpSuggestedPromptsServices;\n}\n\nenum Phase {\n Choose = 'choose',\n Authenticating = 'authenticating',\n Greeting = 'greeting',\n PromptPicker = 'prompt-picker',\n Running = 'running',\n FollowUp = 'follow-up',\n /** Final beat on every dismissal — reminds the user how to keep\n * talking to PostHog after the tutorial ends. */\n Goodbye = 'goodbye',\n Done = 'done',\n}\n\nenum ChoiceValue {\n Login = 'login',\n ConnectSlack = 'connect-slack',\n Exit = 'exit',\n}\n\n// Cap how many prompts a single tutorial session can run, including\n// follow-ups. Once reached, FollowUp shows a cap-reached state and the\n// only escape is [esc]. Keeps the wizard from becoming a free-tier MCP\n// front-end and gives the tutorial a natural \"done\" point.\nconst MAX_PROMPT_RUNS = 5;\n\n// How long to hold the final streamed result on screen before swapping\n// into FollowUp. Gives the user a beat to read the result before the\n// picker mounts underneath. [esc] / [p] still work during the delay.\nconst FOLLOW_UP_DELAY_MS = 3000;\n\nexport const McpSuggestedPromptsScreen = ({\n store,\n services,\n}: McpSuggestedPromptsScreenProps) => {\n useSyncExternalStore(\n (cb) => store.subscribe(cb),\n () => store.getSnapshot(),\n );\n\n const session = store.session;\n // Role + framework family drive the kit, greeting, and cross-sell\n // prompts. All helpers fall back to neutral defaults when either\n // input is missing, so these are always populated.\n const kit = getRolePrompts(session.roleAtOrganization, session.integration);\n const crossSell = useMemo(\n () => getCrossSellPrompts(session.roleAtOrganization),\n [session.roleAtOrganization],\n );\n const greeting = useMemo(\n () => getRoleGreeting(session.roleAtOrganization),\n [session.roleAtOrganization],\n );\n\n // Auth runs up front: the whole flow (Choose-phase Slack option, the\n // Connect-Slack step after) needs credentials to know whether Slack\n // is already connected, so without them we go straight into the\n // OAuth dance and land on Choose informed. Esc cancels back to\n // Choose for users who don't want to log in.\n const [phase, setPhase] = useState<Phase>(() =>\n store.session.credentials ? Phase.Choose : Phase.Authenticating,\n );\n const [loginError, setLoginError] = useState<string | null>(null);\n // Whether the user picked \"Start MCP tutorial\" — decides where a\n // successful login lands: Greeting for a started tutorial, Choose\n // for the up-front auth.\n const startedTutorialRef = useRef(false);\n const [runningPrompt, setRunningPrompt] = useState<string | null>(null);\n const [runChunks, setRunChunks] = useState<AgentChunk[]>([]);\n const [runStartedAt, setRunStartedAt] = useState<number | null>(null);\n // Frozen elapsed-seconds value, set the moment the stream emits\n // 'done' / 'error'. Without this, the \"Done in Xs.\" line ticks up\n // every render once the result is parked under the FollowUp picker.\n const [runDurationSecs, setRunDurationSecs] = useState<number | null>(null);\n // Count every prompt the user has selected this session (including ones\n // they aborted mid-stream). Counted at pick-time, not completion-time,\n // so a user can't tap-cancel-tap-cancel to bypass the cap.\n const [runCount, setRunCount] = useState(0);\n const canPickAnother = runCount < MAX_PROMPT_RUNS;\n\n // The last tool the agent invoked during the current run. Drives the\n // context-aware follow-up suggestions in FollowUp. Cleared at the\n // start of each new run.\n const [lastToolName, setLastToolName] = useState<string | null>(null);\n // Every prompt the user has picked this session — initial + follow-ups.\n // Used to filter out already-seen suggestions in getFollowUps().\n const [branchHistory, setBranchHistory] = useState<string[]>([]);\n\n // AbortController for the in-flight runPromptStreaming call. Lifted\n // to a ref so [esc] / unmount can call abort() without the closure\n // needing to re-bind on every state change.\n const runAbortRef = useRef<AbortController | null>(null);\n\n // The Claude Agent SDK session ID of the most recent completed run.\n // Carried forward into follow-up runs via `resumeSessionId` so the\n // agent sees prior turns as context. Held in a ref so updating it\n // doesn't re-trigger the Running useEffect. Cleared whenever the\n // user returns to PromptPicker — that's a fresh conversation.\n const currentSessionIdRef = useRef<string | null>(null);\n\n // Run OAuth when entering Authenticating phase.\n useEffect(() => {\n if (phase !== Phase.Authenticating) return;\n let cancelled = false;\n\n void (async () => {\n try {\n const { credentials, roleAtOrganization, user } =\n await services.performLogin();\n if (cancelled) return;\n store.setCredentials(credentials);\n store.setRoleAtOrganization(roleAtOrganization);\n store.setApiUser(user);\n store.setLoginUrl(null);\n setPhase(startedTutorialRef.current ? Phase.Greeting : Phase.Choose);\n } catch (err) {\n if (cancelled) return;\n const message = err instanceof Error ? err.message : String(err);\n logToFile(`[McpSuggestedPromptsScreen] login failed: ${message}`);\n store.setLoginUrl(null);\n setLoginError(message);\n setPhase(Phase.Choose);\n }\n })();\n\n return () => {\n cancelled = true;\n };\n }, [phase, services, store]);\n\n // Detect whether Slack is already connected, as soon as credentials\n // are available — pre-seeded by the install flow, or set by the login\n // above. Stored in the session so the Connect-Slack step that follows\n // renders the right variant immediately. Drives the Choose-phase\n // \"Connect Slack now\" option here. On failure `slackConnected` stays\n // null and renders as \"not connected\".\n const credentials = session.credentials;\n const slackConnected = session.slackConnected;\n useEffect(() => {\n if (!credentials || slackConnected !== null) return;\n let cancelled = false;\n const controller = new AbortController();\n void services\n .checkSlackConnected(credentials, controller.signal)\n .then((connected) => {\n if (!cancelled) store.setSlackConnected(connected);\n })\n .catch((err: unknown) => {\n if (cancelled) return;\n analytics.captureException(\n err instanceof Error ? err : new Error(String(err)),\n { step: 'slack_connected_check' },\n );\n });\n return () => {\n cancelled = true;\n controller.abort();\n };\n }, [credentials, slackConnected, services, store]);\n\n // Stream the chosen prompt against the agent. On terminal chunks\n // ('done' or 'error') we schedule a short delay before swapping into\n // FollowUp so the user gets a beat to read the final text.\n useEffect(() => {\n if (phase !== Phase.Running) return;\n if (!runningPrompt) return;\n if (!session.credentials) {\n throw new Error(\n '[McpSuggestedPromptsScreen] Running phase reached without credentials. The Choose gate should have prevented this.',\n );\n }\n\n const controller = new AbortController();\n runAbortRef.current = controller;\n const startedAt = Date.now();\n setRunStartedAt(startedAt);\n setRunChunks([]);\n setLastToolName(null);\n setRunDurationSecs(null);\n\n const finishStream = (\n kind: 'done' | 'error',\n durationMs: number,\n errorText?: string,\n ) => {\n if (controller.signal.aborted) return;\n setRunDurationSecs(Math.round(durationMs / 1000));\n if (kind === 'done') {\n analytics.wizardCapture('mcp suggested prompts run', {\n prompt: runningPrompt,\n durationMs,\n });\n } else {\n analytics.wizardCapture('mcp suggested prompts run failed', {\n prompt: runningPrompt,\n error: errorText,\n });\n }\n // Hold the final result on screen for a beat before swapping into\n // FollowUp, so the user has a moment to read without the picker\n // jumping in underneath. Guard via the abort controller so an\n // [esc] / [p] press inside the delay window cancels the swap.\n setTimeout(() => {\n if (controller.signal.aborted) return;\n setPhase(Phase.FollowUp);\n }, FOLLOW_UP_DELAY_MS);\n };\n\n void (async () => {\n const credentials = session.credentials;\n if (!credentials) return;\n try {\n for await (const chunk of services.runPromptStreaming({\n prompt: runningPrompt,\n credentials,\n signal: controller.signal,\n // Read at call-time so a session id captured by the previous\n // run carries into the follow-up. Null on a fresh start.\n resumeSessionId: currentSessionIdRef.current ?? undefined,\n })) {\n if (controller.signal.aborted) return;\n setRunChunks((prev) => [...prev, chunk]);\n if (chunk.kind === 'tool-call') {\n setLastToolName(chunk.toolName);\n }\n if (chunk.kind === 'done') {\n // Remember the SDK session id so the next follow-up can\n // resume it. The SDK may issue a new id on resume — always\n // overwrite with the latest.\n if (chunk.sessionId) {\n currentSessionIdRef.current = chunk.sessionId;\n }\n finishStream('done', Date.now() - startedAt);\n return;\n }\n if (chunk.kind === 'error') {\n finishStream('error', Date.now() - startedAt, chunk.text);\n return;\n }\n }\n } catch (err) {\n if (controller.signal.aborted) return;\n const text = err instanceof Error ? err.message : String(err);\n setRunChunks((prev) => [...prev, { kind: 'error', text }]);\n finishStream('error', Date.now() - startedAt, text);\n }\n })();\n\n return () => {\n controller.abort();\n if (runAbortRef.current === controller) runAbortRef.current = null;\n };\n }, [phase, runningPrompt, services, session.credentials]);\n\n // Two-stage exit so the user always sees the Goodbye reminder\n // (installed clients + sample prompts) before the screen actually\n // tears down. `enterGoodbye` routes any dismissal into the reminder;\n // `closeWizard` does the actual store mutation that lets the router\n // move on.\n const enterGoodbye = (): void => {\n runAbortRef.current?.abort();\n setPhase(Phase.Goodbye);\n };\n\n const closeWizard = (): void => {\n setPhase(Phase.Done);\n setTimeout(() => {\n store.setMcpSuggestedPromptsDismissed();\n }, 0);\n };\n\n const handleChoice = (value: ChoiceValue | ChoiceValue[]): void => {\n const choice = Array.isArray(value) ? value[0] : value;\n setLoginError(null);\n if (choice === ChoiceValue.Login) {\n analytics.wizardCapture('mcp suggested prompts choose', {\n choice: 'login',\n });\n startedTutorialRef.current = true;\n // Already authenticated by the up-front login — skip straight in.\n setPhase(session.credentials ? Phase.Greeting : Phase.Authenticating);\n } else if (choice === ChoiceValue.ConnectSlack) {\n analytics.wizardCapture('mcp suggested prompts choose', {\n choice: 'connect-slack',\n });\n // Open the Slack integration settings and stay on the Choose screen\n // so the user can still start the tutorial. opn throws in headless\n // environments — swallow it; the URL is also printed on screen.\n if (process.env.NODE_ENV !== 'test') {\n opn(getSlackAppCard().setupUrl, {\n wait: false,\n }).catch(() => {\n // No browser available.\n });\n }\n } else {\n analytics.wizardCapture('mcp suggested prompts choose', {\n choice: 'exit',\n });\n enterGoodbye();\n }\n };\n\n // Single entry-point for kicking off a stream. Used by both the\n // initial picker and the follow-up picker.\n const startRun = (prompt: string): void => {\n setRunningPrompt(prompt);\n setRunCount((c) => c + 1);\n setBranchHistory((h) => [...h, prompt]);\n setPhase(Phase.Running);\n };\n\n const handlePromptPick = (value: string | string[]): void => {\n const picked = Array.isArray(value) ? value[0] : value;\n startRun(picked);\n };\n\n const handleFollowUpPick = (value: string | string[]): void => {\n const picked = Array.isArray(value) ? value[0] : value;\n if (picked === FOLLOW_UP_EXIT_SENTINEL) {\n analytics.wizardCapture('mcp suggested prompts follow-up', {\n choice: 'exit',\n depth: branchHistory.length,\n });\n enterGoodbye();\n return;\n }\n analytics.wizardCapture('mcp suggested prompts follow-up', {\n choice: 'continue',\n depth: branchHistory.length,\n lastToolName,\n });\n startRun(picked);\n };\n\n // `[enter]` skips the auto-paced Greeting to the picker. Only\n // registered while Greeting is on screen — PickerMenu owns enter\n // during the picker phases, and Running auto-transitions on done\n // (no auto-advance timer left to short-circuit).\n const canSkipForward = phase === Phase.Greeting;\n\n useKeyBindings('mcp-suggested-prompts', [\n {\n match: KeyMatch.Escape,\n label: 'esc',\n action:\n phase === Phase.Goodbye\n ? 'close'\n : phase === Phase.Authenticating\n ? 'cancel'\n : 'exit',\n handler: () => {\n if (phase === Phase.Goodbye) {\n closeWizard();\n } else if (phase === Phase.Authenticating) {\n // Cancel the OAuth dance — the login effect's cleanup discards\n // the in-flight result. Choose still works without credentials.\n setPhase(Phase.Choose);\n } else if (\n phase === Phase.Running ||\n phase === Phase.PromptPicker ||\n phase === Phase.FollowUp ||\n phase === Phase.Greeting\n ) {\n enterGoodbye();\n }\n },\n },\n {\n // `[p]` is the primary \"pick a different prompt\" hotkey during\n // Running and FollowUp — always returns to the PromptPicker\n // (aborting the stream if necessary). No-op once the per-session\n // cap is reached. Clearing the session id here is what makes\n // the next pick a fresh conversation rather than a follow-up.\n match: 'p',\n label: 'p',\n action: canPickAnother ? 'pick new prompt' : 'cap reached',\n handler: () => {\n if (phase !== Phase.Running && phase !== Phase.FollowUp) return;\n if (!canPickAnother) return;\n runAbortRef.current?.abort();\n currentSessionIdRef.current = null;\n setPhase(Phase.PromptPicker);\n },\n },\n // Conditional enter binding — only active during the Greeting\n // (where it short-circuits the typewriter pacing). PickerMenu\n // owns enter in the picker phases; Running flips straight to\n // FollowUp the moment the stream completes.\n ...(canSkipForward\n ? [\n {\n match: KeyMatch.Return,\n label: 'enter',\n action: 'continue',\n handler: () => {\n setPhase(Phase.PromptPicker);\n },\n },\n ]\n : []),\n ]);\n\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n <Box marginTop={1} flexDirection=\"column\">\n {phase === Phase.Choose && (\n <ChoosePhase\n error={loginError}\n slackConnected={slackConnected}\n onSelect={handleChoice}\n />\n )}\n\n {phase === Phase.Authenticating && (\n <AuthenticatingPhase loginUrl={session.loginUrl} />\n )}\n\n {phase === Phase.Greeting && (\n <GreetingPhase\n greeting={greeting}\n userDisplayName={session.apiUser?.first_name || null}\n onComplete={() => setPhase(Phase.PromptPicker)}\n />\n )}\n\n {phase === Phase.PromptPicker && (\n <PromptPickerPhase\n promptKit={kit}\n crossSell={crossSell}\n onSelect={handlePromptPick}\n />\n )}\n\n {phase === Phase.Running && runningPrompt && (\n <RunningPhase\n prompt={runningPrompt}\n chunks={runChunks}\n startedAt={runStartedAt}\n frozenDurationSecs={runDurationSecs}\n runCount={runCount}\n maxRuns={MAX_PROMPT_RUNS}\n />\n )}\n\n {phase === Phase.FollowUp && (\n <Box flexDirection=\"column\" flexGrow={1}>\n {/* Result area absorbs flex and shrinks first when the\n terminal is short. `capTextChunks` does the actual\n row-aware truncation; flexShrink here is belt-and-\n suspenders so Ink's layout never squeezes the picker. */}\n {runningPrompt && (\n <Box flexDirection=\"column\" flexShrink={1}>\n <RunningPhase\n prompt={runningPrompt}\n chunks={runChunks}\n startedAt={runStartedAt}\n frozenDurationSecs={runDurationSecs}\n runCount={runCount}\n maxRuns={MAX_PROMPT_RUNS}\n />\n </Box>\n )}\n {/* Picker is pinned: flexShrink={0} means it never gives\n up rows to siblings. flexBasis=\"auto\" keeps its\n natural height. */}\n <Box marginTop={1} flexShrink={0} flexDirection=\"column\">\n <FollowUpPhase\n lastToolName={lastToolName}\n lastPrompt={runningPrompt}\n chunks={runChunks}\n role={session.roleAtOrganization}\n branchHistory={branchHistory}\n canPickAnother={canPickAnother}\n maxRuns={MAX_PROMPT_RUNS}\n onSelect={handleFollowUpPick}\n />\n </Box>\n </Box>\n )}\n\n {phase === Phase.Goodbye && (\n <GoodbyePhase\n installedClients={session.mcpInstalledClients}\n role={session.roleAtOrganization}\n integration={session.integration}\n engaged={branchHistory.length > 0}\n onClose={closeWizard}\n />\n )}\n </Box>\n </Box>\n );\n};\n\n// ── Choose phase ───────────────────────────────────────────────────────\n\ninterface ChoosePhaseProps {\n error: string | null;\n slackConnected: boolean | null;\n onSelect: (value: ChoiceValue | ChoiceValue[]) => void;\n}\n\nconst ChoosePhase = ({ error, slackConnected, onSelect }: ChoosePhaseProps) => {\n return (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n PostHog MCP\n </Text>\n\n <Box marginTop={1}>\n <Text>\n With MCP your agent works directly with the PostHog platform. You can\n prompt it to:\n </Text>\n </Box>\n\n <Box marginTop={1} flexDirection=\"column\">\n <Text>\n <Text color=\"cyan\">{Icons.diamond}</Text> Build dashboards\n </Text>\n <Text>\n <Text color=\"cyan\">{Icons.diamond}</Text> Run SQL queries\n </Text>\n <Text>\n <Text color=\"cyan\">{Icons.diamond}</Text> Deploy feature flags\n </Text>\n <Text>\n <Text color=\"cyan\">{Icons.diamond}</Text> Debug exceptions and errors\n </Text>\n <Text>\n <Text color=\"cyan\">{Icons.diamond}</Text> And lots more...\n </Text>\n </Box>\n\n <Box marginTop={1} flexDirection=\"column\">\n {slackConnected ? (\n <Text>\n <Text color={Colors.success}>{Icons.check}</Text> Slack is connected\n — analyze data and ship product changes there by tagging{' '}\n <Text bold>@PostHog</Text>.\n </Text>\n ) : (\n <Text>\n You can also connect PostHog to Slack, so you can analyze data and\n ship product changes there by tagging <Text bold>@PostHog</Text>.\n </Text>\n )}\n </Box>\n\n <Box marginTop={1}>\n <Text>Want a live demo using real data from your project?</Text>\n </Box>\n\n <Box>\n <PickerMenu\n options={[\n { label: 'Start MCP tutorial', value: ChoiceValue.Login },\n slackConnected\n ? {\n label: 'Already connected to Slack',\n value: ChoiceValue.ConnectSlack,\n icon: { glyph: Icons.check, color: Colors.success },\n disabled: true,\n }\n : { label: 'Connect Slack now', value: ChoiceValue.ConnectSlack },\n { label: 'Exit', value: ChoiceValue.Exit },\n ]}\n onSelect={onSelect}\n />\n </Box>\n {error && (\n <Box marginTop={1}>\n <Text color=\"red\">Login failed: {error}. Try again or exit.</Text>\n </Box>\n )}\n </Box>\n );\n};\n\n// ── Authenticating phase ───────────────────────────────────────────────\n\ninterface AuthenticatingPhaseProps {\n loginUrl: string | null;\n}\n\nconst AuthenticatingPhase = ({ loginUrl }: AuthenticatingPhaseProps) => (\n <Box flexDirection=\"column\">\n <LoadingBox message=\"Waiting for authentication...\" />\n {loginUrl && (\n <Box marginTop={1} marginBottom={1} flexDirection=\"column\">\n <Text>\n <Text dimColor>If the browser didn't open, copy and paste:</Text>\n {'\\n\\n'}\n <Text color=\"cyan\">{loginUrl}</Text>\n </Text>\n </Box>\n )}\n </Box>\n);\n\n// ── Greeting phase ─────────────────────────────────────────────────────\n\ninterface GreetingPhaseProps {\n greeting: RoleGreeting;\n userDisplayName: string | null;\n onComplete: () => void;\n}\n\nconst GreetingPhase = ({\n greeting,\n userDisplayName,\n onComplete,\n}: GreetingPhaseProps) => {\n // Sequence: optional first-name greeting → role-tuned headline →\n // bullets reveal line-by-line → outro fades in → handoff to picker.\n //\n // Pacing notes: `pause` is the time the sequencer waits AFTER a\n // block finishes before advancing — that's the user's reading\n // window. Each typed block is \"ready to read\" only after the\n // typewriter finishes, so the pauses are sized for the absorbed\n // length, not the typing time.\n const blocks: ContentBlock[] = [];\n\n if (userDisplayName) {\n blocks.push({\n content: `Hi ${userDisplayName}!`,\n mode: TextRevealMode.Typewriter,\n animationInterval: 70,\n pause: 1200,\n });\n }\n\n blocks.push({\n content: greeting.headline,\n mode: TextRevealMode.Typewriter,\n animationInterval: 45,\n pause: 2000,\n });\n\n blocks.push({\n type: 'lines',\n lines: greeting.bullets.map((bullet, i) => (\n <Text key={i}>\n <Text color={Colors.primary}>{Icons.diamond}</Text>{' '}\n <Text dimColor>{bullet}</Text>\n </Text>\n )),\n interval: 700,\n pause: 2200,\n });\n\n blocks.push({\n content: greeting.outro,\n mode: TextRevealMode.Typewriter,\n animationInterval: 38,\n pause: 1800,\n });\n\n return (\n <Box flexDirection=\"column\">\n <Box marginBottom={1}>\n <Text bold color={Colors.accent}>\n MCP tutorial\n </Text>\n </Box>\n <ContentSequencer\n blocks={blocks}\n mode={TextRevealMode.Typewriter}\n blockInterval={500}\n onSequenceComplete={onComplete}\n />\n </Box>\n );\n};\n\n// ── Prompt picker phase ────────────────────────────────────────────────\n\ninterface PromptPickerPhaseProps {\n promptKit: PromptOption[];\n crossSell: PromptOption[];\n onSelect: (value: string | string[]) => void;\n}\n\nconst PromptPickerPhase = ({\n promptKit,\n crossSell,\n onSelect,\n}: PromptPickerPhaseProps) => {\n // PINNED_FIRST_PROMPT is the always-first option — a safe generic\n // read (\"Show me my top 5 events from the last 7 days\") that works\n // on any project regardless of role or setup. Cross-sells follow,\n // then the role kit. Dedupe by prompt text so the pinned entry\n // doesn't appear twice when the role kit also contains it. Cap at\n // 4 options total so the picker fits without scrolling.\n const seenPrompts = new Set<string>();\n const options = [PINNED_FIRST_PROMPT, ...crossSell, ...promptKit]\n .filter((o) => {\n if (seenPrompts.has(o.prompt)) return false;\n seenPrompts.add(o.prompt);\n return true;\n })\n .slice(0, 4)\n .map((o) => ({\n label: o.product\n ? `Try ${o.product} — ${o.label ?? o.prompt}`\n : o.label ?? o.prompt,\n value: o.prompt,\n }));\n\n return (\n <Box flexDirection=\"column\">\n <Box marginBottom={1}>\n <Text bold color={Colors.accent}>\n MCP tutorial\n </Text>\n </Box>\n <Box marginBottom={1}>\n <Text>Pick a prompt to see the PostHog MCP in action.</Text>\n </Box>\n <PickerMenu\n options={options}\n optionMarginBottom={1}\n onSelect={onSelect}\n />\n <Box marginTop={2}>\n <Text>\n <Text bold>[esc]</Text>\n <Text> to exit</Text>\n </Text>\n </Box>\n </Box>\n );\n};\n\n// ── Running phase ──────────────────────────────────────────────────────\n\ninterface RunningPhaseProps {\n prompt: string;\n chunks: AgentChunk[];\n startedAt: number | null;\n /** Set the instant the stream finishes; freezes the displayed elapsed\n * time so re-renders under FollowUp don't keep ticking it forward. */\n frozenDurationSecs: number | null;\n runCount: number;\n maxRuns: number;\n}\n\nconst RunningPhase = ({\n prompt,\n chunks,\n startedAt,\n frozenDurationSecs,\n runCount,\n maxRuns,\n}: RunningPhaseProps) => {\n const isDone = chunks.some((c) => c.kind === 'done');\n const errorChunk = chunks.find((c) => c.kind === 'error');\n const finished = isDone || !!errorChunk;\n const elapsed =\n frozenDurationSecs ??\n (startedAt ? Math.round((Date.now() - startedAt) / 1000) : 0);\n\n // When finished, collapse to just the agent's final answer + any\n // error. The tool-call / tool-result chatter has already served its\n // purpose as a \"work in progress\" indicator. We also drop every text\n // block EXCEPT the last one — Sonnet often emits a \"I'll query X…\"\n // preamble alongside its first tool_use, and showing both the\n // preamble and the final answer doubles the noise above the picker.\n const visibleChunks = finished\n ? capTextChunks(collapseToFinalAnswer(chunks))\n : chunks;\n\n return (\n <Box flexDirection=\"column\">\n <Text>\n <Text bold>Prompt:</Text> <Text color={Colors.accent}>{prompt}</Text>\n </Text>\n\n <Box marginTop={1} gap={1}>\n {/* Spinner spins for the full duration of the stream — visual\n confirmation that work is still in flight even during pauses\n between chunks. */}\n {!finished && <Spinner />}\n <Text bold={finished}>\n {finished\n ? errorChunk\n ? `Failed after ${elapsed}s.`\n : `Done in ${elapsed}s.`\n : 'Streaming from PostHog MCP'}\n </Text>\n <Text dimColor>\n ({runCount}/{maxRuns} prompts)\n </Text>\n </Box>\n\n <Box marginTop={1} flexDirection=\"column\">\n {visibleChunks.map((chunk, idx) => (\n <ChunkLine key={idx} chunk={chunk} />\n ))}\n </Box>\n </Box>\n );\n};\n\n/**\n * Strip everything except the agent's final answer + any error chunks.\n * Drops tool-call / tool-result chatter (their work is done once the\n * stream completes) and any text blocks emitted BEFORE the last text\n * block — those are typically Sonnet's \"I'll query X…\" preamble that\n * arrives alongside the first tool_use and adds noise above the picker.\n *\n * If the run produced no text at all (pure tool calls, or only errors),\n * fall through to whatever chunks survived so the user isn't left with\n * a blank result.\n */\nfunction collapseToFinalAnswer(chunks: AgentChunk[]): AgentChunk[] {\n const textChunks = chunks.filter((c) => c.kind === 'text');\n const errors = chunks.filter((c) => c.kind === 'error');\n if (textChunks.length === 0) return errors;\n // Keep only the last text block — that's the model's final answer.\n // Anything earlier was preamble emitted alongside tool_use.\n return [textChunks[textChunks.length - 1], ...errors];\n}\n\n/**\n * Belt-and-suspenders fallback for runs where Claude ignored the\n * terminal-fit system prompt and produced an overlong response. Joins\n * all text chunks, then walks them from the bottom keeping only as many\n * lines as fit in the visual row budget — wide lines that wrap to\n * multiple rows on a narrow terminal cost their wrapped row count, not\n * 1. Prepends an indicator showing how many source lines got cut. Tool\n * calls, results, and errors are preserved separately so they don't\n * disappear into the truncation.\n *\n * Visual-row-aware truncation is what makes the FollowUp picker feel\n * pinned: a 5-row table that wraps to 12 visual rows on a 60-col\n * terminal correctly counts as 12, so the cap leaves exactly the room\n * the picker needs.\n */\nfunction capTextChunks(chunks: AgentChunk[]): AgentChunk[] {\n const rows = process.stdout.rows ?? 24;\n const cols = process.stdout.columns ?? 120;\n // Reserve rows for the FollowUp picker that sits below the result:\n // recap line, 4 picker options, marginTop, plus the prompt + status\n // chrome above the result and the global keyboard hints bar. Be\n // pessimistic — `process.stdout.rows` doesn't always match the actual\n // visible area (terminal padding, host UI chrome, etc.), and an\n // off-by-a-few rows shows up as the result overlapping the picker.\n // Better to leave the picker breathing room than risk overprint.\n const maxVisualRows = Math.max(3, rows - 19);\n\n const textChunks = chunks.filter((c) => c.kind === 'text');\n const errors = chunks.filter((c) => c.kind === 'error');\n if (textChunks.length === 0) return chunks;\n\n const joined = textChunks.map((c) => c.text).join('');\n const lines = joined.split('\\n');\n\n // How many visual rows does this source line consume after wrap?\n // Empty lines still take 1; everything else is ceil(width / cols).\n const visualRows = (line: string): number =>\n Math.max(1, Math.ceil(line.length / cols));\n\n // Walk from the bottom, accumulating visual rows until budget runs\n // out, so we keep the tail of the message (which has the punchline).\n let used = 0;\n let keepFrom = lines.length;\n for (let i = lines.length - 1; i >= 0; i--) {\n const cost = visualRows(lines[i]);\n if (used + cost > maxVisualRows) break;\n used += cost;\n keepFrom = i;\n }\n\n if (keepFrom === 0) return chunks;\n\n const hidden = keepFrom;\n const tail = lines.slice(keepFrom).join('\\n');\n\n return [\n {\n kind: 'text',\n text: `[${hidden} line${\n hidden === 1 ? '' : 's'\n } above — expand terminal to see more]\\n\\n${tail}`,\n },\n ...errors,\n ];\n}\n\ninterface ChunkLineProps {\n chunk: AgentChunk;\n}\n\nconst ChunkLine = ({ chunk }: ChunkLineProps) => {\n if (chunk.kind === 'text') {\n return <Text>{chunk.text}</Text>;\n }\n if (chunk.kind === 'tool-call') {\n return (\n <Text>\n {' '}\n <Text color=\"cyan\">↳ {chunk.toolName}</Text>\n {chunk.detail ? ` ${chunk.detail}` : ''}\n </Text>\n );\n }\n if (chunk.kind === 'tool-result') {\n return (\n <Text>\n {' '}\n <Text color=\"green\">✓</Text> {chunk.detail}\n </Text>\n );\n }\n if (chunk.kind === 'error') {\n return <Text color=\"red\">Error: {chunk.text}</Text>;\n }\n // 'done' — no visual chunk; the dim status line above handles it.\n return null;\n};\n\n// ── Follow-up phase ────────────────────────────────────────────────────\n\ninterface FollowUpPhaseProps {\n lastToolName: string | null;\n lastPrompt: string | null;\n chunks: AgentChunk[];\n role: string | null;\n branchHistory: string[];\n canPickAnother: boolean;\n maxRuns: number;\n onSelect: (value: string | string[]) => void;\n}\n\nconst FollowUpPhase = ({\n lastToolName,\n lastPrompt,\n chunks,\n role,\n branchHistory,\n canPickAnother,\n maxRuns,\n onSelect,\n}: FollowUpPhaseProps) => {\n const followUps = useMemo(\n () =>\n getFollowUps({\n lastToolName,\n lastPrompt: lastPrompt || '',\n role,\n branchHistory,\n }),\n [lastToolName, lastPrompt, role, branchHistory],\n );\n\n // When the cap is reached, only the exit entry is available. Follow-up\n // entries always set `label`; fall back to `prompt` defensively in case\n // a future contributor omits it.\n const options = canPickAnother\n ? followUps.map((f) => ({ label: f.label ?? f.prompt, value: f.prompt }))\n : [{ label: 'Exit', value: FOLLOW_UP_EXIT_SENTINEL }];\n\n const errorChunk = chunks.find((c) => c.kind === 'error');\n const recap = errorChunk\n ? 'That one errored out — try a different angle?'\n : !canPickAnother\n ? `You've hit the ${maxRuns}-prompt tutorial cap.`\n : `Want to keep exploring? Select a follow-up prompt.`;\n\n return (\n <Box flexDirection=\"column\">\n <Text>{recap}</Text>\n <PickerMenu options={options} onSelect={onSelect} />\n </Box>\n );\n};\n\n// ── Goodbye phase ──────────────────────────────────────────────────────\n// Always shown before final dismissal. Reminds the user where MCP is\n// available and what to ask once they're back in their IDE.\n\ninterface GoodbyePhaseProps {\n installedClients: string[];\n role: string | null;\n integration: Integration | null;\n /** True if the user actually ran at least one prompt this session. */\n engaged: boolean;\n onClose: () => void;\n}\n\nconst GoodbyePhase = ({\n installedClients,\n role,\n integration,\n engaged,\n onClose,\n}: GoodbyePhaseProps) => {\n // Take 3 starter prompts from the role-tailored kit. These act as\n // \"next time you open your IDE, try this\" reminders.\n const kit = getRolePrompts(role, integration);\n const samples = kit.slice(0, 3);\n\n const headline = engaged\n ? 'Nice work. You can keep talking to PostHog anytime.'\n : \"You're all set — PostHog MCP is here when you're ready.\";\n\n const introLine =\n installedClients.length > 0 ? (\n <Text>\n MCP is set up in{' '}\n <Text bold color={Colors.primary}>\n {installedClients.join(', ')}\n </Text>\n . Open one and try a prompt like:\n </Text>\n ) : (\n <Text>\n Wherever you have MCP set up (Claude Code, Cursor, VS Code, Windsurf,\n Zed, etc.), open the agent and try a prompt like:\n </Text>\n );\n\n return (\n <Box flexDirection=\"column\">\n <Box marginBottom={1}>\n <Text bold color={Colors.accent}>\n {headline}\n </Text>\n </Box>\n\n <Box marginBottom={1}>{introLine}</Box>\n\n <Box marginBottom={1} flexDirection=\"column\">\n {samples.map((p, i) => (\n <Box key={i}>\n <Text color={Colors.primary}>{Icons.triangleSmallRight}</Text>\n <Text> </Text>\n <Text dimColor>{p.prompt}</Text>\n </Box>\n ))}\n </Box>\n\n <Box marginBottom={1}>\n <Text dimColor>\n Re-run this tutorial anytime with{' '}\n <Text bold>npx @posthog/wizard mcp tutorial</Text>.\n </Text>\n </Box>\n\n <PickerMenu\n options={[{ label: 'Close', value: 'close' }]}\n onSelect={() => onClose()}\n />\n </Box>\n );\n};\n","import { Box, Text } from 'ink';\n\ninterface AreaHeaderRowProps {\n area: string;\n resolved: number;\n total: number;\n}\n\n/** Sub-header row inside the scrollable body — one per area group. */\nexport const AreaHeaderRow = ({\n area,\n resolved,\n total,\n}: AreaHeaderRowProps) => (\n <Box flexShrink={0} marginTop={1}>\n <Text bold color=\"cyan\">\n {area}{' '}\n </Text>\n <Text dimColor>\n ({resolved}/{total})\n </Text>\n </Box>\n);\n","import { MAX_WIDTH } from '@ui/tui/primitives/ScreenContainer';\n\n/** Terminal rows used by chrome outside the viewer\n * (TitleBar, spacer, screen padding, status bar, tab bar). */\nexport const CHROME_ROWS = 10;\n\n/** Rows used by the viewer's own header / footer\n * (title, subtitle, top summary, spacer, column headers, divider,\n * scroll-up marker, scroll-down marker, legend, footer summary). */\nexport const VIEWER_CHROME_BASE = 10;\n\nexport const COL_AREA_WIDTH = 18;\nexport const COL_LABEL_MIN = 28;\nexport const COL_GAP = 2;\n\nexport interface ViewerLayout {\n cols: number;\n visibleHeight: number;\n viewerChrome: number;\n padding: number;\n statusWidth: number;\n areaWidth: number;\n labelWidth: number;\n colGap: number;\n dividerWidth: number;\n detailIndent: number;\n detailWidth: number;\n}\n\n/** ScreenContainer wraps content in paddingX={1} inside a width capped at\n * MAX_WIDTH, so the actual width available to the viewer is\n * min(cols, MAX_WIDTH) - 2. */\nfunction getViewerWidth(rawCols: number): number {\n return Math.min(MAX_WIDTH, rawCols) - 2;\n}\n\nexport function computeLayout(rawCols: number, termRows: number): ViewerLayout {\n const cols = getViewerWidth(rawCols);\n const padding = 2;\n const statusWidth = 2;\n\n // CHECK flexes to consume the rest of the row so long labels stay readable\n // instead of getting truncated.\n const fixedExceptLabel =\n padding + statusWidth + COL_GAP + COL_AREA_WIDTH + COL_GAP + COL_GAP;\n const labelWidth = Math.max(COL_LABEL_MIN, cols - fixedExceptLabel);\n\n const detailIndent = statusWidth + COL_GAP + COL_AREA_WIDTH + COL_GAP;\n\n const viewerChrome = VIEWER_CHROME_BASE;\n const visibleHeight = Math.max(5, termRows - CHROME_ROWS - viewerChrome);\n\n return {\n cols,\n visibleHeight,\n viewerChrome,\n padding,\n statusWidth,\n areaWidth: COL_AREA_WIDTH,\n labelWidth,\n colGap: COL_GAP,\n dividerWidth: Math.max(20, cols - padding),\n detailIndent,\n detailWidth: Math.max(20, cols - detailIndent - padding),\n };\n}\n\nexport function truncate(text: string, max: number): string {\n if (max <= 0) return '';\n if (text.length <= max) return text;\n return text.slice(0, Math.max(1, max - 1)) + '…';\n}\n","import { Box, Text } from 'ink';\nimport {\n AUDIT_SEVERITY_STYLE,\n type AuditCheck,\n} from '@lib/programs/audit/types';\nimport { truncate, type ViewerLayout } from './layout.js';\n\ninterface CheckRowProps {\n item: AuditCheck;\n layout: ViewerLayout;\n}\n\nexport const CheckRow = ({ item, layout }: CheckRowProps) => {\n const style = AUDIT_SEVERITY_STYLE[item.status];\n return (\n <Box flexShrink={0}>\n <Box width={layout.statusWidth + layout.colGap}>\n <Text color={style.color}>{style.glyph}</Text>\n </Box>\n <Box width={layout.areaWidth + layout.colGap}>\n <Text dimColor>{truncate(item.area, layout.areaWidth)}</Text>\n </Box>\n <Box width={layout.labelWidth + layout.colGap}>\n <Text\n bold={item.status !== 'pending'}\n dimColor={item.status === 'pending'}\n >\n {truncate(item.label, layout.labelWidth)}\n </Text>\n </Box>\n </Box>\n );\n};\n","import { Box, Text } from 'ink';\nimport type { AuditCheck } from '@lib/programs/audit/types';\nimport type { ViewerLayout } from './layout.js';\n\ninterface DetailRowProps {\n item: AuditCheck;\n layout: ViewerLayout;\n}\n\n/** Format a `details` string. If it parses as a JSON object, render it as\n * indented key: value lines (skipping huge nested arrays/objects which we\n * truncate). Otherwise return the original text. v3000 emits structured\n * JSON for several event-quality checks — a raw dump is unreadable. */\nfunction formatDetails(raw: string): string[] {\n const trimmed = raw.trim();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return [raw];\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n return [raw];\n }\n if (parsed === null || typeof parsed !== 'object') return [raw];\n const lines: string[] = [];\n const renderValue = (v: unknown): string => {\n if (v === null) return 'null';\n if (typeof v === 'string') return v;\n if (typeof v === 'number' || typeof v === 'boolean') return String(v);\n if (Array.isArray(v)) {\n if (v.length === 0) return '[]';\n const allPrimitive = v.every((e) => e === null || typeof e !== 'object');\n if (allPrimitive) return v.map(renderValue).join(', ');\n return `[${v.length} item${v.length === 1 ? '' : 's'}]`;\n }\n if (typeof v === 'object') {\n const keys = Object.keys(v);\n return `{${keys.length} field${keys.length === 1 ? '' : 's'}}`;\n }\n return String(v);\n };\n for (const [key, value] of Object.entries(parsed)) {\n lines.push(`${key}: ${renderValue(value)}`);\n }\n return lines.length > 0 ? lines : [raw];\n}\n\n/** Indented under the CHECK column; wrap continuation aligns with the prefix. */\nexport const DetailRow = ({ item, layout }: DetailRowProps) => {\n const detailLines = item.details ? formatDetails(item.details) : [];\n return (\n <Box flexShrink={0}>\n <Box width={layout.detailIndent} />\n <Box flexDirection=\"column\" width={layout.detailWidth}>\n {item.file && (\n <Text dimColor wrap=\"wrap\">\n {`↳ File: ${item.file}`}\n </Text>\n )}\n {detailLines.map((line, i) => (\n <Text key={i} dimColor italic wrap=\"wrap\">\n {i === 0 ? `${item.file ? ' ' : '↳ '}${line}` : ` ${line}`}\n </Text>\n ))}\n </Box>\n </Box>\n );\n};\n","import { Text } from 'ink';\n\nexport const Legend = () => (\n <Text>\n <Text color=\"green\">✔ pass</Text>\n <Text dimColor>{' · '}</Text>\n <Text color=\"red\">✘ error</Text>\n <Text dimColor>{' · '}</Text>\n <Text color=\"yellow\">⚠ warning</Text>\n <Text dimColor>{' · '}</Text>\n <Text color=\"cyan\">• suggestion</Text>\n </Text>\n);\n","import { Box, Text } from 'ink';\nimport type { AuditCheck, AuditStatus } from '@lib/programs/audit/types';\nimport type { ViewerLayout } from './layout.js';\n\ninterface HeaderProps {\n layout: ViewerLayout;\n}\n\ninterface SummaryProps {\n total: number;\n counts: Record<AuditStatus, number>;\n}\n\nfunction statusCounts(checks: AuditCheck[]): Record<AuditStatus, number> {\n const out: Record<AuditStatus, number> = {\n pending: 0,\n pass: 0,\n error: 0,\n warning: 0,\n suggestion: 0,\n };\n for (const c of checks) out[c.status] += 1;\n return out;\n}\n\nexport { statusCounts };\n\nexport const Header = ({ layout }: HeaderProps) => (\n <Box>\n <Box width={layout.statusWidth + layout.colGap}>\n <Text dimColor bold>\n {' '}\n </Text>\n </Box>\n <Box width={layout.areaWidth + layout.colGap}>\n <Text dimColor bold>\n AREA\n </Text>\n </Box>\n <Box width={layout.labelWidth + layout.colGap}>\n <Text dimColor bold>\n CHECK\n </Text>\n </Box>\n </Box>\n);\n\nexport const Summary = ({ total, counts }: SummaryProps) => (\n <Text dimColor>\n {total} total · {counts.pending} pending · {counts.error} errors ·{' '}\n {counts.warning} warnings · {counts.suggestion} suggestions · {counts.pass}{' '}\n passes\n </Text>\n);\n","import { Legend } from './Legend.js';\nimport { Summary } from './Header.js';\nimport type { AuditStatus } from '@lib/programs/audit/types';\n\ninterface FooterProps {\n total: number;\n counts: Record<AuditStatus, number>;\n}\n\nexport const Footer = ({ total, counts }: FooterProps) => (\n <>\n <Legend />\n <Summary total={total} counts={counts} />\n </>\n);\n","import type { AuditCheck, AuditStatus } from '@lib/programs/audit/types';\n\nconst STATUS_ORDER: Record<AuditStatus, number> = {\n error: 0,\n warning: 1,\n suggestion: 2,\n pass: 3,\n pending: 4,\n};\n\n/** Audit areas in the order they should be displayed. Areas not listed\n * here fall through to alphabetical order at the end. Mirrors the\n * Full audit section grouping in the generated report. */\nconst AREA_ORDER: string[] = [\n 'Installation',\n 'Identification',\n 'Event Capture',\n 'Event Quality',\n 'Feature Flags',\n 'Session Replay',\n 'Session Replay — Optimize',\n 'Use Case: Expansion',\n 'Additional Sections',\n];\n\nfunction areaRank(area: string): number {\n const idx = AREA_ORDER.indexOf(area);\n return idx === -1 ? AREA_ORDER.length : idx;\n}\n\n/** Issues at the top (error → warning → suggestion), then passes, then pending todos. */\nexport function sortChecks(checks: ReadonlyArray<AuditCheck>): AuditCheck[] {\n return [...checks].sort((a, b) => {\n const da = STATUS_ORDER[a.status] - STATUS_ORDER[b.status];\n if (da !== 0) return da;\n return a.area.localeCompare(b.area);\n });\n}\n\nexport interface AreaGroup {\n area: string;\n checks: AuditCheck[];\n counts: { total: number; resolved: number };\n}\n\n/** Group checks by area, in AREA_ORDER. Within each area, sort by status. */\nexport function groupChecksByArea(\n checks: ReadonlyArray<AuditCheck>,\n): AreaGroup[] {\n const byArea = new Map<string, AuditCheck[]>();\n for (const c of checks) {\n const list = byArea.get(c.area);\n if (list) list.push(c);\n else byArea.set(c.area, [c]);\n }\n const groups: AreaGroup[] = [];\n for (const [area, areaChecks] of byArea) {\n const sorted = [...areaChecks].sort(\n (a, b) => STATUS_ORDER[a.status] - STATUS_ORDER[b.status],\n );\n const resolved = sorted.filter((c) => c.status !== 'pending').length;\n groups.push({\n area,\n checks: sorted,\n counts: { total: sorted.length, resolved },\n });\n }\n groups.sort((a, b) => {\n const dr = areaRank(a.area) - areaRank(b.area);\n if (dr !== 0) return dr;\n return a.area.localeCompare(b.area);\n });\n return groups;\n}\n","/**\n * AuditChecksViewer — \"Audit plan\" tab.\n *\n * Renders the full audit ledger as a scrollable, area-grouped list that\n * mirrors the structure of the final report. Each area gets a sub-header\n * with a resolved/total count; checks within an area are sorted by\n * severity (error → warning → suggestion → pass → pending).\n *\n * Two interactions, both registered via `useKeyBindings`:\n * - `e` — toggle detail rows (file:line + agent's `details` text)\n * - `↑` / `↓` — scroll one row at a time, clamped to content bounds\n *\n * Auto-expands on first mount when the ledger contains any issue, since\n * the AuditAreaPane's `[→] View issues` hint sends users here precisely\n * to read those details.\n */\n\nimport { Box, Text } from 'ink';\nimport { Fragment, useMemo, useState, type ReactNode } from 'react';\nimport { useStdoutDimensions } from '@ui/tui/hooks/useStdoutDimensions';\nimport {\n KeyMatch,\n useKeyBindings,\n type KeyBinding,\n} from '@ui/tui/hooks/useKeyBindings';\nimport type { AuditCheck } from '@lib/programs/audit/types';\nimport { AreaHeaderRow } from './AreaHeaderRow.js';\nimport { CheckRow } from './CheckRow.js';\nimport { DetailRow } from './DetailRow.js';\nimport { Footer } from './Footer.js';\nimport { Header, Summary, statusCounts } from './Header.js';\nimport { computeLayout } from './layout.js';\nimport { groupChecksByArea } from './sort.js';\n\ninterface AuditChecksViewerProps {\n checks: AuditCheck[];\n}\n\nexport const AuditChecksViewer = ({ checks }: AuditChecksViewerProps) => {\n // ── Layout ─────────────────────────────────────────────────────────\n const [rawCols, termRows] = useStdoutDimensions();\n const layout = computeLayout(rawCols, termRows);\n const totalHeight = layout.visibleHeight + layout.viewerChrome;\n\n // ── Group by area ──────────────────────────────────────────────────\n const groups = useMemo(() => groupChecksByArea(checks), [checks]);\n const counts = useMemo(() => statusCounts(checks), [checks]);\n\n // ── Expand state ───────────────────────────────────────────────────\n const hasExpandable = checks.some((c) => Boolean(c.details || c.file));\n const hasIssues = checks.some(\n (c) =>\n c.status === 'error' ||\n c.status === 'warning' ||\n c.status === 'suggestion',\n );\n const [expanded, setExpanded] = useState(hasIssues && hasExpandable);\n\n // ── Flat row list ──────────────────────────────────────────────────\n // One ReactNode per visible terminal row so scroll math stays simple.\n // Sub-header + check rows + (optional) detail rows interleave here.\n const allRows = useMemo<ReactNode[]>(() => {\n const rows: ReactNode[] = [];\n for (const group of groups) {\n rows.push(\n <AreaHeaderRow\n key={`header-${group.area}`}\n area={group.area}\n resolved={group.counts.resolved}\n total={group.counts.total}\n />,\n );\n for (const item of group.checks) {\n rows.push(<CheckRow key={item.id} item={item} layout={layout} />);\n if (expanded && (item.details || item.file)) {\n rows.push(\n <DetailRow key={`${item.id}-detail`} item={item} layout={layout} />,\n );\n }\n }\n }\n return rows;\n }, [groups, expanded, layout]);\n\n // ── Scroll viewport ────────────────────────────────────────────────\n const [offset, setOffset] = useState(0);\n const maxOffset = Math.max(0, allRows.length - layout.visibleHeight);\n const clampedOffset = Math.min(offset, maxOffset);\n const hiddenAbove = clampedOffset;\n const hiddenBelow = Math.max(\n 0,\n allRows.length - clampedOffset - layout.visibleHeight,\n );\n\n // ── Key bindings ───────────────────────────────────────────────────\n const bindings: KeyBinding[] = [];\n if (hasExpandable) {\n bindings.push({\n match: 'e',\n label: 'e',\n action: expanded ? 'collapse details' : 'expand details',\n handler: () => setExpanded((prev) => !prev),\n });\n }\n bindings.push({\n match: [KeyMatch.UpArrow, KeyMatch.DownArrow],\n label: '↑↓',\n action: 'scroll',\n handler: (_input, key) => {\n if (key.upArrow) setOffset((o) => Math.max(0, o - 1));\n else if (key.downArrow) setOffset((o) => Math.min(maxOffset, o + 1));\n },\n });\n useKeyBindings('audit-checks-viewer', bindings);\n\n // ── Render ─────────────────────────────────────────────────────────\n const visibleRows = allRows.slice(\n clampedOffset,\n clampedOffset + layout.visibleHeight,\n );\n\n // Dynamic subtitle — lists the actual areas in the ledger.\n const subtitle =\n groups.length === 0\n ? 'No checks yet.'\n : `Review across ${groups.length} ${\n groups.length === 1 ? 'area' : 'areas'\n } — mirrors the final report.`;\n\n return (\n <Box flexDirection=\"column\" paddingX={1} height={totalHeight}>\n {/* Title + dynamic subtitle */}\n <Text bold>Audit plan</Text>\n <Text dimColor>{subtitle}</Text>\n\n {/* Top summary — same as Footer summary, promoted here for at-a-glance */}\n <Summary total={checks.length} counts={counts} />\n <Box height={1} />\n\n {/* Column headers + divider */}\n <Header layout={layout} />\n <Text dimColor>{'─'.repeat(layout.dividerWidth)}</Text>\n\n {/* Scroll-up marker */}\n <Text dimColor>{hiddenAbove > 0 ? `↑ ${hiddenAbove} more` : ' '}</Text>\n\n {/* Scrollable body */}\n <Box\n flexDirection=\"column\"\n height={layout.visibleHeight}\n overflow=\"hidden\"\n >\n {visibleRows.map((node, i) => (\n <Fragment key={`row-${clampedOffset + i}`}>{node}</Fragment>\n ))}\n </Box>\n\n {/* Scroll-down marker */}\n <Text dimColor>{hiddenBelow > 0 ? `↓ ${hiddenBelow} more` : ' '}</Text>\n\n {/* Legend (counts already shown at the top) */}\n <Footer total={checks.length} counts={counts} />\n </Box>\n );\n};\n","import { Box } from 'ink';\nimport type { ReactNode } from 'react';\nimport { Colors } from '@ui/tui/styles';\n\n/** Slide shape consumed by `AuditAreaPane`. One per `AuditCheck.area` value. */\nexport interface AreaSlide {\n area: string;\n /** One element per paragraph — rendered as separate `<Text>` blocks. */\n intro: string[];\n visual?: ReactNode;\n docsUrl: string;\n}\n\n/** Narrow bordered box for the small ASCII illustrations in baseline slides. */\nexport const VisualBox = ({ children }: { children: ReactNode }) => (\n <Box\n borderStyle=\"single\"\n borderColor={Colors.muted}\n paddingX={1}\n flexDirection=\"column\"\n marginBottom={1}\n >\n {children}\n </Box>\n);\n","import { Text } from 'ink';\nimport { VisualBox, type AreaSlide } from './shared.js';\n\nconst InstallationVisual = () => (\n <VisualBox>\n <Text dimColor>app boot</Text>\n <Text>\n <Text dimColor>{' ▼ '}</Text>\n <Text color=\"green\">posthog.init(...)</Text>\n <Text dimColor>{' once'}</Text>\n </Text>\n <Text dimColor>{' │'}</Text>\n <Text>\n <Text dimColor>{' ▼ '}</Text>\n <Text color=\"cyan\">posthog.capture('pageview')</Text>\n </Text>\n <Text>\n <Text dimColor>{' '}</Text>\n <Text color=\"cyan\">posthog.capture('signup')</Text>\n </Text>\n <Text>\n <Text dimColor>{' '}</Text>\n <Text color=\"cyan\">posthog.capture('purchase')</Text>\n </Text>\n </VisualBox>\n);\n\nexport const InstallationSlide: AreaSlide = {\n area: 'Installation',\n intro: [\n \"PostHog releases frequent SDK updates to fix bugs and add new features. We're checking your project's SDK version and making sure it's up to date.\",\n \"We're also checking that your SDK is initialized correctly and in the right part of your app's lifecycle.\",\n \"This ensures you won't miss any autocaptured events.\",\n ],\n visual: <InstallationVisual />,\n docsUrl: 'https://posthog.com/docs/getting-started/install',\n};\n","import { Text } from 'ink';\nimport { VisualBox, type AreaSlide } from './shared.js';\n\nconst IdentificationVisual = () => (\n <VisualBox>\n <Text>\n <Text bold>{'browser '}</Text>\n <Text dimColor>capture</Text>\n <Text>{' ('}</Text>\n <Text color=\"cyan\">u_42</Text>\n <Text>{', \"click\")'}</Text>\n </Text>\n <Text dimColor>{' │'}</Text>\n <Text>\n <Text dimColor>{' ▼ '}</Text>\n <Text color=\"green\">same distinct_id</Text>\n </Text>\n <Text dimColor>{' │'}</Text>\n <Text>\n <Text bold>{'server '}</Text>\n <Text dimColor>capture</Text>\n <Text>{' ('}</Text>\n <Text color=\"cyan\">u_42</Text>\n <Text>{', \"charged\")'}</Text>\n </Text>\n </VisualBox>\n);\n\nexport const IdentificationSlide: AreaSlide = {\n area: 'Identification',\n intro: [\n 'For events to be useful, they need to be reliably attributed to a user.',\n \"We're checking your project's `identify()` calls to make sure they're correctly and consistently implemented.\",\n \"We're also checking that your `distinct_id`s are correctly passed between your client and server runtimes if applicable.\",\n ],\n visual: <IdentificationVisual />,\n docsUrl: 'https://posthog.com/docs/product-analytics/identify',\n};\n","import { Text } from 'ink';\nimport { VisualBox, type AreaSlide } from './shared.js';\n\nconst CaptureVisual = () => (\n <VisualBox>\n <Text>\n <Text color=\"cyan\">{'pageview '}</Text>\n <Text color=\"green\">{'████████████'}</Text>\n <Text dimColor>{' 1000'}</Text>\n </Text>\n <Text>\n <Text color=\"cyan\">{'signup '}</Text>\n <Text color=\"green\">{'████████'}</Text>\n <Text dimColor>{' 640'}</Text>\n </Text>\n <Text>\n <Text color=\"cyan\">{'activated '}</Text>\n <Text color=\"green\">{'█████'}</Text>\n <Text dimColor>{' 410'}</Text>\n </Text>\n <Text>\n <Text color=\"cyan\">{'purchased '}</Text>\n <Text color=\"green\">{'██'}</Text>\n <Text dimColor>{' 120'}</Text>\n </Text>\n </VisualBox>\n);\n\nexport const EventCaptureSlide: AreaSlide = {\n area: 'Event Capture',\n intro: [\n 'Everything you do in PostHog starts with event captures. Every dashboard, insight, funnel, cohort, and replay is built on top of events.',\n \"We're checking that your project's event capture calls cover key user actions and use sensible event names, so you can build high-quality insights and reports.\",\n \"We're also checking that you use a reverse proxy so your events are not blocked by ad blockers or tracking blockers.\",\n ],\n visual: <CaptureVisual />,\n docsUrl: 'https://posthog.com/docs/product-analytics/capture-events',\n};\n","import { Text } from 'ink';\nimport { VisualBox, type AreaSlide } from './shared.js';\n\nconst ReportVisual = () => (\n <VisualBox>\n <Text dimColor>posthog-audit-report.md</Text>\n <Text>\n <Text dimColor>{' # '}</Text>\n <Text>Summary</Text>\n </Text>\n <Text>\n <Text dimColor>{' # '}</Text>\n <Text>Recommended actions</Text>\n </Text>\n <Text>\n <Text dimColor>{' # '}</Text>\n <Text>Full audit</Text>\n </Text>\n </VisualBox>\n);\n\nexport const WriteReportSlide: AreaSlide = {\n area: 'Write report',\n intro: [\n 'Now we write an audit report at ./posthog-audit-report.md. that summarizes our findings.',\n 'The report leads with a summary, then a prioritized list of fixes with file:line citations, then every check we ran grouped by area so nothing is hidden.',\n 'We will upload the report into a PostHog notebook in the next step.',\n ],\n visual: <ReportVisual />,\n docsUrl: 'https://posthog.com/docs/product-analytics/best-practices',\n};\n","import { Text } from 'ink';\nimport { VisualBox, type AreaSlide } from './shared.js';\n\nconst NotebookVisual = () => (\n <VisualBox>\n <Text dimColor>posthog-audit-report.md</Text>\n <Text dimColor>{' │'}</Text>\n <Text>\n <Text dimColor>{' ▼ '}</Text>\n <Text color=\"cyan\">PostHog notebook</Text>\n </Text>\n <Text dimColor>{' # Summary'}</Text>\n <Text dimColor>{' # Recommended actions'}</Text>\n <Text dimColor>{' # Full audit'}</Text>\n </VisualBox>\n);\n\nexport const UploadNotebookSlide: AreaSlide = {\n area: 'Upload notebook',\n intro: [\n 'Next we upload the report into a PostHog notebook so you can share it with your team as a URL.',\n 'Hang tight.',\n 'The markdown file on disk is still there for you to read locally.',\n ],\n visual: <NotebookVisual />,\n docsUrl: 'https://posthog.com/docs/notebooks',\n};\n","/**\n * Slide registry for `AuditAreaPane`. Each entry is a stand-alone module\n * keyed by `AuditCheck.area`. To add a new area, drop a `<area>.tsx` file\n * exporting an `AreaSlide` and append it here.\n */\n\nimport type { AreaSlide } from './shared.js';\nimport { InstallationSlide } from './installation.js';\nimport { IdentificationSlide } from './identification.js';\nimport { EventCaptureSlide } from './eventCapture.js';\nimport { WriteReportSlide } from './writeReport.js';\nimport { UploadNotebookSlide } from './uploadNotebook.js';\n\nexport type { AreaSlide };\n\nexport const AUDIT_AREA_SLIDES: AreaSlide[] = [\n InstallationSlide,\n IdentificationSlide,\n EventCaptureSlide,\n WriteReportSlide,\n UploadNotebookSlide,\n];\n","import { Text } from 'ink';\nimport { VisualBox, type AreaSlide } from '@ui/tui/screens/audit/slides/shared';\n\nconst EventQualityVisual = () => (\n <VisualBox>\n <Text>\n <Text color=\"green\">{'event_clicked '}</Text>\n <Text color=\"green\">{'\\u2713'}</Text>\n </Text>\n <Text>\n <Text color=\"yellow\">{'eventClicked '}</Text>\n <Text color=\"yellow\">{'~ duplicate?'}</Text>\n </Text>\n <Text>\n <Text color=\"yellow\">{'click_event '}</Text>\n <Text color=\"yellow\">{'~ duplicate?'}</Text>\n </Text>\n <Text>\n <Text color=\"red\">{'big_kitchen_sink '}</Text>\n <Text color=\"red\">{'\\u2717 22 props'}</Text>\n </Text>\n </VisualBox>\n);\n\nexport const EventQualitySlide: AreaSlide = {\n area: 'Event Quality',\n intro: [\n 'LEVEL 5: EVENT QUALITY. The capture call-sites are clean. The events themselves are the real boss fight.',\n 'Scanning for: naming inconsistencies, semantic duplicates, kitchen-sink event payloads, and (if your PostHog project is linked) which captured events actually drive insights and dashboards.',\n '4 subagents fan out in parallel. The ticker shows them clearing checks live.',\n ],\n visual: <EventQualityVisual />,\n docsUrl: 'https://posthog.com/docs/product-analytics/best-practices',\n};\n","import { Text } from 'ink';\nimport { VisualBox, type AreaSlide } from '@ui/tui/screens/audit/slides/shared';\n\nconst FeatureFlagsVisual = () => (\n <VisualBox>\n <Text>\n <Text color=\"red\">{'new-checkout-v2 '}</Text>\n <Text dimColor>{'no code refs '}</Text>\n <Text color=\"red\">{'DROP'}</Text>\n </Text>\n <Text>\n <Text color=\"yellow\">{'beta-dashboard '}</Text>\n <Text dimColor>{'1 ref, 100% on '}</Text>\n <Text color=\"yellow\">{'REVIEW'}</Text>\n </Text>\n <Text>\n <Text color=\"green\">{'killswitch-payments'}</Text>\n <Text dimColor>{'live experiment'}</Text>\n <Text color=\"green\">{'KEEP'}</Text>\n </Text>\n </VisualBox>\n);\n\nexport const FeatureFlagsSlide: AreaSlide = {\n area: 'Feature Flags',\n intro: [\n 'LEVEL 6: STALE FLAGS. Old flags add evaluation overhead and confuse the next engineer who wonders if a flag is still live.',\n \"Cross-referencing PostHog's stale-flag classification against your source tree. Each flag scored: safe-to-disable, needs-review, or unknown.\",\n 'The final report ships with a copy-paste cleanup prompt. We never touch a flag.',\n ],\n visual: <FeatureFlagsVisual />,\n docsUrl: 'https://posthog.com/docs/feature-flags',\n};\n","import { Text } from 'ink';\nimport { VisualBox, type AreaSlide } from '@ui/tui/screens/audit/slides/shared';\n\nconst ExpansionVisual = () => (\n <VisualBox>\n <Text>\n <Text color=\"cyan\">{'product analytics '}</Text>\n <Text color=\"green\">{'\\u25A0\\u25A0\\u25A0\\u25A0\\u25A0'}</Text>\n </Text>\n <Text>\n <Text color=\"cyan\">{'error tracking '}</Text>\n <Text color=\"red\">{'\\u25A1\\u25A1\\u25A1\\u25A1\\u25A1'}</Text>\n <Text dimColor>{' sentry detected'}</Text>\n </Text>\n <Text>\n <Text color=\"cyan\">{'session replay '}</Text>\n <Text color=\"yellow\">{'\\u25A0\\u25A0\\u25A1\\u25A1\\u25A1'}</Text>\n <Text dimColor>{' partial'}</Text>\n </Text>\n <Text>\n <Text color=\"cyan\">{'llm observability '}</Text>\n <Text color=\"red\">{'\\u25A1\\u25A1\\u25A1\\u25A1\\u25A1'}</Text>\n <Text dimColor>{' greenfield'}</Text>\n </Text>\n </VisualBox>\n);\n\nexport const ExpansionSlide: AreaSlide = {\n area: 'Use Case: Expansion',\n intro: [\n 'BONUS ROUND: EXPANSION. You might be paying for tools PostHog covers natively.',\n 'Scanning for competitive SDKs (Sentry, LaunchDarkly, Mixpanel, Datadog, OpenTelemetry, GA4) and PostHog coverage gaps across 8 product surfaces.',\n '8 subagents in two waves of 4. Each one returns one of: cross-sell, greenfield, gap, or pass.',\n ],\n visual: <ExpansionVisual />,\n docsUrl: 'https://posthog.com/docs',\n};\n","/**\n * Audit-3000 slide registry. Re-uses the original audit slides for the\n * shared areas (Installation, Identification, Event Capture) and adds\n * arcade-flavoured slides for the three new areas the v3000 audit covers.\n */\n\nimport type { AreaSlide } from '@ui/tui/screens/audit/slides/shared';\nimport { InstallationSlide } from '@ui/tui/screens/audit/slides/installation';\nimport { IdentificationSlide } from '@ui/tui/screens/audit/slides/identification';\nimport { EventCaptureSlide } from '@ui/tui/screens/audit/slides/eventCapture';\nimport { EventQualitySlide } from './eventQuality.js';\nimport { FeatureFlagsSlide } from './featureFlags.js';\nimport { ExpansionSlide } from './expansion.js';\n\nexport type { AreaSlide };\n\nexport const AUDIT_3000_AREA_SLIDES: AreaSlide[] = [\n InstallationSlide,\n IdentificationSlide,\n EventCaptureSlide,\n EventQualitySlide,\n FeatureFlagsSlide,\n ExpansionSlide,\n];\n","/**\n * SlackConnectScreen — the dedicated \"Connect Slack\" step shown after the\n * MCP tutorial (`wizard mcp tutorial`) and after a successful install\n * (`wizard mcp add`).\n *\n * Presents the PostHog Slack app plus role-tailored use-cases. The copy\n * adapts to whether Slack is already connected (polled while the screen\n * is up, held as local state):\n * • not connected (or unknown) — nudge + \"Open Slack setup\", which\n * launches the browser at the integration settings page and keeps\n * the screen alive; the poll flips it to connected once the user\n * finishes the manual OAuth step in the browser.\n * • already connected — confirm it and skip the connect CTA, so users\n * who already have it aren't nagged.\n * \"Skip\" / \"Done\" / esc dismiss the step (`slackStepDismissed`) and let\n * the router advance to exit.\n */\n\nimport { Box, Text } from 'ink';\nimport { useEffect, useSyncExternalStore } from 'react';\nimport opn from 'opn';\n\nimport type { WizardStore } from '@ui/tui/store';\nimport { Colors, Icons } from '@ui/tui/styles';\nimport { PickerMenu } from '@ui/tui/primitives/index';\nimport { useKeyBindings, KeyMatch } from '@ui/tui/hooks/useKeyBindings';\nimport { getSlackAppCard } from '@lib/mcp-role-prompts';\nimport { fetchSlackConnected } from '@lib/api';\nimport { analytics } from '@utils/analytics';\n\ninterface SlackConnectScreenProps {\n store: WizardStore;\n}\n\nenum ChoiceValue {\n Open = 'open',\n Skip = 'skip',\n}\n\nconst POLL_INTERVAL_MS = 3000;\n\nexport const SlackConnectScreen = ({ store }: SlackConnectScreenProps) => {\n useSyncExternalStore(\n (cb) => store.subscribe(cb),\n () => store.getSnapshot(),\n );\n\n const role = store.session.roleAtOrganization;\n const slack = getSlackAppCard();\n\n // Impression — once per mount, not per render.\n useEffect(() => {\n analytics.wizardCapture('slack connect shown', { role });\n }, []);\n\n // Seeded by the tutorial screen's prefetch (session.slackConnected),\n // so the first render already shows the right variant. While not\n // connected, poll: connecting Slack is a manual OAuth step in the\n // browser, so the poll is what flips the screen to the connected\n // state when the user comes back. Without credentials (user skipped\n // login) it renders the connect nudge.\n const connected = store.session.slackConnected === true;\n const credentials = store.session.credentials;\n useEffect(() => {\n if (!credentials || connected) return;\n let cancelled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const controller = new AbortController();\n const check = (): void => {\n fetchSlackConnected(\n credentials.accessToken,\n credentials.projectId,\n credentials.host,\n controller.signal,\n )\n .then((isConnected) => {\n if (cancelled) return;\n if (isConnected) {\n store.setSlackConnected(true);\n } else {\n timer = setTimeout(check, POLL_INTERVAL_MS);\n }\n })\n .catch((err: unknown) => {\n if (cancelled) return;\n // Capture once and stop polling — repeating a failing call\n // every tick would spam error tracking. The nudge copy is\n // the fallback either way.\n analytics.captureException(\n err instanceof Error ? err : new Error(String(err)),\n { step: 'slack_connected_check' },\n );\n });\n };\n check();\n return () => {\n // Tear down fully on exit: no new ticks (cancelled), no pending\n // tick (clearTimeout), no in-flight request (abort).\n cancelled = true;\n if (timer) clearTimeout(timer);\n controller.abort();\n };\n }, [credentials, connected, store]);\n\n const dismiss = (): void => {\n analytics.wizardCapture('slack connect skipped', { role, connected });\n store.setSlackStepDismissed();\n };\n\n const handleSelect = (value: ChoiceValue | ChoiceValue[]): void => {\n const choice = Array.isArray(value) ? value[0] : value;\n if (choice === ChoiceValue.Open) {\n analytics.wizardCapture('slack connect opened', { role });\n // Fire-and-forget. opn throws in environments without a browser\n // (headless/remote) — the setup URL is printed on screen as a\n // fallback, so swallow the error. The screen stays up; the poll\n // flips it to connected once the OAuth step completes.\n if (process.env.NODE_ENV !== 'test') {\n opn(slack.setupUrl, { wait: false }).catch(() => {\n // No browser available — the printed URL is the fallback.\n });\n }\n return;\n }\n dismiss();\n };\n\n useKeyBindings('slack-connect', [\n {\n match: KeyMatch.Escape,\n label: 'esc',\n action: connected ? 'done' : 'skip',\n handler: () => dismiss(),\n },\n ]);\n\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n <Box marginTop={1} flexDirection=\"column\">\n {connected ? (\n <Text bold color={Colors.success}>\n {Icons.check} Slack connected\n </Text>\n ) : (\n <Text bold color={Colors.accent}>\n {slack.headline}\n </Text>\n )}\n\n <Box marginTop={1}>\n <Text>\n {connected\n ? \"Slack is connected — here's what you can do:\"\n : slack.pitch}\n </Text>\n </Box>\n\n <Box marginTop={1} flexDirection=\"column\">\n {slack.capabilities.map((capability, i) => (\n // Marker + copy in one <Text> so the (long) line wraps as a\n // single flow — separate row-Box siblings drop the marker on\n // wrapped bullets.\n <Box key={i} marginTop={i === 0 ? 0 : 1}>\n <Text>\n <Text color=\"cyan\">{Icons.diamond} </Text>\n {capability}\n </Text>\n </Box>\n ))}\n </Box>\n\n <Box marginTop={1} flexDirection=\"column\">\n {!connected && (\n <Text dimColor>\n Connect it: <Text color=\"cyan\">{slack.setupUrl}</Text>\n </Text>\n )}\n <Text dimColor>\n Learn more: <Text color=\"cyan\">{slack.learnMoreUrl}</Text>\n </Text>\n </Box>\n\n <Box marginTop={1}>\n <PickerMenu\n options={\n connected\n ? [{ label: 'Done', value: ChoiceValue.Skip }]\n : [\n { label: 'Open Slack setup', value: ChoiceValue.Open },\n { label: 'Skip', value: ChoiceValue.Skip },\n ]\n }\n onSelect={handleSelect}\n />\n </Box>\n </Box>\n </Box>\n );\n};\n","/**\n * OutroScreen — Default post-run summary.\n *\n * Renders the success / error / cancel views from `outroData`. Programs\n * that need a different success view (e.g. with extra summary content)\n * ship their own screen component (see audit/AuditOutroScreen.tsx).\n */\n\nimport { Box, Text, useInput } from 'ink';\nimport { useSyncExternalStore } from 'react';\nimport type { WizardStore } from '@ui/tui/store';\nimport { OutroKind } from '@lib/wizard-session';\nimport { Colors } from '@ui/tui/styles';\n\ninterface OutroScreenProps {\n store: WizardStore;\n}\n\nexport const OutroScreen = ({ store }: OutroScreenProps) => {\n useSyncExternalStore(\n (cb) => store.subscribe(cb),\n () => store.getSnapshot(),\n );\n\n useInput(() => {\n store.setOutroDismissed();\n });\n\n const outroData = store.session.outroData;\n\n if (!outroData) {\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n <Text dimColor>Finishing up...</Text>\n </Box>\n );\n }\n\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n {outroData.kind === OutroKind.Success && (\n <Box flexDirection=\"column\">\n <Text color=\"green\" bold>\n ✔ {outroData.message || 'Done!'}\n </Text>\n\n {outroData.body && (\n <Box marginTop={1}>\n <Text dimColor>{outroData.body}</Text>\n </Box>\n )}\n\n {outroData.reportFile && (\n <Box marginTop={1}>\n <Text>\n Check <Text bold>./{outroData.reportFile}</Text> for details\n </Text>\n </Box>\n )}\n\n {outroData.changes && outroData.changes.length > 0 && (\n <Box flexDirection=\"column\" marginTop={1}>\n <Text color=\"cyan\" bold>\n What the agent did:\n </Text>\n {outroData.changes.map((change, i) => (\n <Text key={i}>• {change}</Text>\n ))}\n </Box>\n )}\n\n {store.eventPlan.length > 0 && (\n <Box flexDirection=\"column\" marginTop={1}>\n <Text color=\"cyan\" bold>\n Events added:\n </Text>\n {store.eventPlan.map((event) => (\n <Text key={event.name}>\n • <Text bold>{event.name}</Text>\n <Text dimColor> {event.description}</Text>\n </Text>\n ))}\n </Box>\n )}\n\n {outroData.dashboardUrl && (\n <Box marginTop={1}>\n <Text>\n We've also made you a dashboard:{' '}\n <Text color=\"cyan\">{outroData.dashboardUrl}</Text>\n </Text>\n </Box>\n )}\n\n {outroData.notebookUrl && (\n <Box marginTop={1}>\n <Text>\n And uploaded the report to a PostHog notebook:{' '}\n <Text color=\"cyan\">{outroData.notebookUrl}</Text>\n </Text>\n </Box>\n )}\n\n {outroData.docsUrl && (\n <Box marginTop={1}>\n <Text>\n Learn more: <Text color=\"cyan\">{outroData.docsUrl}</Text>\n </Text>\n </Box>\n )}\n\n {outroData.continueUrl && (\n <Box>\n <Text>\n Continue onboarding:{' '}\n <Text color=\"cyan\">{outroData.continueUrl}</Text>\n </Text>\n </Box>\n )}\n\n <Box marginTop={1}>\n <Text dimColor>\n Note: This wizard uses an LLM agent to analyze and modify your\n project. Please review the changes made.\n </Text>\n </Box>\n <Text dimColor>\n How did this work for you? Drop us a line: wizard@posthog.com\n </Text>\n </Box>\n )}\n\n {outroData.kind === OutroKind.Error && (\n <Box flexDirection=\"column\">\n <Text color=\"red\" bold>\n ✘ {outroData.message || 'An error occurred'}\n </Text>\n\n {outroData.body && (\n <Box marginTop={1}>\n <Text dimColor>{outroData.body}</Text>\n </Box>\n )}\n\n {outroData.docsUrl && (\n <Box marginTop={1}>\n <Text>\n Docs: <Text color=\"cyan\">{outroData.docsUrl}</Text>\n </Text>\n </Box>\n )}\n </Box>\n )}\n\n {outroData.kind === OutroKind.Cancel && (\n <Box flexDirection=\"column\">\n <Text color=\"yellow\">■ {outroData.message || 'Cancelled'}</Text>\n </Box>\n )}\n\n <Box marginTop={1}>\n <Text color={Colors.muted}>Press any key to continue</Text>\n </Box>\n </Box>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoMA,SAAgB,sBAAsB,OAInC;CACD,MAAM,UAAU,MACb,QAAQ,SAAS,KAAK,YAAY,KAAK,CACvC,KAAK,UAAU;EACd,IAAI,KAAK;EACT,MAAM,KAAK;EAIX,YAAY,KAAK,cAAc,KAAK;EACrC,EAAE;AAGL,SAAQ,KAAK;EAAE,IAAI;EAAQ,MAAM,KAAA;EAAW,YAAY,KAAA;EAAW,CAAC;AAEpE,QAAO;;;;;AC7JT,MAAa,oBACX,OAAO,YACL,iBAAiB,KA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