From 23884ebf538daa14e4254804a554a8622f6eed63 Mon Sep 17 00:00:00 2001 From: John W Date: Wed, 25 Nov 2026 09:05:04 -0700 Subject: [PATCH 01/13] chore(deps): pin pnpm 10.34.9 pnpm 12 refuses the pinned 10.34.5 with "High-risk trust downgrade (possible package takeover)": 10.34.6 and later are published through GitHub trusted publishing, and 10.34.5 was not. Local installs on current pnpm stopped before resolving anything. Moves packageManager (with its sha512), the volta pins and every CI pin to 10.34.9. pnpm install --frozen-lockfile on 10.34.9 leaves pnpm-lock.yaml unchanged. --- .github/workflows/build.yml | 8 ++++---- .github/workflows/mcp-install.yml | 2 +- .github/workflows/provisioning-probe.yml | 2 +- .github/workflows/publish.yml | 2 +- .github/workflows/smoke-test.yml | 2 +- e2e-tests/package.json | 2 +- package.json | 4 ++-- 7 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b4dc9cf94..7b4b13e2b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -16,7 +16,7 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@eae0cfeb286e66ffb5155f1a79b90583a127a68b # v2.4.1 with: - version: 10.34.5 + version: 10.34.9 run_install: false - name: Set up Node uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 @@ -46,7 +46,7 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@eae0cfeb286e66ffb5155f1a79b90583a127a68b # v2.4.1 with: - version: 10.34.5 + version: 10.34.9 run_install: false - name: Set up Node uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 @@ -68,7 +68,7 @@ jobs: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 - uses: pnpm/action-setup@eae0cfeb286e66ffb5155f1a79b90583a127a68b # v2.4.1 with: - version: 10.34.5 + version: 10.34.9 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '22.22.0' @@ -98,7 +98,7 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@eae0cfeb286e66ffb5155f1a79b90583a127a68b # v2.4.1 with: - version: 10.34.5 + version: 10.34.9 run_install: false - name: Set up Node uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 diff --git a/.github/workflows/mcp-install.yml b/.github/workflows/mcp-install.yml index effa8a69d..8977fdda3 100644 --- a/.github/workflows/mcp-install.yml +++ b/.github/workflows/mcp-install.yml @@ -55,7 +55,7 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@eae0cfeb286e66ffb5155f1a79b90583a127a68b # v2.4.1 with: - version: 10.34.5 + version: 10.34.9 run_install: false - name: Set up Node diff --git a/.github/workflows/provisioning-probe.yml b/.github/workflows/provisioning-probe.yml index 2ae7d2e8b..e1fa7964f 100644 --- a/.github/workflows/provisioning-probe.yml +++ b/.github/workflows/provisioning-probe.yml @@ -48,7 +48,7 @@ jobs: if: steps.config.outputs.configured == 'true' uses: pnpm/action-setup@eae0cfeb286e66ffb5155f1a79b90583a127a68b # v2.4.1 with: - version: 10.34.5 + version: 10.34.9 run_install: false - name: Set up Node diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 31f41b174..0d6a42c98 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -49,7 +49,7 @@ jobs: registry-url: https://registry.npmjs.org - name: Install pnpm - run: npm install -g pnpm@10.34.5 + run: npm install -g pnpm@10.34.9 - name: Install package.json dependencies with pnpm run: pnpm install --frozen-lockfile diff --git a/.github/workflows/smoke-test.yml b/.github/workflows/smoke-test.yml index 8b8b6256a..9c5cd6ce7 100644 --- a/.github/workflows/smoke-test.yml +++ b/.github/workflows/smoke-test.yml @@ -35,7 +35,7 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@eae0cfeb286e66ffb5155f1a79b90583a127a68b # v2.4.1 with: - version: 10.34.5 + version: 10.34.9 run_install: false - name: Set up Node diff --git a/e2e-tests/package.json b/e2e-tests/package.json index b30f9adf7..b1b5be2f4 100644 --- a/e2e-tests/package.json +++ b/e2e-tests/package.json @@ -9,6 +9,6 @@ }, "volta": { "node": "20.18.3", - "pnpm": "10.34.5" + "pnpm": "10.34.9" } } diff --git a/package.json b/package.json index 99e0dd584..09f736790 100644 --- a/package.json +++ b/package.json @@ -120,7 +120,7 @@ "node": ">=22.22.0", "npm": ">=3.10.7" }, - "packageManager": "pnpm@10.34.5+sha512.a4ee05f2f73658255bd6a89859c065a45c28a57daefae2c893a168ee2b73168c37b91e83e57ea67654ad03f03031746430e8bce38e362e042605fb8abc80192e", + "packageManager": "pnpm@10.34.9+sha512.f49b5a8ea0fdedb44bb3c0c1d6575092a53c2950d95b7ad15df11f17974877a2de3a01c07e934e9b28ce716e51c09a94962c7306d09be2e1e4b18a8c8762fd32", "scripts": { "clean": "rm -rf ./dist", "prebuild": "pnpm clean && node scripts/generate-version.cjs", @@ -173,7 +173,7 @@ "license": "MIT", "volta": { "node": "24.14.1", - "pnpm": "10.34.5" + "pnpm": "10.34.9" }, "pnpm": { "onlyBuiltDependencies": [ From 703bfee22f9be896d37e951389834ff6d97b3d2a Mon Sep 17 00:00:00 2001 From: John W Date: Wed, 25 Nov 2026 09:13:57 -0700 Subject: [PATCH 02/13] fix(tui): show what failed and offer to send the report A run that failed for any reason other than a deliberate stop showed "The Wizard's a little busy", and the exit line said the wizard was unavailable, even when a task failed (init on a plain HTML site ends in PHW_AGENT_ORCHESTRATOR_TASKS_FAILED). Reporting it meant emailing the log by hand. Only capacity codes (rate limit, API error, mint refused or failed, service outage) keep the busy copy. Every other failure shows "The wizard couldn't finish setup" with the failure message, and the exit line starts with "Setup did not finish:". The handoff screen asks once whether to send the report. Send report captures "wizard: failure reported" with the error code, message, a capacity flag and up to 64 KB of this run's log, read from where this process started writing, with recognized secrets and home paths masked. The manual report option and the email line are gone; the exit line keeps the log path. redactSecrets now masks secrets logged as JSON keys (raw or escaped) and pha_/phr_ tokens, and scrubHomePaths handles JSON-escaped Windows paths, which also tightens the other places that scrub through them. Ticket: task-failure-outro/U2 Confidence: high Scope-risk: moderate --- .../mcp-clients/__tests__/results.test.ts | 15 +++++ src/shared/mcp-clients/results.ts | 9 ++- src/shared/utils/bounded-fs.ts | 26 +++++++++ src/shared/utils/debug.ts | 18 +++++- src/tui/__tests__/MintFailureScreen.test.tsx | 53 +++++++++++++---- .../frames/mint-failure-120x40.txt | 12 ++-- .../frames/mint-failure-80x28.txt | 14 ++--- src/tui/__tests__/exit-line.test.ts | 21 ++++--- src/tui/__tests__/frames.test.tsx | 2 + src/tui/__tests__/store-invariants.test.ts | 2 + src/tui/exit-line.ts | 8 ++- src/tui/mint-failure.ts | 51 +++++++++++++++- src/tui/screen-registry.tsx | 5 -- src/tui/screens/MintFailureScreen.tsx | 58 +++++++++++++------ src/tui/store.ts | 8 +++ 15 files changed, 241 insertions(+), 61 deletions(-) diff --git a/src/shared/mcp-clients/__tests__/results.test.ts b/src/shared/mcp-clients/__tests__/results.test.ts index 32fbb0b34..e8beec94d 100644 --- a/src/shared/mcp-clients/__tests__/results.test.ts +++ b/src/shared/mcp-clients/__tests__/results.test.ts @@ -51,6 +51,15 @@ describe('isOk', () => { }); 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 the bearer token the CLIs echo back in their error output', () => { expect( redactSecrets( @@ -175,6 +184,12 @@ describe('namesWithStatus', () => { }); describe('scrubHomePaths', () => { + 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..06fa5019f 100644 --- a/src/shared/mcp-clients/results.ts +++ b/src/shared/mcp-clients/results.ts @@ -53,7 +53,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[xspcar]_[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]@') @@ -73,6 +73,11 @@ export const redactSecrets = (raw: string): string => .replace( /\b([A-Za-z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?)[A-Za-z0-9_]*)(\s*[=:]\s*)["']?[A-Za-z0-9_\-./+]{8,}["']?/gi, '$1$2[redacted]', + ) + // The same names as JSON keys, raw or escaped, as tool inputs reach the log. + .replace( + /("[A-Za-z0-9_-]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?)[A-Za-z0-9_-]*\\?"\s*:\s*\\?")[^"\\]{4,}/gi, + '$1[redacted]', ); /** @@ -83,7 +88,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]:\\{1,2}Users\\{1,2}[^\\\s'"]+/gi, '~'); /** * A failure that lives entirely in the user's environment: a CLI too old, a diff --git a/src/shared/utils/bounded-fs.ts b/src/shared/utils/bounded-fs.ts index 7a7dcd029..8159ebe23 100644 --- a/src/shared/utils/bounded-fs.ts +++ b/src/shared/utils/bounded-fs.ts @@ -329,6 +329,32 @@ export function safeReadFile( } } +/** The last `bytes` of a file from offset `from` on, without materializing the rest. */ +export function readFileTail( + filePath: string, + bytes: number, + from = 0, +): { text: string; truncated: boolean } | null { + try { + const fd = fs.openSync(filePath, 'r'); + try { + const size = fs.fstatSync(fd).size; + const start = Math.max(from, size - bytes); + const length = Math.max(0, size - start); + const buffer = Buffer.alloc(length); + const read = fs.readSync(fd, buffer, 0, length, start); + return { + text: buffer.toString('utf-8', 0, read), + truncated: start > from, + }; + } finally { + fs.closeSync(fd); + } + } catch { + return null; + } +} + /** * The first `bytes` of a file without materializing the rest. */ diff --git a/src/shared/utils/debug.ts b/src/shared/utils/debug.ts index cc2e0f839..dc6acf13f 100644 --- a/src/shared/utils/debug.ts +++ b/src/shared/utils/debug.ts @@ -1,4 +1,4 @@ -import { appendFileSync, mkdirSync } from 'fs'; +import { appendFileSync, mkdirSync, statSync } from 'fs'; import path from 'path'; import { inspect } from 'node:util'; import { IS_DEV, runtimeEnv } from '@env'; @@ -10,6 +10,8 @@ let logFilePath = let fileLoggingEnabled = true; // An explicit --log-file wins over every later path change while pinned. let logFilePinned = false; +// Byte offset of this process's first line, since every run appends to one shared file. +let processLogStart: number | null = null; function stringify(value: unknown): string { if (typeof value === 'string') return value; @@ -41,6 +43,7 @@ export function configureLogFile(opts: { if (opts.path !== undefined && !logFilePinned) { logFilePath = opts.path; ensuredLogDir = false; + processLogStart = null; } if (opts.pin === true) logFilePinned = true; if (opts.enabled !== undefined) fileLoggingEnabled = opts.enabled; @@ -72,7 +75,20 @@ function reportLogFailureOnce(err: unknown): void { // The log's directory isn't guaranteed to exist (Windows %TEMP%, // POSTHOG_WIZARD_LOG_DIR) — create it on first failure. +function currentLogSize(): number { + try { + return statSync(logFilePath).size; + } catch { + return 0; + } +} + +export function getProcessLogStart(): number | null { + return fileLoggingEnabled ? processLogStart : null; +} + function appendLine(text: string): void { + processLogStart ??= currentLogSize(); try { appendFileSync(logFilePath, text); } catch (err) { diff --git a/src/tui/__tests__/MintFailureScreen.test.tsx b/src/tui/__tests__/MintFailureScreen.test.tsx index 685c8bfaf..7085af627 100644 --- a/src/tui/__tests__/MintFailureScreen.test.tsx +++ b/src/tui/__tests__/MintFailureScreen.test.tsx @@ -7,13 +7,16 @@ import { } from '../screens/MintFailureScreen'; import { KeyboardHintsProvider } from '../hooks/useKeyboardHints'; import { OutroKind } from '@shared/outro'; +import { ErrorCodes, type ErrorCode } from '@shared/errors'; import { HostResolution } from '@shared/host-resolution'; import { ScreenId } from '../router'; +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,7 +29,7 @@ const saved = { }; const delay = () => new Promise((resolve) => setTimeout(resolve, 30)); -function setup() { +function setup(errorCode?: ErrorCode) { const store = new WizardStore(); store.setCredentials({ accessToken: 'tok', @@ -34,11 +37,14 @@ function setup() { host: HostResolution.fromApiHost('https://app.posthog.com'), projectId: 1, }); - store.setOutroData({ kind: OutroKind.Error, message: 'agent failed' }); + store.setOutroData({ + kind: OutroKind.Error, + message: 'agent failed', + errorCode, + }); const services: MintFailureServices = { leaveSpellbook: vi.fn().mockResolvedValue(saved), openAgent: vi.fn().mockResolvedValue(undefined), - logPath: '/tmp/posthog-wizard.log', }; const app = render( @@ -57,12 +63,19 @@ 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 report, 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('Report sent to the wizard team.'); await choose(0); expect(app.lastFrame()).toContain(saved.path); expect(store.mintHandoff).toBeNull(); @@ -78,6 +91,7 @@ it.each(['save', 'open'] as const)( vi.mocked( failure === 'save' ? services.leaveSpellbook : services.openAgent, ).mockRejectedValueOnce(new Error('Unavailable')); + await choose(1); await choose(2); expect(app.lastFrame()).toContain( failure === 'save' ? 'Could not save' : 'Unavailable', @@ -95,8 +109,27 @@ it.each(['save', 'open'] as const)( it('exits without saving or launching', async () => { const { store, services, choose } = setup(); - await choose(4); + await choose(1); + 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.each([ + [ + ErrorCodes.AgentOrchestratorTasksFailed, + "The wizard couldn't finish setup", + true, + ], + [ErrorCodes.GatewayMintRefused, "The Wizard's a little busy", false], +])('heads a %s failure with %s', async (errorCode, headline, showsMessage) => { + const { app } = setup(errorCode); + await delay(); + expect(app.lastFrame()).toContain(headline); + expect(app.lastFrame()?.includes('agent failed')).toBe(showsMessage); +}); diff --git a/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt b/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt index 0d05d3788..e0665bdcf 100644 --- a/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt +++ b/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt @@ -14,15 +14,15 @@ + ✘ The Wizard's a little busy - The wizard can still share spells. Grab a skill and let your agent take over. + Send this failure and this run's wizard log to the wizard team? Keys and + tokens we recognize, and your home folder, are masked first. + + ▸ Send report + Don't send - ▸ Save skill - Open in Claude Code - Open in Codex - Report this issue - Exit diff --git a/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt b/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt index 21aba7dcb..af2d10762 100644 --- a/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt +++ b/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt @@ -8,16 +8,16 @@ + ✘ The Wizard's a little busy - The wizard can still share spells. Grab a skill and let your agent take - over. + Send this failure and this run's wizard log to the wizard team? Keys and + tokens we recognize, and your home folder, are masked first. + + ▸ Send report + Don't send + - ▸ Save skill - Open in Claude Code - Open in Codex - Report this issue - Exit diff --git a/src/tui/__tests__/exit-line.test.ts b/src/tui/__tests__/exit-line.test.ts index fe41666a9..522fab55e 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,8 @@ 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]).toMatch(/^Wizard log: \S/); expect(line).not.toContain('successfully'); }); @@ -252,12 +252,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, 'Setup did not finish: boom'], + [ErrorCodes.AgentRateLimit, 'The wizard is unavailable'], + ])('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 fd75a792f..b97988037 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'; @@ -665,6 +666,7 @@ const FIXTURES: Record = { s.setOutroData({ kind: OutroKind.Error, message: 'The agent run failed', + errorCode: ErrorCodes.GatewayMintRefused, }); }, }, diff --git a/src/tui/__tests__/store-invariants.test.ts b/src/tui/__tests__/store-invariants.test.ts index cc84e4319..5e0099736 100644 --- a/src/tui/__tests__/store-invariants.test.ts +++ b/src/tui/__tests__/store-invariants.test.ts @@ -557,6 +557,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/exit-line.ts b/src/tui/exit-line.ts index fb0f3aaf6..2fc80c4fe 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 { isCapacityFailure, isRunFailure } from '@tui/mint-failure'; import { formatTokenCount, formatCostUsd } from '@shared/token-pricing'; import { getLogFilePath } from '@utils/debug'; import { readFileHead } from '@utils/bounded-fs'; @@ -122,10 +122,12 @@ function exitSummary(store: WizardStore): string { if (isRunFailure(store.session)) { const spellbook = store.spellbook; return [ - 'The wizard is unavailable. Setup has not been completed.', + isCapacityFailure(store.session) + ? 'The wizard is unavailable. Setup has not been completed.' + : `Setup did not finish: ${outro?.message ?? 'the agent run failed.'}`, 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()}`, + `${DIM}Wizard log:${RESET_ATTRS} ${getLogFilePath()}`, loginBlock, costLine, ] diff --git a/src/tui/mint-failure.ts b/src/tui/mint-failure.ts index c0e497f3e..23ee9ac5e 100644 --- a/src/tui/mint-failure.ts +++ b/src/tui/mint-failure.ts @@ -1,4 +1,7 @@ import { ErrorCodes } from '@shared/errors'; +import { redactSecrets, scrubHomePaths } from '@shared/mcp-clients/results'; +import { getLogFilePath, getProcessLogStart } from '@utils/debug'; +import { readFileTail } from '@utils/bounded-fs'; import { OutroKind } from '@shared/outro'; import type { WizardSession } from '@programs/types'; @@ -7,8 +10,14 @@ export const MINT_FAILURE_MESSAGE = "The Wizard's a little busy"; export const MINT_FAILURE_BODY = 'The wizard can still share spells. Grab a skill and let your agent take over.'; -export const MINT_FAILURE_CONTACT = - 'Email wizard@posthog.com and tell us what happened. Please attach this log:'; +export const RUN_FAILURE_HEADLINE = "The wizard couldn't finish setup"; + +export const RUN_FAILURE_BODY = 'Grab a skill and let your agent take over.'; + +export const REPORT_PROMPT = + "Send this failure and this run's wizard log to the wizard team? Keys and tokens we recognize, and your home folder, are masked first."; + +export const REPORT_SENT = 'Report sent to the wizard team.'; // A security stop or the agent's own [ABORT] is a decision, not an outage: // it shows its own outro, never the busy handoff. @@ -29,3 +38,41 @@ export function isRunFailure( !DECISIONS.has(session.outroData.errorCode ?? '') ); } + +const CAPACITY = new Set([ + ErrorCodes.AgentRateLimit, + ErrorCodes.AgentApiError, + ErrorCodes.GatewayMintRefused, + ErrorCodes.GatewayMintFailed, + ErrorCodes.EnvServiceOutage, +]); + +export function isCapacityFailure( + session: Pick, +): boolean { + return ( + isRunFailure(session) && CAPACITY.has(session.outroData?.errorCode ?? '') + ); +} + +const LOG_TAIL_BYTES = 64 * 1024; + +function readRunLog(): string { + const start = getProcessLogStart(); + if (start === null) return ''; + const tail = readFileTail(getLogFilePath(), LOG_TAIL_BYTES, start); + if (tail === null) return '[log unreadable]'; + if (!tail.truncated) return tail.text; + return tail.text.slice(tail.text.indexOf('\n') + 1); +} + +export function failureReportProperties( + session: Pick, +): Record { + return { + error_code: session.outroData?.errorCode, + message: session.outroData?.message, + is_capacity: isCapacityFailure(session), + log_tail: scrubHomePaths(redactSecrets(readRunLog())), + }; +} diff --git a/src/tui/screen-registry.tsx b/src/tui/screen-registry.tsx index f53220765..914028544 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..8623fdb32 100644 --- a/src/tui/screens/MintFailureScreen.tsx +++ b/src/tui/screens/MintFailureScreen.tsx @@ -7,7 +7,11 @@ import { Colors, Icons } from '@tui/styles'; import { MINT_FAILURE_MESSAGE, MINT_FAILURE_BODY, - MINT_FAILURE_CONTACT, + REPORT_PROMPT, + REPORT_SENT, + RUN_FAILURE_BODY, + RUN_FAILURE_HEADLINE, + isCapacityFailure, } from '@tui/mint-failure'; import type { WizardSpellbook } from '@tui/services/wizard-spellbook'; import type { CodingAgent } from '../services/coding-agent-launcher'; @@ -15,10 +19,16 @@ 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-report' + | 'skip-report' + | 'continue' + | 'exit' + | 'retry'; export function MintFailureScreen({ store, @@ -35,15 +45,23 @@ export function MintFailureScreen({ const busy = useRef(false); const [working, setWorking] = useState(null); const [error, setError] = useState(null); - const [report, setReport] = useState(false); + const [reportChoice, setReportChoice] = useState<'sent' | 'skipped' | null>( + null, + ); const [retry, setRetry] = useState<'save' | CodingAgent>('save'); const { spellbook } = store; + const isCapacity = isCapacityFailure(store.session); + const failureMessage = store.session.outroData?.message; 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 === 'skip-report') return setReportChoice('skipped'); + if (action === 'send-report') { + store.sendFailureReport(); + return setReportChoice('sent'); + } const task = action === 'retry' ? retry : action; setRetry(task); busy.current = true; @@ -84,16 +102,15 @@ export function MintFailureScreen({ { label: 'Continue', value: 'continue' }, { label: 'Exit', value: 'exit' }, ] - : report + : reportChoice === null ? [ - { label: 'Save skill', value: 'save' }, - { label: 'Exit', value: 'exit' }, + { label: 'Send report', value: 'send-report' }, + { label: "Don't send", value: 'skip-report' }, ] : [ { label: 'Save skill', value: 'save' }, { label: 'Open in Claude Code', value: 'claude' }, { label: 'Open in Codex', value: 'codex' }, - { label: 'Report this issue', value: 'report' }, { label: 'Exit', value: 'exit' }, ]; @@ -115,25 +132,30 @@ export function MintFailureScreen({ ) : ( - ✘ {MINT_FAILURE_MESSAGE} + ✘ {isCapacity ? MINT_FAILURE_MESSAGE : RUN_FAILURE_HEADLINE} )} + {!spellbook && !isCapacity && failureMessage && ( + + {failureMessage} + + )} {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} + : reportChoice === null + ? REPORT_PROMPT + : isCapacity + ? MINT_FAILURE_BODY + : RUN_FAILURE_BODY} - {report && !spellbook && ( + {reportChoice === 'sent' && !spellbook && ( - - {services.logPath} - + {REPORT_SENT} )} {spellbook && ( @@ -153,7 +175,7 @@ export function MintFailureScreen({ {working} ) : ( void select(action as Action)} /> diff --git a/src/tui/store.ts b/src/tui/store.ts index a99797147..f893b1bda 100644 --- a/src/tui/store.ts +++ b/src/tui/store.ts @@ -45,6 +45,7 @@ import { type ProgramId, } from './router.js'; import { analytics, sessionProperties } from '@utils/analytics'; +import { failureReportProperties } from './mint-failure.js'; import { buildSession, findProgramConfig, @@ -624,6 +625,13 @@ export class WizardStore implements TuiView { }); } + sendFailureReport(): void { + analytics.wizardCapture( + 'failure reported', + failureReportProperties(this.session), + ); + } + setSkillId(skillId: string | null): void { this.sessions.setSkillId(skillId); } From 06b938aca79822faa9c4de06532f0a84e22c794e Mon Sep 17 00:00:00 2001 From: John W Date: Wed, 25 Nov 2026 09:38:54 -0700 Subject: [PATCH 03/13] fix(tui): one failure card with plain copy, log opt-in from the menu The failure screen stacked a headline, the runner's technical message, a send-or-not question and a second menu. It is now one red card with a plain cause and a suggested fix, a line saying the wizard team already knows, and one menu: Send log to the wizard team, Open in Claude Code, Open in Codex, Save skill, Exit. The log stays opt-in, and the item greys out once sent. Capacity failures and every other failure share the same shape with their own copy, and the exit line uses the same words. The report's message now goes through redactSecrets and scrubHomePaths, and secrets logged as JSON values are masked whole, raw or escaped, including escapes, quotes and newlines inside the value. Ticket: task-failure-outro/U2 Confidence: high Scope-risk: moderate --- .../mcp-clients/__tests__/results.test.ts | 12 ++ src/shared/mcp-clients/results.ts | 12 +- src/tui/__tests__/MintFailureScreen.test.tsx | 25 ++-- .../frames/mint-failure-120x40.txt | 32 ++--- .../frames/mint-failure-80x28.txt | 32 ++--- src/tui/__tests__/exit-line.test.ts | 9 +- src/tui/exit-line.ts | 9 +- src/tui/mint-failure.ts | 32 +++-- src/tui/screens/MintFailureScreen.tsx | 110 ++++++++---------- 9 files changed, 148 insertions(+), 125 deletions(-) diff --git a/src/shared/mcp-clients/__tests__/results.test.ts b/src/shared/mcp-clients/__tests__/results.test.ts index e8beec94d..f60c19da0 100644 --- a/src/shared/mcp-clients/__tests__/results.test.ts +++ b/src/shared/mcp-clients/__tests__/results.test.ts @@ -60,6 +60,18 @@ describe('redactSecrets', () => { 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( diff --git a/src/shared/mcp-clients/results.ts b/src/shared/mcp-clients/results.ts index 06fa5019f..c9d7c02e1 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 @@ -76,7 +79,14 @@ export const redactSecrets = (raw: string): string => ) // The same names as JSON keys, raw or escaped, as tool inputs reach the log. .replace( - /("[A-Za-z0-9_-]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?)[A-Za-z0-9_-]*\\?"\s*:\s*\\?")[^"\\]{4,}/gi, + new RegExp( + String.raw`(\\"${SECRET_NAME}\\"\s*:\s*\\")(?:\\\\(?:\\.|[^\\])|\\[^"\\]|[^\\])+`, + 'gi', + ), + '$1[redacted]', + ) + .replace( + new RegExp(String.raw`("${SECRET_NAME}"\s*:\s*")(?:[^"\\]|\\.)+`, 'gi'), '$1[redacted]', ); diff --git a/src/tui/__tests__/MintFailureScreen.test.tsx b/src/tui/__tests__/MintFailureScreen.test.tsx index 7085af627..6635b60c2 100644 --- a/src/tui/__tests__/MintFailureScreen.test.tsx +++ b/src/tui/__tests__/MintFailureScreen.test.tsx @@ -68,15 +68,15 @@ afterEach(() => { vi.clearAllMocks(); }); -it('sends the report, saves the skill, then continues setup', async () => { +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('Report sent to the wizard team.'); - await choose(0); + expect(app.lastFrame()).toContain('Log sent.'); + await choose(2); expect(app.lastFrame()).toContain(saved.path); expect(store.mintHandoff).toBeNull(); await choose(0); @@ -91,7 +91,6 @@ it.each(['save', 'open'] as const)( vi.mocked( failure === 'save' ? services.leaveSpellbook : services.openAgent, ).mockRejectedValueOnce(new Error('Unavailable')); - await choose(1); await choose(2); expect(app.lastFrame()).toContain( failure === 'save' ? 'Could not save' : 'Unavailable', @@ -107,10 +106,9 @@ it.each(['save', 'open'] as const)( }, ); -it('exits without saving or launching', async () => { +it('exits without sending the log, saving or launching', async () => { const { store, services, choose } = setup(); - await choose(1); - await choose(3); + await choose(4); expect(store.mintHandoff).toBe('exit'); expect(wizardCapture).not.toHaveBeenCalledWith( 'failure reported', @@ -121,15 +119,12 @@ it('exits without saving or launching', async () => { }); it.each([ - [ - ErrorCodes.AgentOrchestratorTasksFailed, - "The wizard couldn't finish setup", - true, - ], - [ErrorCodes.GatewayMintRefused, "The Wizard's a little busy", false], -])('heads a %s failure with %s', async (errorCode, headline, showsMessage) => { + [ErrorCodes.AgentOrchestratorTasksFailed, "PostHog isn't set up yet"], + [ErrorCodes.GatewayMintRefused, 'The wizard is busy right now'], +])('heads a %s failure with %s, no error text', async (errorCode, headline) => { const { app } = setup(errorCode); await delay(); expect(app.lastFrame()).toContain(headline); - expect(app.lastFrame()?.includes('agent failed')).toBe(showsMessage); + expect(app.lastFrame()).toContain("We've let the wizard team know."); + expect(app.lastFrame()).not.toContain('agent failed'); }); diff --git a/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt b/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt index e0665bdcf..22ef069bf 100644 --- a/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt +++ b/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt @@ -11,22 +11,22 @@ - - - - - ✘ The Wizard's a little busy - - Send this failure and this run's wizard log to the wizard team? Keys and - tokens we recognize, and your home folder, are masked first. - - ▸ Send report - Don't send - - - - - + ╭────────────────────────────────────────────────────────────────────────────╮ + │ ✘ The wizard is busy right now │ + │ The wizard's AI service is busy, so setup stopped before finishing. │ + │ │ + │ Try this: run the wizard again in a few minutes, or hand the setup to your │ + │ own agent with the saved skill. │ + ╰────────────────────────────────────────────────────────────────────────────╯ + + We've let the wizard team know. Your log stays on this computer unless you + send it. + + ▸ Send log to the wizard team + Open in Claude Code + Open in Codex + Save skill + Exit diff --git a/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt b/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt index af2d10762..9977c941c 100644 --- a/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt +++ b/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt @@ -5,22 +5,22 @@ - - - - - ✘ The Wizard's a little busy - - Send this failure and this run's wizard log to the wizard team? Keys and - tokens we recognize, and your home folder, are masked first. - - ▸ Send report - Don't send - - - - - + ╭──────────────────────────────────────────────────────────────────────────╮ + │ ✘ The wizard is busy right now │ + │ The wizard's AI service is busy, so setup stopped before finishing. │ + │ │ + │ Try this: run the wizard again in a few minutes, or hand the setup to │ + │ your own agent with the saved skill. │ + ╰──────────────────────────────────────────────────────────────────────────╯ + + We've let the wizard team know. Your log stays on this computer unless you + send it. + + ▸ Send log to the wizard team + Open in Claude Code + Open in Codex + Save skill + Exit diff --git a/src/tui/__tests__/exit-line.test.ts b/src/tui/__tests__/exit-line.test.ts index 522fab55e..889ca57e2 100644 --- a/src/tui/__tests__/exit-line.test.ts +++ b/src/tui/__tests__/exit-line.test.ts @@ -50,7 +50,10 @@ describe('getExitLine', () => { const lines = line.split('\n'); expect(lines).toContain(path); expect(line).not.toContain('wizard@posthog.com'); - expect(lines[lines.indexOf(path) + 2]).toMatch(/^Wizard log: \S/); + expect(lines[lines.indexOf(path) + 2]).toBe( + "We've let the wizard team know.", + ); + expect(lines[lines.indexOf(path) + 3]).toMatch(/^Wizard log: \S/); expect(line).not.toContain('successfully'); }); @@ -253,8 +256,8 @@ describe('getExitLine needs-attention block', () => { }); it.each([ - [ErrorCodes.AgentOrchestratorTasksFailed, 'Setup did not finish: boom'], - [ErrorCodes.AgentRateLimit, 'The wizard is unavailable'], + [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, diff --git a/src/tui/exit-line.ts b/src/tui/exit-line.ts index 2fc80c4fe..3c06879fa 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 { isCapacityFailure, isRunFailure } 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'; @@ -121,13 +121,12 @@ function exitSummary(store: WizardStore): string { if (isRunFailure(store.session)) { const spellbook = store.spellbook; + const { headline, cause } = failureCopy(store.session); return [ - isCapacityFailure(store.session) - ? 'The wizard is unavailable. Setup has not been completed.' - : `Setup did not finish: ${outro?.message ?? 'the agent run failed.'}`, + `${headline}. ${cause}`, spellbook && `${DIM}Point your agent at this skill (triple-click to select):${RESET_ATTRS}\n${spellbook.path}`, - `${DIM}Wizard log:${RESET_ATTRS} ${getLogFilePath()}`, + `We've let the wizard team know.\n${DIM}Wizard log:${RESET_ATTRS} ${getLogFilePath()}`, loginBlock, costLine, ] diff --git a/src/tui/mint-failure.ts b/src/tui/mint-failure.ts index 23ee9ac5e..91eb2ca02 100644 --- a/src/tui/mint-failure.ts +++ b/src/tui/mint-failure.ts @@ -5,19 +5,25 @@ import { readFileTail } from '@utils/bounded-fs'; import { OutroKind } from '@shared/outro'; import type { WizardSession } from '@programs/types'; -export const MINT_FAILURE_MESSAGE = "The Wizard's a little busy"; +export type FailureCopy = { headline: string; cause: string; fix: string }; -export const MINT_FAILURE_BODY = - 'The wizard can still share spells. Grab a skill and let your agent take over.'; +const CAPACITY_COPY: FailureCopy = { + headline: 'The wizard is busy right now', + cause: "The wizard's AI service is busy, so setup stopped before finishing.", + fix: 'Try this: run the wizard again in a few minutes, or hand the setup to your own agent with the saved skill.', +}; -export const RUN_FAILURE_HEADLINE = "The wizard couldn't finish setup"; +const RUN_FAILURE_COPY: FailureCopy = { + headline: "PostHog isn't set up yet", + cause: + 'The wizard ran into a problem partway through and stopped before finishing.', + fix: 'Try this: run the wizard again, or hand the setup to your own agent with the saved skill.', +}; -export const RUN_FAILURE_BODY = 'Grab a skill and let your agent take over.'; +export const REPORTED_NOTE = + "We've let the wizard team know. Your log stays on this computer unless you send it."; -export const REPORT_PROMPT = - "Send this failure and this run's wizard log to the wizard team? Keys and tokens we recognize, and your home folder, are masked first."; - -export const REPORT_SENT = 'Report sent to the wizard team.'; +export const LOG_SENT_NOTE = 'Log sent. Thanks, it helps us fix this.'; // A security stop or the agent's own [ABORT] is a decision, not an outage: // it shows its own outro, never the busy handoff. @@ -71,8 +77,14 @@ export function failureReportProperties( ): Record { return { error_code: session.outroData?.errorCode, - message: session.outroData?.message, + message: scrubHomePaths(redactSecrets(session.outroData?.message ?? '')), is_capacity: isCapacityFailure(session), log_tail: scrubHomePaths(redactSecrets(readRunLog())), }; } + +export function failureCopy( + session: Pick, +): FailureCopy { + return isCapacityFailure(session) ? CAPACITY_COPY : RUN_FAILURE_COPY; +} diff --git a/src/tui/screens/MintFailureScreen.tsx b/src/tui/screens/MintFailureScreen.tsx index 8623fdb32..c08e5b0e7 100644 --- a/src/tui/screens/MintFailureScreen.tsx +++ b/src/tui/screens/MintFailureScreen.tsx @@ -4,15 +4,7 @@ import type { WizardStore } from '@tui/store'; 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, - REPORT_PROMPT, - REPORT_SENT, - RUN_FAILURE_BODY, - RUN_FAILURE_HEADLINE, - isCapacityFailure, -} from '@tui/mint-failure'; +import { LOG_SENT_NOTE, REPORTED_NOTE, failureCopy } from '@tui/mint-failure'; import type { WizardSpellbook } from '@tui/services/wizard-spellbook'; import type { CodingAgent } from '../services/coding-agent-launcher'; @@ -21,14 +13,7 @@ export type MintFailureServices = { openAgent: (agent: CodingAgent, spellbookPath: string) => Promise; }; -type Action = - | 'save' - | CodingAgent - | 'send-report' - | 'skip-report' - | 'continue' - | 'exit' - | 'retry'; +type Action = 'save' | CodingAgent | 'send-log' | 'continue' | 'exit' | 'retry'; export function MintFailureScreen({ store, @@ -45,22 +30,18 @@ export function MintFailureScreen({ const busy = useRef(false); const [working, setWorking] = useState(null); const [error, setError] = useState(null); - const [reportChoice, setReportChoice] = useState<'sent' | 'skipped' | null>( - null, - ); + const [isLogSent, setIsLogSent] = useState(false); const [retry, setRetry] = useState<'save' | CodingAgent>('save'); const { spellbook } = store; - const isCapacity = isCapacityFailure(store.session); - const failureMessage = store.session.outroData?.message; + const copy = failureCopy(store.session); const select = async (action: Action) => { if (busy.current) return; if (action === 'exit' || action === 'continue') return store.setMintHandoff(action); - if (action === 'skip-report') return setReportChoice('skipped'); - if (action === 'send-report') { + if (action === 'send-log') { store.sendFailureReport(); - return setReportChoice('sent'); + return setIsLogSent(true); } const task = action === 'retry' ? retry : action; setRetry(task); @@ -89,7 +70,7 @@ export function MintFailureScreen({ } }; - const options: { label: string; value: Action }[] = error + const options: { label: string; value: Action; disabled?: boolean }[] = error ? [ { label: 'Try again', value: 'retry' }, ...(spellbook @@ -102,15 +83,15 @@ export function MintFailureScreen({ { label: 'Continue', value: 'continue' }, { label: 'Exit', value: 'exit' }, ] - : reportChoice === null - ? [ - { label: 'Send report', value: 'send-report' }, - { label: "Don't send", value: 'skip-report' }, - ] : [ - { label: 'Save skill', value: 'save' }, + { + label: 'Send log to the wizard team', + value: 'send-log', + disabled: isLogSent, + }, { label: 'Open in Claude Code', value: 'claude' }, { label: 'Open in Codex', value: 'codex' }, + { label: 'Save skill', value: 'save' }, { label: 'Exit', value: 'exit' }, ]; @@ -127,35 +108,46 @@ 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.'} + + + ) : ( - - ✘ {isCapacity ? MINT_FAILURE_MESSAGE : RUN_FAILURE_HEADLINE} - - )} - {!spellbook && !isCapacity && failureMessage && ( - - {failureMessage} + + + ✘ {copy.headline} + + {copy.cause} + + {copy.fix} + )} - - - {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.' - : reportChoice === null - ? REPORT_PROMPT - : isCapacity - ? MINT_FAILURE_BODY - : RUN_FAILURE_BODY} - - - {reportChoice === 'sent' && !spellbook && ( - - {REPORT_SENT} + {!spellbook && ( + + {isLogSent ? ( + + {Icons.check} {LOG_SENT_NOTE} + + ) : ( + + {REPORTED_NOTE} + + )} )} {spellbook && ( @@ -175,7 +167,7 @@ export function MintFailureScreen({ {working} ) : ( void select(action as Action)} /> From a9d0469a0a4a160fec778f602effb856c703cdbc Mon Sep 17 00:00:00 2001 From: John W Date: Wed, 25 Nov 2026 10:08:12 -0700 Subject: [PATCH 04/13] fix(tui): drop the failure card border, say the error came without the log The red border made the screen busy; the red headline already marks the error. "We've let the wizard team know" read as if the log had gone too, next to the opt-in Send log item, so the note now says the error came in automatically but not the log. The exit line keeps only the first half, which holds whether or not the log was sent. Ticket: task-failure-outro/U2 Confidence: high Scope-risk: narrow --- src/tui/__tests__/MintFailureScreen.test.tsx | 4 +++- .../frames/mint-failure-120x40.txt | 18 +++++++++--------- .../frames/mint-failure-80x28.txt | 18 +++++++++--------- src/tui/__tests__/exit-line.test.ts | 2 +- src/tui/exit-line.ts | 2 +- src/tui/mint-failure.ts | 2 +- src/tui/screens/MintFailureScreen.tsx | 8 +------- 7 files changed, 25 insertions(+), 29 deletions(-) diff --git a/src/tui/__tests__/MintFailureScreen.test.tsx b/src/tui/__tests__/MintFailureScreen.test.tsx index 6635b60c2..b3f34c2a7 100644 --- a/src/tui/__tests__/MintFailureScreen.test.tsx +++ b/src/tui/__tests__/MintFailureScreen.test.tsx @@ -125,6 +125,8 @@ it.each([ const { app } = setup(errorCode); await delay(); expect(app.lastFrame()).toContain(headline); - expect(app.lastFrame()).toContain("We've let the wizard team know."); + expect(app.lastFrame()).toContain( + 'We got the error automatically, but not your log.', + ); expect(app.lastFrame()).not.toContain('agent failed'); }); diff --git a/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt b/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt index 22ef069bf..3f066af4b 100644 --- a/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt +++ b/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt @@ -11,16 +11,15 @@ - ╭────────────────────────────────────────────────────────────────────────────╮ - │ ✘ The wizard is busy right now │ - │ The wizard's AI service is busy, so setup stopped before finishing. │ - │ │ - │ Try this: run the wizard again in a few minutes, or hand the setup to your │ - │ own agent with the saved skill. │ - ╰────────────────────────────────────────────────────────────────────────────╯ - We've let the wizard team know. Your log stays on this computer unless you - send it. + ✘ The wizard is busy right now + The wizard's AI service is busy, so setup stopped before finishing. + + Try this: run the wizard again in a few minutes, or hand the setup to your own + agent with the saved skill. + + We got the error automatically, but not your log. Sending it helps us find the + cause. ▸ Send log to the wizard team Open in Claude Code @@ -36,4 +35,5 @@ + ↑↓ navigate enter select diff --git a/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt b/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt index 9977c941c..ba2ef7fd0 100644 --- a/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt +++ b/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt @@ -5,16 +5,15 @@ - ╭──────────────────────────────────────────────────────────────────────────╮ - │ ✘ The wizard is busy right now │ - │ The wizard's AI service is busy, so setup stopped before finishing. │ - │ │ - │ Try this: run the wizard again in a few minutes, or hand the setup to │ - │ your own agent with the saved skill. │ - ╰──────────────────────────────────────────────────────────────────────────╯ - We've let the wizard team know. Your log stays on this computer unless you - send it. + ✘ The wizard is busy right now + The wizard's AI service is busy, so setup stopped before finishing. + + Try this: run the wizard again in a few minutes, or hand the setup to your + own agent with the saved skill. + + We got the error automatically, but not your log. Sending it helps us find + the cause. ▸ Send log to the wizard team Open in Claude Code @@ -24,4 +23,5 @@ + ↑↓ navigate enter select diff --git a/src/tui/__tests__/exit-line.test.ts b/src/tui/__tests__/exit-line.test.ts index 889ca57e2..4e5951656 100644 --- a/src/tui/__tests__/exit-line.test.ts +++ b/src/tui/__tests__/exit-line.test.ts @@ -51,7 +51,7 @@ describe('getExitLine', () => { expect(lines).toContain(path); expect(line).not.toContain('wizard@posthog.com'); expect(lines[lines.indexOf(path) + 2]).toBe( - "We've let the wizard team know.", + 'We got the error automatically.', ); expect(lines[lines.indexOf(path) + 3]).toMatch(/^Wizard log: \S/); expect(line).not.toContain('successfully'); diff --git a/src/tui/exit-line.ts b/src/tui/exit-line.ts index 3c06879fa..e9f6805e2 100644 --- a/src/tui/exit-line.ts +++ b/src/tui/exit-line.ts @@ -126,7 +126,7 @@ function exitSummary(store: WizardStore): string { `${headline}. ${cause}`, spellbook && `${DIM}Point your agent at this skill (triple-click to select):${RESET_ATTRS}\n${spellbook.path}`, - `We've let the wizard team know.\n${DIM}Wizard log:${RESET_ATTRS} ${getLogFilePath()}`, + `We got the error automatically.\n${DIM}Wizard log:${RESET_ATTRS} ${getLogFilePath()}`, loginBlock, costLine, ] diff --git a/src/tui/mint-failure.ts b/src/tui/mint-failure.ts index 91eb2ca02..75f3bc192 100644 --- a/src/tui/mint-failure.ts +++ b/src/tui/mint-failure.ts @@ -21,7 +21,7 @@ const RUN_FAILURE_COPY: FailureCopy = { }; export const REPORTED_NOTE = - "We've let the wizard team know. Your log stays on this computer unless you send it."; + 'We got the error automatically, but not your log. Sending it helps us find the cause.'; export const LOG_SENT_NOTE = 'Log sent. Thanks, it helps us fix this.'; diff --git a/src/tui/screens/MintFailureScreen.tsx b/src/tui/screens/MintFailureScreen.tsx index c08e5b0e7..b1d9341aa 100644 --- a/src/tui/screens/MintFailureScreen.tsx +++ b/src/tui/screens/MintFailureScreen.tsx @@ -121,13 +121,7 @@ export function MintFailureScreen({ ) : ( - + ✘ {copy.headline} From 1fa5fd7b0b9fad9eacd862b5f4e502338d40528d Mon Sep 17 00:00:00 2001 From: John W Date: Wed, 25 Nov 2026 10:20:43 -0700 Subject: [PATCH 05/13] feat(tui): split the failure screen into a log question and retry steps One screen held what happened, the log question and every way to finish, which read as busy. Step 1 says what happened, that the error already reached us, and asks Send log or Don't send. Either answer moves to step 2, "Finish setting up PostHog": run the wizard again (in a few minutes when busy), or hand the setup to your own agent, with Open in Claude Code, Open in Codex, Save skill and Exit. The log prompt says we mask the keys and tokens we recognize, which is what the redaction covers. Ticket: task-failure-outro/U2 Confidence: high Scope-risk: narrow --- src/tui/__tests__/MintFailureScreen.test.tsx | 31 +++++--- .../frames/mint-failure-120x40.txt | 20 ++--- .../frames/mint-failure-80x28.txt | 20 ++--- src/tui/mint-failure.ts | 19 +++-- src/tui/screens/MintFailureScreen.tsx | 76 +++++++++++++------ 5 files changed, 104 insertions(+), 62 deletions(-) diff --git a/src/tui/__tests__/MintFailureScreen.test.tsx b/src/tui/__tests__/MintFailureScreen.test.tsx index b3f34c2a7..6cddb9250 100644 --- a/src/tui/__tests__/MintFailureScreen.test.tsx +++ b/src/tui/__tests__/MintFailureScreen.test.tsx @@ -76,6 +76,7 @@ it('sends the log, saves the skill, then continues setup', async () => { expect.objectContaining({ message: 'agent failed', is_capacity: false }), ); expect(app.lastFrame()).toContain('Log sent.'); + expect(app.lastFrame()).toContain('Finish setting up PostHog'); await choose(2); expect(app.lastFrame()).toContain(saved.path); expect(store.mintHandoff).toBeNull(); @@ -91,7 +92,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', ); @@ -107,8 +109,10 @@ it.each(['save', 'open'] as const)( ); it('exits without sending the log, saving or launching', async () => { - const { store, services, choose } = setup(); - await choose(4); + 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', @@ -121,12 +125,15 @@ it('exits without sending the log, saving or launching', async () => { it.each([ [ErrorCodes.AgentOrchestratorTasksFailed, "PostHog isn't set up yet"], [ErrorCodes.GatewayMintRefused, 'The wizard is busy right now'], -])('heads a %s failure with %s, no error text', async (errorCode, headline) => { - const { app } = setup(errorCode); - await delay(); - expect(app.lastFrame()).toContain(headline); - expect(app.lastFrame()).toContain( - 'We got the error automatically, but not your log.', - ); - expect(app.lastFrame()).not.toContain('agent failed'); -}); +])( + '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'); + }, +); diff --git a/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt b/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt index 3f066af4b..daffb7a54 100644 --- a/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt +++ b/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt @@ -12,20 +12,20 @@ + + ✘ The wizard is busy right now - The wizard's AI service is busy, so setup stopped before finishing. + The wizard's AI service is busy, so setup stopped before finishing. We got the + error automatically. + + Send your log too? It helps us find the cause. We mask the keys and tokens we + recognize. + + ▸ Send log + Don't send - Try this: run the wizard again in a few minutes, or hand the setup to your own - agent with the saved skill. - We got the error automatically, but not your log. Sending it helps us find the - cause. - ▸ Send log to the wizard team - Open in Claude Code - Open in Codex - Save skill - Exit diff --git a/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt b/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt index ba2ef7fd0..e4e47a7c3 100644 --- a/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt +++ b/src/tui/__tests__/__snapshots__/frames/mint-failure-80x28.txt @@ -6,20 +6,20 @@ + + ✘ The wizard is busy right now - The wizard's AI service is busy, so setup stopped before finishing. + The wizard's AI service is busy, so setup stopped before finishing. We got + the error automatically. + + Send your log too? It helps us find the cause. We mask the keys and tokens + we recognize. + + ▸ Send log + Don't send - Try this: run the wizard again in a few minutes, or hand the setup to your - own agent with the saved skill. - We got the error automatically, but not your log. Sending it helps us find - the cause. - ▸ Send log to the wizard team - Open in Claude Code - Open in Codex - Save skill - Exit diff --git a/src/tui/mint-failure.ts b/src/tui/mint-failure.ts index 75f3bc192..a9807e9be 100644 --- a/src/tui/mint-failure.ts +++ b/src/tui/mint-failure.ts @@ -5,26 +5,35 @@ import { readFileTail } from '@utils/bounded-fs'; import { OutroKind } from '@shared/outro'; import type { WizardSession } from '@programs/types'; -export type FailureCopy = { headline: string; cause: string; fix: string }; +export type FailureCopy = { headline: string; cause: string; rerun: string }; const CAPACITY_COPY: FailureCopy = { headline: 'The wizard is busy right now', cause: "The wizard's AI service is busy, so setup stopped before finishing.", - fix: 'Try this: run the wizard again in a few minutes, or hand the setup to your own agent with the saved skill.', + rerun: 'Run the wizard again in a few minutes:', }; const RUN_FAILURE_COPY: FailureCopy = { headline: "PostHog isn't set up yet", cause: 'The wizard ran into a problem partway through and stopped before finishing.', - fix: 'Try this: run the wizard again, or hand the setup to your own agent with the saved skill.', + rerun: 'Run the wizard again:', }; -export const REPORTED_NOTE = - 'We got the error automatically, but not your log. Sending it helps us find the cause.'; +export const REPORTED_NOTE = 'We got the error automatically.'; + +export const LOG_PROMPT = + 'Send your log too? 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 RETRY_HEADLINE = 'Finish setting up PostHog'; + +export const RERUN_COMMAND = 'npx @posthog/wizard@latest'; + +export const AGENT_HANDOFF_STEP = + 'Or hand the setup to your own agent. The saved skill has every step.'; + // 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([ diff --git a/src/tui/screens/MintFailureScreen.tsx b/src/tui/screens/MintFailureScreen.tsx index b1d9341aa..f6fe748e7 100644 --- a/src/tui/screens/MintFailureScreen.tsx +++ b/src/tui/screens/MintFailureScreen.tsx @@ -4,7 +4,15 @@ import type { WizardStore } from '@tui/store'; import { PickerMenu } from '@tui/primitives/index'; import { useStdoutDimensions } from '@tui/hooks/useStdoutDimensions'; import { Colors, Icons } from '@tui/styles'; -import { LOG_SENT_NOTE, REPORTED_NOTE, failureCopy } from '@tui/mint-failure'; +import { + AGENT_HANDOFF_STEP, + LOG_PROMPT, + LOG_SENT_NOTE, + REPORTED_NOTE, + RERUN_COMMAND, + RETRY_HEADLINE, + failureCopy, +} from '@tui/mint-failure'; import type { WizardSpellbook } from '@tui/services/wizard-spellbook'; import type { CodingAgent } from '../services/coding-agent-launcher'; @@ -13,7 +21,16 @@ export type MintFailureServices = { openAgent: (agent: CodingAgent, spellbookPath: string) => Promise; }; -type Action = 'save' | CodingAgent | 'send-log' | 'continue' | 'exit' | 'retry'; +type Action = + | 'save' + | CodingAgent + | 'send-log' + | 'keep-log' + | 'continue' + | 'exit' + | 'retry'; + +type LogChoice = 'unanswered' | 'sent' | 'kept'; export function MintFailureScreen({ store, @@ -30,7 +47,7 @@ export function MintFailureScreen({ const busy = useRef(false); const [working, setWorking] = useState(null); const [error, setError] = useState(null); - const [isLogSent, setIsLogSent] = useState(false); + const [logChoice, setLogChoice] = useState('unanswered'); const [retry, setRetry] = useState<'save' | CodingAgent>('save'); const { spellbook } = store; const copy = failureCopy(store.session); @@ -39,9 +56,10 @@ export function MintFailureScreen({ if (busy.current) return; if (action === 'exit' || action === 'continue') return store.setMintHandoff(action); + if (action === 'keep-log') return setLogChoice('kept'); if (action === 'send-log') { store.sendFailureReport(); - return setIsLogSent(true); + return setLogChoice('sent'); } const task = action === 'retry' ? retry : action; setRetry(task); @@ -70,7 +88,14 @@ export function MintFailureScreen({ } }; - const options: { label: string; value: Action; disabled?: boolean }[] = error + const isAskingAboutLog = logChoice === 'unanswered' && !spellbook && !error; + + const options: { label: string; value: Action }[] = isAskingAboutLog + ? [ + { label: 'Send log', value: 'send-log' }, + { label: "Don't send", value: 'keep-log' }, + ] + : error ? [ { label: 'Try again', value: 'retry' }, ...(spellbook @@ -84,11 +109,6 @@ export function MintFailureScreen({ { label: 'Exit', value: 'exit' }, ] : [ - { - label: 'Send log to the wizard team', - value: 'send-log', - disabled: isLogSent, - }, { label: 'Open in Claude Code', value: 'claude' }, { label: 'Open in Codex', value: 'codex' }, { label: 'Save skill', value: 'save' }, @@ -120,28 +140,34 @@ export function MintFailureScreen({ - ) : ( + ) : isAskingAboutLog ? ( ✘ {copy.headline} - {copy.cause} + + {copy.cause} {REPORTED_NOTE} + - {copy.fix} + {LOG_PROMPT} - )} - {!spellbook && ( - - {isLogSent ? ( - - {Icons.check} {LOG_SENT_NOTE} - - ) : ( - - {REPORTED_NOTE} - + ) : ( + + {logChoice === 'sent' && ( + + + {Icons.check} {LOG_SENT_NOTE} + + )} + {RETRY_HEADLINE} + + + 1. {copy.rerun} {RERUN_COMMAND} + + + 2. {AGENT_HANDOFF_STEP} )} {spellbook && ( @@ -161,7 +187,7 @@ export function MintFailureScreen({ {working} ) : ( void select(action as Action)} /> From fb5afddadde1f9bb9fd3faa7461ae046e4d7f985 Mon Sep 17 00:00:00 2001 From: John W Date: Wed, 25 Nov 2026 11:10:02 -0700 Subject: [PATCH 06/13] feat(tui): step-labelled failure screen that also covers failed logins Review found the two steps read as two screens and leaned on sub-headers. Both steps now keep the same red headline under a dim "Step N of 2", bullets replace the numbered list, the command sits on its own line, and the log choices read "Send log and continue" / "Continue without sending", since "try again" sounded like the wizard would retry. A failed login ended on the generic outro with the raw error and OAuth bug-report details. Login failures with PHW_AUTH_LOGIN_FAILED or PHW_AUTH_PROJECT_FETCH_FAILED now take the same two steps, minus the agent handoff, which needs a project. PHW_AUTH_ACCESS_DENIED is a decision: one screen, no log question. The two new codes are for the login abort to emit. Ticket: task-failure-outro/U2 Confidence: high Scope-risk: moderate --- docs/error-catalog.md | 18 ++--- src/shared/errors/catalog.ts | 12 ++++ src/shared/errors/codes.ts | 2 + src/tui/__tests__/MintFailureScreen.test.tsx | 28 +++++--- .../frames/mint-failure-120x40.txt | 14 ++-- .../frames/mint-failure-80x28.txt | 14 ++-- src/tui/exit-line.ts | 9 ++- src/tui/mint-failure.ts | 66 ++++++++++++++++--- src/tui/screens/MintFailureScreen.tsx | 66 ++++++++++++------- 9 files changed, 163 insertions(+), 66 deletions(-) diff --git a/docs/error-catalog.md b/docs/error-catalog.md index a6862c9f1..68690b3b9 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 | @@ -113,8 +115,8 @@ screen, debug log) keep the full detail. | `PHW_AGENT_ORCHESTRATOR_NO_PLANNER` | agent | the flow the orchestrator fetched has no planner prompt | no | | `PHW_SETTINGS_UNFIXABLE_CONFLICT` | settings | Claude settings conflict that cannot be auto-neutralized (managed/unwritable) | no | | `PHW_INTERNAL_UNHANDLED` | internal | catch-all: an unexpected error escaped the pipeline | yes | -| `PHW_GATEWAY_MINT_REFUSED` | gateway | the gateway-token mint refused this run (blocked, throttled, unlisted program); the server's reason is shown | no | -| `PHW_GATEWAY_MINT_FAILED` | gateway | the gateway-token mint could not be reached or answered unusably | yes | +| `PHW_GATEWAY_MINT_REFUSED` | gateway | the gateway-token mint refused this run (blocked, throttled, unlisted program); the server's reason is shown | no | +| `PHW_GATEWAY_MINT_FAILED` | gateway | the gateway-token mint could not be reached or answered unusably | yes | Retry advice is guidance for automated hosts (sandbox re-run policies), not a guarantee. @@ -123,8 +125,8 @@ guarantee. Program detect steps write `{ kind, ...detail }` into `session.frameworkContext.detectError`. `detectErrorCode()` -([`src/programs/program-runner/detect-map.ts`](../src/programs/program-runner/detect-map.ts)) maps `kind` -→ code, and the whole object — `kind` included — rides along as +([`src/programs/program-runner/detect-map.ts`](../src/programs/program-runner/detect-map.ts)) +maps `kind` → code, and the whole object — `kind` included — rides along as `OutroData.errorDetail`. `DETECT_CODES` is keyed on `DetectErrorKind`, a union assembled from the @@ -168,9 +170,9 @@ no distinguishing signal is available. The Pi harness reports every 401 as 1. Add the code to `ErrorCodes` (`codes.ts`) and an entry to `ERROR_CATALOG` (`catalog.ts`) — the unit test enforces catalog completeness. -2. Pass it to `wizardAbort(host, { code })` or `new WizardError(msg, ctx, - code)` at the failure site. Prefer explicit `code` over inference so call - sites stay greppable. For agent-emitted `[ABORT] ` preconditions, - declare `errorCode` on the program's `abortCases` entry so the generic +2. Pass it to `wizardAbort(host, { code })` or `new WizardError(msg, ctx, code)` + at the failure site. Prefer explicit `code` over inference so call sites stay + greppable. For agent-emitted `[ABORT] ` preconditions, declare + `errorCode` on the program's `abortCases` entry so the generic `PHW_AGENT_ABORT` is overridden with the specific class. 3. Add the row here. diff --git a/src/shared/errors/catalog.ts b/src/shared/errors/catalog.ts index 92cd4f8a1..4766e8a23 100644 --- a/src/shared/errors/catalog.ts +++ b/src/shared/errors/catalog.ts @@ -85,6 +85,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 1f3678ebc..3325fd1c1 100644 --- a/src/shared/errors/codes.ts +++ b/src/shared/errors/codes.ts @@ -16,6 +16,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/tui/__tests__/MintFailureScreen.test.tsx b/src/tui/__tests__/MintFailureScreen.test.tsx index 6cddb9250..741303800 100644 --- a/src/tui/__tests__/MintFailureScreen.test.tsx +++ b/src/tui/__tests__/MintFailureScreen.test.tsx @@ -29,14 +29,15 @@ const saved = { }; const delay = () => new Promise((resolve) => setTimeout(resolve, 30)); -function setup(errorCode?: ErrorCode) { +function setup(errorCode?: ErrorCode, isLoggedIn = true) { const store = new WizardStore(); - store.setCredentials({ - accessToken: 'tok', - projectApiKey: 'pk', - host: HostResolution.fromApiHost('https://app.posthog.com'), - projectId: 1, - }); + 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', @@ -76,7 +77,7 @@ it('sends the log, saves the skill, then continues setup', async () => { expect.objectContaining({ message: 'agent failed', is_capacity: false }), ); expect(app.lastFrame()).toContain('Log sent.'); - expect(app.lastFrame()).toContain('Finish setting up PostHog'); + expect(app.lastFrame()).toContain('Step 2 of 2'); await choose(2); expect(app.lastFrame()).toContain(saved.path); expect(store.mintHandoff).toBeNull(); @@ -137,3 +138,14 @@ it.each([ 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'); +}); diff --git a/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt b/src/tui/__tests__/__snapshots__/frames/mint-failure-120x40.txt index daffb7a54..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 is busy right now - The wizard's AI service is busy, so setup stopped before finishing. We got the - error automatically. + The wizard's AI service is busy, so setup stopped before finishing. + We got the error automatically. - Send your log too? It helps us find the cause. We mask the keys and tokens we - recognize. - - ▸ Send log - Don't send + 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 e4e47a7c3..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 is busy right now - The wizard's AI service is busy, so setup stopped before finishing. We got - the error automatically. + The wizard's AI service is busy, so setup stopped before finishing. + We got the error automatically. - Send your log too? It helps us find the cause. We mask the keys and tokens - we recognize. - - ▸ Send log - Don't send + 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/exit-line.ts b/src/tui/exit-line.ts index e9f6805e2..e0760f750 100644 --- a/src/tui/exit-line.ts +++ b/src/tui/exit-line.ts @@ -121,12 +121,17 @@ function exitSummary(store: WizardStore): string { if (isRunFailure(store.session)) { const spellbook = store.spellbook; - const { headline, cause } = failureCopy(store.session); + const { headline, cause, asksAboutLog } = failureCopy(store.session); return [ `${headline}. ${cause}`, spellbook && `${DIM}Point your agent at this skill (triple-click to select):${RESET_ATTRS}\n${spellbook.path}`, - `We got the error automatically.\n${DIM}Wizard log:${RESET_ATTRS} ${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 a9807e9be..b4a27d581 100644 --- a/src/tui/mint-failure.ts +++ b/src/tui/mint-failure.ts @@ -5,12 +5,20 @@ import { readFileTail } from '@utils/bounded-fs'; import { OutroKind } from '@shared/outro'; import type { WizardSession } from '@programs/types'; -export type FailureCopy = { headline: string; cause: string; rerun: string }; +export type FailureCopy = { + headline: string; + cause: string; + rerun: string; + asksAboutLog: boolean; + canHandOffToAgent: boolean; +}; 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, }; const RUN_FAILURE_COPY: FailureCopy = { @@ -18,21 +26,57 @@ const RUN_FAILURE_COPY: FailureCopy = { cause: 'The wizard ran into a problem partway through and stopped before finishing.', rerun: 'Run the wizard again:', + asksAboutLog: true, + canHandOffToAgent: true, }; +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, + }, + ], +]); + export const REPORTED_NOTE = 'We got the error automatically.'; +export const LOG_QUESTION = 'Send your log too?'; + export const LOG_PROMPT = - 'Send your log too? It helps us find the cause. We mask the keys and tokens we recognize.'; + '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 RETRY_HEADLINE = 'Finish setting up PostHog'; - export const RERUN_COMMAND = 'npx @posthog/wizard@latest'; export const AGENT_HANDOFF_STEP = - 'Or hand the setup to your own agent. The saved skill has every step.'; + 'Or hand it to your own agent. The saved skill has every step.'; // A security stop or the agent's own [ABORT] is a decision, not an outage: // it shows its own outro, never the busy handoff. @@ -42,15 +86,17 @@ const DECISIONS = new Set([ ErrorCodes.DetectUnsupportedPlatform, ]); -/** 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. */ +/** The run ended in an error the handoff screen explains: an agent run with + * credentials, or a login failure with its own copy. Other login failures keep + * their specific outro. */ export function isRunFailure( session: Pick, ): boolean { + const errorCode = session.outroData?.errorCode ?? ''; return ( session.outroData?.kind === OutroKind.Error && - session.credentials !== null && - !DECISIONS.has(session.outroData.errorCode ?? '') + !DECISIONS.has(errorCode) && + (session.credentials !== null || LOGIN_COPY.has(errorCode)) ); } @@ -95,5 +141,7 @@ export function failureReportProperties( export function failureCopy( session: Pick, ): FailureCopy { + const loginCopy = LOGIN_COPY.get(session.outroData?.errorCode ?? ''); + if (loginCopy) return loginCopy; return isCapacityFailure(session) ? CAPACITY_COPY : RUN_FAILURE_COPY; } diff --git a/src/tui/screens/MintFailureScreen.tsx b/src/tui/screens/MintFailureScreen.tsx index f6fe748e7..3dd0846fb 100644 --- a/src/tui/screens/MintFailureScreen.tsx +++ b/src/tui/screens/MintFailureScreen.tsx @@ -7,10 +7,10 @@ import { Colors, Icons } from '@tui/styles'; import { AGENT_HANDOFF_STEP, LOG_PROMPT, + LOG_QUESTION, LOG_SENT_NOTE, REPORTED_NOTE, RERUN_COMMAND, - RETRY_HEADLINE, failureCopy, } from '@tui/mint-failure'; import type { WizardSpellbook } from '@tui/services/wizard-spellbook'; @@ -88,12 +88,13 @@ export function MintFailureScreen({ } }; - const isAskingAboutLog = logChoice === 'unanswered' && !spellbook && !error; + const isAskingAboutLog = + copy.asksAboutLog && logChoice === 'unanswered' && !spellbook && !error; const options: { label: string; value: Action }[] = isAskingAboutLog ? [ - { label: 'Send log', value: 'send-log' }, - { label: "Don't send", value: 'keep-log' }, + { label: 'Send log and continue', value: 'send-log' }, + { label: 'Continue without sending', value: 'keep-log' }, ] : error ? [ @@ -109,9 +110,13 @@ export function MintFailureScreen({ { label: 'Exit', value: 'exit' }, ] : [ - { label: 'Open in Claude Code', value: 'claude' }, - { label: 'Open in Codex', value: 'codex' }, - { label: 'Save skill', value: 'save' }, + ...(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' }, ]; @@ -140,34 +145,45 @@ export function MintFailureScreen({ - ) : isAskingAboutLog ? ( + ) : ( + {copy.asksAboutLog && ( + + Step {isAskingAboutLog ? 1 : 2} of 2 + + )} ✘ {copy.headline} - - {copy.cause} {REPORTED_NOTE} - - - {LOG_PROMPT} - - - ) : ( - + {copy.cause} + {copy.asksAboutLog && ( + + {REPORTED_NOTE} + + )} {logChoice === 'sent' && ( - + {Icons.check} {LOG_SENT_NOTE} )} - {RETRY_HEADLINE} - - - 1. {copy.rerun} {RERUN_COMMAND} - - - 2. {AGENT_HANDOFF_STEP} + {isAskingAboutLog ? ( + + {LOG_QUESTION} + + {LOG_PROMPT} + + + ) : ( + + • {copy.rerun} + {` ${RERUN_COMMAND}`} + {copy.canHandOffToAgent && ( + • {AGENT_HANDOFF_STEP} + )} + + )} )} {spellbook && ( From f9f07b9f9d1333d99c49be4aeeb98a3ac4f5c7c9 Mon Sep 17 00:00:00 2001 From: John W Date: Wed, 25 Nov 2026 11:23:36 -0700 Subject: [PATCH 07/13] fix(auth): end a failed login as failed, on the failure screen Brings in #1613's login fixes, written by Rafa (@rafaeelaudibert): a failed project or user fetch after login ended the run as completed with exit 0, a failed OAuth login showed only "Wizard setup cancelled.", and the paste-code overlay could cover the screens after login. The OAuth abort now carries PHW_AUTH_ACCESS_DENIED or PHW_AUTH_LOGIN_FAILED, so those logins reach the two-step failure screen. The project fetch throws PHW_AUTH_PROJECT_FETCH_FAILED and only the run's login aborts on it, since `wizard slack` and the MCP tutorial show that error inline with a retry. Ticket: task-failure-outro/U2 Confidence: high Scope-risk: moderate --- .../react-router/__tests__/utils.test.ts | 1 - src/tui/__tests__/store-invariants.test.ts | 6 +++ src/tui/__tests__/store.test.ts | 21 ++++++++ src/tui/auth/__tests__/ci-region.test.ts | 40 +++++++++++++++ src/tui/auth/__tests__/login.test.ts | 29 +++++++++++ src/tui/auth/__tests__/oauth-flow.test.ts | 49 ++++++++++++------- src/tui/auth/login.ts | 14 ++++++ src/tui/auth/oauth.ts | 44 ++++++++++------- src/tui/auth/project-data.ts | 37 ++++++++------ src/tui/store.ts | 6 +++ 10 files changed, 197 insertions(+), 50 deletions(-) diff --git a/src/services/frameworks/react-router/__tests__/utils.test.ts b/src/services/frameworks/react-router/__tests__/utils.test.ts index 30c53dccf..3033451ec 100644 --- a/src/services/frameworks/react-router/__tests__/utils.test.ts +++ b/src/services/frameworks/react-router/__tests__/utils.test.ts @@ -23,7 +23,6 @@ describe('getReactRouterMode', () => { debug: false, benchmark: false, yaraReport: false, - signup: false, }); }; diff --git a/src/tui/__tests__/store-invariants.test.ts b/src/tui/__tests__/store-invariants.test.ts index 6e1e7e1da..25dffda07 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(), 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..798950434 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,27 @@ it("passes the program's completion-scope opt-out to the login", async () => { }), ); }); + +it('ends the run on a failed project fetch, and passes any other login error 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('other')); + await expect(oauthLogin(session, 'metrics', store)).rejects.toThrow('other'); + 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..2b1b299f6 100644 --- a/src/tui/auth/__tests__/oauth-flow.test.ts +++ b/src/tui/auth/__tests__/oauth-flow.test.ts @@ -36,6 +36,7 @@ function fakeStore() { store.loginUrl = url; }, setAuthorizeUrl: vi.fn(), + closeManualAuthCode: vi.fn(), pushStatus: vi.fn(), showSessionTimeout: vi.fn(), waitForManualAuthCode: () => pasted, @@ -79,6 +80,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 +96,34 @@ 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'], + ['invalid_scope', 'invalid_scope', 'PHW_AUTH_LOGIN_FAILED'], + ])( + 'stops the login when the callback carries %s, says why, and frees its port', + async (oauthError, shown, code) => { + 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, + }); + 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..6efd4bcef 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 { 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,18 @@ export async function oauthLogin( localMcp: session.localMcp, programId, completionScopeOptional, + }).catch(async (error: unknown) => { + if ( + !(error instanceof WizardError) || + error.code !== ErrorCodes.AuthProjectFetchFailed + ) + throw error; + // Without this abort the error reaches the TUI host with no credentials set, which ends the run as completed. + return abortOnScreens(store, { + code: error.code, + message: error.message, + error, + }); }); 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..57389a5d8 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 } 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 @@ -620,7 +620,17 @@ export async function performOAuthFlow( $exception_fingerprint: `wizard_oauth_${oauthErrorCode}`, }); - await abortOnScreens(store); + await abortOnScreens( + store, + failureMessage + ? { + message: failureMessage, + code: accessDenied + ? ErrorCodes.AuthAccessDenied + : ErrorCodes.AuthLoginFailed, + } + : undefined, + ); 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/store.ts b/src/tui/store.ts index c99f0012d..09556423c 100644 --- a/src/tui/store.ts +++ b/src/tui/store.ts @@ -747,6 +747,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. From 88ae1c69dd22e8706c61ac947e10ac535eb9f4f3 Mon Sep 17 00:00:00 2001 From: John W Date: Wed, 25 Nov 2026 11:25:04 -0700 Subject: [PATCH 08/13] fix(test): drop the removed signup option from a react router test #1607 removed signup from WizardRunOptions, but this test from #1598 still passed it, so tsc -b failed on main and on every branch synced with it. Confidence: high Scope-risk: narrow --- src/services/frameworks/react-router/__tests__/utils.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/services/frameworks/react-router/__tests__/utils.test.ts b/src/services/frameworks/react-router/__tests__/utils.test.ts index 30c53dccf..3033451ec 100644 --- a/src/services/frameworks/react-router/__tests__/utils.test.ts +++ b/src/services/frameworks/react-router/__tests__/utils.test.ts @@ -23,7 +23,6 @@ describe('getReactRouterMode', () => { debug: false, benchmark: false, yaraReport: false, - signup: false, }); }; From c7c235ef5c5bd3c4b5694cf35d591a447e7f88f5 Mon Sep 17 00:00:00 2001 From: John W Date: Wed, 25 Nov 2026 11:32:53 -0700 Subject: [PATCH 09/13] fix(tui): report only this run's log lines, kept in memory Every run appends to one shared log file, so reading it from this run's starting offset also picked up a concurrent run's prompts and tool output. The run now keeps its own last 64K of log lines as it writes them, and Send log uploads that, still masked. Ticket: task-failure-outro/U2 Confidence: high Scope-risk: narrow --- src/shared/utils/bounded-fs.ts | 26 -------------------- src/shared/utils/debug.ts | 26 ++++++++++---------- src/tui/__tests__/MintFailureScreen.test.tsx | 20 +++++++++++++++ src/tui/mint-failure.ts | 16 ++---------- 4 files changed, 35 insertions(+), 53 deletions(-) diff --git a/src/shared/utils/bounded-fs.ts b/src/shared/utils/bounded-fs.ts index 8159ebe23..7a7dcd029 100644 --- a/src/shared/utils/bounded-fs.ts +++ b/src/shared/utils/bounded-fs.ts @@ -329,32 +329,6 @@ export function safeReadFile( } } -/** The last `bytes` of a file from offset `from` on, without materializing the rest. */ -export function readFileTail( - filePath: string, - bytes: number, - from = 0, -): { text: string; truncated: boolean } | null { - try { - const fd = fs.openSync(filePath, 'r'); - try { - const size = fs.fstatSync(fd).size; - const start = Math.max(from, size - bytes); - const length = Math.max(0, size - start); - const buffer = Buffer.alloc(length); - const read = fs.readSync(fd, buffer, 0, length, start); - return { - text: buffer.toString('utf-8', 0, read), - truncated: start > from, - }; - } finally { - fs.closeSync(fd); - } - } catch { - return null; - } -} - /** * The first `bytes` of a file without materializing the rest. */ diff --git a/src/shared/utils/debug.ts b/src/shared/utils/debug.ts index dc6acf13f..0d5174d66 100644 --- a/src/shared/utils/debug.ts +++ b/src/shared/utils/debug.ts @@ -1,4 +1,4 @@ -import { appendFileSync, mkdirSync, statSync } from 'fs'; +import { appendFileSync, mkdirSync } from 'fs'; import path from 'path'; import { inspect } from 'node:util'; import { IS_DEV, runtimeEnv } from '@env'; @@ -10,8 +10,6 @@ let logFilePath = let fileLoggingEnabled = true; // An explicit --log-file wins over every later path change while pinned. let logFilePinned = false; -// Byte offset of this process's first line, since every run appends to one shared file. -let processLogStart: number | null = null; function stringify(value: unknown): string { if (typeof value === 'string') return value; @@ -43,7 +41,6 @@ export function configureLogFile(opts: { if (opts.path !== undefined && !logFilePinned) { logFilePath = opts.path; ensuredLogDir = false; - processLogStart = null; } if (opts.pin === true) logFilePinned = true; if (opts.enabled !== undefined) fileLoggingEnabled = opts.enabled; @@ -75,20 +72,23 @@ function reportLogFailureOnce(err: unknown): void { // The log's directory isn't guaranteed to exist (Windows %TEMP%, // POSTHOG_WIZARD_LOG_DIR) — create it on first failure. -function currentLogSize(): number { - try { - return statSync(logFilePath).size; - } catch { - return 0; - } +// 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; +let processLogTail = ''; + +export function getProcessLogTail(): string { + return processLogTail; } -export function getProcessLogStart(): number | null { - return fileLoggingEnabled ? processLogStart : null; +function keepInProcessTail(text: string): void { + processLogTail += text; + if (processLogTail.length <= PROCESS_LOG_TAIL_CHARS) return; + const kept = processLogTail.slice(-PROCESS_LOG_TAIL_CHARS); + processLogTail = kept.slice(kept.indexOf('\n') + 1); } function appendLine(text: string): void { - processLogStart ??= currentLogSize(); + 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 741303800..dba842af3 100644 --- a/src/tui/__tests__/MintFailureScreen.test.tsx +++ b/src/tui/__tests__/MintFailureScreen.test.tsx @@ -10,6 +10,11 @@ import { OutroKind } from '@shared/outro'; import { ErrorCodes, type ErrorCode } from '@shared/errors'; 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()); @@ -149,3 +154,18 @@ it('routes a failed login here and offers only Exit after the log question', asy 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'); + const { store } = setup(); + const logTail = String(failureReportProperties(store.session).log_tail); + expect(logTail).toContain('this run failed'); + expect(logTail).not.toContain('another run'); +}); diff --git a/src/tui/mint-failure.ts b/src/tui/mint-failure.ts index b4a27d581..fd2de52a1 100644 --- a/src/tui/mint-failure.ts +++ b/src/tui/mint-failure.ts @@ -1,7 +1,6 @@ import { ErrorCodes } from '@shared/errors'; import { redactSecrets, scrubHomePaths } from '@shared/mcp-clients/results'; -import { getLogFilePath, getProcessLogStart } from '@utils/debug'; -import { readFileTail } from '@utils/bounded-fs'; +import { getProcessLogTail } from '@utils/debug'; import { OutroKind } from '@shared/outro'; import type { WizardSession } from '@programs/types'; @@ -116,17 +115,6 @@ export function isCapacityFailure( ); } -const LOG_TAIL_BYTES = 64 * 1024; - -function readRunLog(): string { - const start = getProcessLogStart(); - if (start === null) return ''; - const tail = readFileTail(getLogFilePath(), LOG_TAIL_BYTES, start); - if (tail === null) return '[log unreadable]'; - if (!tail.truncated) return tail.text; - return tail.text.slice(tail.text.indexOf('\n') + 1); -} - export function failureReportProperties( session: Pick, ): Record { @@ -134,7 +122,7 @@ export function failureReportProperties( error_code: session.outroData?.errorCode, message: scrubHomePaths(redactSecrets(session.outroData?.message ?? '')), is_capacity: isCapacityFailure(session), - log_tail: scrubHomePaths(redactSecrets(readRunLog())), + log_tail: scrubHomePaths(redactSecrets(getProcessLogTail())), }; } From 621a38b1a8d8fc91a2c4aef255f5f23429a4d397 Mon Sep 17 00:00:00 2001 From: John W Date: Fri, 27 Nov 2026 08:35:23 -0700 Subject: [PATCH 10/13] fix(tui): show the failure screen only for program runs that need it The failure screen took any logged-in error. A tool such as wizard doctor never waits on the handoff, so Exit left a blank terminal, and auth errors and tailored abort outros (missing SDK, missing scope, settings conflict) lost the screen that names their fix. Only a registered program shows it now, every error code has a route the compiler checks, and overlays resolve first. GatewayMintRefused and AgentApiError no longer show busy copy. Programs other than the integration say the wizard did not finish and name their own rerun command, or ask for the same command when they have none. Ticket: failure-routing-review-fixes/U1 Confidence: high Scope-risk: moderate --- src/tui/__tests__/MintFailureScreen.test.tsx | 37 ++++- src/tui/__tests__/frames.test.tsx | 2 +- src/tui/__tests__/router.test.ts | 43 ++++- src/tui/exit-line.ts | 9 +- src/tui/mint-failure.ts | 156 ++++++++++++++----- src/tui/router.ts | 8 +- src/tui/run.ts | 2 +- src/tui/screens/MintFailureScreen.tsx | 7 +- src/tui/store.ts | 2 +- 9 files changed, 211 insertions(+), 55 deletions(-) diff --git a/src/tui/__tests__/MintFailureScreen.test.tsx b/src/tui/__tests__/MintFailureScreen.test.tsx index dba842af3..542aa3a94 100644 --- a/src/tui/__tests__/MintFailureScreen.test.tsx +++ b/src/tui/__tests__/MintFailureScreen.test.tsx @@ -8,6 +8,7 @@ import { 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'; @@ -34,8 +35,12 @@ const saved = { }; const delay = () => new Promise((resolve) => setTimeout(resolve, 30)); -function setup(errorCode?: ErrorCode, isLoggedIn = true) { - const store = new WizardStore(); +function setup( + errorCode?: ErrorCode, + isLoggedIn = true, + program: ProgramId = Program.PostHogIntegration, +) { + const store = new WizardStore(program); if (isLoggedIn) store.setCredentials({ accessToken: 'tok', @@ -128,9 +133,31 @@ it('exits without sending the log, saving or launching', async () => { expect(services.openAgent).not.toHaveBeenCalled(); }); +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.GatewayMintRefused, 'The wizard is busy right now'], + [ErrorCodes.AgentRateLimit, 'The wizard is busy right now'], ])( 'asks about the log under a %s headline of %s, no error text', async (errorCode, headline) => { @@ -165,7 +192,9 @@ it("reports only this run's log lines when another run shares the log file", () fs.appendFileSync(logPath, 'another run read its secret source\n'); logToFile('this run failed'); const { store } = setup(); - const logTail = String(failureReportProperties(store.session).log_tail); + const logTail = String( + failureReportProperties(store.session, store.router.activeProgram).log_tail, + ); expect(logTail).toContain('this run failed'); expect(logTail).not.toContain('another run'); }); diff --git a/src/tui/__tests__/frames.test.tsx b/src/tui/__tests__/frames.test.tsx index 11d801b40..5219f0665 100644 --- a/src/tui/__tests__/frames.test.tsx +++ b/src/tui/__tests__/frames.test.tsx @@ -676,7 +676,7 @@ const FIXTURES: Record = { s.setOutroData({ kind: OutroKind.Error, message: 'The agent run failed', - errorCode: ErrorCodes.GatewayMintRefused, + 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/exit-line.ts b/src/tui/exit-line.ts index e0760f750..ee10496ff 100644 --- a/src/tui/exit-line.ts +++ b/src/tui/exit-line.ts @@ -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,9 +119,12 @@ 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); + const { headline, cause, asksAboutLog } = failureCopy( + store.session, + store.router.activeProgram, + ); return [ `${headline}. ${cause}`, spellbook && diff --git a/src/tui/mint-failure.ts b/src/tui/mint-failure.ts index fd2de52a1..1b9ff8b76 100644 --- a/src/tui/mint-failure.ts +++ b/src/tui/mint-failure.ts @@ -1,10 +1,13 @@ -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 type FailureCopy = { +type FailureSession = Pick; + +type FailureCopy = { headline: string; cause: string; rerun: string; @@ -21,7 +24,7 @@ const CAPACITY_COPY: FailureCopy = { }; const RUN_FAILURE_COPY: FailureCopy = { - headline: "PostHog isn't set up yet", + headline: "The wizard didn't finish", cause: 'The wizard ran into a problem partway through and stopped before finishing.', rerun: 'Run the wizard again:', @@ -29,6 +32,13 @@ const RUN_FAILURE_COPY: FailureCopy = { 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, @@ -77,59 +87,135 @@ 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.'; -// 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, -]); +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: an agent run with - * credentials, or a login failure with its own copy. Other login failures keep - * their specific outro. */ +/** 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 { - const errorCode = session.outroData?.errorCode ?? ''; - return ( - session.outroData?.kind === OutroKind.Error && - !DECISIONS.has(errorCode) && - (session.credentials !== null || LOGIN_COPY.has(errorCode)) - ); + 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; } -const CAPACITY = new Set([ - ErrorCodes.AgentRateLimit, - ErrorCodes.AgentApiError, - ErrorCodes.GatewayMintRefused, - ErrorCodes.GatewayMintFailed, - ErrorCodes.EnvServiceOutage, -]); - -export function isCapacityFailure( - session: Pick, +function isCapacityFailure( + session: FailureSession, + programId: ProgramId, ): boolean { return ( - isRunFailure(session) && CAPACITY.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: Pick, + session: FailureSession, + programId: ProgramId, ): Record { return { error_code: session.outroData?.errorCode, message: scrubHomePaths(redactSecrets(session.outroData?.message ?? '')), - is_capacity: isCapacityFailure(session), + is_capacity: isCapacityFailure(session, programId), log_tail: scrubHomePaths(redactSecrets(getProcessLogTail())), }; } export function failureCopy( - session: Pick, + 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; - return isCapacityFailure(session) ? CAPACITY_COPY : RUN_FAILURE_COPY; + 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/screens/MintFailureScreen.tsx b/src/tui/screens/MintFailureScreen.tsx index 3dd0846fb..7fe6e979d 100644 --- a/src/tui/screens/MintFailureScreen.tsx +++ b/src/tui/screens/MintFailureScreen.tsx @@ -10,8 +10,8 @@ import { LOG_QUESTION, LOG_SENT_NOTE, REPORTED_NOTE, - RERUN_COMMAND, failureCopy, + rerunCommand, } from '@tui/mint-failure'; import type { WizardSpellbook } from '@tui/services/wizard-spellbook'; import type { CodingAgent } from '../services/coding-agent-launcher'; @@ -50,7 +50,8 @@ export function MintFailureScreen({ const [logChoice, setLogChoice] = useState('unanswered'); const [retry, setRetry] = useState<'save' | CodingAgent>('save'); const { spellbook } = store; - const copy = failureCopy(store.session); + const copy = failureCopy(store.session, store.router.activeProgram); + const command = rerunCommand(store.router.activeProgram); const select = async (action: Action) => { if (busy.current) return; @@ -178,7 +179,7 @@ export function MintFailureScreen({ ) : ( • {copy.rerun} - {` ${RERUN_COMMAND}`} + {command && {` ${command}`}} {copy.canHandOffToAgent && ( • {AGENT_HANDOFF_STEP} )} diff --git a/src/tui/store.ts b/src/tui/store.ts index 166bd0e60..ac086aedc 100644 --- a/src/tui/store.ts +++ b/src/tui/store.ts @@ -634,7 +634,7 @@ export class WizardStore implements TuiView { sendFailureReport(): void { analytics.wizardCapture( 'failure reported', - failureReportProperties(this.session), + failureReportProperties(this.session, this.router.activeProgram), ); } From 31d0173e2578f53f56561dd5bd6c4236444ff365 Mon Sep 17 00:00:00 2001 From: John W Date: Fri, 27 Nov 2026 08:44:08 -0700 Subject: [PATCH 11/13] fix(tui): mask more secrets in the failure log and report logins once The opt-in failure log now masks minted phe_ gateway tokens, PEM private keys (including a block the log tail cut), and secret-named values that are JSON-escaped, quoted, or carry punctuation, without crossing a line or re-matching an earlier mask. Windows user paths nested in JSON are scrubbed. A failed login reports error status and is captured once, through the abort, with its OAuth fingerprint. The failure reported event carries the session properties like the events beside it. Ticket: failure-routing-review-fixes/U2 Confidence: high Scope-risk: narrow --- .../mcp-clients/__tests__/results.test.ts | 49 ++++++++++++++++++- src/shared/mcp-clients/results.ts | 13 +++-- src/shared/utils/__tests__/debug.test.ts | 12 +++++ src/shared/utils/debug.ts | 4 +- src/tui/__tests__/MintFailureScreen.test.tsx | 6 ++- src/tui/auth/__tests__/oauth-flow.test.ts | 20 ++++++-- src/tui/auth/oauth.ts | 32 ++++++------ src/tui/store.ts | 8 +-- 8 files changed, 116 insertions(+), 28 deletions(-) diff --git a/src/shared/mcp-clients/__tests__/results.test.ts b/src/shared/mcp-clients/__tests__/results.test.ts index f60c19da0..8f9c463ab 100644 --- a/src/shared/mcp-clients/__tests__/results.test.ts +++ b/src/shared/mcp-clients/__tests__/results.test.ts @@ -50,6 +50,10 @@ 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 = @@ -149,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', () => { @@ -196,6 +237,12 @@ 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"'), diff --git a/src/shared/mcp-clients/results.ts b/src/shared/mcp-clients/results.ts index c9d7c02e1..80dc8cae1 100644 --- a/src/shared/mcp-clients/results.ts +++ b/src/shared/mcp-clients/results.ts @@ -56,7 +56,7 @@ const SECRET_NAME = export const redactSecrets = (raw: string): string => raw .replace(/Bearer\s+\S+/gi, 'Bearer [redacted]') - .replace(/ph[xspcar]_[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]@') @@ -69,12 +69,19 @@ 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. @@ -98,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]:\\{1,2}Users\\{1,2}[^\\\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..ac57be9e1 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,17 @@ 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('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 0d5174d66..2c4e3ddb0 100644 --- a/src/shared/utils/debug.ts +++ b/src/shared/utils/debug.ts @@ -70,8 +70,6 @@ function reportLogFailureOnce(err: unknown): void { }); } -// The log's directory isn't guaranteed to exist (Windows %TEMP%, -// POSTHOG_WIZARD_LOG_DIR) — create it on first failure. // 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; let processLogTail = ''; @@ -87,6 +85,8 @@ function keepInProcessTail(text: string): void { processLogTail = kept.slice(kept.indexOf('\n') + 1); } +// 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 { diff --git a/src/tui/__tests__/MintFailureScreen.test.tsx b/src/tui/__tests__/MintFailureScreen.test.tsx index 542aa3a94..be0d30ab5 100644 --- a/src/tui/__tests__/MintFailureScreen.test.tsx +++ b/src/tui/__tests__/MintFailureScreen.test.tsx @@ -190,11 +190,15 @@ it("reports only this run's log lines when another run shares the log file", () configureLogFile({ path: logPath, enabled: true }); logToFile('this run started'); fs.appendFileSync(logPath, 'another run read its secret source\n'); - logToFile('this run failed'); + 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/auth/__tests__/oauth-flow.test.ts b/src/tui/auth/__tests__/oauth-flow.test.ts index 2b1b299f6..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'; @@ -97,11 +98,16 @@ describe('the OAuth flow', () => { }); it.each([ - ['access_denied', 'Authorization was cancelled', 'PHW_AUTH_ACCESS_DENIED'], - ['invalid_scope', 'invalid_scope', 'PHW_AUTH_LOGIN_FAILED'], + [ + '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) => { + async (oauthError, shown, code, status) => { const { store, wizardStore } = fakeStore(); const flow = performOAuthFlow({ scopes: ['user:read'] }, wizardStore); @@ -115,7 +121,15 @@ describe('the OAuth flow', () => { 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(); diff --git a/src/tui/auth/oauth.ts b/src/tui/auth/oauth.ts index 57389a5d8..9699fdf25 100644 --- a/src/tui/auth/oauth.ts +++ b/src/tui/auth/oauth.ts @@ -14,7 +14,7 @@ import { OAUTH_TIMEOUT_MS, WIZARD_USER_AGENT, } from '@shared/constants'; -import { ErrorCodes } from '@shared/errors'; +import { ErrorCodes, WizardError } from '@shared/errors'; import { abortOnScreens } from '@tui/abort'; import type { WizardStore } from '@tui/store'; import { analytics } from '@utils/analytics'; @@ -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,19 +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, - failureMessage - ? { - message: failureMessage, - code: accessDenied - ? ErrorCodes.AuthAccessDenied - : ErrorCodes.AuthLoginFailed, - } - : undefined, - ); + 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/store.ts b/src/tui/store.ts index ac086aedc..f39600b42 100644 --- a/src/tui/store.ts +++ b/src/tui/store.ts @@ -632,10 +632,10 @@ export class WizardStore implements TuiView { } sendFailureReport(): void { - analytics.wizardCapture( - 'failure reported', - failureReportProperties(this.session, this.router.activeProgram), - ); + analytics.wizardCapture('failure reported', { + ...sessionProperties(this.session), + ...failureReportProperties(this.session, this.router.activeProgram), + }); } setSkillId(skillId: string | null): void { From 0f0119ce503815005e8d755f64aa94f0a90fb715 Mon Sep 17 00:00:00 2001 From: John W Date: Fri, 27 Nov 2026 10:43:14 -0700 Subject: [PATCH 12/13] fix(tui): end a login that throws as a failed login, keep long log lines An uncoded error from the OAuth login (no callback ports, a port loop that exits) reached the TUI host with no credentials, so the run ended as completed with exit 0. The login now aborts it as AuthLoginFailed, which shows the login failure screen; coded errors pass through. A single log line over the 64K tail emptied the failure report log_tail; the tail keeps the end of that line. A test pins the access-denied screen skipping the log question. Confidence: high Scope-risk: narrow --- src/shared/utils/__tests__/debug.test.ts | 6 ++++ src/shared/utils/debug.ts | 7 ++++- src/tui/__tests__/MintFailureScreen.test.tsx | 11 ++++++++ src/tui/auth/__tests__/login.test.ts | 26 ++++++++++++++++-- src/tui/auth/login.ts | 29 ++++++++++++++------ 5 files changed, 66 insertions(+), 13 deletions(-) diff --git a/src/shared/utils/__tests__/debug.test.ts b/src/shared/utils/__tests__/debug.test.ts index ac57be9e1..1c8c3243c 100644 --- a/src/shared/utils/__tests__/debug.test.ts +++ b/src/shared/utils/__tests__/debug.test.ts @@ -33,6 +33,12 @@ describe('log file writing', () => { expect(tail).toContain('line 699'); }); + it('keeps the end of a single line longer than the tail', () => { + configureLogFile({ path: path.join(tmpRoot, 'w.log'), enabled: true }); + logToFile(`huge ${'y'.repeat(70 * 1024)} end-marker`); + expect(getProcessLogTail()).toContain('end-marker'); + }); + 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 2c4e3ddb0..235056649 100644 --- a/src/shared/utils/debug.ts +++ b/src/shared/utils/debug.ts @@ -82,7 +82,12 @@ function keepInProcessTail(text: string): void { processLogTail += text; if (processLogTail.length <= PROCESS_LOG_TAIL_CHARS) return; const kept = processLogTail.slice(-PROCESS_LOG_TAIL_CHARS); - processLogTail = kept.slice(kept.indexOf('\n') + 1); + const firstBreak = kept.indexOf('\n'); + // A single line longer than the cap has its only break at the end; keep its tail rather than nothing. + processLogTail = + firstBreak >= 0 && firstBreak < kept.length - 1 + ? kept.slice(firstBreak + 1) + : kept; } // The log's directory isn't guaranteed to exist (Windows %TEMP%, diff --git a/src/tui/__tests__/MintFailureScreen.test.tsx b/src/tui/__tests__/MintFailureScreen.test.tsx index be0d30ab5..e04555f8e 100644 --- a/src/tui/__tests__/MintFailureScreen.test.tsx +++ b/src/tui/__tests__/MintFailureScreen.test.tsx @@ -133,6 +133,17 @@ it('exits without sending the log, saving or launching', async () => { 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(); diff --git a/src/tui/auth/__tests__/login.test.ts b/src/tui/auth/__tests__/login.test.ts index 798950434..8136f45ae 100644 --- a/src/tui/auth/__tests__/login.test.ts +++ b/src/tui/auth/__tests__/login.test.ts @@ -66,7 +66,7 @@ it("passes the program's completion-scope opt-out to the login", async () => { ); }); -it('ends the run on a failed project fetch, and passes any other login error through', 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( @@ -85,7 +85,27 @@ it('ends the run on a failed project fetch, and passes any other login error thr }); vi.mocked(abortOnScreens).mockClear(); - vi.mocked(getOrAskForProjectData).mockRejectedValueOnce(new Error('other')); - await expect(oauthLogin(session, 'metrics', store)).rejects.toThrow('other'); + 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/login.ts b/src/tui/auth/login.ts index 6efd4bcef..130d1423d 100644 --- a/src/tui/auth/login.ts +++ b/src/tui/auth/login.ts @@ -7,7 +7,7 @@ import type { import { analytics } from '@utils/analytics'; import { logToFile } from '@utils/debug'; import type { WizardStore } from '@tui/store'; -import { ErrorCodes, WizardError } from '@shared/errors'; +import { classifyRunFailure, ErrorCodes, WizardError } from '@shared/errors'; import { abortOnScreens } from '@tui/abort'; import { getOrAskForProjectData } from './project-data.js'; @@ -27,16 +27,27 @@ export async function oauthLogin( 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 - ) - throw error; - // Without this abort the error reaches the TUI host with no credentials set, which ends the run as completed. + 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: error.code, - message: error.message, - error, + code: ErrorCodes.AuthLoginFailed, + message: failure.message, + error: new WizardError( + failure.message, + undefined, + ErrorCodes.AuthLoginFailed, + ), }); }); analytics.wizardCapture('auth complete', { project_id: data.projectId }); From 3cb6818f6e33c3336369bd17ab44d178d9a034b3 Mon Sep 17 00:00:00 2001 From: John W Date: Fri, 27 Nov 2026 11:25:00 -0700 Subject: [PATCH 13/13] fix(tui): leave an oversized log line out of the failure report Keeping the end of a line longer than the 64K tail could keep a secret value without the PASSWORD= name that gets it masked, since masking runs after the cut. Such a line is now replaced with a note. Confidence: high Scope-risk: narrow --- src/shared/utils/__tests__/debug.test.ts | 8 +++++--- src/shared/utils/debug.ts | 5 +++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/shared/utils/__tests__/debug.test.ts b/src/shared/utils/__tests__/debug.test.ts index 1c8c3243c..8b63491da 100644 --- a/src/shared/utils/__tests__/debug.test.ts +++ b/src/shared/utils/__tests__/debug.test.ts @@ -33,10 +33,12 @@ describe('log file writing', () => { expect(tail).toContain('line 699'); }); - it('keeps the end of a single line longer than the tail', () => { + 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(`huge ${'y'.repeat(70 * 1024)} end-marker`); - expect(getProcessLogTail()).toContain('end-marker'); + 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', () => { diff --git a/src/shared/utils/debug.ts b/src/shared/utils/debug.ts index 235056649..0eefdfd6b 100644 --- a/src/shared/utils/debug.ts +++ b/src/shared/utils/debug.ts @@ -72,6 +72,7 @@ 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 { @@ -83,11 +84,11 @@ function keepInProcessTail(text: string): void { if (processLogTail.length <= PROCESS_LOG_TAIL_CHARS) return; const kept = processLogTail.slice(-PROCESS_LOG_TAIL_CHARS); const firstBreak = kept.indexOf('\n'); - // A single line longer than the cap has its only break at the end; keep its tail rather than nothing. + // 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) - : kept; + : OVERSIZED_LINE_NOTE; } // The log's directory isn't guaranteed to exist (Windows %TEMP%,