diff --git a/src/__tests__/architecture/known-violations.json b/src/__tests__/architecture/known-violations.json index 13cfc727c..fec4b10c8 100644 --- a/src/__tests__/architecture/known-violations.json +++ b/src/__tests__/architecture/known-violations.json @@ -116,6 +116,7 @@ "src/programs/task-stream/task-stream-push.ts -> src/ui/wizard-ui.ts", "src/programs/task-stream/types.ts -> src/lib/wizard-session.ts", "src/programs/task-stream/wizard-run-sync.ts -> src/lib/wizard-session.ts", + "src/programs/warehouse-scan-reporting.ts -> src/lib/wizard-session.ts", "src/programs/warehouse-source/detect.ts -> src/lib/wizard-session.ts", "src/programs/warehouse-source/index.ts -> src/lib/wizard-session.ts", "src/programs/warehouse-source/index.ts -> src/ui/tui/decks/warehouse-source/index.tsx", @@ -165,7 +166,6 @@ "src/ui/tui/screens/doctor/IssueTable.tsx -> src/programs/posthog-doctor/index.ts", "src/ui/tui/screens/health/HealthCheckScreen.tsx -> src/agent/index.ts", "src/ui/tui/services/mcp-suggested-prompts-services.ts -> src/agent/index.ts", - "src/ui/tui/store.ts -> src/programs/ai-opt-in-gate.ts", - "src/ui/tui/store.ts -> src/programs/posthog-integration/detect.ts" + "src/ui/tui/store.ts -> src/programs/ai-opt-in-gate.ts" ] } diff --git a/src/lib/runners/run-non-interactive.ts b/src/lib/runners/run-non-interactive.ts index d977733f4..062deba47 100644 --- a/src/lib/runners/run-non-interactive.ts +++ b/src/lib/runners/run-non-interactive.ts @@ -318,6 +318,9 @@ export function runNonInteractive( setPosthogSdkDetected: (detected: boolean) => { session.posthogSdkDetected = detected; }, + markScanReported: () => { + session.warehouseSourcesReported = true; + }, }; for (const step of config.steps) { if (step.onReady) { diff --git a/src/programs/__tests__/run-agent-legacy.test.ts b/src/programs/__tests__/run-agent-legacy.test.ts index d47545e20..43618e60c 100644 --- a/src/programs/__tests__/run-agent-legacy.test.ts +++ b/src/programs/__tests__/run-agent-legacy.test.ts @@ -92,6 +92,7 @@ vi.mock('@utils/wizard-abort', async (original) => ({ })); vi.mock('../posthog-integration/detect', () => ({ maybeStampAiSdkDetected: vi.fn(), + reportWarehouseSourcesDetected: vi.fn(), })); vi.mock('../posthog-integration/ai-sdk-stamp', () => ({ stampAiSdkDetected: vi.fn(), diff --git a/src/programs/posthog-integration/__tests__/detect.test.ts b/src/programs/posthog-integration/__tests__/detect.test.ts index 7a949336f..fd15ae1c8 100644 --- a/src/programs/posthog-integration/__tests__/detect.test.ts +++ b/src/programs/posthog-integration/__tests__/detect.test.ts @@ -67,6 +67,7 @@ function makeCtx(session: WizardSession): ProgramReadyContext { setUnsupportedVersion: vi.fn(), addDiscoveredFeature: vi.fn(), setDetectionComplete: vi.fn(), + markScanReported: vi.fn(), }; } @@ -293,9 +294,13 @@ describe('reportWarehouseSourcesDetected', () => { const { detectWarehousePrerequisites } = await import( '@programs/warehouse-source/detect' ); - detectWarehousePrerequisites(session, (key, value) => { - session.frameworkContext[key] = value; - }); + detectWarehousePrerequisites( + session, + (key, value) => { + session.frameworkContext[key] = value; + }, + () => undefined, + ); expect( session.frameworkContext[DETECTED_WAREHOUSE_SOURCES_KEY], ).toBeDefined(); diff --git a/src/programs/posthog-integration/detect.ts b/src/programs/posthog-integration/detect.ts index bcfa60dc1..f4ff5b13b 100644 --- a/src/programs/posthog-integration/detect.ts +++ b/src/programs/posthog-integration/detect.ts @@ -10,11 +10,7 @@ */ import type { ProgramReadyContext } from '@programs/program-step'; -import { - mayReportScanResults, - ScanConsent, - type WizardSession, -} from '@lib/wizard-session'; +import { mayReportScanResults, type WizardSession } from '@lib/wizard-session'; import { FRAMEWORK_REGISTRY } from '@programs/frameworks/registry'; import { detectFramework, @@ -24,6 +20,7 @@ import { } from '@programs/detection/index'; import { analytics } from '@utils/analytics'; import { detectWarehouseSources } from '@programs/warehouse-sources/detect'; +import { resolveScanReporting } from '@programs/warehouse-scan-reporting'; import { DETECTED_WAREHOUSE_SOURCES_KEY, getDetectedWarehouseSources, @@ -95,13 +92,9 @@ export async function detectPostHogIntegration( } /** - * How the scan went, for the reporter to read later. Three states, and the - * absent one carries the most weight: + * How the scan went, for the reporter to read later. Three states: * - * absent this program never scanned. Only `posthog-integration` runs the - * scan below, but every program's intro screen resolves consent - * through the same store method, so the reporter is reached on runs - * where no scan ever happened. + * absent this program never scanned. * 'failed' the scan threw. A zero-count row would read as "scanned, found * nothing", which is a different fact. * 'ok' the scan ran. Zero sources is a real result and gets reported. @@ -189,49 +182,45 @@ export function maybeStampAiSdkDetected(session: WizardSession): void { * Returns true when consent has resolved and the caller should latch * `warehouseSourcesReported`, which is not the same as "this sent something": * a decline, a failed scan, and a program that never scanned all resolve - * without sending. + * without sending. Nothing fires on 'declined': saved insights read every row + * of this event as a scan that ran. Decline rate comes from 'intro menu + * selected' instead. */ export function reportWarehouseSourcesDetected( session: WizardSession, ): boolean { - if (session.warehouseSourcesReported) return false; - // 'undecided' means come back later, not no. - if (session.scanConsent === ScanConsent.Undecided) return false; - - if (mayReportScanResults(session)) { - const sources = getDetectedWarehouseSources(session); - - // Only an 'ok' scan has something to say. Absent means this program never - // scanned, and reporting a zero count there would invent a scan that never - // ran; 'failed' already fired captureException. - const scanState = session.frameworkContext[WAREHOUSE_SCAN_STATE_KEY] as - | WarehouseScanState - | undefined; - if (scanState !== 'ok') return true; - - // Captured on every run, including the empty case. The denominator is - // the whole point: without the zero rows, "20% of runs have a Postgres" - // is unanswerable. - analytics.wizardCapture('warehouse sources detected', { - warehouse_source_count: sources.length, - warehouse_source_kinds: sources.map((s) => s.kind), - warehouse_source_modes: sources.map((s) => s.mode), - }); - - if (sources.length > 0) { - // Tag subsequent events too, so any downstream funnel can slice on what the - // project had available without re-joining to the event above. - analytics.setTag( - 'warehouse_source_kinds', - sources.map((s) => s.kind).join(','), - ); - analytics.setTag('warehouse_source_count', sources.length); - } - } - // Nothing on 'declined': saved insights read every row of this event as a - // scan that ran. Decline rate comes from 'intro menu selected' instead. - - return true; + return resolveScanReporting( + session, + getDetectedWarehouseSources(session), + (sources) => { + // Only an 'ok' scan has something to say. Absent means this program never + // scanned, and reporting a zero count there would invent a scan that never + // ran; 'failed' already fired captureException. + const scanState = session.frameworkContext[WAREHOUSE_SCAN_STATE_KEY] as + | WarehouseScanState + | undefined; + if (scanState !== 'ok') return; + + // Captured on every run, including the empty case. The denominator is + // the whole point: without the zero rows, "20% of runs have a Postgres" + // is unanswerable. + analytics.wizardCapture('warehouse sources detected', { + warehouse_source_count: sources.length, + warehouse_source_kinds: sources.map((s) => s.kind), + warehouse_source_modes: sources.map((s) => s.mode), + }); + + if (sources.length > 0) { + // Tag subsequent events too, so any downstream funnel can slice on what the + // project had available without re-joining to the event above. + analytics.setTag( + 'warehouse_source_kinds', + sources.map((s) => s.kind).join(','), + ); + analytics.setTag('warehouse_source_count', sources.length); + } + }, + ); } /** Dependency-level signal, not a verified install. A failed scan reports false. */ diff --git a/src/programs/posthog-integration/index.ts b/src/programs/posthog-integration/index.ts index 593f5954a..54d2b5782 100644 --- a/src/programs/posthog-integration/index.ts +++ b/src/programs/posthog-integration/index.ts @@ -28,6 +28,7 @@ import { openTrackedLink, withUtm } from '@utils/links'; import type { HostResolution } from '@shared/host-resolution'; import { getDetectedWarehouseSources } from '@programs/warehouse-source/detect'; import { POSTHOG_INTEGRATION_PROGRAM } from './steps.js'; +import { reportWarehouseSourcesDetected } from './detect.js'; import { getContentBlocks } from '../../ui/tui/decks/posthog-integration/index.js'; import { buildCodingAgentPrompt } from './handoff.js'; import { EVENT_PLAN_FILE } from './constants.js'; @@ -252,6 +253,7 @@ export const posthogIntegrationConfig: ProgramConfig = { disallowedTools: [WIZARD_TOOL_NAMES.wizardAsk], seedTasks: warehouseSeedTasks, + reportScanResults: reportWarehouseSourcesDetected, // Kill switch over the shipped default: only an explicit 'false' excludes, // so a failed flag fetch keeps AI Observability and Logs in the run. diff --git a/src/programs/program-step.ts b/src/programs/program-step.ts index c1274f3b9..3be0465ef 100644 --- a/src/programs/program-step.ts +++ b/src/programs/program-step.ts @@ -61,6 +61,8 @@ export interface ProgramReadyContext { readonly addDiscoveredFeature: (feature: DiscoveredFeature) => void; readonly setDetectionComplete: () => void; readonly setPosthogSdkDetected: (detected: boolean) => void; + /** Latches `warehouseSourcesReported` once a scan has been reported or declined. */ + readonly markScanReported: () => void; } export interface ProgramStep { @@ -280,6 +282,16 @@ export interface ProgramConfig { excludedTaskTypes?: (flags: Record) => readonly string[]; /** Prerequisites: other program ids that must have run first */ requires?: string[]; + /** + * Turn this program's warehouse-source scan into telemetry once scan + * consent resolves. `WizardStore` calls this generically (via + * `getProgramConfig`) rather than importing a specific program's reporting + * function — so the store stays unaware of which program is active. + * Returns whether reporting resolved (granted or declined), so the store + * can set its idempotency flag. Omit for a program that never scans for + * warehouse sources. + */ + reportScanResults?: (session: WizardSession) => boolean; /** * Path (relative to installDir) of the report file the program writes. * Mirrors `run.reportFile` but lifted to the top level so UI screens can diff --git a/src/programs/warehouse-scan-reporting.ts b/src/programs/warehouse-scan-reporting.ts new file mode 100644 index 000000000..80e8050a9 --- /dev/null +++ b/src/programs/warehouse-scan-reporting.ts @@ -0,0 +1,35 @@ +/** + * Consent-gated telemetry for a completed warehouse-source scan. + * + * Both the `posthog-integration` and `warehouse-source` programs scan the + * same project for warehouse sources and want to report what they found — + * but only once the user has been asked. `resolveScanReporting` is the one + * place that question gets answered, so a future reporting site can't + * forget the check and report on an undecided or declined scan. + */ + +import { + mayReportScanResults, + ScanConsent, + type WizardSession, +} from '@lib/wizard-session'; +import type { DetectedSource } from '@programs/warehouse-sources/types'; + +/** + * The one consent check for scan telemetry. Callers pass `sources` because a + * caller mid-detection may hold a fresher value than `session` does, and own + * the `warehouseSourcesReported` flag themselves: 'declined' resolves (returns + * true) without emitting, 'undecided' does not resolve at all. + */ +export function resolveScanReporting( + session: WizardSession, + sources: DetectedSource[], + emit: (sources: DetectedSource[]) => void, +): boolean { + if (session.warehouseSourcesReported) return false; + if (session.scanConsent === ScanConsent.Undecided) return false; + + if (mayReportScanResults(session)) emit(sources); + + return true; +} diff --git a/src/programs/warehouse-source/__tests__/detect.test.ts b/src/programs/warehouse-source/__tests__/detect.test.ts new file mode 100644 index 000000000..4abc71326 --- /dev/null +++ b/src/programs/warehouse-source/__tests__/detect.test.ts @@ -0,0 +1,231 @@ +/** Detection always runs; reporting waits for consent, except in CI where it's already resolved. */ + +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +vi.mock('@utils/analytics', () => ({ + analytics: { + wizardCapture: vi.fn(), + setTag: vi.fn(), + capture: vi.fn(), + captureException: vi.fn(), + groupIdentify: vi.fn(), + }, +})); + +import { analytics } from '@utils/analytics'; +import { + detectWarehousePrerequisites, + reportDetectedWarehouseSources, + getDetectedWarehouseSources, +} from '@programs/warehouse-source/detect'; +import { maybeStampAiSdkDetected } from '@programs/posthog-integration/detect'; +import { + buildSession, + ScanConsent, + type WizardSession, +} from '@lib/wizard-session'; + +function makeTmpDir(): string { + return fs.mkdtempSync(path.join(os.tmpdir(), 'warehouse-source-reporting-')); +} + +function cleanup(dir: string): void { + fs.rmSync(dir, { recursive: true, force: true }); +} + +function withDeps(dir: string, deps: Record): void { + fs.writeFileSync( + path.join(dir, 'package.json'), + JSON.stringify({ dependencies: deps }), + ); +} + +function setFrameworkContext(session: WizardSession) { + return (key: string, value: unknown) => { + session.frameworkContext[key] = value; + }; +} + +function markScanReported(session: WizardSession) { + return () => { + session.warehouseSourcesReported = true; + }; +} + +describe('detectWarehousePrerequisites', () => { + let tmpDir: string; + + beforeEach(() => { + vi.clearAllMocks(); + tmpDir = makeTmpDir(); + withDeps(tmpDir, { stripe: '^14.0.0' }); + }); + + afterEach(() => cleanup(tmpDir)); + + it('populates the detected sources regardless of consent', () => { + const session = buildSession({ installDir: tmpDir }); + expect(session.scanConsent).toBe(ScanConsent.Undecided); + + detectWarehousePrerequisites( + session, + setFrameworkContext(session), + markScanReported(session), + ); + + const sources = getDetectedWarehouseSources(session); + expect(sources.map((s) => s.kind)).toContain('Stripe'); + }); + + it("an interactive session reports nothing at detect time — consent is still 'undecided'", () => { + const session = buildSession({ installDir: tmpDir }); + + detectWarehousePrerequisites( + session, + setFrameworkContext(session), + markScanReported(session), + ); + + expect(analytics.setTag).not.toHaveBeenCalled(); + expect(session.warehouseSourcesReported).toBe(false); + }); + + it("reports immediately for a 'ci: true' session, since consent is already resolved there", () => { + const session = buildSession({ installDir: tmpDir, ci: true }); + expect(session.scanConsent).toBe(ScanConsent.Granted); + + detectWarehousePrerequisites( + session, + setFrameworkContext(session), + markScanReported(session), + ); + + expect(analytics.setTag).toHaveBeenCalledWith( + 'warehouse_source_kinds', + 'Stripe', + ); + expect(analytics.setTag).toHaveBeenCalledWith( + 'warehouse_source_modes', + 'Stripe:in-cli', + ); + expect(analytics.setTag).toHaveBeenCalledWith('warehouse_source_count', 1); + expect(session.warehouseSourcesReported).toBe(true); + }); +}); + +describe('reportDetectedWarehouseSources', () => { + let tmpDir: string; + + beforeEach(() => { + vi.clearAllMocks(); + tmpDir = makeTmpDir(); + withDeps(tmpDir, { stripe: '^14.0.0' }); + }); + + afterEach(() => cleanup(tmpDir)); + + /** Mirrors the real flow: detect while undecided, resolve consent later. */ + function scannedSession(consent: ScanConsent): WizardSession { + const session = buildSession({ installDir: tmpDir }); + detectWarehousePrerequisites( + session, + setFrameworkContext(session), + markScanReported(session), + ); + session.scanConsent = consent; + return session; + } + + it("'undecided' reports nothing and does not resolve", () => { + const session = scannedSession(ScanConsent.Undecided); + + const fired = reportDetectedWarehouseSources(session); + + expect(fired).toBe(false); + expect(analytics.setTag).not.toHaveBeenCalled(); + }); + + it("'declined' reports nothing, but the detected sources stay available for local use", () => { + const session = scannedSession(ScanConsent.Declined); + + const fired = reportDetectedWarehouseSources(session); + + expect(fired).toBe(true); + expect(analytics.setTag).not.toHaveBeenCalled(); + const sources = getDetectedWarehouseSources(session); + expect(sources.map((s) => s.kind)).toContain('Stripe'); + }); + + it("'granted' reports the original property shape: three tags, no capture event", () => { + const session = scannedSession(ScanConsent.Granted); + + const fired = reportDetectedWarehouseSources(session); + + expect(fired).toBe(true); + expect(analytics.setTag).toHaveBeenCalledTimes(3); + expect(analytics.setTag).toHaveBeenCalledWith( + 'warehouse_source_kinds', + 'Stripe', + ); + expect(analytics.setTag).toHaveBeenCalledWith( + 'warehouse_source_modes', + 'Stripe:in-cli', + ); + expect(analytics.setTag).toHaveBeenCalledWith('warehouse_source_count', 1); + expect(analytics.wizardCapture).not.toHaveBeenCalled(); + }); + + it('is idempotent: a second call, once the flag is set, does nothing further', () => { + const session = scannedSession(ScanConsent.Granted); + + expect(reportDetectedWarehouseSources(session)).toBe(true); + session.warehouseSourcesReported = true; // the store setter's job, done here directly + expect(analytics.setTag).toHaveBeenCalledTimes(3); + + const secondCallFired = reportDetectedWarehouseSources(session); + + expect(secondCallFired).toBe(false); + expect(analytics.setTag).toHaveBeenCalledTimes(3); + }); +}); + +describe('wizard_ai_sdk_detected group stamp for the warehouse-source program', () => { + let tmpDir: string; + + beforeEach(() => { + vi.clearAllMocks(); + tmpDir = makeTmpDir(); + }); + + afterEach(() => cleanup(tmpDir)); + + function withOrgUser(session: WizardSession): void { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + session.apiUser = { organization: { id: 'org-1' } } as any; + } + + it('stamps after auth, not when the scan reports', () => { + withDeps(tmpDir, { openai: '^4.0.0' }); + const session = buildSession({ installDir: tmpDir, ci: true }); + withOrgUser(session); + + detectWarehousePrerequisites( + session, + setFrameworkContext(session), + markScanReported(session), + ); + expect(session.warehouseSourcesReported).toBe(true); + expect(analytics.groupIdentify).not.toHaveBeenCalled(); + + maybeStampAiSdkDetected(session); + + expect(analytics.groupIdentify).toHaveBeenCalledTimes(1); + expect(analytics.groupIdentify).toHaveBeenCalledWith( + 'organization', + 'org-1', + { wizard_ai_sdk_detected: true }, + ); + }); +}); diff --git a/src/programs/warehouse-source/detect.ts b/src/programs/warehouse-source/detect.ts index 0fa74c37e..1c8e00034 100644 --- a/src/programs/warehouse-source/detect.ts +++ b/src/programs/warehouse-source/detect.ts @@ -11,6 +11,7 @@ import { analytics } from '@utils/analytics'; import type { WizardSession } from '@lib/wizard-session'; import type { AbortCase } from '@agent/types'; import { detectWarehouseSources } from '@programs/warehouse-sources/detect'; +import { resolveScanReporting } from '@programs/warehouse-scan-reporting'; import type { DetectedSource } from '@programs/warehouse-sources/types'; /** Structured detection errors rendered by the intro screen. */ @@ -64,13 +65,37 @@ export const WAREHOUSE_ABORT_CASES: AbortCase[] = [ }, ]; +/** + * Tag every subsequent event (agent started/completed, setup wizard + * finished, …) with what was detected — without this the analytics can't + * say which source types a run attempted, only that a run happened. + */ +function emitWarehouseSourceTags(sources: DetectedSource[]): void { + analytics.setTag( + 'warehouse_source_kinds', + sources.map((s) => s.kind).join(','), + ); + analytics.setTag( + 'warehouse_source_modes', + sources.map((s) => `${s.kind}:${s.mode}`).join(','), + ); + analytics.setTag('warehouse_source_count', sources.length); +} + /** * Scan `session.installDir` for warehouse-source signals. Writes the detected - * sources (or a `detectError`) into frameworkContext for the intro screen. + * sources (or a `detectError`) into frameworkContext for the intro screen — + * unconditionally, so a declined scan still powers the in-CLI suggestion. + * Reporting is gated separately: a `ci: true` session already has consent + * resolved, so it reports here immediately; an interactive session is still + * `undecided` at this point and reports later, once the intro screen + * resolves consent (see `reportDetectedWarehouseSources`, called by + * `WizardStore`). */ export function detectWarehousePrerequisites( session: WizardSession, setFrameworkContext: (key: string, value: unknown) => void, + markScanReported: () => void, ): void { const fail = (error: WarehouseDetectError) => setFrameworkContext('detectError', error); @@ -102,18 +127,25 @@ export function detectWarehousePrerequisites( return; } - // Tag every subsequent event (agent started/completed, setup wizard - // finished, …) with what was detected — without this the analytics can't - // say which source types a run attempted, only that a run happened. - analytics.setTag( - 'warehouse_source_kinds', - sources.map((s) => s.kind).join(','), - ); - analytics.setTag( - 'warehouse_source_modes', - sources.map((s) => `${s.kind}:${s.mode}`).join(','), - ); - analytics.setTag('warehouse_source_count', sources.length); - setFrameworkContext(DETECTED_WAREHOUSE_SOURCES_KEY, sources); + if (resolveScanReporting(session, sources, emitWarehouseSourceTags)) { + markScanReported(); + } +} + +/** + * The single place this program's scan results become telemetry once an + * interactive session's consent resolves after `detectWarehousePrerequisites` + * already ran undecided. Mirrors `reportWarehouseSourcesDetected` in the + * posthog-integration program, sharing its consent gate via + * `resolveScanReporting`. + */ +export function reportDetectedWarehouseSources( + session: WizardSession, +): boolean { + return resolveScanReporting( + session, + getDetectedWarehouseSources(session), + emitWarehouseSourceTags, + ); } diff --git a/src/programs/warehouse-source/index.ts b/src/programs/warehouse-source/index.ts index fb23dd28c..3535b347e 100644 --- a/src/programs/warehouse-source/index.ts +++ b/src/programs/warehouse-source/index.ts @@ -6,6 +6,7 @@ import { WAREHOUSE_SOURCE_PROGRAM } from './steps.js'; import { WAREHOUSE_ABORT_CASES, getDetectedWarehouseSources, + reportDetectedWarehouseSources, } from './detect.js'; import { getContentBlocks } from '../../ui/tui/decks/warehouse-source/index.js'; @@ -50,6 +51,7 @@ export const warehouseSourceConfig: ProgramConfig = { getContentBlocks, reportFile: 'posthog-warehouse-report.md', allowedTools: ['Agent'], + reportScanResults: reportDetectedWarehouseSources, run: (session: WizardSession): Promise => Promise.resolve({ skillId: 'data-warehouse-source-setup', @@ -74,6 +76,7 @@ export { WAREHOUSE_SOURCE_PROGRAM } from './steps.js'; export { detectWarehousePrerequisites, getDetectedWarehouseSources, + reportDetectedWarehouseSources, DETECTED_WAREHOUSE_SOURCES_KEY, WAREHOUSE_ABORT_CASES, type WarehouseDetectError, diff --git a/src/programs/warehouse-source/steps.ts b/src/programs/warehouse-source/steps.ts index 0a8ed69db..423800789 100644 --- a/src/programs/warehouse-source/steps.ts +++ b/src/programs/warehouse-source/steps.ts @@ -18,7 +18,11 @@ export const WAREHOUSE_SOURCE_PROGRAM: ProgramStep[] = [ // detected sources (or a detectError) to frameworkContext for the // intro screen to render. onReady: (ctx) => - detectWarehousePrerequisites(ctx.session, ctx.setFrameworkContext), + detectWarehousePrerequisites( + ctx.session, + ctx.setFrameworkContext, + ctx.markScanReported, + ), }, { id: 'intro', diff --git a/src/ui/tui/__tests__/store.test.ts b/src/ui/tui/__tests__/store.test.ts index eca82cdb5..4c5f56a48 100644 --- a/src/ui/tui/__tests__/store.test.ts +++ b/src/ui/tui/__tests__/store.test.ts @@ -19,6 +19,7 @@ import { HostResolution } from '@shared/host-resolution'; import { Integration } from '@shared/constants'; import { analytics } from '@utils/analytics'; import { getProgramConfig } from '@programs'; +import { DETECTED_WAREHOUSE_SOURCES_KEY } from '@programs/warehouse-source/detect'; vi.mock('@utils/analytics.js', () => ({ analytics: { @@ -362,6 +363,39 @@ describe('WizardStore', () => { expect(store.session.warehouseSourcesReported).toBe(true); }); + it("completeSetup reports the warehouse-source program's own shape, not posthog-integration's, when that program is active", () => { + const store = createStore(Program.WarehouseSource); + store.setFrameworkContext(DETECTED_WAREHOUSE_SOURCES_KEY, [ + { + kind: 'Stripe', + label: 'Stripe', + mode: 'in-cli', + matchedSignal: 'npm:stripe', + }, + ]); + + store.grantSharing(); + store.completeSetup(); + + expect(store.session.warehouseSourcesReported).toBe(true); + expect(analytics.setTag).toHaveBeenCalledWith( + 'warehouse_source_kinds', + 'Stripe', + ); + expect(analytics.setTag).toHaveBeenCalledWith( + 'warehouse_source_modes', + 'Stripe:in-cli', + ); + expect(analytics.setTag).toHaveBeenCalledWith( + 'warehouse_source_count', + 1, + ); + expect(wizardCaptureMock).not.toHaveBeenCalledWith( + 'warehouse sources detected', + expect.anything(), + ); + }); + it('setRunPhase updates session.runPhase', () => { const store = createStore(); store.setRunPhase(RunPhase.Running); diff --git a/src/ui/tui/components/PrivacyPanel.tsx b/src/ui/tui/components/PrivacyPanel.tsx index b4357a4bb..3f725d60b 100644 --- a/src/ui/tui/components/PrivacyPanel.tsx +++ b/src/ui/tui/components/PrivacyPanel.tsx @@ -11,9 +11,7 @@ * their browser. * * The scan paragraph is opt-in per caller. It ends by pointing at a control, - * so it may only render on a screen that puts one below the panel — three of - * the four callers show `Back` and nothing else, and would be promising a - * choice that is not there. + * so it may only render on a screen that puts one below the panel. */ import { useEffect } from 'react'; @@ -35,8 +33,8 @@ export const PRIVACY_PANEL_LABEL = 'Privacy & data'; interface PrivacyPanelProps { /** * True only on a screen that renders the sharing choice below the panel. - * Gates the scan paragraph, whose last sentence sends the reader to a - * control that exists on one screen. + * Gates the scan paragraph, whose last sentence sends the reader to that + * choice. */ canOptOut?: boolean; } diff --git a/src/ui/tui/primitives/ScreenContainer.tsx b/src/ui/tui/primitives/ScreenContainer.tsx index afc385c9b..276b1d058 100644 --- a/src/ui/tui/primitives/ScreenContainer.tsx +++ b/src/ui/tui/primitives/ScreenContainer.tsx @@ -22,10 +22,7 @@ import { KeyboardHintsProvider } from '@ui/tui/hooks/useKeyboardHints'; import { DissolveTransition } from './DissolveTransition.js'; import { KeyboardHintsBar } from './KeyboardHintsBar.js'; import { ScreenErrorBoundary } from './ScreenErrorBoundary.js'; -import { - ViewportTooSmall, - isViewportTooSmall, -} from './ViewportTooSmall.js'; +import { ViewportTooSmall, isViewportTooSmall } from './ViewportTooSmall.js'; import type { WizardStore } from '@ui/tui/store'; const MIN_WIDTH = 80; @@ -88,8 +85,7 @@ export const ScreenContainer = ({ store, screens }: ScreenContainerProps) => { // Only enforced on a real terminal: with stdout piped there are no // dimensions to read (useStdoutDimensions substitutes 80×24) and no window // for anyone to resize, so nagging would be both wrong and unactionable. - const tooSmall = - Boolean(stdout.isTTY) && isViewportTooSmall(columns, rows); + const tooSmall = Boolean(stdout.isTTY) && isViewportTooSmall(columns, rows); const inner = ( { const [showingMoreInfo, setShowingMoreInfo] = useState(false); const { session } = store; + const sharing = session.scanConsent !== ScanConsent.Declined; const detectError = session.frameworkContext.detectError as | WarehouseDetectError | undefined; @@ -119,15 +123,27 @@ export const WarehouseIntroScreen = ({ store }: WarehouseIntroScreenProps) => { programLabel={session.programLabel} skillId={session.skillId} menuOptions={menuOptions} + privacyOptions={sharingOptions(sharing)} errorView={errorView} onSelect={(value) => { + analytics.wizardCapture('intro menu selected', { + value, + view: showingMoreInfo ? 'more-info' : 'default', + }); if (value === 'cancel') { process.exit(0); } else if (value === 'more-info') { setShowingMoreInfo(true); } else if (value === 'back') { setShowingMoreInfo(false); + } else if (value === 'share') { + store.grantSharing(); + } else if (value === 'no-share') { + store.declineSharing(); } else { + if (session.scanConsent === ScanConsent.Undecided) { + store.grantSharing(); + } store.completeSetup(); } }} diff --git a/src/ui/tui/screens/audit/AuditChecksOutroSection.tsx b/src/ui/tui/screens/audit/AuditChecksOutroSection.tsx index d9178db01..f8cd53a43 100644 --- a/src/ui/tui/screens/audit/AuditChecksOutroSection.tsx +++ b/src/ui/tui/screens/audit/AuditChecksOutroSection.tsx @@ -1,8 +1,5 @@ import { Box, Text } from 'ink'; -import { - AUDIT_SEVERITY_STYLE, - type AuditCheck, -} from '@programs/audit/types'; +import { AUDIT_SEVERITY_STYLE, type AuditCheck } from '@programs/audit/types'; import { relativeToInstallDir } from '@utils/paths'; import { countNoun } from '@utils/count-noun'; diff --git a/src/ui/tui/screens/audit/AuditChecksViewer/CheckRow.tsx b/src/ui/tui/screens/audit/AuditChecksViewer/CheckRow.tsx index 7506a87df..54ed07eaf 100644 --- a/src/ui/tui/screens/audit/AuditChecksViewer/CheckRow.tsx +++ b/src/ui/tui/screens/audit/AuditChecksViewer/CheckRow.tsx @@ -1,8 +1,5 @@ import { Box, Text } from 'ink'; -import { - AUDIT_SEVERITY_STYLE, - type AuditCheck, -} from '@programs/audit/types'; +import { AUDIT_SEVERITY_STYLE, type AuditCheck } from '@programs/audit/types'; import { truncate, type ViewerLayout } from './layout.js'; interface CheckRowProps { diff --git a/src/ui/tui/screens/audit/PendingChecksList.tsx b/src/ui/tui/screens/audit/PendingChecksList.tsx index c6eb4f6f7..a481d2886 100644 --- a/src/ui/tui/screens/audit/PendingChecksList.tsx +++ b/src/ui/tui/screens/audit/PendingChecksList.tsx @@ -1,9 +1,6 @@ import { Box, Text } from 'ink'; import { Spinner } from '@inkjs/ui'; -import { - AUDIT_SEVERITY_STYLE, - type AuditCheck, -} from '@programs/audit/types'; +import { AUDIT_SEVERITY_STYLE, type AuditCheck } from '@programs/audit/types'; import { Colors, Icons } from '@ui/tui/styles'; import { LoadingBox } from '@ui/tui/primitives/index'; import { useStdoutDimensions } from '@ui/tui/hooks/useStdoutDimensions'; diff --git a/src/ui/tui/store.ts b/src/ui/tui/store.ts index 97573dead..e48358157 100644 --- a/src/ui/tui/store.ts +++ b/src/ui/tui/store.ts @@ -52,7 +52,6 @@ import { analytics, sessionProperties } from '@utils/analytics'; import type { StoreInitContext, ProgramReadyContext } from '@programs/types'; import { getProgramConfig } from '@programs'; import { withAiOptInGate } from '@programs/ai-opt-in-gate'; -import { reportWarehouseSourcesDetected } from '@programs/posthog-integration/detect'; import { appendStatus } from '@shared/status-history'; import { IS_DEV } from '@shared/constants'; import { computeTokenCostUsd } from '@shared/token-pricing'; @@ -267,6 +266,8 @@ export class WizardStore { setUnsupportedVersion: (info) => this.setUnsupportedVersion(info), addDiscoveredFeature: (f) => this.addDiscoveredFeature(f), setDetectionComplete: () => this.setDetectionComplete(), + markScanReported: () => + this.$session.setKey('warehouseSourcesReported', true), }; for (const step of steps) { if (step.onReady) { @@ -426,14 +427,15 @@ export class WizardStore { } /** - * reportWarehouseSourcesDetected() is the single place scan results turn - * into telemetry; this just supplies its idempotency flag via the normal - * setter path (never mutate session directly). A no-op once - * `warehouseSourcesReported` is set, or for any program that never - * populated a warehouse-scan result in the first place. + * Delegates to the active program's own `reportScanResults` (each program + * owns its own event/tag shape; this store stays product-agnostic) and + * supplies its idempotency flag via the normal setter path (never mutate + * session directly). A no-op once `warehouseSourcesReported` is set, or for + * a program that never declared `reportScanResults` in the first place. */ private _markWarehouseSourcesReportedIfNeeded(): void { - if (reportWarehouseSourcesDetected(this.session)) { + const { reportScanResults } = getProgramConfig(this.router.activeProgram); + if (reportScanResults?.(this.session)) { this.$session.setKey('warehouseSourcesReported', true); } }