Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): make a failed bug-report send diagnosable (PRD-8092) (#3730)
Andrew Mikofalvy75062b219303
diff --git a/.changeset/bug-report-send-failure-diagnostics.md b/.changeset/bug-report-send-failure-diagnostics.mdnew file mode 100644index 000000000..9cee9f185--- /dev/null+++ b/.changeset/bug-report-send-failure-diagnostics.md@@ -0,0 +1,9 @@+---+"@inkeep/open-knowledge": patch+---++When sending a bug report fails, the report you send us afterwards can now explain why. Previously a failed send left a single line reading "network error" and nothing else: not which of the three requests failed, not whether your machine could not find our server or our server refused the connection or a certificate had expired, and no record at all once the logs aged out a week later. A report about a failed report was the one kind of report we could not answer.++Three things changed. Failures across every part of the app now record the error's type and its system error code in the log file that ships inside a report, rather than only on a developer console that nothing captures in an installed app. A failed send now names which request failed, so "our intake was unreachable" and "the storage the file uploads to was unreachable" are told apart. And the small record kept beside each report, which lists every send attempt and how it went, is now included in the reports you send — it is the only account that survives after the logs rotate.++The added detail is deliberately narrow: error types and system error codes, never messages, file paths, or stack traces, since those can carry your folder names and the addresses files upload to. Everything included goes through the same secret scrub as the rest of a report.diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 7f87aac8d..ad677c164 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -293,7 +293,7 @@ None of your content, by default. Everything above is written to your own disk.| What | When | Where it goes || --- | --- | --- || Diagnostic bundle | Only when you run `ok diagnose bundle` (you can inspect it first) | Wherever you send it |-| In-app bug report | Only when you click **Send** in the desktop app's **Help → Report a bug…** dialog — it builds a secret-redacted zip you can reveal and inspect first, and nothing is sent without that explicit click. After a crash, the same dialog adds an **off-by-default** "Include crash dump" checkbox: a crash dump is a memory snapshot that can contain document content and can't be redacted, and it is only ever attached when you check that box. On macOS the zip also carries the update helper's install log (listed above), which is machine-wide rather than project-scoped; the zip's own README names it and says where it came from | By default, Send makes no network request — it opens a prefilled email draft to [email protected] that you send yourself, naming the zip to attach. Only when an operator has configured a bug-report intake endpoint ([`OK_BUG_REPORT_INTAKE_URL`](./configuration.mdx#environment-variables)) does Send upload the zip there, falling back to the same email draft if the upload fails |+| In-app bug report | Only when you click **Send** in the desktop app's **Help → Report a bug…** dialog — it builds a secret-redacted zip you can reveal and inspect first, and nothing is sent without that explicit click. After a crash, the same dialog adds an **off-by-default** "Include crash dump" checkbox: a crash dump is a memory snapshot that can contain document content and can't be redacted, and it is only ever attached when you check that box. On macOS the zip also carries the update helper's install log (listed above), which is machine-wide rather than project-scoped; the zip's own README names it and says where it came from. The zip also carries a short send history of the bug reports previously generated on this machine — when each was generated and whether sending it succeeded — which is what makes a report that failed to send diagnosable at all. That history is machine-wide too, so it names the other projects you have filed reports from; it carries no document content, and the README names it the same way | By default, Send makes no network request — it opens a prefilled email draft to [email protected] that you send yourself, naming the zip to attach. Only when an operator has configured a bug-report intake endpoint ([`OK_BUG_REPORT_INTAKE_URL`](./configuration.mdx#environment-variables)) does Send upload the zip there, falling back to the same email draft if the upload fails || Uninstall feedback | Only after an uninstall has already succeeded, and only if you pick a reason, type a note, or give an email address on the optional "Before you go" screen (desktop app) or prompt (`ok uninstall`). Skipping it, `--yes`, `--json`, and any non-interactive run send nothing | `openknowledge.ai/api/feedback` — the reason you picked, your note, your email address if you gave one, plus the app version and platform. It files one ticket for the team; nothing from your notes is included || Semantic search embeddings | Only when you enable [semantic search](./configuration.mdx#semantic-search) **and** set a key — off by default | Your configured embeddings provider (OpenAI by default) || GitHub sync / share | When you sync, clone, publish, or share | GitHub |diff --git a/packages/cli/src/commands/bug-report-bundle.test.ts b/packages/cli/src/commands/bug-report-bundle.test.tsindex 1e5500278..53f648628 100644--- a/packages/cli/src/commands/bug-report-bundle.test.ts+++ b/packages/cli/src/commands/bug-report-bundle.test.ts@@ -11,6 +11,7 @@ import { basename, dirname, join, resolve } from 'node:path';import { afterEach, describe, expect, test } from 'vitest';import {type BundleLogger,+ collectBugReportLedgerFiles,collectShipItLogFiles,collectStandardBundle,collectUserLogFiles,@@ -693,6 +694,90 @@ describe('collectStandardBundle — bundle scope disclosure', () => {const readme = readZipEntry(zipPath, 'README.md');expect(readme).not.toContain('user-wide rather than project-scoped');});++ // A sidecar records the project ITS OWN report was filed from, so a bundle+ // filed from project A ships the slugs of B, C and D. The `Project:` header+ // names one project, and the "safe to attach" claim sits a few lines below —+ // so a reader who is not told would reasonably take the whole zip to be+ // scoped to the project named at the top. Filtering by slug is not the fix:+ // a system-wide report carries no slug and is routinely the record being+ // reported on, so narrowing would drop exactly the evidence this collects.+ test('discloses the send ledger as machine-wide, naming its entries', async () => {+ const reportsDir = makeTmpDir('ok-bugreport-ledger-');+ writeFileSync(+ join(reportsDir, '2026-08-19T16-42-03-547Z-bugreport.yaml'),+ 'id: 2026-08-19T16-42-03-547Z-bugreport.zip\nprojectSlug: someotherproject\n',+ );+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectStandardBundle({+ projectDir: makeProjectDir('bundle-proj'),+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ bugReportLedgerFiles: collectBugReportLedgerFiles(reportsDir),+ });++ // Scoped to the Privacy section: the Contents list names every file, so a+ // whole-README assertion would pass whatever the notes actually said.+ const readme = readZipEntry(zipPath, 'README.md');+ const privacy = readme.slice(readme.indexOf('## Privacy'));+ expect(privacy).toContain('Send history:');+ expect(privacy).toContain('names the other projects reports were filed');+ expect(+ privacy.match(/^- state\/bug-reports\/2026-08-19T16-42-03-547Z-bugreport\.yaml$/gm),+ ).toHaveLength(1);+ });++ // The unscoped bundle is the one most likely to be attached to a public issue+ // under "safe to attach", and it is exactly the case a slug-based filter+ // would have handled worst — so the disclosure cannot ride on the scope note,+ // which stays silent when nothing was narrowed.+ test('discloses the send ledger in an unscoped bundle too', async () => {+ const reportsDir = makeTmpDir('ok-bugreport-ledger-');+ writeFileSync(+ join(reportsDir, '2026-08-19T16-42-03-547Z-bugreport.yaml'),+ 'id: 2026-08-19T16-42-03-547Z-bugreport.zip\nprojectSlug: null\n',+ );+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectStandardBundle({+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ bugReportLedgerFiles: collectBugReportLedgerFiles(reportsDir),+ });++ const readme = readZipEntry(zipPath, 'README.md');+ const privacy = readme.slice(readme.indexOf('## Privacy'));+ expect(privacy).not.toContain('user-wide rather than project-scoped');+ expect(privacy).toContain('Send history:');+ });++ // Disclosure is intersected with what was actually written, so a sidecar that+ // vanished between listing and staging is not announced as present. A README+ // that over-claims is its own privacy defect: it tells a reader to look for+ // something, and its absence reads as the collector having hidden it.+ test('does not disclose a sidecar that failed to stage', async () => {+ const reportsDir = makeTmpDir('ok-bugreport-ledger-');+ const ghost = join(reportsDir, '2026-08-19T16-42-03-547Z-bugreport.yaml');+ writeFileSync(ghost, 'id: x\n');+ const listed = collectBugReportLedgerFiles(reportsDir);+ rmSync(ghost);+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectStandardBundle({+ projectDir: makeProjectDir('bundle-proj'),+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ bugReportLedgerFiles: listed,+ });++ const readme = readZipEntry(zipPath, 'README.md');+ expect(readme.slice(readme.indexOf('## Privacy'))).not.toContain('Send history:');+ expect(listZipEntries(zipPath).filter((e) => e.startsWith('state/bug-reports/'))).toEqual([]);+ });});describe('collectStandardBundle — system-wide (no projectDir)', () => {diff --git a/packages/cli/src/commands/bug-report-bundle.ts b/packages/cli/src/commands/bug-report-bundle.tsindex 5f5a170e8..744ff003a 100644--- a/packages/cli/src/commands/bug-report-bundle.ts+++ b/packages/cli/src/commands/bug-report-bundle.ts@@ -18,6 +18,7 @@ import { basename, dirname, join, resolve } from 'node:path';import {type BundleManifest,type BundleRedaction,+ REPORT_SIDECAR_BUNDLE_DIR,SERVER_CRASH_LOG,} from '@inkeep/open-knowledge-core';import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';@@ -88,6 +89,13 @@ export interface CollectStandardBundleOptions {* same reason `userLogsDir` is injectable, but enforced by construction.*/shipItLogFiles?: string[];+ /**+ * Per-report send-ledger sidecars, already resolved by the caller (see+ * `collectBugReportLedgerFiles`). Injected rather than resolved here for the+ * same reason as `shipItLogFiles`: this collector keeps no implicit+ * dependency on the real home directory.+ */+ bugReportLedgerFiles?: string[];/** User note added as `note.txt`, scrubbed like any content file when `redact` is on. */note?: string;/** Extra files (e.g. an opted-in crash minidump) added under `extra/`. */@@ -272,6 +280,48 @@ export function collectShipItLogFiles(return SHIPIT_LOG_FILES.map((name) => join(shipItDir, name)).filter((p) => existsSync(p));}+/**+ * How many sidecars a bundle carries. Retention keeps reports around, so this+ * directory grows without limit on a machine that files often, and a bundle+ * must not scale with a reporter's history. Each file is small and bounded by+ * construction (the writer caps the attempt list), so the count is the only+ * bound needed.+ */+const MAX_BUNDLED_LEDGER_FILES = 25;++/**+ * The per-report send ledger: one small YAML sidecar per report, recording+ * every send attempt with its outcome and reason.+ *+ * This is the artifact that answers "did the send fail before, and how" — and+ * the only one that still answers it later, because `desktop.*.log` rotates on+ * a seven-day budget while a sidecar persists beside its zip. Without it, a+ * report about a failed send carries no account of the failure unless the+ * reporter happens to file it the same day, on a machine we can read.+ *+ * Sidecars ONLY: `*.yaml` is an allowlist, not a filter, so the zips sitting+ * beside them in the same directory cannot be swept in. That matters twice —+ * a bundle must not contain other bundles, and the zips are the bulk of the+ * directory.+ *+ * Newest kept, ranked by name: report ids are timestamp-prefixed, so+ * lexicographic order IS chronological order and no `stat` call is needed.+ */+export function collectBugReportLedgerFiles(bugReportsDir: string): string[] {+ if (!existsSync(bugReportsDir)) return [];+ try {+ return readdirSync(bugReportsDir)+ .filter((name) => name.endsWith('.yaml'))+ .sort()+ .slice(-MAX_BUNDLED_LEDGER_FILES)+ .map((name) => join(bugReportsDir, name));+ } catch {+ // An unreadable reports dir must cost the ledger, never the report the+ // user is trying to file.+ return [];+ }+}+function collectLogs(projectSlug: string | null,logsDir: string,@@ -467,6 +517,18 @@ export async function collectStandardBundle(redactions,logger,});+ // The send ledger. Scrubbed like every other content file here: a sidecar+ // carries the reporter's own note, so it is user-authored text, not machine+ // output.+ addContentFiles({+ zipfile,+ files: opts.bugReportLedgerFiles ?? [],+ prefix: REPORT_SIDECAR_BUNDLE_DIR,+ redact,+ bundleFiles,+ redactions,+ logger,+ });for (const extra of opts.extraFiles ?? []) {try {@@ -524,6 +586,21 @@ export async function collectStandardBundle(const shipItEntryNames = new Set(shipItFiles.map((f) => `logs/${basename(f)}`));const installerLogEntries = bundleFiles.filter((f) => shipItEntryNames.has(f));+ // Disclosed independently of project scope, for a different reason than the+ // installer log above: a sidecar records the project its own report was filed+ // from, so a bundle filed from one project names every OTHER project this+ // machine has reported from. `collectLogs` narrows the families a slug CAN+ // narrow and reports what it dropped; this family cannot be narrowed that+ // way, because a system-wide report carries no slug at all and is routinely+ // the very record being reported on — filtering by slug would drop exactly+ // the evidence the ledger exists to preserve. So the scope is stated instead.+ // Intersected with what was actually written, so a sidecar that turned out to+ // be unreadable is never disclosed as present.+ const ledgerEntryNames = new Set(+ (opts.bugReportLedgerFiles ?? []).map((f) => `${REPORT_SIDECAR_BUNDLE_DIR}/${basename(f)}`),+ );+ const ledgerEntries = bundleFiles.filter((f) => ledgerEntryNames.has(f));+// The families the slug cannot narrow are per-machine, per-day singletons, so// a project-scoped bundle still carries whatever else the machine was doing// that day. Secret scrubbing does not narrow this — it matches credentials,@@ -575,6 +652,18 @@ export async function collectStandardBundle('',]: []),+ ...(ledgerEntries.length > 0+ ? [+ 'Send history: one small record per bug report previously generated',+ 'on this machine — when it was generated, whether sending it',+ 'succeeded, and why it failed if it did. This is what makes a failed',+ 'send diagnosable at all. It is machine-wide rather than scoped to',+ 'this project, so it names the other projects reports were filed',+ 'from. It carries no document content:',+ ...ledgerEntries.map((f) => `- ${f}`),+ '',+ ]+ : []),...(redact? ['This bundle was auto-redacted before packaging.',diff --git a/packages/cli/src/diagnose/bundle.ts b/packages/cli/src/diagnose/bundle.tsindex 21d73e116..a658875b6 100644--- a/packages/cli/src/diagnose/bundle.ts+++ b/packages/cli/src/diagnose/bundle.ts@@ -29,7 +29,11 @@ import {import { arch as osArch, platform as osPlatform, tmpdir } from 'node:os';import { basename, dirname, join, relative, resolve, sep } from 'node:path';import type { BundleRedaction as SecretScrubEntry } from '@inkeep/open-knowledge-core';-import { SERVER_CRASH_LOG, SERVER_EXIT_LOG } from '@inkeep/open-knowledge-core';+import {+ REPORT_SIDECAR_BUNDLE_DIR,+ SERVER_CRASH_LOG,+ SERVER_EXIT_LOG,+} from '@inkeep/open-knowledge-core';import {DEFAULT_LOGS_MAX_BYTES,DEFAULT_SPANS_MAX_BYTES,@@ -201,6 +205,20 @@ export interface CollectBundleOpts {* text and must be scrubbed.*/userLogFiles?: string[];+ /**+ * Absolute paths to user-level state files staged under+ * `state/bug-reports/` — the per-report send-ledger sidecars, resolved by the+ * caller (see `collectBugReportLedgerFiles`).+ *+ * They answer a question the logs stop being able to answer: `desktop.*.log`+ * rotates on a seven-day budget, while a sidecar persists beside its zip, so+ * a report filed about a send that failed last week has the ledger and no+ * log line.+ *+ * Staged BEFORE the redaction + secret scrub, like `userLogFiles` and unlike+ * `extraFiles` — these are text, and a sidecar carries the reporter's note.+ */+ userStateFiles?: string[];/** Test-injectable dependencies — every field defaults to a real-system implementation. */deps?: CollectBundleDeps;}@@ -672,7 +690,18 @@ function shouldCountLines(relPath: string): boolean {return LINE_COUNTED_EXTENSIONS.has(relPath.slice(lastDot));}-const SECRET_SCRUB_EXTENSIONS = new Set(['.jsonl', '.json', '.txt', '.log', '.lock']);+// `.yaml`/`.yml` are here for the bug-report sidecars staged under+// `state/bug-reports/`: they carry the reporter's own note, so they are+// user-authored text and have to be scrubbed like any other.+const SECRET_SCRUB_EXTENSIONS = new Set([+ '.jsonl',+ '.json',+ '.txt',+ '.log',+ '.lock',+ '.yaml',+ '.yml',+]);function isSecretScrubbable(relPath: string): boolean {// A rotated log's real extension is its counter (`.log.3` slices to `.3`), so@@ -745,6 +774,12 @@ export async function collectBundle(opts: CollectBundleOpts): Promise<CollectedBfor (const userLogPath of opts.userLogFiles ?? []) {stageFileIfPresent(userLogPath, join(stagingDir, 'logs', basename(userLogPath)));}+ for (const userStatePath of opts.userStateFiles ?? []) {+ stageFileIfPresent(+ userStatePath,+ join(stagingDir, REPORT_SIDECAR_BUNDLE_DIR, basename(userStatePath)),+ );+ }// Server lock + status + agent presence.const lockDir = join(projectDir, '.ok', 'local');diff --git a/packages/cli/src/report-bundle.test.ts b/packages/cli/src/report-bundle.test.tsindex 63f02b599..d2015c03b 100644--- a/packages/cli/src/report-bundle.test.ts+++ b/packages/cli/src/report-bundle.test.ts@@ -10,7 +10,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSyncimport { tmpdir } from 'node:os';import { dirname, join, resolve } from 'node:path';import { SERVER_CRASH_LOG } from '@inkeep/open-knowledge-core';-import { afterEach, describe, expect, test } from 'vitest';+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';import { collectReportBundle as collectReportBundleFromIndex } from './index.ts';import { collectReportBundle } from './report-bundle.ts';import type { LanguageMetadata } from './report-language.ts';@@ -23,6 +23,22 @@ function makeTmpDir(prefix = 'ok-report-test-'): string {return dir;}+// Several sources default to a path under the home directory when the caller+// supplies no override — the user-level logs, the ShipIt cache, and the+// bug-report send ledger. Every one of those resolves `homedir()` at call time+// rather than at import, precisely so a test can move it. Point HOME at an+// empty directory for the whole file so a developer's own logs and prior bug+// reports cannot end up staged into a fixture bundle, and so a run here matches+// a run on CI, where that directory does not exist.+const realHome = process.env.HOME;+beforeAll(() => {+ process.env.HOME = mkdtempSync(resolve(tmpdir(), 'ok-report-test-home-'));+});+afterAll(() => {+ if (realHome === undefined) delete process.env.HOME;+ else process.env.HOME = realHome;+});+afterEach(() => {for (const d of tmpDirs) {if (existsSync(d)) rmSync(d, { recursive: true, force: true });@@ -876,3 +892,176 @@ describe('collectReportBundle — package surface', () => {expect(collectReportBundleFromIndex).toBe(collectReportBundle);});});++/**+ * The per-report send ledger (`~/.ok/bug-reports/*.yaml`) records every send+ * attempt with its outcome, and it is the artifact that made the two observed+ * send failures diagnosable at all — but only because they happened on a+ * machine we could read directly.+ *+ * It is also the copy that outlives the logs: `desktop.*.log` rotates on a+ * seven-day/45 MB budget, while a sidecar persists next to its zip. A reporter+ * filing a bug about a send that failed last week has the ledger and no log.+ */+describe('collectReportBundle — bug-report send ledger', () => {+ const LEDGER_YAML = [+ 'version: 1',+ 'id: 2026-08-19T16-42-03-547Z-bugreport.zip',+ 'createdAt: 2026-08-19T16:42:03.547Z',+ 'bundleLevel: full',+ 'state: upload-failed',+ 'lastError:',+ ' reason: upload-network-error',+ ' at: 2026-08-19T16:42:19.000Z',+ 'attempts:',+ ' - at: 2026-08-19T16:42:03.547Z',+ ' transport: upload',+ ' outcome: failed',+ ' error: upload-network-error',+ '',+ ].join('\n');++ /** A reports dir shaped like the real one: sidecars beside their payloads. */+ function makeBugReportsDir(): string {+ const dir = makeTmpDir('ok-bug-reports-');+ writeAt(dir, '2026-08-19T16-42-03-547Z-bugreport.yaml', LEDGER_YAML);+ writeAt(dir, '2026-08-19T16-42-03-547Z-bugreport.zip', Buffer.from([0x50, 0x4b, 0x03, 0x04]));+ return dir;+ }++ test('full level stages the ledger so a failed send is answerable from the bundle', async () => {+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath, summary } = await collectReportBundle({+ level: 'full',+ projectDir: makeFullProjectDir(),+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ bugReportsDir: makeBugReportsDir(),+ });++ const entry = 'state/bug-reports/2026-08-19T16-42-03-547Z-bugreport.yaml';+ expect(listZipEntries(zipPath)).toContain(entry);+ expect(summary.files).toContain(entry);+ // The attempt sequence is the whole point: two failures then a success is+ // what separates a transient fault from a broken intake.+ expect(readZipEntry(zipPath, entry)).toContain('upload-network-error');+ });++ test('standard level stages it too', async () => {+ // A reporter filing at standard level is reporting the same failed send.+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectReportBundle({+ level: 'standard',+ projectDir: makeStandardProjectDir(),+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ bugReportsDir: makeBugReportsDir(),+ });++ expect(listZipEntries(zipPath)).toContain(+ 'state/bug-reports/2026-08-19T16-42-03-547Z-bugreport.yaml',+ );+ });++ test('neither level stages the zip payloads sitting beside the sidecars', async () => {+ // A bundle must not contain other bundles: the reports dir holds every+ // previously-captured zip, and harvesting them would multiply a 6 MB+ // report by every report the machine has ever kept.+ for (const level of ['standard', 'full'] as const) {+ const outputPath = join(makeTmpDir(), `${level}.zip`);+ const { zipPath } = await collectReportBundle({+ level,+ projectDir: level === 'full' ? makeFullProjectDir() : makeStandardProjectDir(),+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ bugReportsDir: makeBugReportsDir(),+ });++ expect(listZipEntries(zipPath).filter((e) => e.endsWith('-bugreport.zip'))).toEqual([]);+ }+ });++ test('the ledger goes through the secret scrub like every other staged text file', async () => {+ // Sidecars carry a `note` field holding the reporter's own words, so this+ // is user-authored text, not machine output. Staging it without the scrub+ // would ship a credential a reporter pasted into a bug description.+ // `.yaml` is not one of the extensions the full-level scrub recognized, so+ // this is the failure mode a scrub-by-extension design invites.+ const dir = makeTmpDir('ok-bug-reports-');+ writeAt(+ dir,+ '2026-08-19T16-42-03-547Z-bugreport.yaml',+ `${LEDGER_YAML}note: it died right after I pasted ${SECRET}\n`,+ );++ for (const level of ['standard', 'full'] as const) {+ const outputPath = join(makeTmpDir(), `${level}.zip`);+ const { zipPath } = await collectReportBundle({+ level,+ projectDir: level === 'full' ? makeFullProjectDir() : makeStandardProjectDir(),+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ bugReportsDir: dir,+ });++ const body = readZipEntry(+ zipPath,+ 'state/bug-reports/2026-08-19T16-42-03-547Z-bugreport.yaml',+ );+ expect(body).toContain('upload-network-error');+ expect(body).not.toContain(SECRET);+ }+ });++ test('a dir with dozens of reports contributes a bounded, newest-first slice', async () => {+ // Retention keeps reports around, so this directory grows without limit on+ // a machine that files often. Report ids are timestamp-prefixed, so newest+ // sorts last lexicographically and no stat call is needed to rank them.+ const dir = makeTmpDir('ok-bug-reports-');+ for (let i = 0; i < 40; i += 1) {+ const stamp = `2026-08-${String((i % 28) + 1).padStart(2, '0')}T10-00-${String(i).padStart(2, '0')}-000Z`;+ writeAt(dir, `${stamp}-bugreport.yaml`, `id: ${stamp}-bugreport.zip\nstate: sent\n`);+ }+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectReportBundle({+ level: 'full',+ projectDir: makeFullProjectDir(),+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ bugReportsDir: dir,+ });++ const staged = listZipEntries(zipPath).filter((e) => e.startsWith('state/bug-reports/'));+ // Exact, not a range: 40 readable sidecars go in, so a range assertion+ // holds just as well if the cap regresses to 1, and the ordering+ // assertions below would still pass. The number is the contract.+ expect(staged.length).toBe(25);+ // Newest kept: the last id by sort order must be present, the first absent.+ expect(staged).toContain('state/bug-reports/2026-08-28T10-00-27-000Z-bugreport.yaml');+ expect(staged).not.toContain('state/bug-reports/2026-08-01T10-00-00-000Z-bugreport.yaml');+ });++ test('an absent reports dir is not an error', async () => {+ const outputPath = join(makeTmpDir(), 'report.zip');++ const { zipPath } = await collectReportBundle({+ level: 'full',+ projectDir: makeFullProjectDir(),+ redact: true,+ outputPath,+ userLogsDir: makeTmpDir(),+ bugReportsDir: join(makeTmpDir(), 'does-not-exist'),+ });++ expect(existsSync(zipPath)).toBe(true);+ expect(listZipEntries(zipPath).filter((e) => e.startsWith('state/bug-reports/'))).toEqual([]);+ });+});diff --git a/packages/cli/src/report-bundle.ts b/packages/cli/src/report-bundle.tsindex 208273766..743248af9 100644--- a/packages/cli/src/report-bundle.ts+++ b/packages/cli/src/report-bundle.ts@@ -16,9 +16,11 @@ import { parse as parseYaml } from 'yaml';import {type BundleExtraFile,type BundleLogger,+ collectBugReportLedgerFiles,collectShipItLogFiles,collectStandardBundle,collectUserLogFiles,+ okBugReportsDir,resolveProjectSlug,} from './commands/bug-report-bundle.ts';import {@@ -57,6 +59,8 @@ export interface CollectReportBundleOptions {userLogsDir?: string;/** Override the macOS caches directory searched for ShipIt install logs (test seam). */cachesDir?: string;+ /** Override the bug-reports directory the send ledger is read from (test seam). */+ bugReportsDir?: string;/*** Collection-progress + warning sink. The full level reports its inventory* via the manifest and uses this only for warnings (e.g. an opted-in extra@@ -140,6 +144,9 @@ async function collectFullBundle(// app bundle, and it is the only record of why a post-exit install failed....collectShipItLogFiles(opts.cachesDir ?? join(homedir(), 'Library', 'Caches')),],+ // The per-report send ledger. Both levels carry it: a reporter filing at+ // standard level is reporting the same failed send.+ userStateFiles: collectBugReportLedgerFiles(opts.bugReportsDir ?? okBugReportsDir()),deps: { readDesktopEnv, readLanguage, logger: opts.logger },});try {@@ -198,6 +205,7 @@ export async function collectReportBundle(outputPath: opts.outputPath,userLogsDir: opts.userLogsDir,shipItLogFiles: collectShipItLogFiles(opts.cachesDir ?? join(homedir(), 'Library', 'Caches')),+ bugReportLedgerFiles: collectBugReportLedgerFiles(opts.bugReportsDir ?? okBugReportsDir()),logger: opts.logger,note: opts.note,extraFiles: opts.extraFiles,diff --git a/packages/core/src/bug-report-sidecar/schema.ts b/packages/core/src/bug-report-sidecar/schema.tsindex 753c41991..b3c4789fc 100644--- a/packages/core/src/bug-report-sidecar/schema.ts+++ b/packages/core/src/bug-report-sidecar/schema.ts@@ -35,6 +35,19 @@ import { z } from 'zod';*/export const REPORT_SIDECAR_SCHEMA_VERSION = 1;+/**+ * Where sidecars land inside a diagnostic bundle, at every bundle level.+ *+ * Shared rather than spelled at each staging site because the two bundle+ * assemblers (the standard zip builder and the full-level staging collector)+ * are independent code paths, and a triager reading a bundle should not have to+ * know which one produced it to know where to look.+ *+ * The sidecars are staged; the zips beside them are not. A bundle must not+ * contain other bundles.+ */+export const REPORT_SIDECAR_BUNDLE_DIR = 'state/bug-reports';+/*** Known report lifecycle states. Read as an OPEN enum: an unrecognized value* (a newer app wrote a state this build doesn't know) normalizes to `'unknown'`@@ -102,6 +115,13 @@ const AttemptSchema = z.looseObject({reference: z.string().optional(),/** Short failure reason when the attempt failed. */error: z.string().optional(),+ /**+ * The errno behind the failure, when the transport reported one. Bounded by+ * the platform's errno table, so it is safe to persist into a file that ships+ * inside a diagnostic bundle — unlike the error's message, which carries the+ * host or path it failed on.+ */+ errorCode: z.string().optional(),});export type ReportSidecarAttempt = z.infer<typeof AttemptSchema>;@@ -109,6 +129,8 @@ export type ReportSidecarAttempt = z.infer<typeof AttemptSchema>;const LastErrorSchema = z.looseObject({reason: z.string(),at: z.string(),+ /** The errno behind the failure, when the transport reported one. */+ errorCode: z.string().optional(),});/**diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex f609121f8..0b586d5ef 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -6,6 +6,7 @@ export {isReportIdShape,normalizeReportSidecarState,REPORT_ID_PATTERN,+ REPORT_SIDECAR_BUNDLE_DIR,REPORT_SIDECAR_SCHEMA_VERSION,REPORT_SIDECAR_STATES,type ReportSidecar,diff --git a/packages/desktop/src/main/bug-report-sidecar.ts b/packages/desktop/src/main/bug-report-sidecar.tsindex 357a3c99b..fa6ce00c8 100644--- a/packages/desktop/src/main/bug-report-sidecar.ts+++ b/packages/desktop/src/main/bug-report-sidecar.ts@@ -364,7 +364,13 @@ async function recordSendResult(outcome.kind === 'sent'? { at, transport: 'upload', outcome: 'success', reference: outcome.reference }: outcome.kind === 'upload-failed'- ? { at, transport: 'upload', outcome: 'failed', error: outcome.reason }+ ? {+ at,+ transport: 'upload',+ outcome: 'failed',+ error: outcome.reason,+ ...(outcome.errorCode === undefined ? {} : { errorCode: outcome.errorCode }),+ }: { at, transport: 'email', outcome: 'success' };const attempts = [...(base.attempts ?? []), attempt].slice(-MAX_REPORT_ATTEMPTS);// Rebuild without a stale lastError, then set the new terminal fields.@@ -373,7 +379,15 @@ async function recordSendResult(if (outcome.kind === 'sent') {next = { ...next, state: 'sent', reference: outcome.reference };} else if (outcome.kind === 'upload-failed') {- next = { ...next, state: 'upload-failed', lastError: { reason: outcome.reason, at } };+ next = {+ ...next,+ state: 'upload-failed',+ lastError: {+ reason: outcome.reason,+ at,+ ...(outcome.errorCode === undefined ? {} : { errorCode: outcome.errorCode }),+ },+ };} else {next = { ...next, state: 'email-drafted' };}diff --git a/packages/desktop/src/main/ipc-log.test.ts b/packages/desktop/src/main/ipc-log.test.tsindex 969824814..157d9ecdc 100644--- a/packages/desktop/src/main/ipc-log.test.ts+++ b/packages/desktop/src/main/ipc-log.test.ts@@ -19,7 +19,7 @@* return shape that retriable-consent dialogs depend on.*/-import { describe, expect, test } from 'vitest';+import { beforeEach, describe, expect, test, vi } from 'vitest';import { logIpcError, withIpcErrorLogging } from './ipc-log.ts';interface CapturedWarn {@@ -274,3 +274,207 @@ describe('logIpcError — bounded details', () => {});});});++/**+ * The pino leg is the ONLY `logIpcError` surface that reaches+ * `~/.ok/logs/desktop.*.log`, and therefore the only one that reaches a+ * diagnostic bundle a reporter sends us. `console.warn` goes to main-process+ * stdio, which nothing captures in a packaged app launched from Finder.+ *+ * Every other test in this file asserts `console.warn`. That asymmetry is why+ * a failed bug-report send reached support as one bare line carrying no cause+ * and no errno: the leg that ships was never exercised, so nothing noticed it+ * was being handed three fields while the leg nobody reads got the rest.+ */+const pinoWarn = vi.hoisted(() => vi.fn());++vi.mock('./desktop-logger.ts', () => ({+ getLogger: () => ({+ warn: pinoWarn,+ info: vi.fn(),+ error: vi.fn(),+ debug: vi.fn(),+ }),+}));++describe('logIpcError — the pino leg (the surface that ships in diagnostic bundles)', () => {+ beforeEach(() => {+ pinoWarn.mockClear();+ });++ /** Emit once with `console.warn` silenced and return what pino was handed. */+ function pinoFields(emit: () => void): Record<string, unknown> {+ const originalWarn = console.warn;+ console.warn = () => {};+ try {+ emit();+ } finally {+ console.warn = originalWarn;+ }+ expect(pinoWarn).toHaveBeenCalledTimes(1);+ return pinoWarn.mock.calls[0]?.[0] as Record<string, unknown>;+ }++ test('the canonical discriminants reach the file logger', () => {+ const fields = pinoFields(() => {+ logIpcError({+ event: 'ipc.error',+ channel: 'ok:bug-report:dispatch',+ reason: 'upload-network-error',+ handler: 'handleBugReportSend',+ });+ });++ expect(fields).toMatchObject({+ channel: 'ok:bug-report:dispatch',+ reason: 'upload-network-error',+ handler: 'handleBugReportSend',+ });+ });++ test('an Error cause contributes its class to the file logger', () => {+ // Every channel that catches an unknown and passes `cause: err` gets this+ // without hand-building `details` — which is what makes the fix worth+ // making here rather than at one call site.+ const fields = pinoFields(() => {+ logIpcError({+ event: 'ipc.error',+ channel: 'ok:window:open-note',+ reason: 'unexpected',+ handler: 'openNoteWindow',+ cause: new TypeError('fetch failed'),+ });+ });++ expect(fields.errName).toBe('TypeError');+ });++ test('an errno hidden one level down in cause is recovered', () => {+ // undici reports every transport failure as the same opaque+ // `TypeError: fetch failed` and hangs the real error in `cause`, so reading+ // `code` off the caught value alone yields nothing on exactly the failures+ // worth triaging.+ const inner = Object.assign(new Error('getaddrinfo ENOTFOUND intake'), {+ code: 'ENOTFOUND',+ });+ const outer = new TypeError('fetch failed', { cause: inner });++ const fields = pinoFields(() => {+ logIpcError({+ event: 'ipc.error',+ channel: 'ok:bug-report:dispatch',+ reason: 'mint-network-error',+ handler: 'handleBugReportSend',+ cause: outer,+ });+ });++ expect(fields.errName).toBe('TypeError');+ expect(fields.errCode).toBe('ENOTFOUND');+ });++ test('no stack and no free-form message reach the file logger', () => {+ // `details` (and everything derived alongside it) is collected into+ // user-submitted bundles, so it takes only values bounded by construction.+ // A stack carries absolute paths out of the reporter's home directory and+ // an errno message carries the filename that could not be opened; neither+ // may be written into a file the reporter hands to support. The class and+ // the errno are what discriminate the failure, and they are bounded.+ const err = Object.assign(+ new Error("ENOENT: no such file or directory, open '/Users/someone/private/notes.md'"),+ { code: 'ENOENT' },+ );+ err.stack = 'Error: ENOENT\n at /Users/someone/private/app.ts:1:1';++ const fields = pinoFields(() => {+ logIpcError({+ event: 'ipc.error',+ channel: 'ok:shell:open-asset',+ reason: 'open-failed',+ handler: 'openAssetSafely',+ cause: err,+ });+ });++ expect(fields.errCode).toBe('ENOENT');+ const serialized = JSON.stringify(fields);+ expect(serialized).not.toContain('/Users/someone');+ expect(serialized).not.toContain('no such file or directory');+ });++ test('call-site details win over facts derived from the cause', () => {+ // A handler that has already classified its own failure knows more than a+ // generic walk of the caught value can.+ const fields = pinoFields(() => {+ logIpcError({+ event: 'ipc.error',+ channel: 'ok:bug-report:dispatch',+ reason: 'upload-network-error',+ handler: 'handleBugReportSend',+ cause: Object.assign(new TypeError('fetch failed'), { code: 'GENERIC' }),+ details: { step: 'upload', errCode: 'UND_ERR_SOCKET', host: 'storage.example.com' },+ });+ });++ expect(fields).toMatchObject({+ step: 'upload',+ errCode: 'UND_ERR_SOCKET',+ host: 'storage.example.com',+ });+ });++ test('a cyclic cause chain cannot cost the log line', () => {+ // `normalizeCause` guards the console leg against this; anything that walks+ // the same hostile input for the pino leg has to guard it too, or the+ // failure that most needs recording is the one that records nothing.+ const a = new Error('a');+ const b = new Error('b');+ Object.assign(a, { cause: b });+ Object.assign(b, { cause: a });++ const fields = pinoFields(() => {+ logIpcError({+ event: 'ipc.error',+ channel: 'ok:mcp-wiring:confirm',+ reason: 'write-mcp-configs-threw',+ handler: 'mcpWiringConfirm',+ cause: a,+ });+ });++ expect(fields).toMatchObject({+ channel: 'ok:mcp-wiring:confirm',+ reason: 'write-mcp-configs-threw',+ });+ });++ test('a cause that throws on inspection cannot suppress the log line', () => {+ // Deriving the bounded facts must not run inside the try that already+ // wraps the emit: a throw there would swallow the whole line and leave the+ // failure with no record at all, which is strictly worse than the bare+ // line this change exists to improve on.+ const hostile: Record<string, unknown> = {};+ Object.defineProperty(hostile, 'code', {+ enumerable: true,+ get() {+ throw new Error('inspection refused');+ },+ });++ const fields = pinoFields(() => {+ logIpcError({+ event: 'ipc.error',+ channel: 'ok:shell:spawn-cursor',+ reason: 'spawn-failed',+ handler: 'spawnCursor',+ cause: hostile,+ });+ });++ expect(fields).toMatchObject({+ channel: 'ok:shell:spawn-cursor',+ reason: 'spawn-failed',+ handler: 'spawnCursor',+ });+ });+});diff --git a/packages/desktop/src/main/ipc-log.ts b/packages/desktop/src/main/ipc-log.tsindex 2885432e0..b962cd1dd 100644--- a/packages/desktop/src/main/ipc-log.ts+++ b/packages/desktop/src/main/ipc-log.ts@@ -4,21 +4,25 @@* Mirrors the HTTP `errorResponse(...)` discipline (RFC 9457) at* the IPC transport. Every IPC handler that returns `{ ok: false; reason }`* (or `{ ok: false; error }`) emits a `logIpcError(...)` call on the same- * code path, producing a JSON-shaped console.warn line that downstream- * consumers (Sentry breadcrumbs, file tail, structured-pipeline) can index- * by channel + reason + handler.- *- * Why not Pino: adding Pino to Electron main has build-graph- * implications (electron-vite externalizeDeps + main bundle entry), and- * the existing per-module Logger interfaces in `mcp-wiring.ts`- * (`McpWiringLogger`) and `auto-updater.ts` (`Logger`) already use a- * JSON-shaped `console.warn` + structured payload pattern. This module- * is the canonical declaration so all 42 channels speak the same shape.- *- * Why structured + JSON-on-console: keeps the host-process bridge simple- * (Electron's stderr/stdout pipe + standard log capture pattern) while- * giving consumers a parseable shape. The `event: 'ipc.error'` discriminant- * lets downstream filters separate IPC failures from arbitrary stdout noise.+ * code path, producing a payload that downstream consumers (file tail,+ * structured-pipeline) can index by channel + reason + handler.+ *+ * TWO legs, and which one a field reaches is the whole design:+ *+ * - the PINO leg writes `~/.ok/logs/desktop.*.log`, the file collected into+ * the diagnostic bundles reporters send us. This is the leg that has to+ * answer "why did it fail" for someone whose machine we cannot read, and+ * it is therefore the leg that must never carry a path, a credential, or+ * free-form user text.+ * - the CONSOLE leg emits one JSON line on main-process stdio. It carries+ * the unbounded context (message, stack) because a developer tailing a+ * terminal wants it — but nothing captures stdio in a packaged app+ * launched from Finder, so anything that reaches ONLY this leg is, for+ * support purposes, unrecorded.+ *+ * The single JSON line per console call keeps multi-line stdio interleaving+ * deterministic; the `event: 'ipc.error'` discriminant lets downstream filters+ * separate IPC failures from arbitrary stdout noise.** The meta-test at* `packages/app/tests/integration/ipc-log-coverage.test.ts` gates that@@ -28,6 +32,8 @@* adopt the discipline.*/+import { getLogger } from './desktop-logger.ts';+/*** Canonical IPC failure-event payload. Internal type — `logIpcError`* below is the public surface. Consumers infer the parameter shape from@@ -45,7 +51,10 @@* - `cause` is optional structured context (Error object, additional* metadata). Normalized at the boundary so Error instances preserve* message + name + stack on the wire and circular references degrade- * safely instead of throwing — see `normalizeCause` below.+ * safely instead of throwing — see `normalizeCause` below. It reaches the+ * console leg WHOLE; the pino leg gets only the bounded facts derived from+ * it by `boundedCauseFacts` (the error's class and its errno), because the+ * message and stack cannot be written into a bundle handed to support.* - `details` is optional BOUNDED context, and the two differ by destination* rather than by taste. `cause` reaches the console only: it carries stacks* and free-form text, which is exactly what you want when tailing a terminal@@ -126,12 +135,72 @@ function normalizeCause(cause: unknown, seen: WeakSet<object> = new WeakSet()):}/**- * Emit an IPC failure to the structured-log surface.+ * Links of an `Error.cause` chain walked when looking for an errno. undici+ * hangs the real transport error one level below its opaque+ * `TypeError: fetch failed`; a handful of links is slack for a wrapper or two+ * above that without letting a long chain turn a log call into a traversal.+ */+const CAUSE_CHAIN_MAX_DEPTH = 5;++/**+ * The bounded half of a `cause` — the part that may reach the pino leg.+ *+ * A failed IPC call reached a diagnostic bundle as one line carrying a channel,+ * a handler, and a single reason token: enough to know that something failed,+ * never enough to know what. The cause was captured and normalized at the+ * boundary, then emitted only to stdio, which a packaged app records nowhere.+ * These two fields are the ones that can close that gap without breaking the+ * bounded-value contract the pino leg is held to:+ *+ * - `errName` — the error's CLASS. Bounded by the set of constructors in play.+ * - `errCode` — the errno, which is what separates "this machine cannot+ * resolve the host" from "the host refused the connection" from "the+ * certificate is not valid yet". Bounded by the platform's errno table.*- * Uses `console.warn(JSON.stringify(...))` for compatibility with Electron's- * stderr capture, Sentry's breadcrumb capture, and any file-tail-based- * structured-pipeline consumer (`bunyan -P`, `vector`, etc.). The single- * JSON line per call keeps multi-line stdio interleaving deterministic.+ * The errno needs the chain walk rather than a direct `code` read: undici+ * reports every transport failure as the same opaque `TypeError: fetch failed`+ * and hangs the real error one level down in `cause`, so reading `code` off the+ * caught value yields nothing on exactly the failures worth triaging.+ *+ * Deliberately omits `message` and `stack`. A stack carries absolute paths out+ * of the reporter's home directory, and an errno message carries the file that+ * could not be opened or the URL that could not be reached — both are exactly+ * what must not be written into a file a reporter hands to support. They stay+ * on the console leg, where the audience is a developer at a terminal.+ *+ * Cycle-safe and depth-bounded for the same reason `normalizeCause` is: the+ * caller passes a raw caught value of unknown shape, and a hostile one must not+ * be able to turn a log call into a hang or a stack overflow.+ */+function boundedCauseFacts(cause: unknown): Record<string, string> {+ const facts: Record<string, string> = {};+ if (cause instanceof Error) facts.errName = cause.name;++ const seen = new Set<unknown>();+ let cursor: unknown = cause;+ for (+ let depth = 0;+ depth < CAUSE_CHAIN_MAX_DEPTH && cursor !== null && cursor !== undefined;+ depth += 1+ ) {+ if (seen.has(cursor)) break;+ seen.add(cursor);+ const code = (cursor as { code?: unknown }).code;+ if (typeof code === 'string' && code !== '') {+ facts.errCode = code;+ break;+ }+ cursor = (cursor as { cause?: unknown }).cause;+ }+ return facts;+}++/**+ * Emit an IPC failure to both structured-log surfaces.+ *+ * The console leg uses `console.warn(JSON.stringify(...))` for compatibility+ * with Electron's stderr capture and any file-tail-based structured-pipeline+ * consumer (`bunyan -P`, `vector`, etc.).** `cause` is normalized at this boundary (Error instances → plain objects;* circular references → degraded-but-safe). Callers can pass any@@ -146,13 +215,26 @@ export function logIpcError(payload: IpcErrorLogPayload): void {const normalized: IpcErrorLogPayload =payload.cause !== undefined ? { ...payload, cause: normalizeCause(payload.cause) } : payload;+ // Derived BEFORE the emit below rather than inside its try/catch. A cause+ // hostile to inspection (a throwing getter, a cyclic chain) must cost its own+ // two fields and nothing else — swallowing the whole line would leave the+ // failure with no record at all, which is worse than the bare line this+ // derivation exists to improve on.+ let causeFacts: Record<string, string> = {};+ if (payload.cause !== undefined) {+ try {+ causeFacts = boundedCauseFacts(payload.cause);+ } catch {}+ }+try {- const { getLogger } = require('./desktop-logger.ts');getLogger('ipc').warn(- // `details` is spread FIRST so the canonical discriminants always win a- // key collision — a caller that passes `channel` in its details cannot- // rewrite the field consumers index on.+ // Derived facts first, then `details`, then the canonical discriminants:+ // a handler that classified its own failure knows more than a generic+ // walk of the caught value, and a caller that passes `channel` in its+ // details cannot rewrite the field consumers index on.{+ ...causeFacts,...payload.details,channel: payload.channel,handler: payload.handler,diff --git a/packages/desktop/src/main/ipc/bug-report.test.ts b/packages/desktop/src/main/ipc/bug-report.test.tsindex 5a7fef205..1b3622608 100644--- a/packages/desktop/src/main/ipc/bug-report.test.ts+++ b/packages/desktop/src/main/ipc/bug-report.test.ts@@ -238,6 +238,35 @@ describe('handleBugReportCreate — project bundle', () => {expect(readZipEntry(result.zipPath, 'note.txt')).toContain('it crashed while saving');});+ test('carries the send ledger from the directory the report is written into', async () => {+ // A sidecar lives beside its zip, so the ledger that belongs with a report+ // is the one in the report's own directory — the real reports dir in+ // production, a fixture dir here. Without that the collector would fall+ // back to the home directory and a test would bundle the developer's own+ // prior reports while proving nothing about the wiring.+ //+ // This is the evidence a send failure leaves behind. Its absence is why the+ // two observed failures were only diagnosable on a machine we could read.+ const reportsDir = makeTmpDir('ok-bugreport-reports-');+ writeFileSync(+ join(reportsDir, '2026-08-19T16-42-03-547Z-bugreport.yaml'),+ ['id: 2026-08-19T16-42-03-547Z-bugreport.zip', 'state: upload-failed'].join('\n'),+ );+ const deps = makeDeps({+ projectDir: makeProjectDir(),+ outputPath: join(reportsDir, 'report.zip'),+ });++ const result = await handleBugReportCreate(deps, { kind: 'create', level: 'standard' });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ const entries = listZipEntries(result.zipPath);+ expect(entries).toContain('state/bug-reports/2026-08-19T16-42-03-547Z-bugreport.yaml');+ // The zip being written is in that same directory; a bundle must not+ // contain itself or any other bundle.+ expect(entries.filter((e) => e.endsWith('.zip'))).toEqual([]);+ });+test('rejects a create request whose note exceeds the length ceiling', async () => {const deps = makeDeps({ projectDir: makeProjectDir() });@@ -2433,6 +2462,43 @@ describe('bug-report sidecar wiring — create writes the record, send tracks stexpect(row?.retryable).toBe(true);});+ test('a transport failure persists its leg and its errno in the durable ledger', async () => {+ // The ledger outlives the log. `desktop.*.log` rotates on a seven-day+ // budget, and a reporter filing about a send that failed last week still+ // has the sidecar beside the zip they are retrying. Whatever the ledger+ // does not record is unrecoverable by then.+ //+ // Driven through real `fetch` against an unresolvable host so the errno is+ // produced the way undici produces it — hung one level down in `cause`+ // under an opaque `TypeError: fetch failed` — rather than by a fake that+ // would let a top-level `err.code` read pass.+ const { dir, store, createDeps, zipPath } = makeSidecarRig();+ await handleBugReportCreate(createDeps, { kind: 'create', level: 'standard' });++ const result = await handleBugReportSend(+ {+ ...makeSendDeps('https://intake.invalid-tld-for-test.invalid', dir),+ sidecar: store.sendHooks,+ },+ { kind: 'send', zipPath, metadata: SEND_METADATA },+ );++ expect(result.ok).toBe(false);+ const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));+ expect(sidecar?.lastError).toMatchObject({+ reason: 'mint-network-error',+ errorCode: 'ENOTFOUND',+ });+ expect(sidecar?.attempts?.at(-1)).toMatchObject({+ outcome: 'failed',+ error: 'mint-network-error',+ errorCode: 'ENOTFOUND',+ });+ // The message and the stack stay out: this file is readable by the reporter+ // and ships inside the bundle they hand to support.+ expect(JSON.stringify(sidecar)).not.toContain('fetch failed');+ });+test('a send refused by the in-flight lock never reaches the intake', async () => {const { dir, store, createDeps, zipPath } = makeSidecarRig();await handleBugReportCreate(createDeps, { kind: 'create', level: 'standard' });@@ -2587,6 +2653,26 @@ describe('handleBugReportSend — structured failure diagnostics', () => {const details = dispatchFailure(lines).details as Record<string, unknown>;expect(details).toMatchObject({ step: 'mint', status: 503 });});++ test('a transport throw names its leg in the reason, not just in the details', async () => {+ // Every other failure return already carries its leg — `mint-rejected`,+ // `upload-rejected`, `upload-redirected`, `complete-rejected`,+ // `mint-malformed`, `complete-malformed`, `upload-url-rejected`. The+ // throw branch was the one exception, so the three-leg flow across two+ // different hosts collapsed to one word and could not say whether the+ // intake or the storage bucket was unreachable.+ //+ // The reason, unlike `details`, is what the durable per-report ledger+ // stores and what the history row shows, so the leg has to live in the+ // string as well as beside it.+ const { deps, zipPath } = makeSendRig('https://intake.invalid-tld-for-test.invalid');++ const lines = await captureIpcErrors(() =>+ handleBugReportSend(deps, { kind: 'send', zipPath, metadata: SEND_METADATA }),+ );++ expect(dispatchFailure(lines).reason).toBe('mint-network-error');+ });});describe('handleBugReportSend — transport phase spans', () => {diff --git a/packages/desktop/src/main/ipc/bug-report.ts b/packages/desktop/src/main/ipc/bug-report.tsindex 804f73f53..d149d1651 100644--- a/packages/desktop/src/main/ipc/bug-report.ts+++ b/packages/desktop/src/main/ipc/bug-report.ts@@ -19,7 +19,7 @@import { randomUUID } from 'node:crypto';import { readFile, realpath, stat, unlink, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';-import { basename, join } from 'node:path';+import { basename, dirname, join } from 'node:path';import {type BundleLogger,collectReportBundle,@@ -422,13 +422,19 @@ export async function handleBugReportCreate(await writeFile(screenshotTmpPath, screenshotBytes, { mode: 0o600 });extraFiles.push({ sourcePath: screenshotTmpPath, zipName: BUG_REPORT_SCREENSHOT_ZIP_NAME });}+ const outputPath = deps.outputPath ?? defaultBugReportZipPath();const { zipPath, summary } = await collectReportBundle({level: request.level,projectDir: deps.projectDir ?? undefined,note: request.note,// The in-app surface always redacts; only the CLI exposes an opt-out.redact: true,- outputPath: deps.outputPath ?? defaultBugReportZipPath(),+ outputPath,+ // A sidecar lives next to its zip, so the ledger to collect is the one in+ // the directory this report is being written into. That is the real+ // reports dir in production and the fixture dir under test, without a+ // second seam that could disagree with where the report actually lands.+ bugReportsDir: dirname(outputPath),userLogsDir: deps.userLogsDir,extraFiles: extraFiles.length === 0 ? undefined : extraFiles,logger: deps.logger,@@ -729,7 +735,7 @@ export interface GeneratedReportMeta {*/export type SidecarSendOutcome =| { kind: 'sent'; reference: string }- | { kind: 'upload-failed'; reason: string }+ | { kind: 'upload-failed'; reason: string; errorCode?: string }| { kind: 'email-drafted' };/**@@ -1222,11 +1228,18 @@ async function uploadBugReport(// `AbortSignal.timeout()` abort carries; the flip side is that no// user-cancel AbortController may be wired to these fetches without// first splitting cancel out of this classification.+ //+ // Both branches name their leg, because the send is three requests across+ // two different hosts and "the intake is unreachable" and "the storage+ // bucket is unreachable" are different investigations with different+ // owners. The leg also rides `details`, but only the reason survives into+ // the durable per-report ledger and the history row, and the ledger is+ // what a reporter still has after the logs have rotated.const timedOut =err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError');return {ok: false,- reason: timedOut ? `${step}-timeout` : 'network-error',+ reason: `${step}-${timedOut ? 'timeout' : 'network-error'}`,cause: err,details: describeTransportFailure(step, stepTarget, { err }),};@@ -1479,7 +1492,16 @@ export async function handleBugReportSend(...(outcome.details === undefined ? {} : { details: outcome.details }),});await runSidecarHook(- deps.sidecar?.onSendResult(reportId, { kind: 'upload-failed', reason: outcome.reason }),+ deps.sidecar?.onSendResult(reportId, {+ kind: 'upload-failed',+ reason: outcome.reason,+ // The errno, and only the errno: the ledger outlives the log, so it is+ // worth carrying, and it is bounded enough to sit in a file the reporter+ // can read and forwards to support. The message and stack are not.+ ...(typeof outcome.details?.errCode === 'string'+ ? { errorCode: outcome.details.errCode }+ : {}),+ }),);sendTrace.end('upload-failed');return { ok: false, reason: 'send-failed', fallback };