From c16ea9bae1e0e1a9cb35029a5d4afa22e7a4a382 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sat, 11 Jul 2026 02:03:14 -0700 Subject: [PATCH] fix(crash-reporting): make Windows capture and submission reliable (#8242) * fix(crash-reporting): make Windows capture and submission reliable * fix(crash-reporting): harden recovery fallbacks * test(crash-reporting): cover returned copy failures * fix(crash-reporting): keep Windows recovery responsive * fix(crash-reporting): retry transient identity lookup --- .../crash-feedback-diagnostic-bundle.ts | 119 ++++++++++ .../crash-report-copy-text.test.ts | 41 ++++ .../crash-reporting/crash-report-copy-text.ts | 53 +++++ .../crash-report-store.test.ts | 83 ++++++- .../crash-reporting/crash-report-store.ts | 73 +++++- .../durable-crash-breadcrumb.test.ts | 74 ++++++ .../durable-crash-breadcrumb.ts | 33 +++ .../process-gone-dedupe.test.ts | 21 ++ .../crash-reporting/process-gone-dedupe.ts | 37 ++- .../process-gone-diagnostics.test.ts | 2 + .../process-gone-diagnostics.ts | 6 +- .../process-gone-recorder.test.ts | 213 ++++++++++++++++++ .../crash-reporting/process-gone-recorder.ts | 137 +++++++++++ src/main/index.ts | 93 +------- src/main/ipc/crash-reporting.test.ts | 110 ++++++++- src/main/ipc/crash-reporting.ts | 160 ++++++------- src/main/ipc/feedback.test.ts | 145 +++++++++++- src/main/ipc/feedback.ts | 111 ++++++++- src/main/observability/tracer.test.ts | 18 ++ src/main/observability/tracer.ts | 18 +- src/main/win32-utils-async-acl.test.ts | 157 +++++++++++++ src/main/win32-utils.ts | 119 ++++++++-- src/main/window/createMainWindow.test.ts | 18 +- src/main/window/createMainWindow.ts | 14 +- src/preload/api-types.ts | 8 +- src/preload/index.ts | 3 +- .../crash-report/CrashReportDialogSurface.tsx | 86 ++++--- .../crash-report-submit-notice.test.ts | 128 +++++++++++ .../crash-report-submit-notice.ts | 134 +++++++++++ .../use-crash-report-copy.test.tsx | 133 +++++++++++ .../crash-report/use-crash-report-copy.ts | 69 ++++++ src/renderer/src/i18n/locales/en.json | 15 ++ src/renderer/src/i18n/locales/es.json | 15 ++ src/renderer/src/i18n/locales/ja.json | 15 ++ src/renderer/src/i18n/locales/ko.json | 17 +- src/renderer/src/i18n/locales/zh.json | 15 ++ src/shared/crash-reporting.ts | 13 ++ 37 files changed, 2222 insertions(+), 284 deletions(-) create mode 100644 src/main/crash-reporting/crash-feedback-diagnostic-bundle.ts create mode 100644 src/main/crash-reporting/crash-report-copy-text.test.ts create mode 100644 src/main/crash-reporting/crash-report-copy-text.ts create mode 100644 src/main/crash-reporting/durable-crash-breadcrumb.test.ts create mode 100644 src/main/crash-reporting/durable-crash-breadcrumb.ts create mode 100644 src/main/crash-reporting/process-gone-recorder.test.ts create mode 100644 src/main/crash-reporting/process-gone-recorder.ts create mode 100644 src/main/win32-utils-async-acl.test.ts create mode 100644 src/renderer/src/components/crash-report/crash-report-submit-notice.test.ts create mode 100644 src/renderer/src/components/crash-report/crash-report-submit-notice.ts create mode 100644 src/renderer/src/components/crash-report/use-crash-report-copy.test.tsx create mode 100644 src/renderer/src/components/crash-report/use-crash-report-copy.ts diff --git a/src/main/crash-reporting/crash-feedback-diagnostic-bundle.ts b/src/main/crash-reporting/crash-feedback-diagnostic-bundle.ts new file mode 100644 index 000000000..4068dcdb8 --- /dev/null +++ b/src/main/crash-reporting/crash-feedback-diagnostic-bundle.ts @@ -0,0 +1,119 @@ +import os from 'node:os' +import { app } from 'electron' +import { + sanitizeCrashReportString, + type CrashReportDiagnosticBundle +} from '../../shared/crash-reporting' +import { collectDiagnosticBundle, getDiagnosticsStatus } from '../observability' +import { resolveDiagnosticOrcaChannel } from '../observability/diagnostic-upload-endpoint' +import type { FeedbackDiagnosticBundleAttachment, FeedbackSubmitResult } from '../ipc/feedback' + +const CRASH_REPORT_LOG_LOOKBACK_MINUTES = 3 * 24 * 60 + +export type CrashDiagnosticBundleAttachment = { + readonly diagnosticBundle: CrashReportDiagnosticBundle + readonly feedbackDiagnosticBundle?: FeedbackDiagnosticBundleAttachment +} + +function formatUnknownError(error: unknown): string { + return sanitizeCrashReportString(error instanceof Error ? error.message : String(error)) +} + +function skippedCrashDiagnosticBundle(): CrashDiagnosticBundleAttachment { + return { + diagnosticBundle: { + status: 'not_uploaded', + reason: 'diagnostic log upload skipped by user' + } + } +} + +function collectCrashDiagnosticBundleAttachment(): CrashDiagnosticBundleAttachment { + const status = getDiagnosticsStatus() + if (!status.bundleEnabled) { + return { + diagnosticBundle: { + status: 'not_uploaded', + reason: status.disabledReason ?? 'diagnostic bundle collection is disabled' + } + } + } + + let bundle: ReturnType + try { + bundle = collectDiagnosticBundle({ + appVersion: app.getVersion(), + platform: os.platform(), + arch: os.arch(), + osRelease: os.release(), + orcaChannel: resolveDiagnosticOrcaChannel(), + // Why: Help > Report Crash is often used after relaunch, long after the + // default 30 minute support bundle window would miss the failure context. + lookbackMinutes: CRASH_REPORT_LOG_LOOKBACK_MINUTES + }) + } catch (error) { + return { diagnosticBundle: { status: 'not_uploaded', reason: formatUnknownError(error) } } + } + + return { + diagnosticBundle: { + status: 'attached', + bundleSubmissionId: bundle.bundleSubmissionId, + bytes: bundle.bytes, + spanCount: bundle.spanCount + }, + feedbackDiagnosticBundle: { + bundleSubmissionId: bundle.bundleSubmissionId, + content: bundle.payload, + bytes: bundle.bytes, + spanCount: bundle.spanCount + } + } +} + +export function prepareCrashDiagnosticBundle( + includeDiagnosticLogs: boolean +): CrashDiagnosticBundleAttachment { + return includeDiagnosticLogs + ? collectCrashDiagnosticBundleAttachment() + : skippedCrashDiagnosticBundle() +} + +export function diagnosticBundleForReportOnlyRetry( + attachment: CrashDiagnosticBundleAttachment +): CrashReportDiagnosticBundle | undefined { + const bundle = attachment.feedbackDiagnosticBundle + if (!bundle) { + return undefined + } + return { + status: 'not_uploaded', + reason: 'diagnostic log attachment could not be sent; report retried without logs', + bundleSubmissionId: bundle.bundleSubmissionId, + bytes: bundle.bytes, + spanCount: bundle.spanCount + } +} + +export function resolveSubmittedDiagnosticBundle( + attachment: CrashDiagnosticBundleAttachment, + result: FeedbackSubmitResult +): CrashReportDiagnosticBundle { + const bundle = attachment.feedbackDiagnosticBundle + if (!bundle) { + return attachment.diagnosticBundle + } + const failure = + result.diagnosticBundleFailure ?? + (!result.ok ? { status: result.status, error: result.error } : undefined) + if (!failure) { + return attachment.diagnosticBundle + } + return { + status: 'not_uploaded', + reason: `diagnostic log attachment failed: ${formatUnknownError(failure.error)}`, + bundleSubmissionId: bundle.bundleSubmissionId, + bytes: bundle.bytes, + spanCount: bundle.spanCount + } +} diff --git a/src/main/crash-reporting/crash-report-copy-text.test.ts b/src/main/crash-reporting/crash-report-copy-text.test.ts new file mode 100644 index 000000000..3a8ec8880 --- /dev/null +++ b/src/main/crash-reporting/crash-report-copy-text.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from 'vitest' +import { formatCrashReportCopyText } from './crash-report-copy-text' + +describe('formatCrashReportCopyText', () => { + it('appends only sanitized report and diagnostic omission failure fields', () => { + const text = formatCrashReportCopyText('[Crash Report]', { + error: 'proxy failed at C:\\Users\\alice\\Orca', + diagnosticContext: { + status: 'not_uploaded', + reason: 'timeout token=super-secret-value\n- Forged field: hidden', + internalEndpointError: 'must-not-cross-copy-boundary' + }, + internalTransportFailure: 'must-not-cross-copy-boundary' + }) + + expect(text).toContain('Submission failure:') + expect(text).toContain('Report error: proxy failed at [redacted-path]') + expect(text).toContain('Diagnostic logs not uploaded: timeout token=[redacted]') + expect(text).not.toContain('\n- Forged field') + expect(text).not.toContain('alice') + expect(text).not.toContain('must-not-cross-copy-boundary') + }) + + it('includes a sanitized uploaded ticket without accepting unrelated fields', () => { + const text = formatCrashReportCopyText('[Crash Report]', { + error: 'report link failed', + diagnosticContext: { + status: 'uploaded', + ticketId: 'ticket-123', + bundleSubmissionId: 'not-allow-listed' + } + }) + + expect(text).toContain('Diagnostic ticket uploaded but not linked: ticket-123') + expect(text).not.toContain('not-allow-listed') + }) + + it('leaves the report unchanged when failure context is invalid', () => { + expect(formatCrashReportCopyText('[Crash Report]', { error: '' })).toBe('[Crash Report]') + }) +}) diff --git a/src/main/crash-reporting/crash-report-copy-text.ts b/src/main/crash-reporting/crash-report-copy-text.ts new file mode 100644 index 000000000..681b8bd9e --- /dev/null +++ b/src/main/crash-reporting/crash-report-copy-text.ts @@ -0,0 +1,53 @@ +import { + sanitizeCrashReportString, + type CrashReportCopySubmissionFailure +} from '../../shared/crash-reporting' + +function sanitizedNonEmptyString(value: unknown): string | null { + if (typeof value !== 'string') { + return null + } + const sanitized = sanitizeCrashReportString(value.replace(/[\r\n]+/g, ' ')).trim() + return sanitized || null +} + +function normalizeSubmissionFailure(value: unknown): CrashReportCopySubmissionFailure | null { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return null + } + const record = value as Record + const error = sanitizedNonEmptyString(record.error) + if (!error) { + return null + } + + const rawContext = record.diagnosticContext + if (!rawContext || typeof rawContext !== 'object' || Array.isArray(rawContext)) { + return { error } + } + const context = rawContext as Record + if (context.status === 'uploaded') { + const ticketId = sanitizedNonEmptyString(context.ticketId) + return ticketId ? { error, diagnosticContext: { status: 'uploaded', ticketId } } : { error } + } + if (context.status === 'not_uploaded') { + const reason = sanitizedNonEmptyString(context.reason) + return reason ? { error, diagnosticContext: { status: 'not_uploaded', reason } } : { error } + } + return { error } +} + +export function formatCrashReportCopyText(baseText: string, submissionFailure: unknown): string { + const failure = normalizeSubmissionFailure(submissionFailure) + if (!failure) { + return baseText + } + + const lines = [baseText, '', 'Submission failure:', `- Report error: ${failure.error}`] + if (failure.diagnosticContext?.status === 'uploaded') { + lines.push(`- Diagnostic ticket uploaded but not linked: ${failure.diagnosticContext.ticketId}`) + } else if (failure.diagnosticContext?.status === 'not_uploaded') { + lines.push(`- Diagnostic logs not uploaded: ${failure.diagnosticContext.reason}`) + } + return lines.join('\n') +} diff --git a/src/main/crash-reporting/crash-report-store.test.ts b/src/main/crash-reporting/crash-report-store.test.ts index 2dc9a87aa..1a14a9fa2 100644 --- a/src/main/crash-reporting/crash-report-store.test.ts +++ b/src/main/crash-reporting/crash-report-store.test.ts @@ -1,7 +1,17 @@ import fs from 'node:fs/promises' import os from 'node:os' import path from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' + +const { grantDirAclAsyncMock } = vi.hoisted(() => ({ + grantDirAclAsyncMock: vi.fn().mockResolvedValue(undefined) +})) + +vi.mock('../win32-utils', async (importOriginal) => { + const actual = (await importOriginal()) as Record + return { ...actual, grantDirAclAsync: grantDirAclAsyncMock } +}) + import { CrashReportStore } from './crash-report-store' import type { CrashReportCreateInput } from '../../shared/crash-reporting' @@ -38,6 +48,9 @@ function input(reason = 'crashed'): CrashReportCreateInput { } afterEach(async () => { + vi.restoreAllMocks() + grantDirAclAsyncMock.mockReset() + grantDirAclAsyncMock.mockResolvedValue(undefined) await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true }))) }) @@ -134,4 +147,72 @@ describe('CrashReportStore', () => { await expect(store.listRecent()).resolves.toHaveLength(5) }) + + it('waits for an in-flight crash write before reading the pending report', async () => { + const { store } = await createStore() + + const recordPromise = store.record(input()) + const pendingPromise = store.getLatestPending() + const report = await recordPromise + + await expect(pendingPromise).resolves.toMatchObject({ id: report.id, status: 'pending' }) + }) + + it('repairs the Windows userData ACL and retries a denied crash write', async () => { + const { store, filePath } = await createStore() + vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + const permissionError = Object.assign(new Error('permission denied'), { code: 'EPERM' }) + const writeFileSpy = vi.spyOn(fs, 'writeFile').mockRejectedValueOnce(permissionError) + + const report = await store.record(input()) + + expect(grantDirAclAsyncMock).toHaveBeenCalledWith(path.dirname(filePath)) + expect(writeFileSpy).toHaveBeenCalledTimes(2) + await expect(store.getLatestPending()).resolves.toMatchObject({ id: report.id }) + }) + + it.each(['EPERM', 'EACCES', 'EBUSY'] as const)( + 'recovers a pending report after a transient Windows %s read failure', + async (code) => { + const { store, filePath } = await createStore() + const report = await store.record(input()) + const reloaded = new CrashReportStore(filePath) + vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + const readError = Object.assign(new Error('temporary read failure'), { code }) + const readFileSpy = vi.spyOn(fs, 'readFile').mockRejectedValueOnce(readError) + + await expect(reloaded.getLatestPending()).resolves.toMatchObject({ id: report.id }) + + expect(readFileSpy).toHaveBeenCalledTimes(2) + if (code === 'EBUSY') { + expect(grantDirAclAsyncMock).not.toHaveBeenCalled() + } else { + expect(grantDirAclAsyncMock).toHaveBeenCalledOnce() + expect(grantDirAclAsyncMock).toHaveBeenCalledWith(path.dirname(filePath)) + } + } + ) + + it('retries a transient Windows rename lock', async () => { + const { store } = await createStore() + vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + const busyError = Object.assign(new Error('file busy'), { code: 'EBUSY' }) + const renameSpy = vi.spyOn(fs, 'rename').mockRejectedValueOnce(busyError) + + await expect(store.record(input())).resolves.toMatchObject({ status: 'pending' }) + + expect(renameSpy).toHaveBeenCalledTimes(2) + expect(grantDirAclAsyncMock).not.toHaveBeenCalled() + }) + + it('removes its temp file after a terminal write failure', async () => { + const { store, filePath } = await createStore() + const ioError = Object.assign(new Error('disk error'), { code: 'EIO' }) + vi.spyOn(fs, 'rename').mockRejectedValueOnce(ioError) + + await expect(store.record(input())).rejects.toBe(ioError) + + const entries = await fs.readdir(path.dirname(filePath)) + expect(entries.filter((entry) => entry.endsWith('.tmp'))).toEqual([]) + }) }) diff --git a/src/main/crash-reporting/crash-report-store.ts b/src/main/crash-reporting/crash-report-store.ts index e1791398e..35f9eb5cb 100644 --- a/src/main/crash-reporting/crash-report-store.ts +++ b/src/main/crash-reporting/crash-report-store.ts @@ -3,6 +3,7 @@ import fs from 'node:fs/promises' import os from 'node:os' import path from 'node:path' import { app } from 'electron' +import { grantDirAclAsync, isPermissionError } from '../win32-utils' import { formatCrashReportText, sanitizeCrashReportBreadcrumbs, @@ -14,6 +15,7 @@ import { const MAX_REPORTS = 5 const RELATED_CRASH_WINDOW_MS = 5_000 +const WINDOWS_FILE_OPERATION_RETRY_DELAYS_MS = [50, 100, 150, 200, 250] type CrashReportFile = { reports: CrashReportRecord[] @@ -37,6 +39,46 @@ function isRelatedCrashEvent(anchor: CrashReportRecord, candidate: CrashReportRe ) } +function isRetryableWindowsFileOperationError(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException).code + return code === 'EPERM' || code === 'EACCES' || code === 'EBUSY' +} + +async function wait(delayMs: number): Promise { + await new Promise((resolve) => setTimeout(resolve, delayMs)) +} + +async function runCrashReportFileOperationWithWindowsRecovery( + directory: string, + operation: () => Promise +): Promise { + let repairedAcl = false + for (let attempt = 0; ; attempt += 1) { + try { + return await operation() + } catch (error) { + if ( + process.platform !== 'win32' || + !isRetryableWindowsFileOperationError(error) || + attempt >= WINDOWS_FILE_OPERATION_RETRY_DELAYS_MS.length + ) { + throw error + } + if (!repairedAcl && isPermissionError(error)) { + repairedAcl = true + try { + // Why: Chromium can reset userData ACLs before startup capture or + // recovery, so both the crash write and next prompt must repair it. + await grantDirAclAsync(directory) + } catch { + // The bounded retry below still handles transient file locks. + } + } + await wait(WINDOWS_FILE_OPERATION_RETRY_DELAYS_MS[attempt]) + } + } +} + export class CrashReportStore { private writeChain = Promise.resolve() @@ -135,7 +177,9 @@ export class CrashReportStore { mutate: (reports: CrashReportRecord[]) => Promise<{ reports: CrashReportRecord[]; result: T }> ): Promise { const run = this.writeChain.then(async () => { - const reports = await this.readReports() + // Why: awaiting writeChain from inside its own callback would deadlock; + // this writer already has exclusive ownership and can read disk directly. + const reports = await this.readReportsFromDisk() const { reports: nextReports, result } = await mutate(reports) await this.writeReports(nextReports) return result @@ -148,8 +192,18 @@ export class CrashReportStore { } private async readReports(): Promise { + // Why: renderer recovery can query the one-shot startup prompt while the + // crash write is still in flight. Wait so a successful capture is visible. + await this.writeChain + return this.readReportsFromDisk() + } + + private async readReportsFromDisk(): Promise { try { - const raw = await fs.readFile(this.filePath, 'utf8') + const raw = await runCrashReportFileOperationWithWindowsRecovery( + path.dirname(this.filePath), + () => fs.readFile(this.filePath, 'utf8') + ) const parsed = JSON.parse(raw) as Partial return Array.isArray(parsed.reports) ? parsed.reports.slice(0, MAX_REPORTS) : [] } catch (error) { @@ -161,9 +215,18 @@ export class CrashReportStore { } private async writeReports(reports: CrashReportRecord[]): Promise { - await fs.mkdir(path.dirname(this.filePath), { recursive: true }) + const directory = path.dirname(this.filePath) const tmpPath = `${this.filePath}.${process.pid}.${Date.now()}.${crypto.randomUUID()}.tmp` - await fs.writeFile(tmpPath, `${JSON.stringify({ reports }, null, 2)}${os.EOL}`, 'utf8') - await fs.rename(tmpPath, this.filePath) + try { + await runCrashReportFileOperationWithWindowsRecovery(directory, async () => { + await fs.mkdir(directory, { recursive: true }) + await fs.writeFile(tmpPath, `${JSON.stringify({ reports }, null, 2)}${os.EOL}`, 'utf8') + await fs.rename(tmpPath, this.filePath) + }) + } finally { + // Why: disk-full and terminal rename failures must not accumulate a new + // orphaned multi-report temp file after every crash. + await fs.rm(tmpPath, { force: true }).catch(() => {}) + } } } diff --git a/src/main/crash-reporting/durable-crash-breadcrumb.test.ts b/src/main/crash-reporting/durable-crash-breadcrumb.test.ts new file mode 100644 index 000000000..78c04f44d --- /dev/null +++ b/src/main/crash-reporting/durable-crash-breadcrumb.test.ts @@ -0,0 +1,74 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { clearCrashBreadcrumbsForTest, getCrashBreadcrumbSnapshot } from './crash-breadcrumb-store' +import { recordDurableCrashBreadcrumb } from './durable-crash-breadcrumb' +import { _resetTracerForTests, setActiveSink, type TracerSink } from '../observability/tracer' + +type CapturingSink = TracerSink & { records: unknown[]; flushMock: ReturnType } + +function capturingSink(): CapturingSink { + const records: unknown[] = [] + const flushMock = vi.fn() + return { + records, + flushMock, + push: (record) => records.push(record), + flush: flushMock, + close: vi.fn() + } +} + +let sink: CapturingSink + +beforeEach(() => { + sink = capturingSink() + setActiveSink(sink) + clearCrashBreadcrumbsForTest() +}) + +afterEach(() => { + _resetTracerForTests() + clearCrashBreadcrumbsForTest() +}) + +describe('recordDurableCrashBreadcrumb', () => { + it('records, traces, and flushes a sanitized crash breadcrumb', () => { + recordDurableCrashBreadcrumb('process_gone_suppressed', { + source: 'renderer', + path: 'C:\\Users\\alice\\project' + }) + + expect(getCrashBreadcrumbSnapshot()).toEqual([ + expect.objectContaining({ + name: 'process_gone_suppressed', + data: { source: 'renderer', path: '[redacted-path]' } + }) + ]) + expect(sink.records).toEqual([ + expect.objectContaining({ + name: 'crash.breadcrumb', + attributes: expect.objectContaining({ + kind: 'crash-breadcrumb', + 'breadcrumb.name': 'process_gone_suppressed' + }), + exit: { _tag: 'Success' } + }) + ]) + expect(sink.flushMock).toHaveBeenCalledOnce() + }) + + it('records persistence failures as failed, flushed spans', () => { + recordDurableCrashBreadcrumb( + 'crash_report_persist_failed', + { errorCode: 'EPERM' }, + 'EPERM at C:\\Users\\alice\\AppData\\Roaming\\Orca' + ) + + expect(sink.records).toEqual([ + expect.objectContaining({ + exit: expect.objectContaining({ _tag: 'Failure', cause: expect.stringContaining('EPERM') }) + }) + ]) + expect(JSON.stringify(sink.records)).not.toContain('alice') + expect(sink.flushMock).toHaveBeenCalledOnce() + }) +}) diff --git a/src/main/crash-reporting/durable-crash-breadcrumb.ts b/src/main/crash-reporting/durable-crash-breadcrumb.ts new file mode 100644 index 000000000..14cca5e1b --- /dev/null +++ b/src/main/crash-reporting/durable-crash-breadcrumb.ts @@ -0,0 +1,33 @@ +import { + sanitizeCrashReportDetails, + sanitizeCrashReportString, + type CrashReportBreadcrumbData +} from '../../shared/crash-reporting' +import { flushActiveSink, startSpan } from '../observability/tracer' +import { recordCrashBreadcrumb } from './crash-breadcrumb-store' + +export function recordDurableCrashBreadcrumb( + name: string, + data?: CrashReportBreadcrumbData, + failureCause?: string +): void { + const sanitizedName = sanitizeCrashReportString(name) + const sanitizedData = data ? sanitizeCrashReportDetails(data) : undefined + recordCrashBreadcrumb(sanitizedName, sanitizedData) + + const span = startSpan('crash.breadcrumb', { + attributes: { + kind: 'crash-breadcrumb', + 'breadcrumb.name': sanitizedName, + ...(sanitizedData ? { 'breadcrumb.data': sanitizedData } : {}) + } + }) + if (failureCause) { + span.fail(sanitizeCrashReportString(failureCause, 1_000)) + } else { + span.end() + } + // Why: these breadcrumbs explain a missing crash record; losing one to the + // normal trace batching window would recreate the diagnostic blind spot. + flushActiveSink() +} diff --git a/src/main/crash-reporting/process-gone-dedupe.test.ts b/src/main/crash-reporting/process-gone-dedupe.test.ts index 6beebfd49..c4a2dc714 100644 --- a/src/main/crash-reporting/process-gone-dedupe.test.ts +++ b/src/main/crash-reporting/process-gone-dedupe.test.ts @@ -11,6 +11,27 @@ describe('ProcessGoneDedupe', () => { expect(dedupe.shouldRecord(key, 3_000)).toBe(true) }) + it('allows an immediate retry after a failed claim is released', () => { + const dedupe = new ProcessGoneDedupe({ windowMs: 2_000 }) + const claim = dedupe.tryClaim('renderer', 1_000) + + expect(claim).not.toBeNull() + expect(dedupe.tryClaim('renderer', 1_001)).toBeNull() + dedupe.release(claim!) + expect(dedupe.tryClaim('renderer', 1_001)).not.toBeNull() + }) + + it('does not release a newer claim when an older persistence attempt fails late', () => { + const dedupe = new ProcessGoneDedupe({ windowMs: 2_000 }) + const oldClaim = dedupe.tryClaim('renderer', 1_000) + const currentClaim = dedupe.tryClaim('renderer', 3_000) + + expect(oldClaim).not.toBeNull() + expect(currentClaim).not.toBeNull() + dedupe.release(oldClaim!) + expect(dedupe.tryClaim('renderer', 3_001)).toBeNull() + }) + it('prunes stale keys outside the dedupe window', () => { const dedupe = new ProcessGoneDedupe({ windowMs: 2_000 }) diff --git a/src/main/crash-reporting/process-gone-dedupe.ts b/src/main/crash-reporting/process-gone-dedupe.ts index eb746a18e..b35cccc65 100644 --- a/src/main/crash-reporting/process-gone-dedupe.ts +++ b/src/main/crash-reporting/process-gone-dedupe.ts @@ -6,10 +6,19 @@ type ProcessGoneDedupeOptions = { maxKeys?: number } +export type ProcessGoneDedupeClaim = { + readonly key: string +} + +type ProcessGoneDedupeEntry = { + readonly recordedAt: number + readonly claim: ProcessGoneDedupeClaim +} + export class ProcessGoneDedupe { private readonly windowMs: number private readonly maxKeys: number - private readonly recentKeys = new Map() + private readonly recentKeys = new Map() constructor(options: ProcessGoneDedupeOptions = {}) { this.windowMs = options.windowMs ?? DEFAULT_PROCESS_GONE_DEDUPE_WINDOW_MS @@ -17,19 +26,33 @@ export class ProcessGoneDedupe { } shouldRecord(key: string, now = Date.now()): boolean { + return this.tryClaim(key, now) !== null + } + + tryClaim(key: string, now = Date.now()): ProcessGoneDedupeClaim | null { this.prune(now) const previous = this.recentKeys.get(key) - if (previous !== undefined && now - previous < this.windowMs) { - return false + if (previous && now - previous.recordedAt < this.windowMs) { + return null } + const claim = { key } // Why: process-gone tuples come from Electron and can vary by exit code; // keep the short dedupe window without retaining stale tuples forever. this.recentKeys.delete(key) - this.recentKeys.set(key, now) + this.recentKeys.set(key, { recordedAt: now, claim }) this.prune(now) - return true + return claim + } + + release(claim: ProcessGoneDedupeClaim): void { + const current = this.recentKeys.get(claim.key) + // Why: an old failed write must not erase a newer claim for the same + // renderer after the dedupe window expires or bounded entries are evicted. + if (current?.claim === claim) { + this.recentKeys.delete(claim.key) + } } get size(): number { @@ -37,8 +60,8 @@ export class ProcessGoneDedupe { } private prune(now: number): void { - for (const [key, recordedAt] of this.recentKeys) { - if (now - recordedAt >= this.windowMs) { + for (const [key, entry] of this.recentKeys) { + if (now - entry.recordedAt >= this.windowMs) { this.recentKeys.delete(key) } } diff --git a/src/main/crash-reporting/process-gone-diagnostics.test.ts b/src/main/crash-reporting/process-gone-diagnostics.test.ts index 769ed6187..e179cec86 100644 --- a/src/main/crash-reporting/process-gone-diagnostics.test.ts +++ b/src/main/crash-reporting/process-gone-diagnostics.test.ts @@ -71,6 +71,7 @@ describe('process gone diagnostics', () => { processType: 'Utility', reason: 'killed', exitCode: 1, + expectedTeardown: 'app-shutdown', details: { name: 'Network Service', serviceName: 'network.mojom.NetworkService', @@ -82,6 +83,7 @@ describe('process gone diagnostics', () => { processType: 'Utility', reason: 'killed', exitCode: 1, + expectedTeardown: 'app-shutdown', name: 'Network Service', serviceName: 'network.mojom.NetworkService' }) diff --git a/src/main/crash-reporting/process-gone-diagnostics.ts b/src/main/crash-reporting/process-gone-diagnostics.ts index 42c8cad31..fd93c48b8 100644 --- a/src/main/crash-reporting/process-gone-diagnostics.ts +++ b/src/main/crash-reporting/process-gone-diagnostics.ts @@ -4,6 +4,7 @@ import { type CrashReportBreadcrumbData, type CrashReportDetailValue } from '../../shared/crash-reporting' +import type { ExpectedTeardownScope } from './process-gone-classification' type ProcessMetricLike = { pid?: unknown @@ -124,19 +125,22 @@ export function buildSuppressedProcessGoneBreadcrumbData({ processType, reason, exitCode, + expectedTeardown, details }: { source: 'renderer' | 'child' processType: string reason: string exitCode: number | null + expectedTeardown: ExpectedTeardownScope details: Record }): CrashReportBreadcrumbData { const breadcrumb: CrashReportBreadcrumbData = { source, processType, reason, - exitCode + exitCode, + expectedTeardown } const name = safeString(details.name) if (name) { diff --git a/src/main/crash-reporting/process-gone-recorder.test.ts b/src/main/crash-reporting/process-gone-recorder.test.ts new file mode 100644 index 000000000..94a67982f --- /dev/null +++ b/src/main/crash-reporting/process-gone-recorder.test.ts @@ -0,0 +1,213 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ + app: { + getVersion: () => '1.2.3-test', + getAppMetrics: () => [] + } +})) + +import { clearCrashBreadcrumbsForTest, getCrashBreadcrumbSnapshot } from './crash-breadcrumb-store' +import { ProcessGoneDedupe } from './process-gone-dedupe' +import { recordProcessGoneCrash, type ProcessGoneCrashEvent } from './process-gone-recorder' +import { _resetTracerForTests, setActiveSink, type TracerSink } from '../observability/tracer' + +type CapturingSink = TracerSink & { records: unknown[]; flushMock: ReturnType } + +function capturingSink(): CapturingSink { + const records: unknown[] = [] + const flushMock = vi.fn() + return { + records, + flushMock, + push: (record) => records.push(record), + flush: flushMock, + close: vi.fn() + } +} + +function event(overrides: Partial = {}): ProcessGoneCrashEvent { + return { + source: 'renderer', + processType: 'renderer', + reason: 'crashed', + exitCode: 5, + expectedTeardown: 'none', + details: { processType: 'renderer' }, + ...overrides + } +} + +let sink: CapturingSink + +beforeEach(() => { + sink = capturingSink() + setActiveSink(sink) + clearCrashBreadcrumbsForTest() +}) + +afterEach(() => { + vi.restoreAllMocks() + _resetTracerForTests() + clearCrashBreadcrumbsForTest() +}) + +describe('recordProcessGoneCrash', () => { + it('durably records when the crash report store is unavailable', () => { + recordProcessGoneCrash(null, event(), new ProcessGoneDedupe()) + + expect(getCrashBreadcrumbSnapshot()).toEqual([ + expect.objectContaining({ + name: 'crash_report_store_unavailable', + data: expect.objectContaining({ + source: 'renderer', + expectedTeardown: 'none' + }) + }) + ]) + expect(sink.records).toEqual([ + expect.objectContaining({ + name: 'crash.breadcrumb', + exit: expect.objectContaining({ _tag: 'Failure' }) + }) + ]) + expect(sink.flushMock).toHaveBeenCalledOnce() + }) + + it('durably records why an expected renderer teardown was suppressed', () => { + const record = vi.fn() + + recordProcessGoneCrash( + { record } as never, + event({ reason: 'killed', exitCode: 1, expectedTeardown: 'renderer-reload' }), + new ProcessGoneDedupe() + ) + + expect(record).not.toHaveBeenCalled() + expect(getCrashBreadcrumbSnapshot()).toEqual([ + expect.objectContaining({ + name: 'process_gone_suppressed', + data: expect.objectContaining({ expectedTeardown: 'renderer-reload' }) + }) + ]) + expect(sink.records).toEqual([ + expect.objectContaining({ + name: 'crash.breadcrumb', + attributes: expect.objectContaining({ + 'breadcrumb.name': 'process_gone_suppressed' + }) + }) + ]) + expect(sink.flushMock).toHaveBeenCalledOnce() + }) + + it('persists a report and flushes the process-gone trace before recovery', async () => { + const record = vi.fn().mockResolvedValue({ id: 'report-1' }) + + recordProcessGoneCrash({ record } as never, event(), new ProcessGoneDedupe()) + + await vi.waitFor(() => expect(record).toHaveBeenCalledOnce()) + expect(record).toHaveBeenCalledWith( + expect.objectContaining({ source: 'renderer', reason: 'crashed', exitCode: 5 }) + ) + expect(sink.records).toEqual([ + expect.objectContaining({ + name: 'electron.process_gone', + exit: expect.objectContaining({ _tag: 'Failure' }) + }) + ]) + expect(sink.flushMock).toHaveBeenCalledOnce() + }) + + it('still persists the report when the forced trace flush fails', async () => { + const record = vi.fn().mockResolvedValue({ id: 'report-1' }) + sink.flushMock.mockImplementation(() => { + throw new Error('trace disk unavailable') + }) + + expect(() => + recordProcessGoneCrash({ record } as never, event(), new ProcessGoneDedupe()) + ).not.toThrow() + await vi.waitFor(() => expect(record).toHaveBeenCalledOnce()) + }) + + it('still persists the report when the trace sink handoff fails', async () => { + const record = vi.fn().mockResolvedValue({ id: 'report-1' }) + sink.push = () => { + throw new Error('trace rotation failed') + } + + expect(() => + recordProcessGoneCrash({ record } as never, event(), new ProcessGoneDedupe()) + ).not.toThrow() + await vi.waitFor(() => expect(record).toHaveBeenCalledOnce()) + }) + + it('durably records a sanitized crash-report persistence failure', async () => { + const persistError = Object.assign( + new Error('EPERM at C:\\Users\\alice\\AppData\\Roaming\\Orca\\crash-reports.json'), + { code: 'EPERM' } + ) + const record = vi.fn().mockRejectedValue(persistError) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + recordProcessGoneCrash({ record } as never, event(), new ProcessGoneDedupe()) + + await vi.waitFor(() => { + expect(getCrashBreadcrumbSnapshot()).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + name: 'crash_report_persist_failed', + data: expect.objectContaining({ errorCode: 'EPERM' }) + }) + ]) + ) + }) + expect(sink.records).toHaveLength(2) + expect(sink.records[1]).toEqual( + expect.objectContaining({ + name: 'crash.breadcrumb', + exit: expect.objectContaining({ _tag: 'Failure' }) + }) + ) + expect(JSON.stringify(sink.records)).not.toContain('alice') + expect(sink.flushMock).toHaveBeenCalledTimes(2) + }) + + it('keeps null persistence rejections inside the fail-open diagnostic path', async () => { + const record = vi.fn().mockRejectedValue(null) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + recordProcessGoneCrash({ record } as never, event(), new ProcessGoneDedupe()) + + await vi.waitFor(() => + expect(getCrashBreadcrumbSnapshot()).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + name: 'crash_report_persist_failed', + data: expect.objectContaining({ errorName: 'object', errorMessage: 'null' }) + }) + ]) + ) + ) + }) + + it('allows the same renderer crash to retry after persistence fails', async () => { + const record = vi + .fn() + .mockRejectedValueOnce(new Error('disk unavailable')) + .mockResolvedValueOnce({ id: 'report-2' }) + const dedupe = new ProcessGoneDedupe() + vi.spyOn(console, 'error').mockImplementation(() => {}) + + recordProcessGoneCrash({ record } as never, event(), dedupe) + await vi.waitFor(() => + expect(getCrashBreadcrumbSnapshot()).toEqual( + expect.arrayContaining([expect.objectContaining({ name: 'crash_report_persist_failed' })]) + ) + ) + recordProcessGoneCrash({ record } as never, event(), dedupe) + + await vi.waitFor(() => expect(record).toHaveBeenCalledTimes(2)) + }) +}) diff --git a/src/main/crash-reporting/process-gone-recorder.ts b/src/main/crash-reporting/process-gone-recorder.ts new file mode 100644 index 000000000..daec429ae --- /dev/null +++ b/src/main/crash-reporting/process-gone-recorder.ts @@ -0,0 +1,137 @@ +import os from 'node:os' +import { app } from 'electron' +import { isCrashReportReason, sanitizeCrashReportString } from '../../shared/crash-reporting' +import type { CrashReportStore } from './crash-report-store' +import { getCrashBreadcrumbSnapshot } from './crash-breadcrumb-store' +import { recordDurableCrashBreadcrumb } from './durable-crash-breadcrumb' +import { + shouldRecordProcessGoneCrash, + type ExpectedTeardownScope, + type ProcessGoneSource +} from './process-gone-classification' +import { + buildProcessGoneCrashDetails, + buildSuppressedProcessGoneBreadcrumbData +} from './process-gone-diagnostics' +import { + getProcessGoneDedupeKey, + processGoneDedupe, + type ProcessGoneDedupe +} from './process-gone-dedupe' +import { flushActiveSink, startSpan } from '../observability/tracer' + +export type ProcessGoneCrashEvent = { + source: ProcessGoneSource + processType: string + reason: string + exitCode: number | null + expectedTeardown: ExpectedTeardownScope + details: Record +} + +type CrashReportRecorderStore = Pick + +function processGoneBreadcrumbData(event: ProcessGoneCrashEvent) { + return buildSuppressedProcessGoneBreadcrumbData(event) +} + +function persistFailureData(event: ProcessGoneCrashEvent, error: unknown) { + const errorCode = + typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string' + ? error.code + : undefined + return { + ...processGoneBreadcrumbData(event), + errorName: error instanceof Error ? error.name : typeof error, + errorMessage: sanitizeCrashReportString(error instanceof Error ? error.message : String(error)), + ...(errorCode ? { errorCode } : {}) + } +} + +export function recordProcessGoneCrash( + store: CrashReportRecorderStore | null, + event: ProcessGoneCrashEvent, + dedupe: ProcessGoneDedupe = processGoneDedupe +): void { + if (!isCrashReportReason(event.reason)) { + return + } + if ( + !shouldRecordProcessGoneCrash({ + source: event.source, + processType: event.processType, + serviceName: + typeof event.details.serviceName === 'string' ? event.details.serviceName : undefined, + reason: event.reason, + exitCode: event.exitCode, + expectedTeardown: event.expectedTeardown + }) + ) { + recordDurableCrashBreadcrumb('process_gone_suppressed', processGoneBreadcrumbData(event)) + return + } + if (!store) { + recordDurableCrashBreadcrumb( + 'crash_report_store_unavailable', + processGoneBreadcrumbData(event), + 'Crash report store unavailable' + ) + return + } + + const key = getProcessGoneDedupeKey(event.source, event.processType, event.reason, event.exitCode) + const claim = dedupe.tryClaim(key) + if (!claim) { + return + } + const crashDetails = buildProcessGoneCrashDetails(event.details) + const breadcrumbs = getCrashBreadcrumbSnapshot() + const span = startSpan('electron.process_gone', { + attributes: { + 'crash.source': event.source, + 'crash.process_type': event.processType, + 'crash.reason': event.reason, + ...(event.exitCode !== null ? { 'crash.exit_code': event.exitCode } : {}), + 'app.version': app.getVersion(), + platform: process.platform, + osRelease: os.release(), + arch: process.arch, + electronVersion: process.versions.electron, + chromeVersion: process.versions.chrome, + details: crashDetails, + breadcrumbs + } + }) + // Why: a renderer crash can be followed by another process exit before the + // trace batch window closes, so make the primary signal durable immediately. + span.fail( + `${event.source} process gone: ${event.processType} ${event.reason} (${event.exitCode ?? 'unknown'})` + ) + flushActiveSink() + + void store + .record({ + source: event.source, + processType: event.processType, + reason: event.reason, + exitCode: event.exitCode, + appVersion: app.getVersion(), + platform: process.platform, + osRelease: os.release(), + arch: process.arch, + electronVersion: process.versions.electron ?? 'unknown', + chromeVersion: process.versions.chrome ?? 'unknown', + details: crashDetails, + breadcrumbs + }) + .catch((error) => { + dedupe.release(claim) + console.error('[crash-reporting] Failed to persist crash report:', error) + const data = persistFailureData(event, error) + recordDurableCrashBreadcrumb( + 'crash_report_persist_failed', + data, + `${String(data.errorName)}: ${String(data.errorMessage)}` + ) + }) +} diff --git a/src/main/index.ts b/src/main/index.ts index 975e3a459..27e9aee2a 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -26,7 +26,6 @@ import { closeAllWatchers } from './ipc/filesystem-watcher' import { disposeWorktreeBaseDirectoryWatchers } from './ipc/worktree-base-directory-watcher' import { registerCoreHandlers } from './ipc/register-core-handlers' import { initObservability, shutdownObservability } from './observability' -import { startSpan } from './observability/tracer' import { registerMobileHandlers } from './ipc/mobile' import { initTelemetry, shutdownTelemetry, trackAppOpenedOnce, track } from './telemetry/client' import { classifyError } from './telemetry/classify-error' @@ -159,28 +158,21 @@ import { buildHeadlessAutomationWorktreeCreateArgs } from './automations/headles import { AgentAwakeService } from './agent-awake-service' import { registerSystemResumeBroadcast } from './system-resume-broadcast' import { - getCrashBreadcrumbSnapshot, recordCoalescedCrashBreadcrumb, recordCrashBreadcrumb } from './crash-reporting/crash-breadcrumb-store' import { CrashReportStore } from './crash-reporting/crash-report-store' import { - shouldRecordProcessGoneCrash, shouldRecoverRendererAfterProcessGone, type ExpectedTeardownScope } from './crash-reporting/process-gone-classification' -import { - buildProcessGoneCrashDetails, - buildSuppressedProcessGoneBreadcrumbData -} from './crash-reporting/process-gone-diagnostics' -import { getProcessGoneDedupeKey, processGoneDedupe } from './crash-reporting/process-gone-dedupe' +import { recordProcessGoneCrash as recordProcessGoneCrashEvent } from './crash-reporting/process-gone-recorder' import { advanceSyntheticTitleSpinnerEntries, type SyntheticTitleSpinnerEntry } from './synthetic-title-spinner' import { shouldSendSyntheticTitleFrame } from './synthetic-title-visibility' import { shouldCopySyntheticTitleFrameToPtyData } from './synthetic-title-frame-routing' -import { isCrashReportReason } from '../shared/crash-reporting' import { getSyntheticAgentTitleProfile, shouldDriveSyntheticAgentTitleFromHook, @@ -833,14 +825,6 @@ function openMainWindow(): BrowserWindow { webContentsId ) }, - shouldRecordRendererCrash: (details, webContentsId) => - shouldRecordProcessGoneCrash({ - source: 'renderer', - processType: 'renderer', - reason: details.reason, - exitCode: details.exitCode ?? null, - expectedTeardown: getExpectedTeardownScope(webContentsId) - }), shouldRecoverRenderer: (details, webContentsId) => shouldRecoverRendererAfterProcessGone({ reason: details.reason, @@ -1229,75 +1213,14 @@ function recordProcessGoneCrash( details: Record, webContentsId?: number ): void { - if (!crashReports || !isCrashReportReason(reason)) { - return - } - if ( - !shouldRecordProcessGoneCrash({ - source, - processType, - serviceName: typeof details.serviceName === 'string' ? details.serviceName : undefined, - reason, - exitCode, - expectedTeardown: getExpectedTeardownScope(webContentsId) - }) - ) { - recordCrashBreadcrumb( - 'process_gone_suppressed', - buildSuppressedProcessGoneBreadcrumbData({ - source, - processType, - reason, - exitCode, - details - }) - ) - return - } - const key = getProcessGoneDedupeKey(source, processType, reason, exitCode) - if (!processGoneDedupe.shouldRecord(key)) { - return - } - const crashDetails = buildProcessGoneCrashDetails(details) - const span = startSpan('electron.process_gone', { - attributes: { - 'crash.source': source, - 'crash.process_type': processType, - 'crash.reason': reason, - ...(exitCode !== null ? { 'crash.exit_code': exitCode } : {}), - 'app.version': app.getVersion(), - platform: process.platform, - osRelease: os.release(), - arch: process.arch, - electronVersion: process.versions.electron, - chromeVersion: process.versions.chrome, - details: crashDetails, - breadcrumbs: getCrashBreadcrumbSnapshot() - } + recordProcessGoneCrashEvent(crashReports, { + source, + processType, + reason, + exitCode, + expectedTeardown: getExpectedTeardownScope(webContentsId), + details }) - // Why: renderer/child crashes belong in the local trace lane so the - // diagnostic bundle has the same process-gone signal as the startup prompt. - span.fail(`${source} process gone: ${processType} ${reason} (${exitCode ?? 'unknown'})`) - void crashReports - .record({ - source, - processType, - reason, - exitCode, - appVersion: app.getVersion(), - platform: process.platform, - osRelease: os.release(), - arch: process.arch, - electronVersion: process.versions.electron, - chromeVersion: process.versions.chrome, - details: crashDetails, - // Why: breadcrumbs stay memory-only during normal operation. Persist a - // snapshot only after Electron reports a crash-like process exit. - breadcrumbs: getCrashBreadcrumbSnapshot() - }) - .catch((error) => { - console.error('[crash-reporting] Failed to persist crash report:', error) - }) } function shutdownWatchersOnce(): Promise { diff --git a/src/main/ipc/crash-reporting.test.ts b/src/main/ipc/crash-reporting.test.ts index 04432899a..2c28cfd6c 100644 --- a/src/main/ipc/crash-reporting.test.ts +++ b/src/main/ipc/crash-reporting.test.ts @@ -185,6 +185,42 @@ describe('registerCrashReportingHandlers', () => { expect(listRecent).not.toHaveBeenCalled() }) + it('copies sanitized submission and diagnostic omission failures for a captured report', async () => { + const pending = report('pending', 'crash-copy-failure') + registerCrashReportingHandlers({ + getById: vi.fn(async () => pending), + dismiss: vi.fn(), + markSent: vi.fn(), + markDismissedSent: vi.fn(), + listRecent: vi.fn(async () => [pending]), + record: vi.fn(), + formatDiagnosticText: vi.fn() + } as never) + + const result = await handlers.get('crashReports:copyLatestDiagnostics')?.(null, { + reportId: pending.id, + notes: 'current notes', + submissionFailure: { + error: 'fallback failed at C:\\Users\\alice\\Orca', + diagnosticContext: { + status: 'not_uploaded', + reason: 'attachment token=super-secret-value', + internalEndpointError: 'must-not-cross-copy-boundary' + }, + diagnosticBundleFailure: 'must-not-cross-copy-boundary' + } + }) + + expect(result).toEqual({ ok: true }) + const copiedText = String(clipboardWriteTextMock.mock.calls[0]?.[0]) + expect(copiedText).toContain('Report ID: crash-copy-failure') + expect(copiedText).toContain('Submission failure:') + expect(copiedText).toContain('Report error: fallback failed at [redacted-path]') + expect(copiedText).toContain('Diagnostic logs not uploaded: attachment token=[redacted]') + expect(copiedText).not.toContain('alice') + expect(copiedText).not.toContain('must-not-cross-copy-boundary') + }) + it('returns dismissed unsent reports for the manual Help menu entry', async () => { const dismissed = report('dismissed', 'crash-help-menu') registerCrashReportingHandlers({ @@ -244,7 +280,8 @@ describe('registerCrashReportingHandlers', () => { content: diagnosticBundle().payload, bytes: 25, spanCount: 1 - } + }, + feedbackWithoutDiagnosticBundle: expect.stringContaining('Status: not uploaded') }) expect(markSent).toHaveBeenCalledWith(pending.id) }) @@ -294,7 +331,8 @@ describe('registerCrashReportingHandlers', () => { content: diagnosticBundle().payload, bytes: 25, spanCount: 1 - } + }, + feedbackWithoutDiagnosticBundle: expect.stringContaining('Status: not uploaded') }) expect(submitFeedbackMock).toHaveBeenCalledWith( expect.objectContaining({ feedback: expect.stringContaining('Status: attached') }) @@ -347,6 +385,52 @@ describe('registerCrashReportingHandlers', () => { ) }) + it('marks the report sent when transport retries successfully without diagnostic logs', async () => { + const pending = report('pending', 'crash-degraded') + const sent = report('sent', pending.id) + const markSent = vi.fn(async () => sent) + submitFeedbackMock.mockResolvedValueOnce({ + ok: true, + diagnosticBundleFailure: { status: 413, error: 'status 413' } + }) + registerCrashReportingHandlers({ + getById: vi.fn(async () => pending), + dismiss: vi.fn(), + markSent, + markDismissedSent: vi.fn(), + listRecent: vi.fn(async () => [pending]), + record: vi.fn(), + formatDiagnosticText: vi.fn() + } as never) + + const result = await handlers.get('crashReports:submit')?.(null, { + reportId: pending.id, + notes: 'manual report', + submitAnonymously: true, + githubLogin: null, + githubEmail: null + }) + + expect(result).toEqual({ + ok: true, + report: sent, + diagnosticBundle: { + status: 'not_uploaded', + reason: 'diagnostic log attachment failed: status 413', + bundleSubmissionId: 'bundleabcdefghijklmnop', + bytes: 25, + spanCount: 1 + } + }) + expect(markSent).toHaveBeenCalledWith(pending.id) + expect(submitFeedbackMock).toHaveBeenCalledWith( + expect.objectContaining({ + feedback: expect.stringContaining('Status: attached'), + feedbackWithoutDiagnosticBundle: expect.stringContaining('Status: not uploaded') + }) + ) + }) + it('submits the crash report without logs when the user excludes diagnostic logs', async () => { registerCrashReportingHandlers({ getById: vi.fn(async () => null), @@ -459,7 +543,8 @@ describe('registerCrashReportingHandlers', () => { content: diagnosticBundle().payload, bytes: 25, spanCount: 1 - } + }, + feedbackWithoutDiagnosticBundle: expect.stringContaining('Status: not uploaded') }) expect(markDismissedSent).toHaveBeenCalledWith(dismissed.id) }) @@ -492,8 +577,9 @@ describe('registerCrashReportingHandlers', () => { const markSent = vi.fn() submitFeedbackMock.mockResolvedValue({ ok: false, - status: 500, - error: 'status 500' + status: null, + error: 'report-only network failed', + diagnosticBundleFailure: { status: 500, error: 'status 500' } }) registerCrashReportingHandlers({ getById: vi.fn(async () => pending), @@ -514,10 +600,18 @@ describe('registerCrashReportingHandlers', () => { expect(result).toEqual({ ok: false, - status: 500, - error: 'status 500', - report: pending + status: null, + error: 'report-only network failed', + report: pending, + diagnosticBundle: { + status: 'not_uploaded', + reason: 'diagnostic log attachment failed: status 500', + bundleSubmissionId: 'bundleabcdefghijklmnop', + bytes: 25, + spanCount: 1 + } }) + expect(result).not.toHaveProperty('diagnosticBundleFailure') expect(submitFeedbackMock).toHaveBeenCalledWith( expect.objectContaining({ diagnosticBundle: { diff --git a/src/main/ipc/crash-reporting.ts b/src/main/ipc/crash-reporting.ts index 7d60da179..ac424d834 100644 --- a/src/main/ipc/crash-reporting.ts +++ b/src/main/ipc/crash-reporting.ts @@ -4,6 +4,7 @@ import os from 'node:os' import { app, clipboard, ipcMain } from 'electron' import { type CrashReportBreadcrumbData, + type CrashReportCopyDiagnosticsArgs, type CrashReportDiagnosticBundle, type ReactErrorBoundaryReportArgs, type ReactErrorBoundaryReportResult, @@ -20,14 +21,17 @@ import { getCrashBreadcrumbSnapshot, recordCrashBreadcrumb } from '../crash-reporting/crash-breadcrumb-store' -import { collectDiagnosticBundle, getDiagnosticsStatus } from '../observability' -import { resolveDiagnosticOrcaChannel } from '../observability/diagnostic-upload-endpoint' import { startSpan } from '../observability/tracer' -import type { FeedbackDiagnosticBundleAttachment } from './feedback' +import { + diagnosticBundleForReportOnlyRetry, + prepareCrashDiagnosticBundle, + resolveSubmittedDiagnosticBundle +} from '../crash-reporting/crash-feedback-diagnostic-bundle' import { assertClipboardTextWriteWithinLimit, isClipboardTextWriteTooLargeError } from '../../shared/clipboard-text' +import { formatCrashReportCopyText } from '../crash-reporting/crash-report-copy-text' const inFlightSubmissions = new Set() const submittedReportIds = new Set() @@ -37,7 +41,6 @@ const RENDERER_ERROR_DEDUPE_MS = 10 * 60 * 1000 const MAX_RENDERER_ERROR_KEY_AGE_MS = RENDERER_ERROR_DEDUPE_MS * 2 const MAX_RECENT_RENDERER_ERROR_REPORT_KEYS = 256 const MAX_SUBMITTED_REPORT_IDS = 256 -const CRASH_REPORT_LOG_LOOKBACK_MINUTES = 3 * 24 * 60 const REACT_ERROR_BOUNDARY_SURFACES = new Set([ 'app-root', @@ -52,11 +55,6 @@ const REACT_ERROR_BOUNDARY_SURFACES = new Set - try { - bundle = collectDiagnosticBundle({ - appVersion: app.getVersion(), - platform: os.platform(), - arch: os.arch(), - osRelease: os.release(), - orcaChannel: resolveDiagnosticOrcaChannel(), - // Why: Help > Report Crash is often used after relaunch, long after the - // default 30 minute support bundle window would miss the failure context. - lookbackMinutes: CRASH_REPORT_LOG_LOOKBACK_MINUTES - }) - } catch (error) { - return { diagnosticBundle: { status: 'not_uploaded', reason: formatUnknownError(error) } } - } - - return { - diagnosticBundle: { - status: 'attached', - bundleSubmissionId: bundle.bundleSubmissionId, - bytes: bundle.bytes, - spanCount: bundle.spanCount - }, - feedbackDiagnosticBundle: { - bundleSubmissionId: bundle.bundleSubmissionId, - content: bundle.payload, - bytes: bundle.bytes, - spanCount: bundle.spanCount - } - } -} - export function registerCrashReportingHandlers(store: CrashReportStore): void { ipcMain.removeHandler('crashReports:getLatestPending') ipcMain.handle('crashReports:getLatestPending', () => getLatestPendingReport(store)) @@ -412,15 +354,16 @@ export function registerCrashReportingHandlers(store: CrashReportStore): void { ipcMain.removeHandler('crashReports:copyLatestDiagnostics') ipcMain.handle( 'crashReports:copyLatestDiagnostics', - async (_event, args?: { reportId?: string; notes?: string }) => { + async (_event, args?: CrashReportCopyDiagnosticsArgs) => { const report = await getRequestedCrashReport(store, args) - if (!report) { - clipboard.writeText(buildUncapturedCrashReportText(args?.notes)) - return { ok: true as const } - } + const baseText = report + ? formatCrashReportText(report, args?.notes) + : buildUncapturedCrashReportText(args?.notes) try { clipboard.writeText( - assertClipboardTextWriteWithinLimit(formatCrashReportText(report, args?.notes)) + assertClipboardTextWriteWithinLimit( + formatCrashReportCopyText(baseText, args?.submissionFailure) + ) ) } catch (error) { if (isClipboardTextWriteTooLargeError(error)) { @@ -448,11 +391,9 @@ export function registerCrashReportingHandlers(store: CrashReportStore): void { async (_event, args: CrashReportSubmitArgs): Promise => { const report = await getRequestedCrashReport(store, args) if (!report) { - const diagnosticUpload = - args.includeDiagnosticLogs === false - ? skippedCrashDiagnosticBundle() - : collectCrashDiagnosticBundleAttachment() + const diagnosticUpload = prepareCrashDiagnosticBundle(args.includeDiagnosticLogs !== false) const diagnosticBundle = diagnosticUpload.diagnosticBundle + const reportOnlyDiagnosticBundle = diagnosticBundleForReportOnlyRetry(diagnosticUpload) const result = await submitFeedback({ feedback: buildUncapturedCrashReportText(args.notes, diagnosticBundle), submissionType: 'crash', @@ -460,14 +401,26 @@ export function registerCrashReportingHandlers(store: CrashReportStore): void { githubLogin: args.githubLogin, githubEmail: args.githubEmail, ...(diagnosticUpload.feedbackDiagnosticBundle - ? { diagnosticBundle: diagnosticUpload.feedbackDiagnosticBundle } + ? { + diagnosticBundle: diagnosticUpload.feedbackDiagnosticBundle, + feedbackWithoutDiagnosticBundle: buildUncapturedCrashReportText( + args.notes, + reportOnlyDiagnosticBundle + ) + } : {}) }) + const submittedDiagnosticBundle = resolveSubmittedDiagnosticBundle(diagnosticUpload, result) return result.ok - ? { ok: true, report: null, diagnosticBundle } + ? { ok: true, report: null, diagnosticBundle: submittedDiagnosticBundle } : { - ...result, - report: null + // Why: the transport-only attachment failure may contain raw + // endpoint detail; only its sanitized bundle reason crosses IPC. + ok: false, + status: result.status, + error: result.error, + report: null, + diagnosticBundle: submittedDiagnosticBundle } } const canSubmitDismissedReport = Boolean(args.reportId && report.status === 'dismissed') @@ -491,11 +444,9 @@ export function registerCrashReportingHandlers(store: CrashReportStore): void { inFlightSubmissions.add(report.id) try { - const diagnosticUpload = - args.includeDiagnosticLogs === false - ? skippedCrashDiagnosticBundle() - : collectCrashDiagnosticBundleAttachment() + const diagnosticUpload = prepareCrashDiagnosticBundle(args.includeDiagnosticLogs !== false) const diagnosticBundle = diagnosticUpload.diagnosticBundle + const reportOnlyDiagnosticBundle = diagnosticBundleForReportOnlyRetry(diagnosticUpload) const result = await submitFeedback({ feedback: formatCrashReportText(report, args.notes, diagnosticBundle), submissionType: 'crash', @@ -503,13 +454,26 @@ export function registerCrashReportingHandlers(store: CrashReportStore): void { githubLogin: args.githubLogin, githubEmail: args.githubEmail, ...(diagnosticUpload.feedbackDiagnosticBundle - ? { diagnosticBundle: diagnosticUpload.feedbackDiagnosticBundle } + ? { + diagnosticBundle: diagnosticUpload.feedbackDiagnosticBundle, + feedbackWithoutDiagnosticBundle: formatCrashReportText( + report, + args.notes, + reportOnlyDiagnosticBundle + ) + } : {}) }) + const submittedDiagnosticBundle = resolveSubmittedDiagnosticBundle(diagnosticUpload, result) if (!result.ok) { return { - ...result, - report + // Why: keep the renderer contract allow-listed instead of leaking + // the transport's internal diagnosticBundleFailure object. + ok: false, + status: result.status, + error: result.error, + report, + diagnosticBundle: submittedDiagnosticBundle } } rememberSubmittedReportId(report.id) @@ -518,21 +482,37 @@ export function registerCrashReportingHandlers(store: CrashReportStore): void { // Why: startup prompts are dismissed before the user can send from // the still-open dialog, so successful uploads must update storage. const sent = await store.markDismissedSent(report.id) - return { ok: true, report: sent ?? { ...report, status: 'sent' }, diagnosticBundle } + return { + ok: true, + report: sent ?? { ...report, status: 'sent' }, + diagnosticBundle: submittedDiagnosticBundle + } } catch (error) { console.error('[crash-reporting] Failed to mark dismissed crash report sent:', error) - return { ok: true, report: { ...report, status: 'sent' }, diagnosticBundle } + return { + ok: true, + report: { ...report, status: 'sent' }, + diagnosticBundle: submittedDiagnosticBundle + } } } try { const sent = await store.markSent(report.id) - return { ok: true, report: sent ?? { ...report, status: 'sent' }, diagnosticBundle } + return { + ok: true, + report: sent ?? { ...report, status: 'sent' }, + diagnosticBundle: submittedDiagnosticBundle + } } catch (error) { // Why: the upstream submission already succeeded. A local persistence // failure must not present as upload failure or invite duplicate sends // during this app session. console.error('[crash-reporting] Failed to mark crash report sent:', error) - return { ok: true, report: { ...report, status: 'sent' }, diagnosticBundle } + return { + ok: true, + report: { ...report, status: 'sent' }, + diagnosticBundle: submittedDiagnosticBundle + } } } finally { inFlightSubmissions.delete(report.id) diff --git a/src/main/ipc/feedback.test.ts b/src/main/ipc/feedback.test.ts index 1d8c30538..52de8251d 100644 --- a/src/main/ipc/feedback.test.ts +++ b/src/main/ipc/feedback.test.ts @@ -22,9 +22,34 @@ function okResponse(): Response { return { ok: true, status: 200 } as unknown as Response } -function postedBody(): Record { - const init = fetchMock.mock.calls[0]?.[1] as RequestInit | undefined - return JSON.parse(String(init?.body)) as Record +function errorResponse(status: number): Response { + return { ok: false, status } as unknown as Response +} + +function requestInit(callIndex = 0): RequestInit { + return fetchMock.mock.calls[callIndex]?.[1] as RequestInit +} + +function postedBody(callIndex = 0): Record { + return JSON.parse(String(requestInit(callIndex).body)) as Record +} + +function diagnosticSubmitArgs(): Parameters[0] { + return { + feedback: '[Crash Report]\n\nDiagnostic log:\n- Status: attached', + feedbackWithoutDiagnosticBundle: + '[Crash Report]\n\nDiagnostic log:\n- Status: not uploaded\n- Reason: attachment failed', + submissionType: 'crash', + submitAnonymously: true, + githubLogin: null, + githubEmail: null, + diagnosticBundle: { + bundleSubmissionId: 'bundleabcdefghijklmnop', + content: '{"type":"bundle-header"}\n', + bytes: 25, + spanCount: 1 + } + } } describe('submitFeedback', () => { @@ -139,6 +164,118 @@ describe('submitFeedback', () => { expect(JSON.parse(String(feedbackInit?.body))).not.toHaveProperty('diagnosticBundle') }) + it('retries a rejected diagnostic attachment as report-only JSON on the website API', async () => { + fetchMock.mockResolvedValueOnce(errorResponse(413)).mockResolvedValueOnce(okResponse()) + + await expect(submitFeedback(diagnosticSubmitArgs())).resolves.toEqual({ + ok: true, + diagnosticBundleFailure: { status: 413, error: 'status 413' } + }) + + expect(fetchMock).toHaveBeenCalledTimes(2) + expect(fetchMock.mock.calls[0]?.[0]).toBe('https://www.onorca.dev/v1/feedback') + expect(requestInit(0).body).toBeInstanceOf(FormData) + expect(fetchMock.mock.calls[1]?.[0]).toBe('https://www.onorca.dev/v1/feedback') + expect(requestInit(1).headers).toEqual({ + 'Content-Type': 'application/json' + }) + expect(postedBody(1)).toMatchObject({ + feedback: + '[Crash Report]\n\nDiagnostic log:\n- Status: not uploaded\n- Reason: attachment failed', + submissionType: 'crash' + }) + expect(postedBody(1)).not.toHaveProperty('diagnosticBundle') + }) + + it('retries a diagnostic attachment server error as report-only JSON on the fallback API', async () => { + fetchMock.mockResolvedValueOnce(errorResponse(500)).mockResolvedValueOnce(okResponse()) + + await expect(submitFeedback(diagnosticSubmitArgs())).resolves.toEqual({ + ok: true, + diagnosticBundleFailure: { status: 500, error: 'status 500' } + }) + + expect(fetchMock.mock.calls[1]?.[0]).toBe('https://api.onorca.dev/v1/feedback') + expect(requestInit(1).headers).toEqual({ 'Content-Type': 'application/json' }) + expect(postedBody(1)).not.toHaveProperty('diagnosticBundle') + }) + + it('retries a diagnostic attachment network error as report-only JSON on the fallback API', async () => { + fetchMock.mockRejectedValueOnce(new Error('attachment network failed')) + fetchMock.mockResolvedValueOnce(okResponse()) + + await expect(submitFeedback(diagnosticSubmitArgs())).resolves.toEqual({ + ok: true, + diagnosticBundleFailure: { status: null, error: 'attachment network failed' } + }) + + expect(fetchMock).toHaveBeenCalledTimes(2) + expect(fetchMock.mock.calls[1]?.[0]).toBe('https://api.onorca.dev/v1/feedback') + expect(requestInit(1).body).not.toBeInstanceOf(FormData) + expect(postedBody(1)).not.toHaveProperty('diagnosticBundle') + }) + + it('allows 60 seconds for a diagnostic attachment before retrying report-only JSON', async () => { + vi.useFakeTimers() + fetchMock.mockImplementationOnce((_url: string, init?: RequestInit) => { + return new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => reject(new Error('runtime abort text'))) + }) + }) + fetchMock.mockResolvedValueOnce(okResponse()) + const result = submitFeedback(diagnosticSubmitArgs()) + + await vi.advanceTimersByTimeAsync(59_999) + expect(fetchMock).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(1) + + await expect(result).resolves.toEqual({ + ok: true, + diagnosticBundleFailure: { status: null, error: 'request timed out after 60 seconds' } + }) + expect(fetchMock).toHaveBeenCalledTimes(2) + expect(fetchMock.mock.calls[1]?.[0]).toBe('https://api.onorca.dev/v1/feedback') + expect(postedBody(1)).not.toHaveProperty('diagnosticBundle') + }) + + it('retries a proxy-rejected diagnostic attachment as website JSON', async () => { + fetchMock.mockResolvedValueOnce(errorResponse(403)).mockResolvedValueOnce(okResponse()) + + await expect(submitFeedback(diagnosticSubmitArgs())).resolves.toEqual({ + ok: true, + diagnosticBundleFailure: { status: 403, error: 'status 403' } + }) + expect(fetchMock.mock.calls[1]?.[0]).toBe('https://www.onorca.dev/v1/feedback') + expect(requestInit(1).body).not.toBeInstanceOf(FormData) + }) + + it.each([401, 409, 429])( + 'does not retry a diagnostic attachment rejected with status %s', + async (status) => { + fetchMock.mockResolvedValueOnce(errorResponse(status)) + + await expect(submitFeedback(diagnosticSubmitArgs())).resolves.toEqual({ + ok: false, + status, + error: `status ${status}` + }) + expect(fetchMock).toHaveBeenCalledTimes(1) + } + ) + + it('preserves attachment and report-only failures when the degraded retry fails', async () => { + fetchMock.mockRejectedValueOnce(new Error('attachment network failed')) + fetchMock.mockRejectedValueOnce(new Error('report-only network failed')) + + await expect(submitFeedback(diagnosticSubmitArgs())).resolves.toEqual({ + ok: false, + status: null, + error: 'report-only network failed', + diagnosticBundleFailure: { status: null, error: 'attachment network failed' } + }) + expect(fetchMock).toHaveBeenCalledTimes(2) + }) + it('falls back when the primary feedback request stalls', async () => { vi.useFakeTimers() fetchMock.mockImplementation((url: string, init?: RequestInit) => { @@ -184,7 +321,7 @@ describe('submitFeedback', () => { await expect(Promise.race([result, Promise.resolve('pending')])).resolves.toEqual({ ok: false, status: null, - error: 'fallback aborted' + error: 'request timed out after 10 seconds' }) expect(fetchMock).toHaveBeenCalledTimes(2) }) diff --git a/src/main/ipc/feedback.ts b/src/main/ipc/feedback.ts index 16c159f6a..d9fa48e3c 100644 --- a/src/main/ipc/feedback.ts +++ b/src/main/ipc/feedback.ts @@ -9,7 +9,11 @@ import { app, ipcMain, net } from 'electron' const FEEDBACK_API_URL = 'https://www.onorca.dev/v1/feedback' const FEEDBACK_API_FALLBACK_URL = 'https://api.onorca.dev/v1/feedback' const FEEDBACK_REQUEST_TIMEOUT_MS = 10_000 +const FEEDBACK_ATTACHMENT_REQUEST_TIMEOUT_MS = 60_000 const DIAGNOSTIC_BUNDLE_CONTENT_TYPE = 'application/x-ndjson' +// Why: corporate filters can reject multipart with 403 while allowing the +// small JSON report, so content-shaped failures should shed the attachment. +const DIAGNOSTIC_BUNDLE_JSON_RETRY_STATUSES = new Set([400, 403, 408, 413, 415, 422]) export type FeedbackSubmissionType = 'feedback' | 'crash' @@ -39,13 +43,21 @@ type FeedbackSubmitBody = { diagnosticBundle?: FeedbackDiagnosticBundleAttachment } +export type FeedbackRequestFailure = { + status: number | null + error: string +} + export type FeedbackSubmitResult = - | { ok: true } - | { ok: false; status: number | null; error: string } + | { ok: true; diagnosticBundleFailure?: FeedbackRequestFailure } + | ({ ok: false } & FeedbackRequestFailure & { + diagnosticBundleFailure?: FeedbackRequestFailure + }) type InternalFeedbackSubmitArgs = FeedbackSubmitArgs & { submissionType?: FeedbackSubmissionType diagnosticBundle?: FeedbackDiagnosticBundleAttachment + feedbackWithoutDiagnosticBundle?: string } // Why: the Slack notification and any follow-up investigation need to know @@ -74,11 +86,15 @@ function buildSubmitBody(args: InternalFeedbackSubmitArgs): FeedbackSubmitBody { } } -async function postFeedback(url: string, body: FeedbackSubmitBody): Promise { +async function postFeedback( + url: string, + body: FeedbackSubmitBody, + timeoutMs = FEEDBACK_REQUEST_TIMEOUT_MS +): Promise { const controller = new AbortController() // Why: a silent feedback endpoint should not leave IPC or crash-report // submission flows pending forever. - const timeout = setTimeout(() => controller.abort(), FEEDBACK_REQUEST_TIMEOUT_MS) + const timeout = setTimeout(() => controller.abort(), timeoutMs) try { const init: RequestInit = { method: 'POST', @@ -86,6 +102,13 @@ async function postFeedback(url: string, body: FeedbackSubmitBody): Promise= 500) { + return FEEDBACK_API_FALLBACK_URL + } + return null +} + +async function submitFeedbackWithoutDiagnosticBundle( + url: string, + body: FeedbackSubmitBody, + diagnosticBundleFailure: FeedbackRequestFailure +): Promise { + try { + const response = await postFeedback(url, body) + if (response.ok) { + return { ok: true, diagnosticBundleFailure } + } + return { ok: false, ...responseFailure(response), diagnosticBundleFailure } + } catch (error) { + return { ok: false, ...errorFailure(error), diagnosticBundleFailure } + } +} + +async function submitFeedbackWithDiagnosticBundle( + body: FeedbackSubmitBody, + bodyWithoutDiagnosticBundle: FeedbackSubmitBody | null +): Promise { + try { + // Why: diagnostic bundles can approach 4 MiB and need more upload time than + // the small JSON report-only path, especially on constrained connections. + const response = await postFeedback( + FEEDBACK_API_URL, + body, + FEEDBACK_ATTACHMENT_REQUEST_TIMEOUT_MS + ) + if (response.ok) { + return { ok: true } + } + const failure = responseFailure(response) + if (bodyWithoutDiagnosticBundle) { + const retryUrl = diagnosticRetryUrl(response.status) + if (retryUrl) { + return submitFeedbackWithoutDiagnosticBundle(retryUrl, bodyWithoutDiagnosticBundle, failure) + } + } + return { ok: false, ...failure } + } catch (error) { + const failure = errorFailure(error) + return bodyWithoutDiagnosticBundle + ? submitFeedbackWithoutDiagnosticBundle( + FEEDBACK_API_FALLBACK_URL, + bodyWithoutDiagnosticBundle, + failure + ) + : { ok: false, ...failure } + } +} + export async function submitFeedback( args: InternalFeedbackSubmitArgs ): Promise { const body = buildSubmitBody(args) + if (body.diagnosticBundle) { + const bodyWithoutDiagnosticBundle = + args.feedbackWithoutDiagnosticBundle !== undefined + ? buildSubmitBody({ + ...args, + feedback: args.feedbackWithoutDiagnosticBundle, + diagnosticBundle: undefined + }) + : null + return submitFeedbackWithDiagnosticBundle(body, bodyWithoutDiagnosticBundle) + } try { const res = await postFeedback(FEEDBACK_API_URL, body) if (res.ok) { diff --git a/src/main/observability/tracer.test.ts b/src/main/observability/tracer.test.ts index d1bec74ab..d28594361 100644 --- a/src/main/observability/tracer.test.ts +++ b/src/main/observability/tracer.test.ts @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { _resetTracerForTests, + flushActiveSink, getActiveSpanContext, setActiveSink, startSpan, @@ -69,6 +70,23 @@ describe('tracer — basic span lifecycle', () => { expect(r.exit.cause).toBe('user-cancelled') }) + it('keeps forced sink flush failures from escaping crash boundaries', () => { + sink.flush = () => { + throw new Error('disk unavailable') + } + + expect(() => flushActiveSink()).not.toThrow() + }) + + it('keeps sink handoff failures from escaping instrumented operations', async () => { + sink.push = () => { + throw new Error('trace rotation failed') + } + + expect(() => startSpan('test').fail('boom')).not.toThrow() + await expect(withSpan('async-test', async () => 'result')).resolves.toBe('result') + }) + it('end() is idempotent — second call is a no-op', () => { const span = startSpan('test') span.end() diff --git a/src/main/observability/tracer.ts b/src/main/observability/tracer.ts index 3ef93449c..c151aa6a2 100644 --- a/src/main/observability/tracer.ts +++ b/src/main/observability/tracer.ts @@ -112,6 +112,17 @@ export function setActiveSink(sink: TracerSink | null): void { activeSink = sink } +/** Force records already handed to the tracer onto disk. Reserve this for + * crash boundaries where the process may not survive the normal batch window. */ +export function flushActiveSink(): void { + try { + activeSink?.flush() + } catch { + // Why: a disk/rotation failure in optional local diagnostics must never + // turn a recoverable renderer crash into a main-process crash. + } +} + /** Get the current parent context, or `undefined` if we are at the top of * the trace tree. Renderer-IPC entry points capture this, embed it in * span-event attributes (so cross-process spans can be visually linked @@ -221,7 +232,12 @@ export function startSpan( // Wrap in a `type: 'effect-span'` envelope so the NDJSON file is // compatible with Effect-style span output. Effect-oriented consumers // (the LGTM stack, jq cookbooks) can read the file unchanged. - activeSink?.push({ type: 'effect-span', ...redacted }) + try { + activeSink?.push({ type: 'effect-span', ...redacted }) + } catch { + // Why: tracing is optional; a local file rotation failure must not turn + // the instrumented operation into an application failure. + } } return { diff --git a/src/main/win32-utils-async-acl.test.ts b/src/main/win32-utils-async-acl.test.ts new file mode 100644 index 000000000..22c9ff992 --- /dev/null +++ b/src/main/win32-utils-async-acl.test.ts @@ -0,0 +1,157 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { execFileMock, execFileSyncMock } = vi.hoisted(() => ({ + execFileMock: vi.fn(), + execFileSyncMock: vi.fn() +})) + +vi.mock('node:child_process', () => ({ + execFile: execFileMock, + execFileSync: execFileSyncMock +})) + +type ExecCallback = (error: Error | null, stdout: string, stderr: string) => void + +const originalUsername = process.env.USERNAME + +beforeEach(() => { + vi.resetModules() + execFileMock.mockReset() + execFileSyncMock.mockReset() +}) + +afterEach(() => { + if (originalUsername === undefined) { + delete process.env.USERNAME + } else { + process.env.USERNAME = originalUsername + } +}) + +describe('grantDirAclAsync', () => { + it('keeps icacls off the synchronous main-process path', async () => { + process.env.USERNAME = 'alice' + let complete: ExecCallback | undefined + execFileMock.mockImplementation( + (_command: string, _args: string[], _options: unknown, callback: ExecCallback) => { + complete = callback + return {} as never + } + ) + const { getIcaclsExePath, grantDirAclAsync } = await import('./win32-utils') + + const pending = grantDirAclAsync('C:\\Users\\alice\\Orca') + await Promise.resolve() + + expect(execFileSyncMock).not.toHaveBeenCalled() + expect(execFileMock).toHaveBeenCalledWith( + getIcaclsExePath(), + ['C:\\Users\\alice\\Orca', '/grant:r', 'alice:(OI)(CI)(F)'], + { encoding: 'utf-8', windowsHide: true, timeout: 10_000 }, + expect.any(Function) + ) + complete?.(null, '', '') + await expect(pending).resolves.toBeUndefined() + }) + + it('resolves a missing username through asynchronous whoami before icacls', async () => { + delete process.env.USERNAME + execFileMock + .mockImplementationOnce( + (_command: string, _args: string[], _options: unknown, callback: ExecCallback) => { + callback(null, '"DOMAIN\\alice","S-1-5-21-123"\r\n', '') + return {} as never + } + ) + .mockImplementationOnce( + (_command: string, _args: string[], _options: unknown, callback: ExecCallback) => { + callback(null, '', '') + return {} as never + } + ) + const { getWhoamiExePath, grantDirAclAsync } = await import('./win32-utils') + + await grantDirAclAsync('C:\\Orca') + + expect(execFileMock.mock.calls[0]?.slice(0, 3)).toEqual([ + getWhoamiExePath(), + ['/user', '/fo', 'csv', '/nh'], + { encoding: 'utf-8', windowsHide: true, timeout: 5000 } + ]) + expect(execFileMock.mock.calls[1]?.[1]).toEqual([ + 'C:\\Orca', + '/grant:r', + '*S-1-5-21-123:(OI)(CI)(F)' + ]) + expect(execFileSyncMock).not.toHaveBeenCalled() + }) + + it('does not overwrite a concurrent cached identity with a late async result', async () => { + delete process.env.USERNAME + let completeWhoami: ExecCallback | undefined + execFileMock + .mockImplementationOnce( + (_command: string, _args: string[], _options: unknown, callback: ExecCallback) => { + completeWhoami = callback + return {} as never + } + ) + .mockImplementationOnce( + (_command: string, _args: string[], _options: unknown, callback: ExecCallback) => { + callback(null, '', '') + return {} as never + } + ) + execFileSyncMock.mockReturnValue('"DOMAIN\\sync","S-1-5-21-456"\r\n') + const { grantDirAclAsync, resolveCurrentWindowsIdentity } = await import('./win32-utils') + + const pending = grantDirAclAsync('C:\\Orca') + await Promise.resolve() + expect(resolveCurrentWindowsIdentity()).toBe('*S-1-5-21-456') + completeWhoami?.(null, '"DOMAIN\\async","S-1-5-21-789"\r\n', '') + await pending + + expect(execFileMock.mock.calls[1]?.[1]).toEqual([ + 'C:\\Orca', + '/grant:r', + '*S-1-5-21-456:(OI)(CI)(F)' + ]) + }) + + it('retries identity resolution after a transient whoami failure', async () => { + delete process.env.USERNAME + execFileMock + .mockImplementationOnce( + (_command: string, _args: string[], _options: unknown, callback: ExecCallback) => { + callback(new Error('whoami timed out'), '', '') + return {} as never + } + ) + .mockImplementationOnce( + (_command: string, _args: string[], _options: unknown, callback: ExecCallback) => { + callback(null, '"DOMAIN\\alice","S-1-5-21-123"\r\n', '') + return {} as never + } + ) + .mockImplementationOnce( + (_command: string, _args: string[], _options: unknown, callback: ExecCallback) => { + callback(null, '', '') + return {} as never + } + ) + const { getWhoamiExePath, grantDirAclAsync } = await import('./win32-utils') + + await grantDirAclAsync('C:\\Orca') + await grantDirAclAsync('C:\\Orca') + + expect( + execFileMock.mock.calls.filter(([command]) => command === getWhoamiExePath()) + ).toHaveLength(2) + expect(execFileMock.mock.calls[2]?.[1]).toEqual([ + 'C:\\Orca', + '/grant:r', + '*S-1-5-21-123:(OI)(CI)(F)' + ]) + expect(execFileSyncMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/win32-utils.ts b/src/main/win32-utils.ts index a4b8dae12..264ed6e66 100644 --- a/src/main/win32-utils.ts +++ b/src/main/win32-utils.ts @@ -1,7 +1,23 @@ -import { execFileSync } from 'node:child_process' +import { execFile, execFileSync, type ExecFileOptionsWithStringEncoding } from 'node:child_process' import { delimiter, join } from 'node:path' import { existsSync } from 'node:fs' +function execFileWithoutBlocking( + command: string, + args: string[], + options: ExecFileOptionsWithStringEncoding +): Promise { + return new Promise((resolve, reject) => { + execFile(command, args, options, (error, stdout) => { + if (error) { + reject(error) + return + } + resolve(stdout) + }) + }) +} + /** * Full path to icacls.exe. Electron's main process may have a stripped PATH * that excludes System32, causing bare `icacls` to throw ENOENT. @@ -10,6 +26,11 @@ export function getIcaclsExePath(): string { return `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\icacls.exe` } +/** Absolute path because service-launched Electron can omit System32 from PATH. */ +export function getWhoamiExePath(): string { + return `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\whoami.exe` +} + /** * Full path to cmd.exe, respecting the ComSpec convention used elsewhere in * the codebase (hooks.ts, repo.ts, ssh-connection-utils.ts). @@ -78,13 +99,10 @@ export function isPermissionError(error: unknown): boolean { // and hardened envs where USERNAME is unset. Fall back to the SID via // `whoami /user` (same strategy as runtime-metadata.ts), which is authoritative // and always available on Windows. Cached because it never changes in-process. -let cachedIdentity: string | null | undefined +let cachedIdentity: string | undefined +let pendingIdentityResolution: Promise | null = null -export function resolveCurrentWindowsIdentity(): string | null { - return resolveCurrentIdentity() -} - -function resolveCurrentIdentity(): string | null { +function cachedOrEnvironmentIdentity(): string | undefined { if (cachedIdentity !== undefined) { return cachedIdentity } @@ -92,20 +110,75 @@ function resolveCurrentIdentity(): string | null { cachedIdentity = process.env.USERNAME return cachedIdentity } + return undefined +} + +function identityFromWhoamiOutput(output: string): string | null { + // CSV columns: "DOMAIN\\user","S-1-5-21-..." + const sidMatch = /"(S-[\d-]+)"\s*$/.exec(output.trim()) + return sidMatch ? `*${sidMatch[1]}` : null +} + +export function resolveCurrentWindowsIdentity(): string | null { + return resolveCurrentIdentity() +} + +function resolveCurrentIdentity(): string | null { + const knownIdentity = cachedOrEnvironmentIdentity() + if (knownIdentity !== undefined) { + return knownIdentity + } try { - const output = execFileSync('whoami', ['/user', '/fo', 'csv', '/nh'], { + const output = execFileSync(getWhoamiExePath(), ['/user', '/fo', 'csv', '/nh'], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, timeout: 5000 - }).trim() - // CSV columns: "DOMAIN\\user","S-1-5-21-..." - const sidMatch = /"(S-[\d-]+)"\s*$/.exec(output) - cachedIdentity = sidMatch ? `*${sidMatch[1]}` : null + }) + const resolvedIdentity = identityFromWhoamiOutput(output) + if (resolvedIdentity) { + cachedIdentity = resolvedIdentity + } + return resolvedIdentity } catch { - cachedIdentity = null + return null } - return cachedIdentity +} + +async function resolveCurrentIdentityAsync(): Promise { + const knownIdentity = cachedOrEnvironmentIdentity() + if (knownIdentity !== undefined) { + return knownIdentity + } + if (!pendingIdentityResolution) { + pendingIdentityResolution = (async () => { + try { + const stdout = await execFileWithoutBlocking( + getWhoamiExePath(), + ['/user', '/fo', 'csv', '/nh'], + { + encoding: 'utf-8', + windowsHide: true, + timeout: 5000 + } + ) + // Why: a synchronous caller may resolve identity while async whoami + // is in flight; its authoritative cached result must win the race. + const resolvedIdentity = identityFromWhoamiOutput(stdout) + if (cachedIdentity === undefined && resolvedIdentity) { + cachedIdentity = resolvedIdentity + } + return cachedIdentity ?? resolvedIdentity + } catch { + // Why: transient service/PATH failures must not permanently disable + // ACL repair for every later crash attempt in this process. + return cachedIdentity ?? null + } + })().finally(() => { + pendingIdentityResolution = null + }) + } + return pendingIdentityResolution } /** @@ -138,6 +211,24 @@ export function grantDirAcl(dirPath: string, options?: { recursive?: boolean }): }) } +export async function grantDirAclAsync(dirPath: string): Promise { + const identity = await resolveCurrentIdentityAsync() + if (!identity) { + return + } + // Why: crash recovery runs on Electron's main thread; an asynchronous + // icacls child keeps its worst-case timeout from freezing every window. + await execFileWithoutBlocking( + getIcaclsExePath(), + [dirPath, '/grant:r', `${identity}:(OI)(CI)(F)`], + { + encoding: 'utf-8', + windowsHide: true, + timeout: 10_000 + } + ) +} + /** * Resolve spawn parameters for a command that may be a Windows batch script. * diff --git a/src/main/window/createMainWindow.test.ts b/src/main/window/createMainWindow.test.ts index b72be7962..54b4728f7 100644 --- a/src/main/window/createMainWindow.test.ts +++ b/src/main/window/createMainWindow.test.ts @@ -2390,7 +2390,7 @@ describe('createMainWindow', () => { expect(onRendererProcessGone).toHaveBeenCalledWith(details, 142) }) - it('passes the renderer webContents id through crash classification callbacks', () => { + it('passes the renderer webContents id through crash recording and recovery callbacks', () => { vi.useFakeTimers() const windowHandlers: Record void> = {} @@ -2423,13 +2423,11 @@ describe('createMainWindow', () => { return browserWindowInstance }) const onRendererProcessGone = vi.fn() - const shouldRecordRendererCrash = vi.fn(() => true) const shouldRecoverRenderer = vi.fn(() => true) try { createMainWindow(null, { onRendererProcessGone, - shouldRecordRendererCrash, shouldRecoverRenderer }) @@ -2437,7 +2435,6 @@ describe('createMainWindow', () => { windowHandlers['render-process-gone']?.({} as never, details) vi.advanceTimersByTime(250) - expect(shouldRecordRendererCrash).toHaveBeenCalledWith(details, 424) expect(onRendererProcessGone).toHaveBeenCalledWith(details, 424) expect(shouldRecoverRenderer).toHaveBeenCalledWith(details, 424) } finally { @@ -2445,9 +2442,10 @@ describe('createMainWindow', () => { } }) - it('does not notify the crash recorder for an expected renderer teardown', () => { + it('forwards expected renderer teardowns so the recorder can diagnose suppression', () => { const windowHandlers: Record void> = {} const webContents = { + id: 142, on: vi.fn((event, handler) => { windowHandlers[event] = handler }), @@ -2476,10 +2474,7 @@ describe('createMainWindow', () => { }) const onRendererProcessGone = vi.fn() - createMainWindow(null, { - onRendererProcessGone, - shouldRecordRendererCrash: () => false - }) + createMainWindow(null, { onRendererProcessGone }) windowHandlers['render-process-gone']?.( {} as never, @@ -2489,7 +2484,10 @@ describe('createMainWindow', () => { } as Electron.RenderProcessGoneDetails ) - expect(onRendererProcessGone).not.toHaveBeenCalled() + expect(onRendererProcessGone).toHaveBeenCalledWith( + expect.objectContaining({ reason: 'killed', exitCode: 15 }), + expect.any(Number) + ) consoleError.mockRestore() }) diff --git a/src/main/window/createMainWindow.ts b/src/main/window/createMainWindow.ts index 1a30178a4..ff66b5ebc 100644 --- a/src/main/window/createMainWindow.ts +++ b/src/main/window/createMainWindow.ts @@ -111,13 +111,6 @@ type CreateMainWindowOptions = { details: Electron.RenderProcessGoneDetails, webContentsId: number ) => void - /** Returns true when a renderer loss should be reported as a crash. Why: - * intentional reload/update/quit paths can emit crash-like `killed` - * renderer exits, but surfacing those as crash reports is noise. */ - shouldRecordRendererCrash?: ( - details: Electron.RenderProcessGoneDetails, - webContentsId: number - ) => boolean /** Returns true when Orca should reload after an unexpected renderer loss. * Why: update relaunch and app quit intentionally tear down child * processes; recovering those paths can fight Electron's shutdown. */ @@ -713,10 +706,9 @@ export function createMainWindow( resetShortcutRecorderFocus() // Why: macOS can report BrowserWindow teardown as renderer `killed`/SIGKILL // after a confirmed close; that is window lifecycle noise, not a crash. - if ( - !windowClosing && - opts?.shouldRecordRendererCrash?.(details, rendererWebContentsId) !== false - ) { + if (!windowClosing) { + // Why: the recorder owns crash classification and durable suppression + // diagnostics; filtering here made expected-teardown evidence unreachable. opts?.onRendererProcessGone?.(details, rendererWebContentsId) } if (!windowClosing) { diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 7c9f989be..ad3c409d0 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -316,6 +316,7 @@ import type { ShellOpenLocalPathResult } from '../shared/shell-open-types' import type { SkillDiscoveryResult, SkillDiscoveryTarget } from '../shared/skills' import type { CrashReportBreadcrumbData, + CrashReportCopyDiagnosticsArgs, CrashReportRecord, CrashReportSubmitArgs, CrashReportSubmitResult, @@ -1397,10 +1398,9 @@ export type PreloadApi = { ) => Promise recordBreadcrumb: (args: { name: string; data?: CrashReportBreadcrumbData }) => void submit: (args: CrashReportSubmitArgs) => Promise - copyLatestDiagnostics: (args?: { - reportId?: string - notes?: string - }) => Promise<{ ok: true } | { ok: false; error: string }> + copyLatestDiagnostics: ( + args?: CrashReportCopyDiagnosticsArgs + ) => Promise<{ ok: true } | { ok: false; error: string }> } export: ExportApi gh: { diff --git a/src/preload/index.ts b/src/preload/index.ts index 059e2aa4e..ae6b06ca1 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -212,6 +212,7 @@ import type { } from '../shared/localhost-worktree-labels' import type { CrashReportBreadcrumbData, + CrashReportCopyDiagnosticsArgs, CrashReportSubmitArgs, CrashReportSubmitResult, ReactErrorBoundaryReportArgs, @@ -1148,7 +1149,7 @@ const api = { ipcRenderer.send('crashReports:recordBreadcrumb', args), submit: (args: CrashReportSubmitArgs): Promise => ipcRenderer.invoke('crashReports:submit', args), - copyLatestDiagnostics: (args?: { reportId?: string; notes?: string }) => + copyLatestDiagnostics: (args?: CrashReportCopyDiagnosticsArgs) => ipcRenderer.invoke('crashReports:copyLatestDiagnostics', args) }, diff --git a/src/renderer/src/components/crash-report/CrashReportDialogSurface.tsx b/src/renderer/src/components/crash-report/CrashReportDialogSurface.tsx index d80deb581..0f263bf53 100644 --- a/src/renderer/src/components/crash-report/CrashReportDialogSurface.tsx +++ b/src/renderer/src/components/crash-report/CrashReportDialogSurface.tsx @@ -16,10 +16,18 @@ import { useMountedRef } from '@/hooks/useMountedRef' import { formatCrashReportText, isReactErrorBoundaryReport, + type CrashReportDiagnosticBundle, type CrashReportRecord } from '../../../../shared/crash-reporting' import type { GitHubViewer } from '../../../../shared/types' import { translate } from '@/i18n/i18n' +import { + CRASH_REPORT_SUBMIT_FAILURE_TOAST_ID, + getCrashReportCopySubmissionFailure, + getCrashReportSubmitFailureNotice, + getCrashReportSubmitWarningNotice +} from './crash-report-submit-notice' +import { useCrashReportCopy } from './use-crash-report-copy' function formatSummary(report: CrashReportRecord): string { if (isReactErrorBoundaryReport(report)) { @@ -88,6 +96,7 @@ export function CrashReportDialogSurface({ () => (report ? formatCrashReportText(report, deferredNotes) : ''), [deferredNotes, report] ) + const copyCrashReportDetails = useCrashReportCopy(report, notes) const clearViewer = useCallback((): void => { viewerRequestIdRef.current += 1 @@ -121,17 +130,25 @@ export function CrashReportDialogSurface({ loadViewerForOpenDialog() }, [clearViewer, loadViewerForOpenDialog, open]) - const handleCopy = async (): Promise => { - const result = await window.api.crashReports.copyLatestDiagnostics( - report ? { reportId: report.id, notes } : { notes } - ) - if (!result.ok) { - toast.error(result.error) - return - } - toast.success( - translate('auto.components.crash.report.CrashReportDialog.8b8473c544', 'Crash report copied.') - ) + const showSubmitFailure = ( + error: unknown, + diagnosticBundle?: CrashReportDiagnosticBundle + ): void => { + const failure = { error, ...(diagnosticBundle ? { diagnosticBundle } : {}) } + const notice = getCrashReportSubmitFailureNotice(failure, includeDiagnosticLogs) + const copyFailure = getCrashReportCopySubmissionFailure(failure) + toast.error(notice.title, { + id: CRASH_REPORT_SUBMIT_FAILURE_TOAST_ID, + description: notice.description, + duration: Infinity, + dismissible: true, + action: { + label: notice.actionLabel, + onClick: () => { + void copyCrashReportDetails(copyFailure) + } + } + }) } const dismissReportIfNeeded = async (): Promise => { @@ -164,22 +181,7 @@ export function CrashReportDialogSurface({ githubEmail: null }) if (!result.ok) { - if (result.diagnosticBundle?.status === 'uploaded') { - toast.error( - translate( - 'auto.components.crash.report.CrashReportDialog.b2e36f53a1', - 'Failed to send crash report. Diagnostic ticket {{value0}} was uploaded but not linked.', - { value0: result.diagnosticBundle.ticketId } - ) - ) - } else { - toast.error( - translate( - 'auto.components.crash.report.CrashReportDialog.56a3dfa283', - 'Failed to send crash report.' - ) - ) - } + showSubmitFailure(result.error, result.diagnosticBundle) console.error('Failed to submit crash report:', result.error) return } @@ -188,17 +190,21 @@ export function CrashReportDialogSurface({ } onReportChange(result.report) setNotes('') - toast.success( - translate('auto.components.crash.report.CrashReportDialog.8e24fe4f75', 'Crash report sent.') - ) + toast.dismiss(CRASH_REPORT_SUBMIT_FAILURE_TOAST_ID) + const warningNotice = getCrashReportSubmitWarningNotice(result, includeDiagnosticLogs) + if (warningNotice) { + toast.warning(warningNotice.title, { description: warningNotice.description }) + } else { + toast.success( + translate( + 'auto.components.crash.report.CrashReportDialog.8e24fe4f75', + 'Crash report sent.' + ) + ) + } onOpenChange(false) } catch (error) { - toast.error( - translate( - 'auto.components.crash.report.CrashReportDialog.56a3dfa283', - 'Failed to send crash report.' - ) - ) + showSubmitFailure(error) console.error('Failed to submit crash report:', error) } finally { if (mountedRef.current) { @@ -304,7 +310,13 @@ export function CrashReportDialogSurface({ - diff --git a/src/renderer/src/components/crash-report/crash-report-submit-notice.test.ts b/src/renderer/src/components/crash-report/crash-report-submit-notice.test.ts new file mode 100644 index 000000000..b7b0c0dd3 --- /dev/null +++ b/src/renderer/src/components/crash-report/crash-report-submit-notice.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from 'vitest' +import { + getCrashReportCopySubmissionFailure, + getCrashReportSubmitFailureNotice, + getCrashReportSubmitWarningNotice +} from './crash-report-submit-notice' + +describe('crash report submit notices', () => { + it('builds an allow-listed copy context with the exact sanitized failure reasons', () => { + expect( + getCrashReportCopySubmissionFailure({ + error: 'request failed at C:\\Users\\alice\\Orca', + diagnosticBundle: { + status: 'not_uploaded', + reason: 'attachment timeout token=super-secret-value' + } + }) + ).toEqual({ + error: 'request failed at [redacted-path]', + diagnosticContext: { + status: 'not_uploaded', + reason: 'attachment timeout token=[redacted]' + } + }) + }) + + it('keeps the returned error and points attached-log failures to the no-log retry', () => { + const notice = getCrashReportSubmitFailureNotice({ error: 'status 413' }, true) + + expect(notice).toEqual({ + title: "Crash report wasn't sent", + description: + 'status 413. Uncheck "Attach recent diagnostic logs" and try again, or copy the details.', + actionLabel: 'Copy Details' + }) + }) + + it('uses connection guidance when diagnostic logs were already excluded', () => { + const notice = getCrashReportSubmitFailureNotice({ error: 'network unreachable' }, false) + + expect(notice.description).toBe( + 'network unreachable. Check your connection and try again, or copy the details.' + ) + expect(notice.description).not.toContain('Uncheck') + }) + + it('preserves an uploaded diagnostic ticket alongside the core failure', () => { + const notice = getCrashReportSubmitFailureNotice( + { + error: 'status 502', + diagnosticBundle: { + status: 'uploaded', + ticketId: 'ticket-123', + bundleSubmissionId: 'bundle-123', + bytes: 42, + spanCount: 2 + } + }, + true + ) + + expect(notice.description).toContain('status 502.') + expect(notice.description).toContain( + 'Diagnostic ticket ticket-123 was uploaded but not linked.' + ) + }) + + it('shows both failures when the attachment was already omitted', () => { + const notice = getCrashReportSubmitFailureNotice( + { + error: 'fallback host unreachable', + diagnosticBundle: { + status: 'not_uploaded', + reason: 'diagnostic log attachment failed: request timed out after 60 seconds' + } + }, + true + ) + + expect(notice.description).toContain('fallback host unreachable.') + expect(notice.description).toContain( + 'Diagnostic logs were not attached: diagnostic log attachment failed: request timed out after 60 seconds.' + ) + expect(notice.description).toContain('Check your connection') + expect(notice.description).not.toContain('Uncheck') + }) + + it('safely surfaces Error messages and ignores unhelpful rejected values', () => { + expect( + getCrashReportSubmitFailureNotice({ error: new Error('IPC channel closed') }, false) + .description + ).toContain('IPC channel closed.') + expect( + getCrashReportSubmitFailureNotice({ error: { unexpected: true } }, false).description + ).toContain('The crash report request failed before it returned a reason.') + }) + + it('redacts paths and tokens before displaying transport errors', () => { + const token = `ghp_${'a'.repeat(30)}` + const notice = getCrashReportSubmitFailureNotice( + { + error: `request failed at C:\\Users\\alice\\Orca\\crash-reports.json token=${token}` + }, + false + ) + + expect(notice.description).not.toContain('alice') + expect(notice.description).not.toContain(token) + expect(notice.description).toContain('[redacted') + }) + + it('warns only when an opted-in diagnostic bundle was not attached', () => { + const result = { + ok: true as const, + report: null, + diagnosticBundle: { + status: 'not_uploaded' as const, + reason: 'bundle collection failed' + } + } + + expect(getCrashReportSubmitWarningNotice(result, true)).toEqual({ + title: 'Crash report sent without diagnostic logs', + description: 'Diagnostic logs were not attached: bundle collection failed' + }) + expect(getCrashReportSubmitWarningNotice(result, false)).toBeNull() + }) +}) diff --git a/src/renderer/src/components/crash-report/crash-report-submit-notice.ts b/src/renderer/src/components/crash-report/crash-report-submit-notice.ts new file mode 100644 index 000000000..29824b604 --- /dev/null +++ b/src/renderer/src/components/crash-report/crash-report-submit-notice.ts @@ -0,0 +1,134 @@ +import { translate } from '@/i18n/i18n' +import { + sanitizeCrashReportString, + type CrashReportCopySubmissionFailure, + type CrashReportDiagnosticBundle, + type CrashReportSubmitResult +} from '../../../../shared/crash-reporting' + +export const CRASH_REPORT_SUBMIT_FAILURE_TOAST_ID = 'crash-report-submit-failure' + +export type CrashReportSubmitFailureNotice = { + title: string + description: string + actionLabel: string +} + +export type CrashReportSubmitWarningNotice = { + title: string + description: string +} + +type CrashReportSubmitFailureLike = { + error: unknown + diagnosticBundle?: CrashReportDiagnosticBundle +} + +function normalizedFailureMessage(error: unknown): string { + const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '' + const sanitized = sanitizeCrashReportString(message).trim() + return ( + sanitized || + translate( + 'auto.components.crash.report.submit.notice.unknownError', + 'The crash report request failed before it returned a reason.' + ) + ) +} + +function asSentence(message: string): string { + return /[.!?]$/.test(message) ? message : `${message}.` +} + +export function getCrashReportCopySubmissionFailure( + failure: CrashReportSubmitFailureLike +): CrashReportCopySubmissionFailure { + const diagnosticContext = + failure.diagnosticBundle?.status === 'uploaded' + ? { + status: 'uploaded' as const, + ticketId: sanitizeCrashReportString(failure.diagnosticBundle.ticketId) + } + : failure.diagnosticBundle?.status === 'not_uploaded' + ? { + status: 'not_uploaded' as const, + reason: normalizedFailureMessage(failure.diagnosticBundle.reason) + } + : undefined + return { + error: normalizedFailureMessage(failure.error), + ...(diagnosticContext ? { diagnosticContext } : {}) + } +} + +export function getCrashReportSubmitFailureNotice( + failure: CrashReportSubmitFailureLike, + includeDiagnosticLogs: boolean +): CrashReportSubmitFailureNotice { + const ticketDetail = + failure.diagnosticBundle?.status === 'uploaded' + ? translate( + 'auto.components.crash.report.submit.notice.ticketUploaded', + 'Diagnostic ticket {{value0}} was uploaded but not linked.', + { value0: sanitizeCrashReportString(failure.diagnosticBundle.ticketId) } + ) + : null + const omittedDetail = + failure.diagnosticBundle?.status === 'not_uploaded' + ? asSentence( + translate( + 'auto.components.crash.report.submit.notice.diagnosticsReason', + 'Diagnostic logs were not attached: {{value0}}', + { value0: normalizedFailureMessage(failure.diagnosticBundle.reason) } + ) + ) + : null + const attachmentAlreadyOmitted = failure.diagnosticBundle?.status === 'not_uploaded' + const recovery = + includeDiagnosticLogs && !attachmentAlreadyOmitted + ? translate( + 'auto.components.crash.report.submit.notice.uncheckDiagnostics', + 'Uncheck "Attach recent diagnostic logs" and try again, or copy the details.' + ) + : translate( + 'auto.components.crash.report.submit.notice.checkConnection', + 'Check your connection and try again, or copy the details.' + ) + + return { + title: translate( + 'auto.components.crash.report.submit.notice.notSent', + "Crash report wasn't sent" + ), + description: [ + asSentence(normalizedFailureMessage(failure.error)), + ticketDetail, + omittedDetail, + recovery + ] + .filter((part): part is string => Boolean(part)) + .join(' '), + actionLabel: translate('auto.components.crash.report.submit.notice.copyDetails', 'Copy Details') + } +} + +export function getCrashReportSubmitWarningNotice( + result: Extract, + includeDiagnosticLogs: boolean +): CrashReportSubmitWarningNotice | null { + if (!includeDiagnosticLogs || result.diagnosticBundle?.status !== 'not_uploaded') { + return null + } + + return { + title: translate( + 'auto.components.crash.report.submit.notice.sentWithoutDiagnostics', + 'Crash report sent without diagnostic logs' + ), + description: translate( + 'auto.components.crash.report.submit.notice.diagnosticsReason', + 'Diagnostic logs were not attached: {{value0}}', + { value0: normalizedFailureMessage(result.diagnosticBundle.reason) } + ) + } +} diff --git a/src/renderer/src/components/crash-report/use-crash-report-copy.test.tsx b/src/renderer/src/components/crash-report/use-crash-report-copy.test.tsx new file mode 100644 index 000000000..69b010907 --- /dev/null +++ b/src/renderer/src/components/crash-report/use-crash-report-copy.test.tsx @@ -0,0 +1,133 @@ +// @vitest-environment happy-dom + +import { act, cleanup, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { toast } from 'sonner' +import type { + CrashReportCopySubmissionFailure, + CrashReportRecord +} from '../../../../shared/crash-reporting' +import { CRASH_REPORT_COPY_FAILURE_TOAST_ID, useCrashReportCopy } from './use-crash-report-copy' + +const copyLatestDiagnostics = vi.fn() + +vi.mock('sonner', () => ({ + toast: { + dismiss: vi.fn(), + error: vi.fn(), + success: vi.fn() + } +})) + +function report(id = 'crash-1'): CrashReportRecord { + return { + id, + createdAt: '2026-05-16T01:00:00.000Z', + status: 'pending', + source: 'renderer', + processType: 'renderer', + reason: 'crashed', + exitCode: 5, + appVersion: '1.0.0', + platform: 'win32', + osRelease: 'test', + arch: 'x64', + electronVersion: '41', + chromeVersion: '141', + details: {} + } +} + +beforeEach(() => { + vi.clearAllMocks() + copyLatestDiagnostics.mockResolvedValue({ ok: true }) + Object.defineProperty(window, 'api', { + configurable: true, + value: { crashReports: { copyLatestDiagnostics } } + }) +}) + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +describe('useCrashReportCopy', () => { + it('uses the latest edited notes from an older failure-toast action', async () => { + const failure: CrashReportCopySubmissionFailure = { + error: 'report request timed out', + diagnosticContext: { status: 'not_uploaded', reason: 'logs timed out' } + } + const { result, rerender } = renderHook(({ notes }) => useCrashReportCopy(report(), notes), { + initialProps: { notes: 'notes at submit' } + }) + const failureToastCopyAction = result.current + + rerender({ notes: 'notes edited while waiting' }) + await act(async () => failureToastCopyAction(failure)) + + expect(copyLatestDiagnostics).toHaveBeenCalledWith({ + reportId: 'crash-1', + notes: 'notes edited while waiting', + submissionFailure: failure + }) + }) + + it("does not combine an older report action with a newer report's notes", async () => { + const { result, rerender } = renderHook( + ({ currentReport, notes }) => useCrashReportCopy(currentReport, notes), + { + initialProps: { + currentReport: report('crash-a'), + notes: 'latest notes for A' + } + } + ) + const reportACopyAction = result.current + + rerender({ currentReport: report('crash-b'), notes: 'private notes for B' }) + await act(async () => reportACopyAction()) + + expect(copyLatestDiagnostics).toHaveBeenCalledWith({ + reportId: 'crash-a', + notes: 'latest notes for A' + }) + expect(JSON.stringify(copyLatestDiagnostics.mock.calls)).not.toContain('private notes for B') + }) + + it('keeps a returned copy failure visible with its safe reason', async () => { + copyLatestDiagnostics.mockResolvedValueOnce({ + ok: false, + error: 'Crash diagnostics are too large to copy safely.' + }) + const { result } = renderHook(() => useCrashReportCopy(report(), 'current notes')) + + await act(async () => result.current()) + + expect(toast.error).toHaveBeenCalledWith('Crash report details could not be copied.', { + id: CRASH_REPORT_COPY_FAILURE_TOAST_ID, + description: 'Crash diagnostics are too large to copy safely.', + duration: Infinity, + dismissible: true + }) + expect(toast.success).not.toHaveBeenCalled() + }) + + it('shows a safe sticky error toast when copy IPC rejects', async () => { + copyLatestDiagnostics.mockRejectedValueOnce( + new Error('renderer destroyed with token=must-not-be-shown') + ) + vi.spyOn(console, 'error').mockImplementation(() => {}) + const { result } = renderHook(() => useCrashReportCopy(report(), 'current notes')) + + await act(async () => result.current()) + + expect(toast.error).toHaveBeenCalledWith('Crash report details could not be copied.', { + id: CRASH_REPORT_COPY_FAILURE_TOAST_ID, + duration: Infinity, + dismissible: true + }) + expect(JSON.stringify(vi.mocked(toast.error).mock.calls)).not.toContain('must-not-be-shown') + expect(toast.success).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/components/crash-report/use-crash-report-copy.ts b/src/renderer/src/components/crash-report/use-crash-report-copy.ts new file mode 100644 index 000000000..b2a604a07 --- /dev/null +++ b/src/renderer/src/components/crash-report/use-crash-report-copy.ts @@ -0,0 +1,69 @@ +import { useCallback, useRef } from 'react' +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import type { + CrashReportCopySubmissionFailure, + CrashReportRecord +} from '../../../../shared/crash-reporting' + +export const CRASH_REPORT_COPY_FAILURE_TOAST_ID = 'crash-report-copy-failure' + +function showCopyFailure(description?: string): void { + toast.error( + translate( + 'auto.components.crash.report.copy.copyFailed', + 'Crash report details could not be copied.' + ), + { + id: CRASH_REPORT_COPY_FAILURE_TOAST_ID, + ...(description ? { description } : {}), + duration: Infinity, + dismissible: true + } + ) +} + +export function useCrashReportCopy( + report: CrashReportRecord | null, + notes: string +): (submissionFailure?: CrashReportCopySubmissionFailure) => Promise { + const reportId = report?.id ?? null + const notesRef = useRef({ reportId, value: notes }) + // Why: a submission toast can outlive the render that created it while the + // user edits or changes reports; keep live notes scoped to that report. + if (notesRef.current.reportId === reportId) { + notesRef.current.value = notes + } else { + notesRef.current = { reportId, value: notes } + } + const reportNotes = notesRef.current + + return useCallback( + async (submissionFailure?: CrashReportCopySubmissionFailure): Promise => { + try { + const result = await window.api.crashReports.copyLatestDiagnostics({ + ...(report ? { reportId: report.id } : {}), + notes: reportNotes.value, + ...(submissionFailure ? { submissionFailure } : {}) + }) + if (!result.ok) { + showCopyFailure(result.error) + return + } + toast.dismiss(CRASH_REPORT_COPY_FAILURE_TOAST_ID) + toast.success( + translate( + 'auto.components.crash.report.CrashReportDialog.8b8473c544', + 'Crash report copied.' + ) + ) + } catch (error) { + console.error('Failed to copy crash report details:', error) + // Why: Sonner closes an action toast when clicked, so a sticky generic + // replacement keeps the failure actionable without exposing raw IPC detail. + showCopyFailure() + } + }, + [report, reportNotes] + ) +} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 0a60a2d35..b920423d8 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -11905,6 +11905,21 @@ "ead6fc0510": "No automatic crash report was captured. You can still send details and include recent diagnostic logs when available.", "b082f27490": "Attach recent diagnostic logs", "e59f0b9427": "Sends a capped redacted log bundle with the report." + }, + "submit": { + "notice": { + "unknownError": "The crash report request failed before it returned a reason.", + "ticketUploaded": "Diagnostic ticket {{value0}} was uploaded but not linked.", + "uncheckDiagnostics": "Uncheck \"Attach recent diagnostic logs\" and try again, or copy the details.", + "checkConnection": "Check your connection and try again, or copy the details.", + "notSent": "Crash report wasn't sent", + "copyDetails": "Copy Details", + "sentWithoutDiagnostics": "Crash report sent without diagnostic logs", + "diagnosticsReason": "Diagnostic logs were not attached: {{value0}}" + } + }, + "copy": { + "copyFailed": "Crash report details could not be copied." } } }, diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index b8c369477..640152506 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -11905,6 +11905,21 @@ "ead6fc0510": "No se capturó ningún informe de fallo automático. Aun así puedes enviar detalles e incluir logs de diagnóstico recientes cuando estén disponibles.", "b082f27490": "Adjuntar logs de diagnóstico recientes", "e59f0b9427": "Envía un paquete limitado de logs redactados junto con el informe." + }, + "submit": { + "notice": { + "unknownError": "The crash report request failed before it returned a reason.", + "ticketUploaded": "Diagnostic ticket {{value0}} was uploaded but not linked.", + "uncheckDiagnostics": "Uncheck \"Attach recent diagnostic logs\" and try again, or copy the details.", + "checkConnection": "Check your connection and try again, or copy the details.", + "notSent": "Crash report wasn't sent", + "copyDetails": "Copy Details", + "sentWithoutDiagnostics": "Crash report sent without diagnostic logs", + "diagnosticsReason": "Diagnostic logs were not attached: {{value0}}" + } + }, + "copy": { + "copyFailed": "No se pudieron copiar los detalles del informe de fallo." } } }, diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 2796e6293..b7b02bf19 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -11905,6 +11905,21 @@ "ead6fc0510": "No automatic crash report was captured. You can still send details and include recent diagnostic logs when available.", "b082f27490": "Attach recent diagnostic logs", "e59f0b9427": "Sends a capped redacted log bundle with the report." + }, + "submit": { + "notice": { + "unknownError": "The crash report request failed before it returned a reason.", + "ticketUploaded": "Diagnostic ticket {{value0}} was uploaded but not linked.", + "uncheckDiagnostics": "Uncheck \"Attach recent diagnostic logs\" and try again, or copy the details.", + "checkConnection": "Check your connection and try again, or copy the details.", + "notSent": "Crash report wasn't sent", + "copyDetails": "Copy Details", + "sentWithoutDiagnostics": "Crash report sent without diagnostic logs", + "diagnosticsReason": "Diagnostic logs were not attached: {{value0}}" + } + }, + "copy": { + "copyFailed": "クラッシュレポートの詳細をコピーできませんでした。" } } }, diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 9cd90833d..5d24f4f3c 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -11905,6 +11905,21 @@ "ead6fc0510": "자동 크래시 보고서가 캡처되지 않았습니다. 그래도 세부 정보를 보내고, 가능한 경우 최근 진단 로그를 포함할 수 있습니다.", "b082f27490": "최근 진단 로그 첨부", "e59f0b9427": "보고서와 함께 크기가 제한되고 민감 정보가 제거된 로그 묶음을 보냅니다." + }, + "submit": { + "notice": { + "unknownError": "The crash report request failed before it returned a reason.", + "ticketUploaded": "Diagnostic ticket {{value0}} was uploaded but not linked.", + "uncheckDiagnostics": "Uncheck \"Attach recent diagnostic logs\" and try again, or copy the details.", + "checkConnection": "Check your connection and try again, or copy the details.", + "notSent": "Crash report wasn't sent", + "copyDetails": "Copy Details", + "sentWithoutDiagnostics": "Crash report sent without diagnostic logs", + "diagnosticsReason": "Diagnostic logs were not attached: {{value0}}" + } + }, + "copy": { + "copyFailed": "충돌 보고서 세부 정보를 복사하지 못했습니다." } } }, @@ -12734,7 +12749,7 @@ "confirm": { "move": { "title": "프로젝트를 이동하시겠습니까?", - "description": "{{repoName}}을(를) {{targetName}}(으)로 이동합니다. Orca가 {{repoName}}을(를) {{activeProfileName}}에서 제거한 뒤 파일은 유지하고 {{targetName}}(으)로 다시 시작합니다.", + "description": "{{repoName}}을(를) {{targetName}}(으)로 이동합니다. Orca가 해당 프로젝트를 {{activeProfileName}}에서 제거한 뒤 파일은 유지하고 {{targetName}}(으)로 다시 시작합니다.", "action": "프로젝트 이동" }, "copy": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index ee6099601..8ef27b221 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -11905,6 +11905,21 @@ "ead6fc0510": "没有捕获到自动崩溃报告。你仍然可以发送详情,并在可用时包含最近的诊断日志。", "b082f27490": "附加最近的诊断日志", "e59f0b9427": "随报告发送经过删减且有大小限制的日志包。" + }, + "submit": { + "notice": { + "unknownError": "The crash report request failed before it returned a reason.", + "ticketUploaded": "Diagnostic ticket {{value0}} was uploaded but not linked.", + "uncheckDiagnostics": "Uncheck \"Attach recent diagnostic logs\" and try again, or copy the details.", + "checkConnection": "Check your connection and try again, or copy the details.", + "notSent": "Crash report wasn't sent", + "copyDetails": "Copy Details", + "sentWithoutDiagnostics": "Crash report sent without diagnostic logs", + "diagnosticsReason": "Diagnostic logs were not attached: {{value0}}" + } + }, + "copy": { + "copyFailed": "无法复制崩溃报告详细信息。" } } }, diff --git a/src/shared/crash-reporting.ts b/src/shared/crash-reporting.ts index af9ef812c..b65c9a3c0 100644 --- a/src/shared/crash-reporting.ts +++ b/src/shared/crash-reporting.ts @@ -108,6 +108,19 @@ export type CrashReportSubmitResult = diagnosticBundle?: CrashReportDiagnosticBundle } +export type CrashReportCopySubmissionFailure = { + error: string + diagnosticContext?: + | { status: 'uploaded'; ticketId: string } + | { status: 'not_uploaded'; reason: string } +} + +export type CrashReportCopyDiagnosticsArgs = { + reportId?: string + notes?: string + submissionFailure?: CrashReportCopySubmissionFailure +} + const MAX_STRING_DETAIL_LENGTH = 240 const MAX_STACK_DETAIL_LENGTH = 4_000 const MAX_BREADCRUMB_NAME_LENGTH = 80