diff --git a/docs/error-catalog.md b/docs/error-catalog.md index ca181e56f..ca33eacec 100644 --- a/docs/error-catalog.md +++ b/docs/error-catalog.md @@ -80,6 +80,8 @@ screen, debug log) keep the full detail. | `PHW_AUTH_SETTINGS_CONFLICT` | auth | Claude settings file overrides the gateway credential | no | | `PHW_AUTH_STORED_LOGIN_CONFLICT` | auth | SDK authenticated from a stored Claude login instead of the gateway token | no | | `PHW_AUTH_PROJECT_FETCH_FAILED` | auth | user/project data fetch from the PostHog API failed | yes | +| `PHW_AUTH_LOGIN_FAILED` | auth | OAuth login failed for a reason other than a timeout or a denial | yes | +| `PHW_AUTH_ACCESS_DENIED` | auth | access denied on the OAuth consent screen | no | | `PHW_ENV_LOCAL_SERVICES_DOWN` | env | a local dev target (`--local-*`) is not running | yes | | `PHW_ENV_SERVICE_OUTAGE` | env | blocking external services down (interactive abort; non-interactive continues) | yes | | `PHW_DETECT_BAD_DIRECTORY` | detect | install dir missing, not a directory, or unreadable | no | diff --git a/src/shared/errors/catalog.ts b/src/shared/errors/catalog.ts index 59778eb67..a4b671e89 100644 --- a/src/shared/errors/catalog.ts +++ b/src/shared/errors/catalog.ts @@ -87,6 +87,18 @@ export const ERROR_CATALOG: Record = { retry: 'yes', description: 'Fetching user or project data from the PostHog API failed.', }, + [ErrorCodes.AuthLoginFailed]: { + group: 'auth', + retry: 'yes', + description: + 'The OAuth login failed for a reason other than a timeout or a denial.', + }, + [ErrorCodes.AuthAccessDenied]: { + group: 'auth', + retry: 'no', + description: + 'The user denied the wizard access on the OAuth consent screen.', + }, [ErrorCodes.EnvLocalServicesDown]: { group: 'env', retry: 'yes', diff --git a/src/shared/errors/codes.ts b/src/shared/errors/codes.ts index 4ce1ef2d5..6ab4032dc 100644 --- a/src/shared/errors/codes.ts +++ b/src/shared/errors/codes.ts @@ -18,6 +18,8 @@ export const ErrorCodes = { AuthSettingsConflict: 'PHW_AUTH_SETTINGS_CONFLICT', AuthStoredLoginConflict: 'PHW_AUTH_STORED_LOGIN_CONFLICT', AuthProjectFetchFailed: 'PHW_AUTH_PROJECT_FETCH_FAILED', + AuthLoginFailed: 'PHW_AUTH_LOGIN_FAILED', + AuthAccessDenied: 'PHW_AUTH_ACCESS_DENIED', EnvLocalServicesDown: 'PHW_ENV_LOCAL_SERVICES_DOWN', EnvServiceOutage: 'PHW_ENV_SERVICE_OUTAGE', DetectBadDirectory: 'PHW_DETECT_BAD_DIRECTORY', diff --git a/src/shared/mcp-clients/__tests__/results.test.ts b/src/shared/mcp-clients/__tests__/results.test.ts index 32fbb0b34..8f9c463ab 100644 --- a/src/shared/mcp-clients/__tests__/results.test.ts +++ b/src/shared/mcp-clients/__tests__/results.test.ts @@ -50,7 +50,32 @@ describe('isOk', () => { }); }); +// Built from parts so the secret scanner does not read a test fixture as a key. +const BEGIN_KEY = ['-----BEGIN', 'PRIVATE KEY-----'].join(' '); +const END_KEY = ['-----END', 'PRIVATE KEY-----'].join(' '); + describe('redactSecrets', () => { + it('masks secrets logged as JSON tool inputs, raw and escaped', () => { + const logged = + '{"values": {"DB_PASSWORD": "hunter2hunter2"}} {\\"api_key\\": \\"abcd1234efgh\\"} pha_oauthtoken123'; + const out = redactSecrets(logged); + expect(out).not.toContain('hunter2hunter2'); + expect(out).not.toContain('abcd1234efgh'); + expect(out).not.toContain('pha_oauthtoken123'); + }); + + it('masks a whole JSON secret value, escapes and newlines included', () => { + const raw = JSON.stringify({ + password: 'abc\\remaining-secret', + api_key: 'pa"leaked-after-quote', + private_key: '-----BEGIN KEY-----\nkeymaterial\n-----END KEY-----', + }); + const out = redactSecrets(`${raw} ${JSON.stringify(raw)}`); + expect(out).not.toContain('remaining-secret'); + expect(out).not.toContain('keymaterial'); + expect(out).not.toContain('leaked-after-quote'); + }); + it('masks the bearer token the CLIs echo back in their error output', () => { expect( redactSecrets( @@ -128,7 +153,44 @@ describe('redactSecrets', () => { // value would file this as an exception instead of hinting. expect( redactSecrets('Missing OPENAI_API_KEY=sk-proj-0123456789abcdefghij'), - ).toContain('OPENAI_API_KEY'); + ).toBe('Missing OPENAI_API_KEY=[redacted]'); + }); + + it('masks a minted gateway token', () => { + expect(redactSecrets('gateway refused phe_abc123DEF456')).toBe( + 'gateway refused [redacted]', + ); + }); + + it('masks an env line inside a JSON-serialized tool output', () => { + const logged = JSON.stringify({ output: 'API_KEY="s3cr3t-value"' }); + expect(redactSecrets(logged)).not.toContain('s3cr3t-value'); + }); + + it('masks a password with punctuation', () => { + expect(redactSecrets("password: 'p@ss!word1234'")).not.toContain( + 'p@ss!word1234', + ); + }); + + it('masks the secret after a quoted value a log line cut short', () => { + const tail = 'TOKEN="abcdefgh\nnext line\nDB_PASSWORD="hunter2hunter2"'; + expect(redactSecrets(tail)).not.toContain('hunter2hunter2'); + }); + + it.each([ + ['its end', `tail:\n${BEGIN_KEY}\nMIIEvQIBADANBg`], + ['its start', `MIIEvQIBADANBg\n${END_KEY}\nnext`], + ])('masks a PEM block cut at %s', (_cut, text) => { + expect(redactSecrets(text)).not.toContain('MIIEvQIBADANBg'); + }); + + it('masks a raw PEM private key block', () => { + const pem = `${BEGIN_KEY.replace( + 'BEGIN', + 'BEGIN RSA', + )}\nMIIEowIBAAKCAQEA\n${END_KEY.replace('END', 'END RSA')}`; + expect(redactSecrets(`key file:\n${pem}`)).toBe('key file:\n[redacted]'); }); it('leaves an ordinary URL and ordinary words alone', () => { @@ -175,6 +237,18 @@ describe('namesWithStatus', () => { }); describe('scrubHomePaths', () => { + it('scrubs a Windows user path nested twice in JSON', () => { + expect( + scrubHomePaths(JSON.stringify(JSON.stringify('C:\\Users\\alice\\proj'))), + ).not.toContain('alice'); + }); + + it('scrubs a Windows home path that JSON escaping doubled', () => { + expect( + scrubHomePaths('"cwd": "C:\\\\Users\\\\alice\\\\proj"'), + ).not.toContain('alice'); + }); + it('replaces a unix home directory with ~ so one cause groups as one issue', () => { expect(scrubHomePaths('spawn /Users/ada/.bun/bin/codex ENOENT')).toBe( 'spawn ~/.bun/bin/codex ENOENT', diff --git a/src/shared/mcp-clients/results.ts b/src/shared/mcp-clients/results.ts index c87fa4599..80dc8cae1 100644 --- a/src/shared/mcp-clients/results.ts +++ b/src/shared/mcp-clients/results.ts @@ -37,6 +37,9 @@ export interface InstallResult { reason?: string; } +const SECRET_NAME = + '[A-Za-z0-9_-]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?)[A-Za-z0-9_-]*'; + /** * Failure text comes from CLIs we invoke with the user's personal API key on the * command line (`--header "Authorization: Bearer phx_..."`), so it can carry the @@ -53,7 +56,7 @@ export interface InstallResult { export const redactSecrets = (raw: string): string => raw .replace(/Bearer\s+\S+/gi, 'Bearer [redacted]') - .replace(/ph[xspc]_[A-Za-z0-9_-]+/g, '[redacted]') + .replace(/ph[xspcare]_[A-Za-z0-9_-]+/g, '[redacted]') // `https://user:token@github.com/...` — git prints the whole remote back; // `postgres://user:password@host/db` is the same shape for a database. .replace(/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@]+:[^/\s@]+@/gi, '$1[redacted]@') @@ -66,13 +69,32 @@ export const redactSecrets = (raw: string): string => .replace(/\b[rs]k_(?:live|test)_[A-Za-z0-9]{16,}/g, '[redacted]') // Google keys, which a config error quotes the same way. .replace(/\bAIza[A-Za-z0-9_-]{16,}/g, '[redacted]') + .replace( + /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g, + '[redacted]', + ) + // A log tail or a sliced log line can cut a key block at either end. + .replace(/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*$/, '[redacted]') + .replace(/^[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/, '[redacted]') // The catch-all for providers we have no shape for: a config error prints // the offending line, and the variable's own name says it holds a secret. // The name is kept — `OPENAI_API_KEY` is wording an expected-failure hint // matches on, and masking it would turn that hint back into an exception. .replace( - /\b([A-Za-z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?)[A-Za-z0-9_]*)(\s*[=:]\s*)["']?[A-Za-z0-9_\-./+]{8,}["']?/gi, + /\b([A-Za-z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?)[A-Za-z0-9_]*)(\s*[=:]\s*)(?:\\"(?:\\\\.|\\[^"\\]|[^\\\n])+\\"|"(?:[^"\\\n]|\\.)+"|'(?:[^'\\\n]|\\.)+'|["']?[^\s"'\\,;}[\])]{8,})/gi, '$1$2[redacted]', + ) + // The same names as JSON keys, raw or escaped, as tool inputs reach the log. + .replace( + new RegExp( + String.raw`(\\"${SECRET_NAME}\\"\s*:\s*\\")(?:\\\\(?:\\.|[^\\])|\\[^"\\]|[^\\])+`, + 'gi', + ), + '$1[redacted]', + ) + .replace( + new RegExp(String.raw`("${SECRET_NAME}"\s*:\s*")(?:[^"\\]|\\.)+`, 'gi'), + '$1[redacted]', ); /** @@ -83,7 +105,7 @@ export const redactSecrets = (raw: string): string => export const scrubHomePaths = (raw: string): string => raw .replace(/\/(?:Users|home)\/[^/\s'"]+/g, '~') - .replace(/[A-Za-z]:\\Users\\[^\\\s'"]+/gi, '~'); + .replace(/[A-Za-z]:\\+Users\\+[^\\\s'"]+/gi, '~'); /** * A failure that lives entirely in the user's environment: a CLI too old, a diff --git a/src/shared/utils/__tests__/debug.test.ts b/src/shared/utils/__tests__/debug.test.ts index 0904a0e91..8b63491da 100644 --- a/src/shared/utils/__tests__/debug.test.ts +++ b/src/shared/utils/__tests__/debug.test.ts @@ -4,6 +4,7 @@ import * as path from 'path'; import { configureLogFile, getLogFilePath, + getProcessLogTail, initLogFile, logToFile, } from '@utils/debug'; @@ -21,6 +22,25 @@ describe('log file writing', () => { fs.rmSync(tmpRoot, { recursive: true, force: true }); }); + it('keeps only whole lines from the last 64K of this process', () => { + configureLogFile({ path: path.join(tmpRoot, 'w.log'), enabled: true }); + logToFile('first line that must age out'); + for (let i = 0; i < 700; i++) logToFile(`line ${i} ${'x'.repeat(100)}`); + const tail = getProcessLogTail(); + expect(tail.length).toBeLessThanOrEqual(64 * 1024); + expect(tail).not.toContain('first line that must age out'); + expect(tail.startsWith('[')).toBe(true); + expect(tail).toContain('line 699'); + }); + + it('leaves out a single line longer than the tail, so no unlabelled secret survives', () => { + configureLogFile({ path: path.join(tmpRoot, 'w.log'), enabled: true }); + logToFile(`PASSWORD=${'y'.repeat(70 * 1024)}`); + const tail = getProcessLogTail(); + expect(tail).toContain('log line over 64K left out'); + expect(tail).not.toContain('yyyy'); + }); + it('creates a missing log directory instead of dropping the log', () => { const logPath = path.join(tmpRoot, 'does', 'not', 'exist', 'wizard.log'); configureLogFile({ path: logPath, enabled: true }); diff --git a/src/shared/utils/debug.ts b/src/shared/utils/debug.ts index cc2e0f839..0eefdfd6b 100644 --- a/src/shared/utils/debug.ts +++ b/src/shared/utils/debug.ts @@ -70,9 +70,31 @@ function reportLogFailureOnce(err: unknown): void { }); } +// Every run appends to one shared file, so a failure report reads this process's own lines from memory. +const PROCESS_LOG_TAIL_CHARS = 64 * 1024; +const OVERSIZED_LINE_NOTE = '[log line over 64K left out]\n'; +let processLogTail = ''; + +export function getProcessLogTail(): string { + return processLogTail; +} + +function keepInProcessTail(text: string): void { + processLogTail += text; + if (processLogTail.length <= PROCESS_LOG_TAIL_CHARS) return; + const kept = processLogTail.slice(-PROCESS_LOG_TAIL_CHARS); + const firstBreak = kept.indexOf('\n'); + // A cut line can keep a secret's value without the name that gets it masked, so a line too long to keep whole is left out. + processLogTail = + firstBreak >= 0 && firstBreak < kept.length - 1 + ? kept.slice(firstBreak + 1) + : OVERSIZED_LINE_NOTE; +} + // The log's directory isn't guaranteed to exist (Windows %TEMP%, // POSTHOG_WIZARD_LOG_DIR) — create it on first failure. function appendLine(text: string): void { + keepInProcessTail(text); try { appendFileSync(logFilePath, text); } catch (err) { diff --git a/src/tui/__tests__/MintFailureScreen.test.tsx b/src/tui/__tests__/MintFailureScreen.test.tsx index 685c8bfaf..e04555f8e 100644 --- a/src/tui/__tests__/MintFailureScreen.test.tsx +++ b/src/tui/__tests__/MintFailureScreen.test.tsx @@ -7,13 +7,22 @@ import { } from '../screens/MintFailureScreen'; import { KeyboardHintsProvider } from '../hooks/useKeyboardHints'; import { OutroKind } from '@shared/outro'; +import { ErrorCodes, type ErrorCode } from '@shared/errors'; +import { Program, type ProgramId } from '@programs'; import { HostResolution } from '@shared/host-resolution'; import { ScreenId } from '../router'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { configureLogFile, logToFile } from '@utils/debug'; +import { failureReportProperties } from '../mint-failure'; + +const wizardCapture = vi.hoisted(() => vi.fn()); vi.mock('ink', () => vi.importActual('ink-actual')); vi.mock('@utils/analytics', () => ({ analytics: { - wizardCapture: vi.fn(), + wizardCapture, capture: vi.fn(), setTag: vi.fn(), } as never, @@ -26,19 +35,27 @@ const saved = { }; const delay = () => new Promise((resolve) => setTimeout(resolve, 30)); -function setup() { - const store = new WizardStore(); - store.setCredentials({ - accessToken: 'tok', - projectApiKey: 'pk', - host: HostResolution.fromApiHost('https://app.posthog.com'), - projectId: 1, +function setup( + errorCode?: ErrorCode, + isLoggedIn = true, + program: ProgramId = Program.PostHogIntegration, +) { + const store = new WizardStore(program); + if (isLoggedIn) + store.setCredentials({ + accessToken: 'tok', + projectApiKey: 'pk', + host: HostResolution.fromApiHost('https://app.posthog.com'), + projectId: 1, + }); + store.setOutroData({ + kind: OutroKind.Error, + message: 'agent failed', + errorCode, }); - store.setOutroData({ kind: OutroKind.Error, message: 'agent failed' }); const services: MintFailureServices = { leaveSpellbook: vi.fn().mockResolvedValue(saved), openAgent: vi.fn().mockResolvedValue(undefined), - logPath: '/tmp/posthog-wizard.log', }; const app = render( @@ -57,13 +74,21 @@ function setup() { return { store, services, app, choose }; } -afterEach(cleanup); +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); -it('reports the log, saves the skill, then continues setup', async () => { - const { app, store, services, choose } = setup(); - await choose(3); - expect(app.lastFrame()).toContain(services.logPath); +it('sends the log, saves the skill, then continues setup', async () => { + const { app, store, choose } = setup(); await choose(0); + expect(wizardCapture).toHaveBeenCalledWith( + 'failure reported', + expect.objectContaining({ message: 'agent failed', is_capacity: false }), + ); + expect(app.lastFrame()).toContain('Log sent.'); + expect(app.lastFrame()).toContain('Step 2 of 2'); + await choose(2); expect(app.lastFrame()).toContain(saved.path); expect(store.mintHandoff).toBeNull(); await choose(0); @@ -78,7 +103,8 @@ it.each(['save', 'open'] as const)( vi.mocked( failure === 'save' ? services.leaveSpellbook : services.openAgent, ).mockRejectedValueOnce(new Error('Unavailable')); - await choose(2); + await choose(1); + await choose(1); expect(app.lastFrame()).toContain( failure === 'save' ? 'Could not save' : 'Unavailable', ); @@ -93,10 +119,97 @@ it.each(['save', 'open'] as const)( }, ); -it('exits without saving or launching', async () => { - const { store, services, choose } = setup(); - await choose(4); +it('exits without sending the log, saving or launching', async () => { + const { app, store, services, choose } = setup(); + await choose(1); + expect(app.lastFrame()).not.toContain('Log sent.'); + await choose(3); expect(store.mintHandoff).toBe('exit'); + expect(wizardCapture).not.toHaveBeenCalledWith( + 'failure reported', + expect.anything(), + ); expect(services.leaveSpellbook).not.toHaveBeenCalled(); expect(services.openAgent).not.toHaveBeenCalled(); }); + +it('skips the log question when the carbon unit declined access, offering only Exit', async () => { + const { app } = setup(ErrorCodes.AuthAccessDenied, false); + await delay(); + const screenText = app.lastFrame()?.replace(/\s+/g, ' '); + expect(screenText).toContain("You didn't authorize the wizard"); + expect(screenText).not.toContain('Step 1 of 2'); + expect(screenText).not.toContain('Send your log too?'); + expect(screenText).toContain('Exit'); + expect(screenText).not.toContain('Save skill'); +}); + +it('names the program it reruns when the run was not the integration', async () => { + const { app, choose } = setup(ErrorCodes.AgentApiError, true, Program.Audit); + await delay(); + expect(app.lastFrame()).toContain("The wizard didn't finish"); + await choose(1); + const screenText = app.lastFrame()?.replace(/\s+/g, ' '); + expect(screenText).toContain('npx @posthog/wizard@latest audit'); +}); + +it('asks for the same command when the program has none of its own', async () => { + const { app, choose } = setup( + ErrorCodes.AgentApiError, + true, + Program.AgentSkill, + ); + await delay(); + await choose(1); + const screenText = app.lastFrame()?.replace(/\s+/g, ' '); + expect(screenText).toContain('Run the same wizard command again.'); + expect(screenText).not.toContain('npx @posthog/wizard@latest'); +}); + +it.each([ + [ErrorCodes.AgentOrchestratorTasksFailed, "PostHog isn't set up yet"], + [ErrorCodes.AgentRateLimit, 'The wizard is busy right now'], +])( + 'asks about the log under a %s headline of %s, no error text', + async (errorCode, headline) => { + const { app } = setup(errorCode); + await delay(); + const screenText = app.lastFrame()?.replace(/\s+/g, ' '); + expect(screenText).toContain(headline); + expect(screenText).toContain('We got the error automatically.'); + expect(screenText).toContain('Send your log too?'); + expect(screenText).not.toContain('agent failed'); + }, +); + +it('routes a failed login here and offers only Exit after the log question', async () => { + const { app, store, choose } = setup(ErrorCodes.AuthLoginFailed, false); + expect(store.router.resolve(store)).toBe(ScreenId.MintFailure); + await choose(1); + const screenText = app.lastFrame()?.replace(/\s+/g, ' '); + expect(screenText).toContain("You're not logged in yet"); + expect(screenText).not.toContain('Open in Claude Code'); + await choose(0); + expect(store.mintHandoff).toBe('exit'); +}); + +it("reports only this run's log lines when another run shares the log file", () => { + const logPath = path.join( + fs.mkdtempSync(path.join(os.tmpdir(), 'wizard-log-')), + 'posthog-wizard.log', + ); + configureLogFile({ path: logPath, enabled: true }); + logToFile('this run started'); + fs.appendFileSync(logPath, 'another run read its secret source\n'); + logToFile( + 'this run failed with Bearer phx_logged_secret in /Users/alice/app', + ); + const { store } = setup(); + const logTail = String( + failureReportProperties(store.session, store.router.activeProgram).log_tail, + ); + expect(logTail).toContain('this run failed'); + expect(logTail).not.toContain('another run'); + expect(logTail).not.toContain('phx_logged_secret'); + expect(logTail).not.toContain('alice'); +}); diff --git a/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt b/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt index 0d05d3788..e3e1f0841 100644 --- a/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt +++ b/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt @@ -13,17 +13,17 @@ + Step 1 of 2 - ✘ The Wizard's a little busy + ✘ The wizard is busy right now + The wizard's AI service is busy, so setup stopped before finishing. + We got the error automatically. - The wizard can still share spells. Grab a skill and let your agent take over. - - ▸ Save skill - Open in Claude Code - Open in Codex - Report this issue - Exit + Send your log too? + It helps us find the cause. We mask the keys and tokens we recognize. + ▸ Send log and continue + Continue without sending diff --git a/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt b/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt index 21aba7dcb..52582b871 100644 --- a/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt +++ b/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt @@ -7,17 +7,17 @@ + Step 1 of 2 - ✘ The Wizard's a little busy + ✘ The wizard is busy right now + The wizard's AI service is busy, so setup stopped before finishing. + We got the error automatically. - The wizard can still share spells. Grab a skill and let your agent take - over. + Send your log too? + It helps us find the cause. We mask the keys and tokens we recognize. - ▸ Save skill - Open in Claude Code - Open in Codex - Report this issue - Exit + ▸ Send log and continue + Continue without sending diff --git a/src/tui/__tests__/exit-line.test.ts b/src/tui/__tests__/exit-line.test.ts index fe41666a9..4e5951656 100644 --- a/src/tui/__tests__/exit-line.test.ts +++ b/src/tui/__tests__/exit-line.test.ts @@ -5,6 +5,7 @@ import { getExitLine } from '@tui/exit-line'; import { buildSession } from '@programs'; import { WizardStore, Program } from '@tui/store'; import { OutroKind } from '@shared/outro'; +import { ErrorCodes } from '@shared/errors'; import { HostResolution } from '@shared/host-resolution'; vi.mock('@utils/analytics.js', () => ({ @@ -35,7 +36,7 @@ function setHudVisible(store: WizardStore, visible: boolean): void { } describe('getExitLine', () => { - it('keeps the saved skill path and contact in scrollback after a failed run', () => { + it('keeps the saved skill path and log path in scrollback after a failed run', () => { const path = '/project/.posthog/wizard-spellbook-123/README.md'; const store = storeWithOutro({ kind: OutroKind.Error, message: 'boom' }); store.setCredentials({ @@ -48,9 +49,11 @@ describe('getExitLine', () => { const line = stripAnsi(getExitLine(store)); const lines = line.split('\n'); expect(lines).toContain(path); - expect(line).toContain('wizard@posthog.com'); - // The log path sits on the line after the contact copy. - expect(lines[lines.indexOf(path) + 3]).toMatch(/\S/); + expect(line).not.toContain('wizard@posthog.com'); + expect(lines[lines.indexOf(path) + 2]).toBe( + 'We got the error automatically.', + ); + expect(lines[lines.indexOf(path) + 3]).toMatch(/^Wizard log: \S/); expect(line).not.toContain('successfully'); }); @@ -252,12 +255,19 @@ describe('getExitLine needs-attention block', () => { expect(stripAnsi(getExitLine(store))).not.toContain('Needs your attention'); }); - it('skips the warning block on a run failure', () => { - const store = storeWithOutro({ kind: OutroKind.Error, message: 'boom' }); + it.each([ + [ErrorCodes.AgentOrchestratorTasksFailed, "PostHog isn't set up yet."], + [ErrorCodes.AgentRateLimit, 'The wizard is busy right now.'], + ])('skips the warning block on a %s run failure', (errorCode, summary) => { + const store = storeWithOutro({ + kind: OutroKind.Error, + message: 'boom', + errorCode, + }); store.session = { ...store.session, credentials: {} as never }; store.setHandoffText(block); const line = stripAnsi(getExitLine(store)); - expect(line).toContain('The wizard is unavailable'); + expect(line).toContain(summary); expect(line).not.toContain('Needs your attention'); }); }); diff --git a/src/tui/__tests__/frames.test.tsx b/src/tui/__tests__/frames.test.tsx index de3dbd278..5219f0665 100644 --- a/src/tui/__tests__/frames.test.tsx +++ b/src/tui/__tests__/frames.test.tsx @@ -120,6 +120,7 @@ import { listTuiTools } from '@tui/tools/index'; import { ScreenId, Overlay } from '@tui/router'; import { createServices, type ScreenServices } from '@tui/screen-registry'; import { OutroKind } from '@shared/outro'; +import { ErrorCodes } from '@shared/errors'; import { RunPhase } from '@shared/run-state'; import { HostResolution } from '@shared/host-resolution'; import { Integration } from '@shared/constants'; @@ -675,6 +676,7 @@ const FIXTURES: Record = { s.setOutroData({ kind: OutroKind.Error, message: 'The agent run failed', + errorCode: ErrorCodes.AgentRateLimit, }); }, }, diff --git a/src/tui/__tests__/router.test.ts b/src/tui/__tests__/router.test.ts index 4ff06320a..7136176ab 100644 --- a/src/tui/__tests__/router.test.ts +++ b/src/tui/__tests__/router.test.ts @@ -48,17 +48,54 @@ describe('WizardRouter', () => { }, ); - it.each([...PROGRAM_REGISTRY, ...TOOL_REGISTRY].map((program) => program.id))( - 'shows a failed run over every step and overlay in %s', + it.each(PROGRAM_REGISTRY.map((program) => program.id))( + 'shows a failed run over every step in %s', (program) => { const router = new WizardRouter(program); - router.pushOverlay(Overlay.WizardAsk); const view = failedRunView(); view.outroDismissed = true; expect(router.resolve(view)).toBe(ScreenId.MintFailure); }, ); + it.each(TOOL_REGISTRY.map((tool) => tool.id))( + 'keeps a logged-in failure in %s on its own outro, so Exit ends the tool', + (tool) => { + const router = new WizardRouter(tool); + const view = failedRunView(); + view.session.runPhase = RunPhase.Error; + expect(router.resolve(view)).toBe(ScreenId.Outro); + view.outroDismissed = true; + expect(router.resolve(view)).toBe(ScreenId.Exit); + }, + ); + + it('shows the auth error overlay over a failed run', () => { + const router = new WizardRouter(Program.PostHogIntegration); + router.pushOverlay(Overlay.AuthError); + const view = failedRunView(); + view.session.outroData = { + kind: OutroKind.Error, + message: 'settings conflict', + errorCode: ErrorCodes.AuthSettingsConflict, + }; + expect(router.resolve(view)).toBe(Overlay.AuthError); + }); + + it.each([ + ErrorCodes.AuthSettingsConflict, + ErrorCodes.AuthInvalidOrExpired, + ErrorCodes.AuthMissingScope, + ErrorCodes.DetectNoPosthogSdk, + ErrorCodes.CliInteractiveRequired, + ])('keeps a logged-in %s on its own outro', (errorCode) => { + const router = new WizardRouter(Program.Audit); + const view = failedRunView(); + view.session.runPhase = RunPhase.Error; + view.session.outroData = { kind: OutroKind.Error, message: 'x', errorCode }; + expect(router.resolve(view)).toBe(ScreenId.Outro); + }); + it('shows a security stop on its own outro, never the busy handoff', () => { const router = new WizardRouter(Program.PostHogIntegration); const view = failedRunView(); diff --git a/src/tui/__tests__/store-invariants.test.ts b/src/tui/__tests__/store-invariants.test.ts index 3c4f47653..a57169555 100644 --- a/src/tui/__tests__/store-invariants.test.ts +++ b/src/tui/__tests__/store-invariants.test.ts @@ -327,6 +327,12 @@ const MUTATIONS: MutationCase[] = [ invoke: (s) => s.dismissManualAuthCode(), emits: 1, }, + { + name: 'closeManualAuthCode', + prepare: (s) => s.showManualAuthCode(), + invoke: (s) => s.closeManualAuthCode(), + emits: 1, + }, { name: 'submitManualAuthCode', prepare: (s) => s.showManualAuthCode(), @@ -550,6 +556,8 @@ const NON_MUTATING = [ 'noteAskProgress', // Captures the MCP outcome; holds no session state. 'reportMcpOutcome', + // Captures the failure report; holds no session state. + 'sendFailureReport', 'getSnapshot', 'getVersion', 'runInitHooks', diff --git a/src/tui/__tests__/store.test.ts b/src/tui/__tests__/store.test.ts index fe68d1d3a..49ddb4e27 100644 --- a/src/tui/__tests__/store.test.ts +++ b/src/tui/__tests__/store.test.ts @@ -542,6 +542,27 @@ describe('WizardStore', () => { // ── wizard_ask overlay ─────────────────────────────────────────── + describe('closeManualAuthCode', () => { + it('closes the paste-code overlay once the login settles', () => { + const store = createStore(); + store.showManualAuthCode(); + + store.closeManualAuthCode(); + + expect(store.currentScreen).not.toBe(Overlay.ManualAuthCode); + }); + + it('leaves an overlay opened after it, such as the session timeout', () => { + const store = createStore(); + store.showManualAuthCode(); + store.showSessionTimeout(); + + store.closeManualAuthCode(); + + expect(store.currentScreen).toBe(Overlay.SessionTimeout); + }); + }); + describe('requestQuestion / resolvePendingQuestion', () => { const pending = { id: 'req-1', diff --git a/src/tui/auth/__tests__/ci-region.test.ts b/src/tui/auth/__tests__/ci-region.test.ts index 6d26a1c77..01589eaa6 100644 --- a/src/tui/auth/__tests__/ci-region.test.ts +++ b/src/tui/auth/__tests__/ci-region.test.ts @@ -6,6 +6,7 @@ import type { WizardStore } from '@tui/store'; import { WIZARD_OAUTH_SCOPES } from '@shared/constants'; import { getOAuthScopesForProgram } from '@programs'; import { CONNECT_SLACK_SCOPE_ADDITIONS } from '@shared/oauth-scopes'; +import { abortOnScreens } from '@tui/abort'; vi.mock('@utils/urls', () => ({ detectRegion: vi.fn(), @@ -25,6 +26,9 @@ vi.mock('@utils/analytics', () => ({ setTag: vi.fn(), }, })); +vi.mock(import('@tui/abort'), () => ({ + abortOnScreens: vi.fn(() => Promise.reject(new Error('aborted'))), +})); vi.mock(import('../oauth'), () => ({ performOAuthFlow: vi.fn(), assertWizardCompletionScope: vi.fn(), @@ -167,3 +171,39 @@ describe('getOrAskForProjectData program login', () => { expect(result.projectApiKey).toBe('phc_test'); }); }); + +// A failure after the browser login must end the run as failed: the TUI host reads a missing login as a finished run. +describe('getOrAskForProjectData after a failed fetch', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockedFetchProject.mockResolvedValue(project); + mockedFetchUser.mockResolvedValue({ + distinct_id: 'user-1', + role_at_organization: null, + }); + mockedOAuthFlow.mockResolvedValue({ + access_token: 'pha_test', + scope: 'event_definition:write', + scoped_teams: [123], + posthog_region: 'us', + }); + }); + + it.each([ + ['project', mockedFetchProject], + ['user', mockedFetchUser], + ])( + 'throws the coded fetch error for its caller when the %s fetch fails', + async (_, fetch) => { + fetch.mockRejectedValue(new Error('Request failed with status code 503')); + + await expect( + getOrAskForProjectData({ store, projectId: 123 }), + ).rejects.toMatchObject({ + code: 'PHW_AUTH_PROJECT_FETCH_FAILED', + message: expect.stringContaining('status code 503'), + }); + expect(abortOnScreens).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/src/tui/auth/__tests__/login.test.ts b/src/tui/auth/__tests__/login.test.ts index c4bfaaed0..8136f45ae 100644 --- a/src/tui/auth/__tests__/login.test.ts +++ b/src/tui/auth/__tests__/login.test.ts @@ -3,6 +3,9 @@ vi.mock(import('@utils/analytics'), () => ({ })); vi.mock(import('@utils/debug')); vi.mock(import('../project-data'), () => ({ getOrAskForProjectData: vi.fn() })); +vi.mock(import('@tui/abort'), () => ({ + abortOnScreens: vi.fn(() => Promise.reject(new Error('aborted'))), +})); import { HostResolution } from '@shared/host-resolution'; import { analytics } from '@utils/analytics'; @@ -10,6 +13,8 @@ import { buildSession } from '@programs'; import type { WizardStore } from '@tui/store'; import { oauthCredentials, oauthLogin } from '../login'; import { getOrAskForProjectData } from '../project-data'; +import { abortOnScreens } from '@tui/abort'; +import { ErrorCodes, WizardError } from '@shared/errors'; const projectData = { host: HostResolution.fromRegion('us'), @@ -60,3 +65,47 @@ it("passes the program's completion-scope opt-out to the login", async () => { }), ); }); + +it('ends the run on a failed project fetch or an uncoded login error, and passes a coded one through', async () => { + const store = {} as WizardStore; + const session = buildSession({ installDir: '/project' }); + const fetchFailed = new WizardError( + 'could not load project', + undefined, + ErrorCodes.AuthProjectFetchFailed, + ); + vi.mocked(getOrAskForProjectData).mockRejectedValueOnce(fetchFailed); + await expect(oauthLogin(session, 'metrics', store)).rejects.toThrow( + 'aborted', + ); + expect(abortOnScreens).toHaveBeenCalledWith(store, { + code: ErrorCodes.AuthProjectFetchFailed, + message: 'could not load project', + error: fetchFailed, + }); + + vi.mocked(abortOnScreens).mockClear(); + vi.mocked(getOrAskForProjectData).mockRejectedValueOnce( + new Error('No OAuth callback ports configured'), + ); + await expect(oauthLogin(session, 'metrics', store)).rejects.toThrow( + 'aborted', + ); + expect(abortOnScreens).toHaveBeenCalledWith( + store, + expect.objectContaining({ + code: ErrorCodes.AuthLoginFailed, + message: 'No OAuth callback ports configured', + }), + ); + + vi.mocked(abortOnScreens).mockClear(); + const coded = new WizardError( + 'scope', + undefined, + ErrorCodes.AuthMissingScope, + ); + vi.mocked(getOrAskForProjectData).mockRejectedValueOnce(coded); + await expect(oauthLogin(session, 'metrics', store)).rejects.toBe(coded); + expect(abortOnScreens).not.toHaveBeenCalled(); +}); diff --git a/src/tui/auth/__tests__/oauth-flow.test.ts b/src/tui/auth/__tests__/oauth-flow.test.ts index d16728dc8..e26c4252b 100644 --- a/src/tui/auth/__tests__/oauth-flow.test.ts +++ b/src/tui/auth/__tests__/oauth-flow.test.ts @@ -14,6 +14,7 @@ import axios from 'axios'; import * as net from 'node:net'; import { abortOnScreens } from '@tui/abort'; import type { WizardStore } from '@tui/store'; +import { analytics } from '@utils/analytics'; import { openTrackedLink } from '@utils/links'; import { performOAuthFlow } from '../oauth'; @@ -36,6 +37,7 @@ function fakeStore() { store.loginUrl = url; }, setAuthorizeUrl: vi.fn(), + closeManualAuthCode: vi.fn(), pushStatus: vi.fn(), showSessionTimeout: vi.fn(), waitForManualAuthCode: () => pasted, @@ -79,6 +81,8 @@ describe('the OAuth flow', () => { }); // A remote shell cannot reach localhost, so the paste modal links PostHog directly. expect(store.setAuthorizeUrl).toHaveBeenNthCalledWith(1, authorize); + // A paste modal left open would cover the screens after login. + expect(store.closeManualAuthCode).toHaveBeenCalled(); expect(abortOnScreens).not.toHaveBeenCalled(); }); @@ -93,24 +97,47 @@ describe('the OAuth flow', () => { expect(abortOnScreens).not.toHaveBeenCalled(); }); - it('stops the login and frees its port when the callback carries an error', async () => { - const { store, wizardStore } = fakeStore(); + it.each([ + [ + 'access_denied', + 'Authorization was cancelled', + 'PHW_AUTH_ACCESS_DENIED', + 'cancelled', + ], + ['invalid_scope', 'invalid_scope', 'PHW_AUTH_LOGIN_FAILED', 'error'], + ])( + 'stops the login when the callback carries %s, says why, and frees its port', + async (oauthError, shown, code, status) => { + const { store, wizardStore } = fakeStore(); - const flow = performOAuthFlow({ scopes: ['user:read'] }, wizardStore); - // Attached before the callback, because the flow rejects while the fetch is still in flight. - const failed = expect(flow).rejects.toThrow('aborted'); - const loginUrl = await shownLoginUrl(store); - await fetch(new URL('/callback?error=access_denied', loginUrl)); + const flow = performOAuthFlow({ scopes: ['user:read'] }, wizardStore); + // Attached before the callback, because the flow rejects while the fetch is still in flight. + const failed = expect(flow).rejects.toThrow('aborted'); + const loginUrl = await shownLoginUrl(store); + await fetch(new URL(`/callback?error=${oauthError}`, loginUrl)); - await failed; - expect(abortOnScreens).toHaveBeenCalledWith(wizardStore); - expect(axios.post).not.toHaveBeenCalled(); - // The next login listens on the same port, so the failed one must have released it. - const reuse = net.createServer(); - await new Promise((resolve, reject) => { - reuse.once('error', reject); - reuse.listen(Number(new URL(loginUrl).port), resolve); - }); - reuse.close(); - }); + await failed; + // The outro is the only screen left, so the reason must reach it. + expect(abortOnScreens).toHaveBeenCalledWith(wizardStore, { + message: expect.stringContaining(shown), + code, + status, + error: expect.objectContaining({ + context: expect.objectContaining({ + $exception_fingerprint: `wizard_oauth_${oauthError}`, + }), + }), + }); + // abortOnScreens captures the error; a second capture here would count it twice. + expect(analytics.captureException).not.toHaveBeenCalled(); + expect(axios.post).not.toHaveBeenCalled(); + // The next login listens on the same port, so the failed one must have released it. + const reuse = net.createServer(); + await new Promise((resolve, reject) => { + reuse.once('error', reject); + reuse.listen(Number(new URL(loginUrl).port), resolve); + }); + reuse.close(); + }, + ); }); diff --git a/src/tui/auth/login.ts b/src/tui/auth/login.ts index f98d1391e..130d1423d 100644 --- a/src/tui/auth/login.ts +++ b/src/tui/auth/login.ts @@ -7,6 +7,8 @@ import type { import { analytics } from '@utils/analytics'; import { logToFile } from '@utils/debug'; import type { WizardStore } from '@tui/store'; +import { classifyRunFailure, ErrorCodes, WizardError } from '@shared/errors'; +import { abortOnScreens } from '@tui/abort'; import { getOrAskForProjectData } from './project-data.js'; /** Log in once through OAuth for the session's launch values. */ @@ -24,6 +26,29 @@ export async function oauthLogin( localMcp: session.localMcp, programId, completionScopeOptional, + }).catch(async (error: unknown) => { + // Without an abort a login error reaches the TUI host with no credentials set, which ends the run as completed. + if ( + error instanceof WizardError && + error.code === ErrorCodes.AuthProjectFetchFailed + ) { + return abortOnScreens(store, { + code: error.code, + message: error.message, + error, + }); + } + const failure = classifyRunFailure(error); + if (failure.coded) throw error; + return abortOnScreens(store, { + code: ErrorCodes.AuthLoginFailed, + message: failure.message, + error: new WizardError( + failure.message, + undefined, + ErrorCodes.AuthLoginFailed, + ), + }); }); analytics.wizardCapture('auth complete', { project_id: data.projectId }); return { diff --git a/src/tui/auth/oauth.ts b/src/tui/auth/oauth.ts index 485c12041..9699fdf25 100644 --- a/src/tui/auth/oauth.ts +++ b/src/tui/auth/oauth.ts @@ -14,6 +14,7 @@ import { OAUTH_TIMEOUT_MS, WIZARD_USER_AGENT, } from '@shared/constants'; +import { ErrorCodes, WizardError } from '@shared/errors'; import { abortOnScreens } from '@tui/abort'; import type { WizardStore } from '@tui/store'; import { analytics } from '@utils/analytics'; @@ -539,7 +540,7 @@ export async function performOAuthFlow( OAUTH_TIMEOUT_MS, ), ), - ]); + ]).finally(() => store.closeManualAuthCode()); const token = await exchangeCodeForToken( code, @@ -577,29 +578,28 @@ export async function performOAuthFlow( ? flowError.code === 'access_denied' : error.message.includes('access_denied'); + // The outro shows this, because the status line is gone once the run aborts. + let failureMessage: string | undefined; if (timedOut) { // Overlay bypasses the auth-step gating (which never completes // without credentials), so the user sees the failure instead of a // spinner that never stops; any key exits. store.showSessionTimeout(); } else if (accessDenied) { - store.pushStatus( - `Authorization was cancelled.\n\nYou denied access to PostHog. To use the wizard, you need to authorize access to your PostHog account.\n\nYou can try again by re-running the wizard.`, - ); + failureMessage = `Authorization was cancelled.\n\nYou denied access to PostHog. To use the wizard, you need to authorize access to your PostHog account.\n\nYou can try again by re-running the wizard.`; } else { - store.pushStatus( - buildOAuthFailureMessage({ - error, - requestedScopes: config.scopes, - clientId, - oauthUrl, - // Same condition that selects the dev client ID: a resolvable - // base URL means a dev-seeded stack, where "fix your local - // OAuth app" beats pointing at the production runbook. - isDevStack: resolveBaseUrl(config.baseUrl) !== undefined, - }), - ); + failureMessage = buildOAuthFailureMessage({ + error, + requestedScopes: config.scopes, + clientId, + oauthUrl, + // Same condition that selects the dev client ID: a resolvable + // base URL means a dev-seeded stack, where "fix your local + // OAuth app" beats pointing at the production runbook. + isDevStack: resolveBaseUrl(config.baseUrl) !== undefined, + }); } + if (failureMessage) store.pushStatus(failureMessage); const oauthErrorCode = flowError ? flowError.code @@ -609,7 +609,7 @@ export async function performOAuthFlow( ? 'timeout' : 'unknown'; - analytics.captureException(error, { + const captureContext = { step: 'oauth_flow', oauth_error_code: oauthErrorCode, oauth_error_description: flowError?.description, @@ -618,9 +618,23 @@ export async function performOAuthFlow( // Collapse OAuth callback failures of the same kind into one issue // instead of fragmenting by each user's install path in the stack trace. $exception_fingerprint: `wizard_oauth_${oauthErrorCode}`, - }); + }; - await abortOnScreens(store); + if (!failureMessage) { + analytics.captureException(error, captureContext); + await abortOnScreens(store); + throw error; + } + const code = accessDenied + ? ErrorCodes.AuthAccessDenied + : ErrorCodes.AuthLoginFailed; + // wizardAbort captures this once; a separate capture here would count the failure twice. + await abortOnScreens(store, { + message: failureMessage, + code, + status: accessDenied ? 'cancelled' : 'error', + error: new WizardError(error.message, captureContext, code), + }); throw error; } } diff --git a/src/tui/auth/project-data.ts b/src/tui/auth/project-data.ts index 8dc328e75..ebf5b7d9c 100644 --- a/src/tui/auth/project-data.ts +++ b/src/tui/auth/project-data.ts @@ -28,6 +28,7 @@ import { } from '@shared/api'; import { abortOnScreens } from '@tui/abort'; import { OutroKind } from '@shared/outro'; +import { ErrorCodes, WizardError } from '@shared/errors'; interface ProjectData { projectApiKey: string; @@ -245,23 +246,31 @@ async function askForWizardLogin(options: { await abortOnScreens(store, { message: error.message }); } - // The issuing region comes with the token; the us/eu @me probe only runs when omitted. - const host = await HostResolution.fromAccessToken( - tokenResponse.access_token, - { + let host: HostResolution; + let projectData: ApiProject; + let userData: ApiUser; + try { + // The issuing region comes with the token; the us/eu @me probe only runs when omitted. + host = await HostResolution.fromAccessToken(tokenResponse.access_token, { region: tokenResponse.posthog_region, localMcp: options.localMcp, baseUrl: options.baseUrl, - }, - ); - const cloudUrl = host.appHost; - - const projectData = await fetchProjectData( - tokenResponse.access_token, - projectId!, - cloudUrl, - ); - const userData = await fetchUserData(tokenResponse.access_token, cloudUrl); + }); + projectData = await fetchProjectData( + tokenResponse.access_token, + projectId!, + host.appHost, + ); + userData = await fetchUserData(tokenResponse.access_token, host.appHost); + } catch (e) { + const reason = e instanceof Error ? e.message : String(e); + // The run's login aborts on this code; tool screens show the message inline and retry. + throw new WizardError( + `You logged in, but the wizard couldn't load your PostHog project: ${reason}\n\nCheck your connection and run the wizard again.`, + undefined, + ErrorCodes.AuthProjectFetchFailed, + ); + } const data = { accessToken: tokenResponse.access_token, diff --git a/src/tui/exit-line.ts b/src/tui/exit-line.ts index fb0f3aaf6..ee10496ff 100644 --- a/src/tui/exit-line.ts +++ b/src/tui/exit-line.ts @@ -16,7 +16,7 @@ import { type WizardStore } from './store.js'; import { totalTokenCount } from '@tui/token-usage'; import { OutroKind } from '@shared/outro'; -import { isRunFailure, MINT_FAILURE_CONTACT } from '@tui/mint-failure'; +import { failureCopy, isRunFailure } from '@tui/mint-failure'; import { formatTokenCount, formatCostUsd } from '@shared/token-pricing'; import { getLogFilePath } from '@utils/debug'; import { readFileHead } from '@utils/bounded-fs'; @@ -106,7 +106,7 @@ function needsAttentionBlock(store: WizardStore): string | null { export function getExitLine(store: WizardStore): string { // A failed run prints its own unavailable notice; the report's warnings don't apply. - const attention = isRunFailure(store.session) + const attention = isRunFailure(store.session, store.router.activeProgram) ? null : needsAttentionBlock(store); const body = exitSummary(store); @@ -119,13 +119,22 @@ function exitSummary(store: WizardStore): string { const costLine = tokenCostLine(store); const loginBlock = mcpLoginBlock(store); - if (isRunFailure(store.session)) { + if (isRunFailure(store.session, store.router.activeProgram)) { const spellbook = store.spellbook; + const { headline, cause, asksAboutLog } = failureCopy( + store.session, + store.router.activeProgram, + ); return [ - 'The wizard is unavailable. Setup has not been completed.', + `${headline}. ${cause}`, spellbook && `${DIM}Point your agent at this skill (triple-click to select):${RESET_ATTRS}\n${spellbook.path}`, - `${DIM}${MINT_FAILURE_CONTACT}${RESET_ATTRS}\n${getLogFilePath()}`, + [ + asksAboutLog && 'We got the error automatically.', + `${DIM}Wizard log:${RESET_ATTRS} ${getLogFilePath()}`, + ] + .filter(Boolean) + .join('\n'), loginBlock, costLine, ] diff --git a/src/tui/mint-failure.ts b/src/tui/mint-failure.ts index c0e497f3e..1b9ff8b76 100644 --- a/src/tui/mint-failure.ts +++ b/src/tui/mint-failure.ts @@ -1,31 +1,221 @@ -import { ErrorCodes } from '@shared/errors'; +import { ErrorCodes, type ErrorCode } from '@shared/errors'; +import { redactSecrets, scrubHomePaths } from '@shared/mcp-clients/results'; +import { getProcessLogTail } from '@utils/debug'; import { OutroKind } from '@shared/outro'; +import { findProgramConfig, Program, type ProgramId } from '@programs'; import type { WizardSession } from '@programs/types'; -export const MINT_FAILURE_MESSAGE = "The Wizard's a little busy"; +type FailureSession = Pick; -export const MINT_FAILURE_BODY = - 'The wizard can still share spells. Grab a skill and let your agent take over.'; +type FailureCopy = { + headline: string; + cause: string; + rerun: string; + asksAboutLog: boolean; + canHandOffToAgent: boolean; +}; -export const MINT_FAILURE_CONTACT = - 'Email wizard@posthog.com and tell us what happened. Please attach this log:'; +const CAPACITY_COPY: FailureCopy = { + headline: 'The wizard is busy right now', + cause: "The wizard's AI service is busy, so setup stopped before finishing.", + rerun: 'Run the wizard again in a few minutes:', + asksAboutLog: true, + canHandOffToAgent: true, +}; -// A security stop or the agent's own [ABORT] is a decision, not an outage: -// it shows its own outro, never the busy handoff. -const DECISIONS = new Set([ - ErrorCodes.AgentYaraViolation, - ErrorCodes.AgentAbort, - ErrorCodes.DetectUnsupportedPlatform, +const RUN_FAILURE_COPY: FailureCopy = { + headline: "The wizard didn't finish", + cause: + 'The wizard ran into a problem partway through and stopped before finishing.', + rerun: 'Run the wizard again:', + asksAboutLog: true, + canHandOffToAgent: true, +}; + +const INTEGRATION_FAILURE_COPY: FailureCopy = { + ...RUN_FAILURE_COPY, + headline: "PostHog isn't set up yet", +}; + +const SAME_COMMAND_RERUN = 'Run the same wizard command again.'; + +const LOGIN_COPY = new Map([ + [ + ErrorCodes.AuthLoginFailed, + { + headline: "You're not logged in yet", + cause: + "PostHog couldn't finish the login, so the wizard stopped before setup.", + rerun: 'Run the wizard again and log in:', + asksAboutLog: true, + canHandOffToAgent: false, + }, + ], + [ + ErrorCodes.AuthProjectFetchFailed, + { + headline: "Your PostHog project didn't load", + cause: "You logged in, but the wizard couldn't load your project.", + rerun: 'Check your connection, then run the wizard again:', + asksAboutLog: true, + canHandOffToAgent: false, + }, + ], + [ + ErrorCodes.AuthAccessDenied, + { + headline: "You didn't authorize the wizard", + cause: 'The wizard needs access to your PostHog account to set it up.', + rerun: 'To try again, run the wizard and approve access:', + asksAboutLog: false, + canHandOffToAgent: false, + }, + ], ]); -/** The agent run ended in an error, whatever the reason. Login failures also - * set an error outro but never had credentials, so they stay on the outro. */ +export const REPORTED_NOTE = 'We got the error automatically.'; + +export const LOG_QUESTION = 'Send your log too?'; + +export const LOG_PROMPT = + 'It helps us find the cause. We mask the keys and tokens we recognize.'; + +export const LOG_SENT_NOTE = 'Log sent. Thanks, it helps us fix this.'; + +export const RERUN_COMMAND = 'npx @posthog/wizard@latest'; + +export const AGENT_HANDOFF_STEP = + 'Or hand it to your own agent. The saved skill has every step.'; + +type FailureRoute = 'outro' | 'run' | 'capacity' | 'login'; + +// Exhaustive so a new code fails typecheck until it picks a route; `outro` keeps its own fix screen. +const FAILURE_ROUTES: Record = { + [ErrorCodes.CliNodeVersion]: 'outro', + [ErrorCodes.CliBadArgs]: 'outro', + [ErrorCodes.CliFlagUnavailable]: 'outro', + [ErrorCodes.CliInteractiveRequired]: 'outro', + [ErrorCodes.ArgsMissingApiKey]: 'outro', + [ErrorCodes.ArgsMissingInstallDir]: 'outro', + [ErrorCodes.ArgsMissingEmail]: 'outro', + [ErrorCodes.ArgsSignupProvisionFailed]: 'outro', + [ErrorCodes.AuthKeyType]: 'outro', + [ErrorCodes.AuthMissingScope]: 'outro', + [ErrorCodes.AuthRegionMismatch]: 'outro', + [ErrorCodes.AuthInvalidOrExpired]: 'outro', + [ErrorCodes.AuthSessionExpired]: 'outro', + [ErrorCodes.AuthSettingsConflict]: 'outro', + [ErrorCodes.AuthStoredLoginConflict]: 'outro', + [ErrorCodes.AuthProjectFetchFailed]: 'login', + [ErrorCodes.AuthLoginFailed]: 'login', + [ErrorCodes.AuthAccessDenied]: 'login', + [ErrorCodes.EnvLocalServicesDown]: 'outro', + [ErrorCodes.EnvServiceOutage]: 'capacity', + [ErrorCodes.DetectBadDirectory]: 'outro', + [ErrorCodes.DetectNoFramework]: 'outro', + [ErrorCodes.DetectUnsupportedVersion]: 'outro', + [ErrorCodes.DetectUnsupportedPlatform]: 'outro', + [ErrorCodes.DetectNoPosthogSdk]: 'outro', + [ErrorCodes.DetectSdkTooOld]: 'outro', + [ErrorCodes.DetectNoProjectFiles]: 'outro', + [ErrorCodes.DetectNoSources]: 'outro', + [ErrorCodes.DetectNoPackageJson]: 'outro', + [ErrorCodes.DetectNoSdks]: 'outro', + [ErrorCodes.DetectMissingStripe]: 'outro', + [ErrorCodes.DetectUnclassified]: 'outro', + [ErrorCodes.SkillMenuFetchFailed]: 'run', + [ErrorCodes.SkillNotFound]: 'outro', + [ErrorCodes.SkillDownloadFailed]: 'run', + [ErrorCodes.AgentAbort]: 'outro', + [ErrorCodes.AgenticDetectionTimeout]: 'run', + [ErrorCodes.AgentMcpMissing]: 'run', + [ErrorCodes.AgentResourceMissing]: 'run', + [ErrorCodes.AgentRateLimit]: 'capacity', + [ErrorCodes.AgentApiError]: 'run', + [ErrorCodes.AgentYaraViolation]: 'outro', + [ErrorCodes.AgentNoProgress]: 'run', + [ErrorCodes.AgentInvalidStructuredOutput]: 'run', + [ErrorCodes.AgentIncompleteTasks]: 'run', + [ErrorCodes.AgentOrchestratorSkillVariantMissing]: 'run', + [ErrorCodes.AgentOrchestratorTasksFailed]: 'run', + [ErrorCodes.AgentOrchestratorTasksBlocked]: 'run', + [ErrorCodes.AgentOrchestratorHollowRun]: 'run', + [ErrorCodes.AgentOrchestratorSinkInvariant]: 'run', + [ErrorCodes.AgentOrchestratorTaskGraph]: 'run', + [ErrorCodes.AgentOrchestratorNoPlanner]: 'run', + [ErrorCodes.GatewayMintRefused]: 'run', + [ErrorCodes.GatewayMintFailed]: 'capacity', + [ErrorCodes.SettingsUnfixableConflict]: 'outro', + [ErrorCodes.InternalUnhandled]: 'run', +}; + +function failureRoute(session: FailureSession): FailureRoute | null { + const outro = session.outroData; + if (outro?.kind !== OutroKind.Error) return null; + const errorCode = outro.errorCode; + return (errorCode && FAILURE_ROUTES[errorCode]) || 'run'; +} + +/** The run ended in an error the handoff screen explains. Only program runs + * wait on the handoff; a tool keeps its own outro. */ export function isRunFailure( - session: Pick, + session: FailureSession, + programId: ProgramId, +): boolean { + if (!findProgramConfig(programId)) return false; + const route = failureRoute(session); + if (route === null || route === 'outro') return false; + if (route === 'login') return true; + return session.credentials !== null; +} + +function isCapacityFailure( + session: FailureSession, + programId: ProgramId, ): boolean { return ( - session.outroData?.kind === OutroKind.Error && - session.credentials !== null && - !DECISIONS.has(session.outroData.errorCode ?? '') + isRunFailure(session, programId) && failureRoute(session) === 'capacity' ); } + +/** The command that reruns the program, or null when the program has no command of its own (a dispatched skill). */ +export function rerunCommand(programId: ProgramId): string | null { + if (programId === Program.PostHogIntegration) return RERUN_COMMAND; + const config = findProgramConfig(programId); + if (!config?.command) return null; + return [RERUN_COMMAND, config.parentCommand, config.command] + .filter(Boolean) + .join(' '); +} + +export function failureReportProperties( + session: FailureSession, + programId: ProgramId, +): Record { + return { + error_code: session.outroData?.errorCode, + message: scrubHomePaths(redactSecrets(session.outroData?.message ?? '')), + is_capacity: isCapacityFailure(session, programId), + log_tail: scrubHomePaths(redactSecrets(getProcessLogTail())), + }; +} + +export function failureCopy( + session: FailureSession, + programId: ProgramId, +): FailureCopy { + const copy = baseFailureCopy(session, programId); + if (rerunCommand(programId) !== null) return copy; + return { ...copy, rerun: SAME_COMMAND_RERUN }; +} + +function baseFailureCopy( + session: FailureSession, + programId: ProgramId, +): FailureCopy { + const loginCopy = LOGIN_COPY.get(session.outroData?.errorCode ?? ''); + if (loginCopy) return loginCopy; + if (isCapacityFailure(session, programId)) return CAPACITY_COPY; + if (programId === Program.PostHogIntegration) return INTEGRATION_FAILURE_COPY; + return RUN_FAILURE_COPY; +} diff --git a/src/tui/router.ts b/src/tui/router.ts index e5425f875..2a08023fd 100644 --- a/src/tui/router.ts +++ b/src/tui/router.ts @@ -60,14 +60,14 @@ export class WizardRouter { const { session } = view; // A failed agent run interrupts every program until the user leaves the // handoff screen: exit, or continue through the post-run steps. - const runFailed = isRunFailure(session); - if (runFailed && view.mintHandoff === 'exit') return ScreenId.Exit; - if (runFailed && !view.mintHandoff) return ScreenId.MintFailure; - if (this.overlays.length > 0) { return this.overlays[this.overlays.length - 1]; } + const runFailed = isRunFailure(session, this.programId); + if (runFailed && view.mintHandoff === 'exit') return ScreenId.Exit; + if (runFailed && !view.mintHandoff) return ScreenId.MintFailure; + // Early aborts must be dismissible even when intro, setup, or auth is incomplete. if ( !runFailed && diff --git a/src/tui/run.ts b/src/tui/run.ts index 51fd686a7..67f1f6ab9 100644 --- a/src/tui/run.ts +++ b/src/tui/run.ts @@ -282,7 +282,7 @@ export async function runTui( } if (signalled) return; - const runFailed = isRunFailure(store.session); + const runFailed = isRunFailure(store.session, store.router.activeProgram); await activeStream.finishRun(runFailed ? 'failed' : 'completed'); // After a failed run the host owns the end: the user leaves the handoff, or // continues through the post-run steps to the exit screen. diff --git a/src/tui/screen-registry.tsx b/src/tui/screen-registry.tsx index 2eb4c5951..c61cfc474 100644 --- a/src/tui/screen-registry.tsx +++ b/src/tui/screen-registry.tsx @@ -11,8 +11,6 @@ */ import type { ReactNode } from 'react'; -import path from 'node:path'; -import { getLogFilePath } from '@utils/debug'; import type { WizardStore } from './store.js'; import { ScreenId, Overlay, type ScreenName } from './router.js'; import { listFlowOwners } from './flow-owner.js'; @@ -49,9 +47,6 @@ export interface ScreenServices extends MintFailureServices { export function createServices(store: WizardStore): ScreenServices { return { - get logPath() { - return path.resolve(getLogFilePath()); - }, openAgent: (agent, spellbookPath) => openCodingAgent(agent, store.session.installDir, spellbookPath), leaveSpellbook: () => diff --git a/src/tui/screens/MintFailureScreen.tsx b/src/tui/screens/MintFailureScreen.tsx index f4b990e7e..7fe6e979d 100644 --- a/src/tui/screens/MintFailureScreen.tsx +++ b/src/tui/screens/MintFailureScreen.tsx @@ -5,9 +5,13 @@ import { PickerMenu } from '@tui/primitives/index'; import { useStdoutDimensions } from '@tui/hooks/useStdoutDimensions'; import { Colors, Icons } from '@tui/styles'; import { - MINT_FAILURE_MESSAGE, - MINT_FAILURE_BODY, - MINT_FAILURE_CONTACT, + AGENT_HANDOFF_STEP, + LOG_PROMPT, + LOG_QUESTION, + LOG_SENT_NOTE, + REPORTED_NOTE, + failureCopy, + rerunCommand, } from '@tui/mint-failure'; import type { WizardSpellbook } from '@tui/services/wizard-spellbook'; import type { CodingAgent } from '../services/coding-agent-launcher'; @@ -15,10 +19,18 @@ import type { CodingAgent } from '../services/coding-agent-launcher'; export type MintFailureServices = { leaveSpellbook: () => Promise; openAgent: (agent: CodingAgent, spellbookPath: string) => Promise; - logPath: string; }; -type Action = 'save' | CodingAgent | 'report' | 'continue' | 'exit' | 'retry'; +type Action = + | 'save' + | CodingAgent + | 'send-log' + | 'keep-log' + | 'continue' + | 'exit' + | 'retry'; + +type LogChoice = 'unanswered' | 'sent' | 'kept'; export function MintFailureScreen({ store, @@ -35,15 +47,21 @@ export function MintFailureScreen({ const busy = useRef(false); const [working, setWorking] = useState(null); const [error, setError] = useState(null); - const [report, setReport] = useState(false); + const [logChoice, setLogChoice] = useState('unanswered'); const [retry, setRetry] = useState<'save' | CodingAgent>('save'); const { spellbook } = store; + const copy = failureCopy(store.session, store.router.activeProgram); + const command = rerunCommand(store.router.activeProgram); const select = async (action: Action) => { if (busy.current) return; if (action === 'exit' || action === 'continue') return store.setMintHandoff(action); - if (action === 'report') return setReport(true); + if (action === 'keep-log') return setLogChoice('kept'); + if (action === 'send-log') { + store.sendFailureReport(); + return setLogChoice('sent'); + } const task = action === 'retry' ? retry : action; setRetry(task); busy.current = true; @@ -71,7 +89,15 @@ export function MintFailureScreen({ } }; - const options: { label: string; value: Action }[] = error + const isAskingAboutLog = + copy.asksAboutLog && logChoice === 'unanswered' && !spellbook && !error; + + const options: { label: string; value: Action }[] = isAskingAboutLog + ? [ + { label: 'Send log and continue', value: 'send-log' }, + { label: 'Continue without sending', value: 'keep-log' }, + ] + : error ? [ { label: 'Try again', value: 'retry' }, ...(spellbook @@ -84,16 +110,14 @@ export function MintFailureScreen({ { label: 'Continue', value: 'continue' }, { label: 'Exit', value: 'exit' }, ] - : report - ? [ - { label: 'Save skill', value: 'save' }, - { label: 'Exit', value: 'exit' }, - ] : [ - { label: 'Save skill', value: 'save' }, - { label: 'Open in Claude Code', value: 'claude' }, - { label: 'Open in Codex', value: 'codex' }, - { label: 'Report this issue', value: 'report' }, + ...(copy.canHandOffToAgent + ? [ + { label: 'Open in Claude Code', value: 'claude' as const }, + { label: 'Open in Codex', value: 'codex' as const }, + { label: 'Save skill', value: 'save' as const }, + ] + : []), { label: 'Exit', value: 'exit' }, ]; @@ -110,30 +134,57 @@ export function MintFailureScreen({ alignItems="center" > {spellbook ? ( - - {Icons.check} Skill saved - + <> + + {Icons.check} Skill saved + + + + {spellbook.skillsIncluded + ? 'Ask your agent to read this file and complete the task.' + : 'The skill could not be downloaded. This file has instructions and links for your agent.'} + + + ) : ( - - ✘ {MINT_FAILURE_MESSAGE} - - )} - - - {spellbook - ? spellbook.skillsIncluded - ? 'Ask your agent to read this file and complete the task.' - : 'The skill could not be downloaded. This file has instructions and links for your agent.' - : report - ? MINT_FAILURE_CONTACT - : MINT_FAILURE_BODY} - - - {report && !spellbook && ( - - - {services.logPath} + + {copy.asksAboutLog && ( + + Step {isAskingAboutLog ? 1 : 2} of 2 + + )} + + ✘ {copy.headline} + {copy.cause} + {copy.asksAboutLog && ( + + {REPORTED_NOTE} + + )} + {logChoice === 'sent' && ( + + + {Icons.check} {LOG_SENT_NOTE} + + + )} + {isAskingAboutLog ? ( + + {LOG_QUESTION} + + {LOG_PROMPT} + + + ) : ( + + • {copy.rerun} + {command && {` ${command}`}} + {copy.canHandOffToAgent && ( + • {AGENT_HANDOFF_STEP} + )} + + )} )} {spellbook && ( @@ -153,7 +204,7 @@ export function MintFailureScreen({ {working} ) : ( void select(action as Action)} /> diff --git a/src/tui/store.ts b/src/tui/store.ts index 288dbb7ae..f39600b42 100644 --- a/src/tui/store.ts +++ b/src/tui/store.ts @@ -44,6 +44,7 @@ import { type ProgramId, } from './router.js'; import { analytics, sessionProperties } from '@utils/analytics'; +import { failureReportProperties } from './mint-failure.js'; import { buildSession, findProgramConfig, @@ -630,6 +631,13 @@ export class WizardStore implements TuiView { }); } + sendFailureReport(): void { + analytics.wizardCapture('failure reported', { + ...sessionProperties(this.session), + ...failureReportProperties(this.session, this.router.activeProgram), + }); + } + setSkillId(skillId: string | null): void { this.sessions.setSkillId(skillId); } @@ -746,6 +754,12 @@ export class WizardStore implements TuiView { this.popOverlay(); } + /** Close the paste-code overlay if it is open, because the login settled without it. */ + closeManualAuthCode(): void { + this._resolveManualAuthCode = null; + if (this.router.activeScreen === Overlay.ManualAuthCode) this.popOverlay(); + } + /** * Submit a manually-entered authorization code: dismiss the overlay and * resolve the in-flight OAuth flow so it can exchange the code for a token.