Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(ok): in-app report-a-bug experience (PRD-6805, Track 1) (#2571)

Andrew Mikofalvy40f06fc9af92
diff --git a/.changeset/report-bug-in-app.md b/.changeset/report-bug-in-app.md
new file mode 100644
index 000000000..14e51b95a
--- /dev/null
+++ b/.changeset/report-bug-in-app.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Report a bug from inside the app. OpenKnowledge Desktop gains a full in-app bug-report flow: open it from Help → Report a Bug… or the ⌘K command palette, add an optional note, and the app packages logs and system info into a single secret-redacted zip you can reveal in Finder and review before anything leaves your machine. By default, Send makes no network request — it opens a prefilled email draft to [email protected] that names the saved report file for you to attach. When a bug-report intake endpoint is configured (`OK_BUG_REPORT_INTAKE_URL`), Send instead uploads the report privately to the OpenKnowledge team, falling back to the same email draft if the upload fails — nothing is ever sent without your explicit action. A successful upload returns a report reference you can quote when opening a public GitHub issue.
+
+The desktop app also detects crashes locally, first-party only (Electron's crash reporter runs with uploads disabled): if a window process dies or the app quit unexpectedly last session, it invites — never auto-sends — the same report flow, with crash context prefilled and an opt-in, default-off checkbox for attaching the crash dump. Error screens (per-document and a new app-wide boundary) gain a "Report this error" action wired to the same dialog.
+
+For programmatic use, the CLI package now exports `collectReportBundle({ level, projectDir, note, redact, outputPath, extraFiles })`, the leveled bundling API behind both the desktop flow and `ok bug-report`: level `standard` collects the bug-report set (logs, lock/spawn diagnostics, system info), `full` adds the diagnose superset (telemetry spans, live server state, runtime metadata) and degrades gracefully by omitting pieces that aren't available, and `extraFiles` attaches pre-collected artifacts verbatim (the crash-dump opt-in rides on it). `ok bug-report` output is unchanged — it now routes through the same API.
diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdx
index de96c8b78..931259395 100644
--- a/docs/content/reference/cli.mdx
+++ b/docs/content/reference/cli.mdx
@@ -118,6 +118,7 @@ Each project runs its own local server. These commands let you see and stop them
| `ok config validate` | Validate the merged config (defaults → user → project) |
| `ok config migrate` | Remove deprecated keys from `config.yml` (`--dry-run` to preview; `--scope` project, user, or both) |
| `ok skills manage` | Control whether OpenKnowledge adopts your editor skills into this project (`--on`, `--off`, `--status`; default off) |
+| `ok bug-report` | Package a support bundle — recent app logs, the project's server logs and lock diagnostics, and system info — as an auto-redacted zip under `~/.ok/bug-reports/`, revealed in Finder when it's done (`--no-reveal` to skip). Collects the same `standard` set as the desktop app's **Help → Report a Bug…**; `ok diagnose bundle` produces the `full` superset (telemetry spans, live server state) into the project's `.ok/local/diagnostics/` |
## Global flags
diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdx
index 0596afece..b2d367f8c 100644
--- a/docs/content/reference/configuration.mdx
+++ b/docs/content/reference/configuration.mdx
@@ -86,6 +86,7 @@ Most users never set these — the schema settings above cover the common cases.
| `OK_SHOWALL_MAX_ENTRIES` | Max entries the sidebar's disk-walk listing returns per level before it stops and marks the list truncated (default `50000`) |
| `OK_BRIDGE_TOLERANCE_TELEMETRY` | Set to `1` to record each bridge-tolerance-class fire as a JSONL line in `<project>/.ok/local/tolerance-telemetry.jsonl` (opt-in, local-only, off by default; unstable diagnostic for triaging markdown-fidelity incidents). **Records doc paths in cleartext** — independent of `telemetry.localSink`'s `attributeDenylist`, which redacts span/log attributes, not this file. Deliberately outside the `.ok/local/telemetry/` subtree `ok diagnose bundle` harvests, so the unredacted paths never ship in a bug bundle. |
| `OTEL_SDK_DISABLED` | OpenTelemetry OTLP push gate. Inverted sense: set to `false` to **enable** push (it is off by default). |
+| `OK_BUG_REPORT_INTAKE_URL` | Base URL of the bug-report intake the desktop app's **Help → Report a Bug…** upload posts to (e.g. `https://openknowledge.ai`). Must be `https:` — plain `http:` is accepted only for loopback hosts (local testing). Unset (the default), Send makes no network request — it opens a prefilled email draft to [email protected] that you send yourself. |
| `OK_EMBEDDINGS_API_KEY` | Fallback embeddings provider API key for [semantic search](#semantic-search), used when none is stored on disk. Prefer `ok embeddings set-key` (writes `~/.ok/secrets.yml`) for normal use; the env var is convenient for CI / scripted runs. |
## Semantic search
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index aa13141e8..1438951c7 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -10,7 +10,7 @@ OpenKnowledge keeps your knowledge base as plain markdown in your own project di
This page lists every one of them: **when** each write happens, **what** it is, and **where** it is written.
<Callout type="info" title="The short version">
- **Nothing leaves your machine by default — except the desktop app's automatic checks.** Diagnostic logs and telemetry stay on your machine. The things that *can* send data off it — semantic search, a diagnostic bundle, and GitHub sync — are opt-in or on-demand. The desktop app is the exception: it checks for updates automatically (sending its app version and channel), and on its first launch opens your browser once to check for a pending share link. All of them are listed under [What leaves your machine](#what-leaves-your-machine).
+ **Nothing leaves your machine by default — except the desktop app's automatic checks.** Diagnostic logs and telemetry stay on your machine. The things that *can* send data off it — semantic search, a diagnostic or bug-report bundle, and GitHub sync — are opt-in or on-demand. The desktop app is the exception: it checks for updates automatically (sending its app version and channel), and on its first launch opens your browser once to check for a pending share link. All of them are listed under [What leaves your machine](#what-leaves-your-machine).
</Callout>
## How to read this page
@@ -37,6 +37,9 @@ The macOS app ships as a signed `.dmg` you drag into `/Applications`. On launch
| `~/.ok/logs/desktop.<date>.log` | Desktop app + renderer log | Outside-project (home dir) |
| `~/.ok/mcp-status.json` | Records your first-launch MCP-setup consent choice | Outside-project (home dir) |
| `~/Library/Caches/OpenKnowledge-updater/` | Staged auto-update downloads (electron-updater) | Outside-project (home dir) |
+| `~/Library/Application Support/OpenKnowledge/Crashpad/` | Native crash minidumps, written by the OS crash handler (Electron's Crashpad) if the app ever crashes. Local-only: the crash reporter runs with `uploadToServer: false`, so no dump is ever uploaded automatically | Outside-project (home dir) |
+| `~/Library/Application Support/OpenKnowledge/bug-report-dirty-shutdown.json` | Dirty-shutdown sentinel — written on **every** launch and removed on a clean quit, so the next launch can tell whether the previous session crashed | Outside-project (home dir) |
+| `~/Library/Application Support/OpenKnowledge/bug-report-crash-acks.json` | Records which crash-report invitations you already answered or dismissed, so the same crash never re-prompts | Outside-project (home dir) |
The app registers the `openknowledge://` URL scheme (for deep links) and checks for updates — on launch and periodically while it runs — against the OpenKnowledge update service at `openknowledge.ai/updates`, which redirects to the GitHub release asset and counts the update per version and channel (falling back to GitHub directly if it's unreachable). An update on your channel downloads in the background and installs on the next quit; you can also check on demand from **Check for updates…** in the app and Help menus. The channel (stable or beta) is fixed by the build you installed — switch by reinstalling the other from `openknowledge.ai/download/stable` or `/download/beta`. Override the feed with `OK_UPDATER_FEED_URL`.
@@ -121,7 +124,7 @@ On each launch and project open, the app also runs **repair sweeps**: it rewrite
| `~/.ok/skills/<name>/` | Your global-scope authored skills (kept by `ok uninstall` unless `--purge-content`) | No |
| `~/.ok/stats.jsonl` | Local "open with AI" handoff stats — local-only, no phone-home | No |
| `~/.ok/mcp-status.json` | First-launch MCP consent record | No |
-| `~/.ok/logs/`, `~/.ok/bug-reports/` | Desktop and CLI logs, and bug-report bundles from `ok bug-report` (`ok diagnose bundle` writes into the project, under `.ok/local/diagnostics/`) | No |
+| `~/.ok/logs/`, `~/.ok/bug-reports/` | Desktop and CLI logs, and bug-report bundles from `ok bug-report` and the app's **Help → Report a Bug…** dialog (`ok diagnose bundle` writes into the project, under `.ok/local/diagnostics/`) | No |
| `~/.ok/bin/`, `~/.ok/env.sh` | `PATH` shim (see [Shell and `PATH`](#shell-and-path) above) | No |
**Auth tokens** (for GitHub sync, sharing, and cloning) are stored in the macOS **Keychain** under the service name `open-knowledge`. The `~/.ok/auth.yml` file is only a fallback for headless environments where the Keychain isn't reachable; when the Keychain becomes available, the token is migrated into it and the file copy is removed.
@@ -235,7 +238,7 @@ Disable all three with `OK_RECLAIM_DISABLE=1`.
| `~/.ok/skills/<name>/` | Your global-scope authored skills (kept by `ok uninstall` unless `--purge-content`) | No |
| `~/.ok/stats.jsonl` | Local "open with AI" handoff stats — local-only, no phone-home | No |
| `~/.ok/logs/` | CLI logs (`cli.<date>.log`), size- and age-capped | No |
-| `~/.ok/bug-reports/` | Bug-report bundles from `ok bug-report` (`ok diagnose bundle` writes into the project, under `.ok/local/diagnostics/`) | No |
+| `~/.ok/bug-reports/` | Bug-report bundles from `ok bug-report` — the desktop app's **Help → Report a Bug…** dialog writes here too (`ok diagnose bundle` writes into the project, under `.ok/local/diagnostics/`) | No |
**Auth tokens** (for GitHub sync, sharing, and cloning) are stored in your operating system's secure credential store when one is available — the macOS **Keychain** (service `open-knowledge`), or the platform equivalent (Windows Credential Manager, Linux Secret Service) — falling back to a `0600` `~/.ok/auth.yml` file on headless systems (a Linux server, CI) where none is reachable.
@@ -267,6 +270,7 @@ By default, **nothing.** Everything above is written to your own disk. The only
| 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 | 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`](/docs/reference/configuration#environment-variables)) does Send upload the zip there, falling back to the same email draft if the upload fails |
| Semantic search embeddings | Only when you enable [semantic search](/docs/reference/configuration#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 |
| Update check | Automatically — on launch and periodically while the desktop app runs | OpenKnowledge update service (`openknowledge.ai/updates`), which redirects to GitHub; sends the app version and channel |
diff --git a/packages/app/package.json b/packages/app/package.json
index 7afaf69d8..704ba7d29 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -44,14 +44,14 @@
{
"name": "main app bundle (gzipped)",
"path": "dist/assets/index-*.js",
- "limit": "466 kB",
+ "limit": "470 kB",
"gzip": true,
"running": false
},
{
"name": "all JS chunks combined (gzipped)",
"path": "dist/assets/*.js",
- "limit": "3.09 MB",
+ "limit": "3.10 MB",
"gzip": true,
"running": false
},
diff --git a/packages/app/src/App.dom.test.tsx b/packages/app/src/App.dom.test.tsx
index 651c8c5bd..cc489d39d 100644
--- a/packages/app/src/App.dom.test.tsx
+++ b/packages/app/src/App.dom.test.tsx
@@ -156,6 +156,10 @@ mock.module('@/components/CreateProjectMenuTrigger', () => ({
CreateProjectMenuTrigger: () => <div data-testid="create-project-menu-trigger" />,
}));
+mock.module('@/components/ReportBugMenuTrigger', () => ({
+ ReportBugMenuTrigger: () => <div data-testid="report-bug-menu-trigger" />,
+}));
+
mock.module('@/components/ShareBranchSwitchDialog', () => ({
ShareBranchSwitchDialog: () => <div data-testid="share-branch-switch-dialog" />,
}));
diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx
index 965d6bd2a..e17e7bd23 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -22,6 +22,7 @@ import {
withLargeFileOpenGuard,
} from '@/components/navigation-targets';
import { PageListProvider, usePageList } from '@/components/PageListContext';
+import { ReportBugMenuTrigger } from '@/components/ReportBugMenuTrigger';
import { SystemDocSubscriber } from '@/components/SystemDocSubscriber';
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar';
import {
@@ -502,6 +503,9 @@ function AppBody() {
Desktop-only — the `new-project` menu action never fires in
the web host, so the dialog stays unmounted there. */}
{desktopBridge ? <CreateProjectMenuTrigger bridge={desktopBridge} /> : null}
+ {/* Help → Report a Bug… opens ReportBugDialog here — same
+ desktop-only App-root trigger pattern as CreateProjectMenuTrigger. */}
+ {desktopBridge ? <ReportBugMenuTrigger bridge={desktopBridge} /> : null}
{/* First-launch consent dialog — host-agnostic. Self-gates on
the shared `mcpConsentStore` snapshot; renders nothing until
main fires `ok:mcp-wiring:show`. Mounted identically in
diff --git a/packages/app/src/components/AppErrorBoundary.dom.test.tsx b/packages/app/src/components/AppErrorBoundary.dom.test.tsx
new file mode 100644
index 000000000..b8a124605
--- /dev/null
+++ b/packages/app/src/components/AppErrorBoundary.dom.test.tsx
@@ -0,0 +1,270 @@
+/**
+ * RTL mount tests for the top-level app-shell boundary: fallback render on a
+ * shell crash, reset recovery, the bridge-gated report action, and the
+ * nesting contract (document errors stay with DocumentErrorBoundary).
+ * Invocation via `bun run test:dom`.
+ */
+import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+import type { OkBugReportCreateResult } from '@inkeep/open-knowledge-core';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { AppErrorBoundary, CrashReportingBoundary } from './AppErrorBoundary';
+import { DocumentErrorBoundary } from './DocumentErrorBoundary';
+
+// Radix Dialog (focus trap) reaches for DOM globals the jsdom preload does not
+// expose on globalThis. Same hoist as CloneDialog.dom.test.tsx.
+type WindowGlobals = { NodeFilter?: typeof NodeFilter };
+type GlobalWithDomShims = typeof globalThis &
+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };
+const globalWithDomShims = globalThis as GlobalWithDomShims;
+if (
+ globalWithDomShims.NodeFilter === undefined &&
+ globalWithDomShims.window?.NodeFilter !== undefined
+) {
+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;
+}
+if (globalWithDomShims.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ globalWithDomShims.ResizeObserver = NoopResizeObserver;
+}
+
+let shouldThrow = false;
+
+function MaybeThrow({ label }: { label: string }) {
+ if (shouldThrow) {
+ throw new Error(`MaybeThrow boom: ${label}`);
+ }
+ return <span data-testid="payload">{label}</span>;
+}
+
+type CreateRequest = { level: 'standard' | 'full'; note?: string };
+
+function installBugReportBridge(mode: 'editor' | 'navigator' = 'editor'): CreateRequest[] {
+ const createCalls: CreateRequest[] = [];
+ const bridge = {
+ config: { mode },
+ bugReport: {
+ create: (request: CreateRequest) => {
+ createCalls.push(request);
+ const result: OkBugReportCreateResult = {
+ ok: true,
+ zipPath: '/tmp/report.zip',
+ zipSizeBytes: 1024,
+ summary: {
+ level: request.level,
+ systemWide: mode === 'navigator',
+ projectSlug: undefined,
+ files: [],
+ redactions: [],
+ redactedLineCount: 0,
+ generatedAt: '2026-07-10T00:00:00.000Z',
+ },
+ };
+ return Promise.resolve(result);
+ },
+ send: () => Promise.resolve({ ok: true as const, reference: 'OK-TEST01' }),
+ },
+ shell: {
+ showItemInFolder: () => Promise.resolve(),
+ openExternal: () => Promise.resolve(),
+ },
+ };
+ for (const host of [window, globalThis] as unknown as Array<Record<string, unknown>>) {
+ Object.defineProperty(host, 'okDesktop', { configurable: true, writable: true, value: bridge });
+ }
+ return createCalls;
+}
+
+function clearBugReportBridge() {
+ for (const host of [window, globalThis] as unknown as Array<Record<string, unknown>>) {
+ Object.defineProperty(host, 'okDesktop', {
+ configurable: true,
+ writable: true,
+ value: undefined,
+ });
+ }
+}
+
+describe('AppErrorBoundary', () => {
+ let consoleErrorSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof spyOn>;
+
+ beforeEach(() => {
+ shouldThrow = false;
+ consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ cleanup();
+ clearBugReportBridge();
+ consoleErrorSpy.mockRestore();
+ consoleWarnSpy.mockRestore();
+ });
+
+ test('renders children when no throw', () => {
+ render(
+ <AppErrorBoundary>
+ <MaybeThrow label="shell" />
+ </AppErrorBoundary>,
+ );
+ expect(screen.getByTestId('payload').textContent).toBe('shell');
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+
+ test('a shell crash renders the fallback with the error message and focuses Try again', () => {
+ shouldThrow = true;
+ installBugReportBridge();
+ render(
+ <AppErrorBoundary>
+ <MaybeThrow label="shell" />
+ </AppErrorBoundary>,
+ );
+
+ const alert = screen.getByRole('alert');
+ expect(alert.getAttribute('data-slot')).toBe('app-error-boundary');
+ expect(screen.getByRole('heading', { name: 'Something went wrong' })).not.toBeNull();
+ expect(screen.getByText('MaybeThrow boom: shell')).not.toBeNull();
+
+ const tryAgain = screen.getByRole('button', { name: 'Try again' });
+ expect(document.activeElement).toBe(tryAgain);
+ expect(screen.getByRole('button', { name: /report this error/i })).not.toBeNull();
+
+ const sawBoundaryError = consoleErrorSpy.mock.calls.some((call: unknown[]) => {
+ const message = call[0];
+ return typeof message === 'string' && message.includes('[AppErrorBoundary]');
+ });
+ expect(sawBoundaryError).toBe(true);
+ });
+
+ test('Try again resets the boundary and re-renders the shell', async () => {
+ shouldThrow = true;
+ installBugReportBridge();
+ render(
+ <AppErrorBoundary>
+ <MaybeThrow label="shell" />
+ </AppErrorBoundary>,
+ );
+ expect(screen.getByRole('alert')).not.toBeNull();
+
+ shouldThrow = false;
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Try again' }));
+
+ expect(screen.getByTestId('payload').textContent).toBe('shell');
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+
+ test('Report this error opens the report dialog with full detail and the shell crash in the note', async () => {
+ shouldThrow = true;
+ const createCalls = installBugReportBridge('navigator');
+ render(
+ <AppErrorBoundary>
+ <MaybeThrow label="shell" />
+ </AppErrorBoundary>,
+ );
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: /report this error/i }));
+
+ // ReportBugDialog is lazy-loaded — await the body chunk mounting.
+ expect(await screen.findByRole('dialog')).not.toBeNull();
+ const checkbox = screen.getByRole('checkbox', { name: 'Include detailed diagnostics' });
+ expect(checkbox.getAttribute('aria-checked')).toBe('true');
+ // Navigator window → the compose summary is labeled system-wide.
+ expect(
+ screen.getByText(
+ 'App & system info, recent app logs — no project is open, so no project logs are included.',
+ ),
+ ).not.toBeNull();
+
+ await user.click(screen.getByRole('button', { name: 'Create report' }));
+ await screen.findByRole('heading', { name: 'Review your report' });
+
+ expect(createCalls).toEqual([
+ {
+ level: 'full',
+ note: 'Crash source: app shell\nError: MaybeThrow boom: shell',
+ },
+ ]);
+ });
+
+ test('does not intercept errors the per-document boundary already handles', () => {
+ shouldThrow = true;
+ installBugReportBridge();
+ render(
+ <AppErrorBoundary>
+ <DocumentErrorBoundary activeDocName="alpha.md" onRecycle={mock(() => {})}>
+ <MaybeThrow label="alpha" />
+ </DocumentErrorBoundary>
+ </AppErrorBoundary>,
+ );
+
+ const alert = screen.getByRole('alert');
+ expect(alert.getAttribute('data-slot')).toBe('document-error-boundary');
+ expect(screen.queryByRole('heading', { name: 'Something went wrong' })).toBeNull();
+ });
+
+ test('the report action is absent without the desktop bridge', () => {
+ shouldThrow = true;
+ clearBugReportBridge();
+ render(
+ <AppErrorBoundary>
+ <MaybeThrow label="shell" />
+ </AppErrorBoundary>,
+ );
+
+ expect(screen.getByRole('button', { name: 'Try again' })).not.toBeNull();
+ expect(screen.queryByRole('button', { name: /report this error/i })).toBeNull();
+ });
+});
+
+describe('CrashReportingBoundary', () => {
+ let consoleErrorSpy: ReturnType<typeof spyOn>;
+
+ beforeEach(() => {
+ shouldThrow = false;
+ consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ cleanup();
+ consoleErrorSpy.mockRestore();
+ });
+
+ test('passes a healthy crash-reporting subtree through untouched', () => {
+ render(
+ <CrashReportingBoundary>
+ <MaybeThrow label="invite" />
+ </CrashReportingBoundary>,
+ );
+ expect(screen.getByTestId('payload').textContent).toBe('invite');
+ });
+
+ test('a throwing crash-invite subtree renders nothing and leaves the app alive', () => {
+ // The trigger mounts as a sibling of the shell boundary, so nothing else
+ // can catch its throws — without this boundary the whole root unmounts.
+ shouldThrow = true;
+ render(
+ <div>
+ <CrashReportingBoundary>
+ <MaybeThrow label="invite" />
+ </CrashReportingBoundary>
+ <span data-testid="app-shell">still rendering</span>
+ </div>,
+ );
+
+ expect(screen.queryByTestId('payload')).toBeNull();
+ expect(screen.getByTestId('app-shell').textContent).toBe('still rendering');
+
+ const sawBoundaryError = consoleErrorSpy.mock.calls.some((call: unknown[]) => {
+ const message = call[0];
+ return typeof message === 'string' && message.includes('[CrashReportingBoundary]');
+ });
+ expect(sawBoundaryError).toBe(true);
+ });
+});
diff --git a/packages/app/src/components/AppErrorBoundary.tsx b/packages/app/src/components/AppErrorBoundary.tsx
new file mode 100644
index 000000000..96f0db365
--- /dev/null
+++ b/packages/app/src/components/AppErrorBoundary.tsx
@@ -0,0 +1,119 @@
+/**
+ * AppErrorBoundary — last-resort boundary for the whole window shell.
+ *
+ * SCOPING: wraps the root app (editor / Navigator / terminal window) from
+ * `main.tsx`, OUTSIDE the hybrid render tree. Document-view errors are caught
+ * first by the per-Activity `DocumentErrorBoundary` instances (and the
+ * settings chunk by `SettingsDialogErrorBoundary`); this boundary only sees
+ * render crashes that escape every inner boundary — app-shell chrome, sidebar,
+ * dialogs mounted outside the editor subtree. Without it, such a crash
+ * unmounts the React root and white-screens the window with no recovery.
+ *
+ * Mounted inside the i18n/theme providers so the fallback keeps translated
+ * copy and theme tokens; a crash in the provider layer itself is out of scope.
+ */
+
+import { Trans, useLingui } from '@lingui/react/macro';
+import { useEffect, useRef, useState } from 'react';
+import { ErrorBoundary, type FallbackProps } from 'react-error-boundary';
+import { OkBlob } from '@/components/OkBlob';
+import { ReportBugDialog } from '@/components/ReportBugDialog';
+import { Button } from '@/components/ui/button';
+
+function AppErrorFallback({ error, resetErrorBoundary }: FallbackProps) {
+ const { t } = useLingui();
+ const [reportOpen, setReportOpen] = useState(false);
+ const retryRef = useRef<HTMLButtonElement>(null);
+ const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
+ const message =
+ error instanceof Error && error.message ? error.message : t`An unexpected error occurred.`;
+
+ // Same focus-order treatment as DocumentErrorFallback: land keyboard and
+ // screen-reader users on the recovery affordance, with role="alert"
+ // announcing the error context first.
+ useEffect(() => {
+ retryRef.current?.focus();
+ }, []);
+
+ return (
+ <div
+ role="alert"
+ aria-labelledby="app-error-title"
+ data-slot="app-error-boundary"
+ className="flex h-screen flex-col items-center justify-center gap-8 p-8 text-center"
+ >
+ <OkBlob size={80} variant="sleeping" />
+ <div className="flex flex-col items-center gap-1">
+ <h1 id="app-error-title" className="text-2xl font-light tracking-tighter text-balance">
+ <Trans>Something went wrong</Trans>
+ </h1>
+ <p className="max-w-sm text-sm break-words text-muted-foreground">{message}</p>
+ </div>
+ <div className="mt-1 flex gap-2">
+ <Button ref={retryRef} variant="default" onClick={() => resetErrorBoundary()}>
+ <Trans>Try again</Trans>
+ </Button>
+ {bridge ? (
+ <Button
+ variant="ghost"
+ className="font-mono uppercase"
+ onClick={() => setReportOpen(true)}
+ >
+ <Trans>Report this error</Trans>
+ </Button>
+ ) : null}
+ </div>
+ {bridge ? (
+ <CrashReportingBoundary>
+ <ReportBugDialog
+ open={reportOpen}
+ onOpenChange={setReportOpen}
+ // The Navigator window has no project; main labels the bundle
+ // truthfully either way — this only keeps the compose summary honest.
+ systemWide={bridge.config.mode === 'navigator'}
+ crashContext={{
+ source: 'app shell',
+ errorMessage: error instanceof Error && error.message ? error.message : String(error),
+ }}
+ />
+ </CrashReportingBoundary>
+ ) : null}
+ </div>
+ );
+}
+
+export function AppErrorBoundary({ children }: { children: React.ReactNode }) {
+ return (
+ <ErrorBoundary
+ FallbackComponent={AppErrorFallback}
+ onError={(error) => {
+ // Full error object so the stack reaches the console — and, via the
+ // renderer console capture, the next diagnostic bundle.
+ console.error('[AppErrorBoundary] app-shell render crash', error);
+ }}
+ >
+ {children}
+ </ErrorBoundary>
+ );
+}
+
+/**
+ * Null-fallback boundary for the crash-reporting surfaces themselves — the
+ * crash-invite trigger mounted as a sibling of the shell boundary, and the
+ * report dialog hosted inside a tripped boundary's fallback. Both render
+ * where no other boundary can catch them, so an uncaught throw would unmount
+ * the whole React root at exactly the moment the user is recovering from a
+ * crash. Losing the reporting affordance is the lesser harm: render nothing.
+ */
+export function CrashReportingBoundary({ children }: { children: React.ReactNode }) {
+ return (
+ <ErrorBoundary
+ fallback={null}
+ onError={(error) => {
+ console.error('[CrashReportingBoundary] crash-reporting UI render crash', error);
+ }}
+ >
+ {children}
+ </ErrorBoundary>
+ );
+}
diff --git a/packages/app/src/components/CommandPalette.dom.test.tsx b/packages/app/src/components/CommandPalette.dom.test.tsx
index 506370e84..8e0bd5bf2 100644
--- a/packages/app/src/components/CommandPalette.dom.test.tsx
+++ b/packages/app/src/components/CommandPalette.dom.test.tsx
@@ -28,6 +28,7 @@ let requestDocPanelTabCalls: string[] = [];
let seedDialogProps: Array<{ open: boolean }> = [];
let newItemDialogProps: Array<{ open: boolean; kind: string; initialDir: string }> = [];
let createProjectDialogProps: Array<{ open: boolean; bridge: unknown }> = [];
+let reportBugDialogProps: Array<{ open: boolean }> = [];
let commandDialogProps: CommandDialogProps[] = [];
let refreshInstallStatesCalls = 0;
const refreshInstallStates = () => {
@@ -140,6 +141,13 @@ mock.module('@/components/CreateProjectDialog', () => ({
},
}));
+mock.module('@/components/ReportBugDialog', () => ({
+ ReportBugDialog: (props: { open: boolean }) => {
+ reportBugDialogProps.push(props);
+ return <div data-open={String(props.open)} data-testid="report-bug-dialog" />;
+ },
+}));
+
mock.module('@/components/PageListContext', () => ({
usePageList: () => ({
pages: new Set<string>(),
@@ -266,6 +274,7 @@ describe('CommandPalette DOM behavior', () => {
seedDialogProps = [];
newItemDialogProps = [];
createProjectDialogProps = [];
+ reportBugDialogProps = [];
commandDialogProps = [];
refreshInstallStatesCalls = 0;
worktreeModelMock = null;
@@ -390,6 +399,30 @@ describe('CommandPalette DOM behavior', () => {
expect(createProjectDialogProps.at(-1)?.bridge).toBe(bridge);
});
+ test('report-a-bug command is desktop-only, searchable by issue tokens, and opens ReportBugDialog', async () => {
+ await renderPalette({ bridge: null });
+
+ await setQuery('bug');
+ expect(screen.queryByTestId('command-palette-report-bug')).toBeNull();
+ expect(screen.queryByTestId('report-bug-dialog')).toBeNull();
+
+ cleanup();
+ const bridge = createBridge();
+ const { onOpenChange } = await renderPalette({ bridge });
+
+ await setQuery('issue');
+ const reportBug = screen.getByTestId('command-palette-report-bug');
+ expect(reportBug.textContent).toContain('Report a bug');
+
+ fireEvent.click(reportBug);
+
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ await waitFor(() => {
+ expect(screen.getByTestId('report-bug-dialog').getAttribute('data-open')).toBe('true');
+ });
+ expect(reportBugDialogProps.at(-1)?.open).toBe(true);
+ });
+
test('starter-pack command is searchable, participates in empty-state aggregation, and opens SeedDialog after closing', async () => {
const { onOpenChange } = await renderPalette({ bridge: null });
diff --git a/packages/app/src/components/CommandPalette.tsx b/packages/app/src/components/CommandPalette.tsx
index c08685474..708f6be5b 100644
--- a/packages/app/src/components/CommandPalette.tsx
+++ b/packages/app/src/components/CommandPalette.tsx
@@ -11,6 +11,7 @@
import { SHOW_INSTALL_SKILL, type WorktreeSelectorEntry } from '@inkeep/open-knowledge-core';
import { Plural, Trans, useLingui } from '@lingui/react/macro';
import {
+ Bug,
Download,
FilePlus2,
FileText,
@@ -70,6 +71,7 @@ import { FileEntryIcon } from '@/components/file-entry-icon';
import { defaultInitialDir } from '@/components/file-tree-utils';
import { NewItemDialog } from '@/components/NewItemDialog';
import { usePageList } from '@/components/PageListContext';
+import { ReportBugDialog } from '@/components/ReportBugDialog';
import { SeedDialog } from '@/components/SeedDialog';
import {
CommandDialog,
@@ -347,6 +349,7 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
const [createDialogKind, setCreateDialogKind] = useState<'file' | 'folder' | null>(null);
const [seedDialogOpen, setSeedDialogOpen] = useState(false);
const [createProjectOpen, setCreateProjectOpen] = useState(false);
+ const [reportBugOpen, setReportBugOpen] = useState(false);
// Tag-mode state. Loaded lazily on first `tag:` keystroke; cached for
// the lifetime of the palette session (cleared on close in the open-
// toggle effect). Loading flag drives the `tag-list` placeholder UI;
@@ -850,6 +853,13 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
matchesCommandQuery(t`Install for Claude Chat & Cowork (Desktop App)`, deferredQuery, [
'claude desktop install cowork',
]);
+ // Desktop-only (bundle creation runs over the Electron bridge). Not gated
+ // on `singleFile`: with no project open the report degrades to the
+ // system-wide bundle, so the command stays available.
+ const showReportBug =
+ !inExclusiveMode &&
+ bridge !== null &&
+ matchesCommandQuery(t`Report a bug`, deferredQuery, ['bug report issue feedback problem']);
const showProjectRecents =
!inExclusiveMode &&
bridge !== null &&
@@ -900,6 +910,7 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
showProjectSwitch ||
showSettings ||
showInstallClaudeDesktop ||
+ showReportBug ||
showProjectRecents ||
showAgentGroup;
@@ -1473,7 +1484,8 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
showProjectOpenFolder ||
showProjectSwitch ||
showSettings ||
- showInstallClaudeDesktop ? (
+ showInstallClaudeDesktop ||
+ showReportBug ? (
<CommandGroup heading={t`Project`}>
{showCreateProject && bridge ? (
<CommandItem
@@ -1561,6 +1573,21 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
</span>
</CommandItem>
) : null}
+ {showReportBug ? (
+ <CommandItem
+ value="report a bug issue feedback"
+ onSelect={() => {
+ onOpenChange(false);
+ setReportBugOpen(true);
+ }}
+ data-testid="command-palette-report-bug"
+ >
+ <Bug />
+ <span>
+ <Trans>Report a bug</Trans>
+ </span>
+ </CommandItem>
+ ) : null}
</CommandGroup>
) : null}
@@ -1702,6 +1729,9 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
bridge={bridge}
/>
) : null}
+ {/* Desktop-only — `showReportBug` gates the launching command on
+ `bridge !== null`, so the dialog only mounts when the bridge exists. */}
+ {bridge ? <ReportBugDialog open={reportBugOpen} onOpenChange={setReportBugOpen} /> : null}
</>
);
}
diff --git a/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx b/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx
index 1e09cd142..2e8c2bebc 100644
--- a/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx
+++ b/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx
@@ -6,11 +6,33 @@
* documented in precedent #43(d).
*/
import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+import type { OkBugReportCreateResult } from '@inkeep/open-knowledge-core';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import * as syncPromiseModule from '@/editor/sync-promise';
import { DocumentErrorBoundary, errorCopy } from './DocumentErrorBoundary';
+// Radix Dialog (focus trap) reaches for DOM globals the jsdom preload does not
+// expose on globalThis. Same hoist as CloneDialog.dom.test.tsx.
+type WindowGlobals = { NodeFilter?: typeof NodeFilter };
+type GlobalWithDomShims = typeof globalThis &
+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };
+const globalWithDomShims = globalThis as GlobalWithDomShims;
+if (
+ globalWithDomShims.NodeFilter === undefined &&
+ globalWithDomShims.window?.NodeFilter !== undefined
+) {
+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;
+}
+if (globalWithDomShims.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ globalWithDomShims.ResizeObserver = NoopResizeObserver;
+}
+
let shouldThrow = false;
function MaybeThrow({ label }: { label: string }) {
@@ -20,6 +42,53 @@ function MaybeThrow({ label }: { label: string }) {
return <span data-testid="payload">{label}</span>;
}
+type CreateRequest = { level: 'standard' | 'full'; note?: string };
+
+function installBugReportBridge(): CreateRequest[] {
+ const createCalls: CreateRequest[] = [];
+ const bridge = {
+ bugReport: {
+ create: (request: CreateRequest) => {
+ createCalls.push(request);
+ const result: OkBugReportCreateResult = {
+ ok: true,
+ zipPath: '/tmp/report.zip',
+ zipSizeBytes: 1024,
+ summary: {
+ level: request.level,
+ systemWide: false,
+ projectSlug: 'demo',
+ files: [],
+ redactions: [],
+ redactedLineCount: 0,
+ generatedAt: '2026-07-10T00:00:00.000Z',
+ },
+ };
+ return Promise.resolve(result);
+ },
+ send: () => Promise.resolve({ ok: true as const, reference: 'OK-TEST01' }),
+ },
+ shell: {
+ showItemInFolder: () => Promise.resolve(),
+ openExternal: () => Promise.resolve(),
+ },
+ };
+ for (const host of [window, globalThis] as unknown as Array<Record<string, unknown>>) {
+ Object.defineProperty(host, 'okDesktop', { configurable: true, writable: true, value: bridge });
+ }
+ return createCalls;
+}
+
+function clearBugReportBridge() {
+ for (const host of [window, globalThis] as unknown as Array<Record<string, unknown>>) {
+ Object.defineProperty(host, 'okDesktop', {
+ configurable: true,
+ writable: true,
+ value: undefined,
+ });
+ }
+}
+
describe('DocumentErrorBoundary (Tier-3 mount)', () => {
let consoleErrorSpy: ReturnType<typeof spyOn>;
let consoleWarnSpy: ReturnType<typeof spyOn>;
@@ -32,6 +101,7 @@ describe('DocumentErrorBoundary (Tier-3 mount)', () => {
afterEach(() => {
cleanup();
+ clearBugReportBridge();
consoleErrorSpy.mockRestore();
consoleWarnSpy.mockRestore();
});
@@ -165,6 +235,48 @@ describe('DocumentErrorBoundary (Tier-3 mount)', () => {
invalidateSpy.mockRestore();
});
+ test('Report this error opens the report dialog with full detail and the crash context in the note', async () => {
+ shouldThrow = true;
+ const createCalls = installBugReportBridge();
+ render(
+ <DocumentErrorBoundary activeDocName="alpha.md" onRecycle={mock(() => {})}>
+ <MaybeThrow label="alpha" />
+ </DocumentErrorBoundary>,
+ );
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: /report this error/i }));
+
+ // ReportBugDialog is lazy-loaded — await the body chunk mounting.
+ expect(await screen.findByRole('dialog')).not.toBeNull();
+ expect(screen.getByRole('heading', { name: 'Report a bug' })).not.toBeNull();
+ const checkbox = screen.getByRole('checkbox', { name: 'Include detailed diagnostics' });
+ expect(checkbox.getAttribute('aria-checked')).toBe('true');
+
+ await user.click(screen.getByRole('button', { name: 'Create report' }));
+ await screen.findByRole('heading', { name: 'Review your report' });
+
+ expect(createCalls).toEqual([
+ {
+ level: 'full',
+ note: 'Crash source: document view\nDocument: alpha.md\nError: MaybeThrow boom: alpha',
+ },
+ ]);
+ });
+
+ test('the report action is absent without the desktop bridge', () => {
+ shouldThrow = true;
+ clearBugReportBridge();
+ render(
+ <DocumentErrorBoundary activeDocName="alpha.md" onRecycle={mock(() => {})}>
+ <MaybeThrow label="alpha" />
+ </DocumentErrorBoundary>,
+ );
+
+ expect(screen.getByRole('button', { name: /try again/i })).not.toBeNull();
+ expect(screen.queryByRole('button', { name: /report this error/i })).toBeNull();
+ });
+
test('onError logs bracket-prefix console.error including the doc name and error title', () => {
shouldThrow = true;
const onRecycle = mock(() => {});
diff --git a/packages/app/src/components/DocumentErrorBoundary.tsx b/packages/app/src/components/DocumentErrorBoundary.tsx
index 62482501f..e0cc0fe97 100644
--- a/packages/app/src/components/DocumentErrorBoundary.tsx
+++ b/packages/app/src/components/DocumentErrorBoundary.tsx
@@ -35,10 +35,11 @@
import { t } from '@lingui/core/macro';
import { Trans } from '@lingui/react/macro';
-import { useEffect, useRef } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { ErrorBoundary, type FallbackProps } from 'react-error-boundary';
import { toast } from 'sonner';
import { OkBlob } from '@/components/OkBlob';
+import { ReportBugDialog } from '@/components/ReportBugDialog';
import { Button } from '@/components/ui/button';
import { MountAbortError } from '@/editor/mount-promise';
import {
@@ -176,6 +177,7 @@ function DocumentErrorFallback({
const { title, summary } = errorCopy(error);
const canGoBack = !!previousDocName && !!onNavigateBack;
const retryRef = useRef<HTMLButtonElement>(null);
+ const [reportOpen, setReportOpen] = useState(false);
// Desktop only, and only for reach failures: "Try again" recycles the
// provider against the SAME server, which never succeeds once that server
// has stopped. Restart spawns a fresh one. `ok ui` (browser) mode has no
@@ -234,6 +236,15 @@ function DocumentErrorFallback({
<Trans>Restart server</Trans>
</Button>
) : null}
+ {bridge ? (
+ <Button
+ variant="ghost"
+ className="font-mono uppercase"
+ onClick={() => setReportOpen(true)}
+ >
+ <Trans>Report this error</Trans>
+ </Button>
+ ) : null}
{canGoBack ? (
<Button
variant="ghost"
@@ -266,6 +277,19 @@ function DocumentErrorFallback({
</Button>
) : null}
</div>
+ {bridge ? (
+ <ReportBugDialog
+ open={reportOpen}
+ onOpenChange={setReportOpen}
+ crashContext={{
+ source: 'document view',
+ // Read the doc from the error itself for the same aborted-transition
+ // reason as back-nav: activeDocName can lag the errored target.
+ docName: errorDocName(error) ?? activeDocName,
+ errorMessage: error instanceof Error && error.message ? error.message : String(error),
+ }}
+ />
+ ) : null}
</div>
);
}
diff --git a/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx b/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
index 45412773b..34ec8f432 100644
--- a/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
+++ b/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
@@ -1,13 +1,15 @@
/**
- * DOM mount test for NavigatorApp's `new-project` menu-action subscription —
- * the launcher-window mirror of `CreateProjectMenuTrigger`'s editor-window
- * subscription. Both windows must react when main fires the `new-project`
- * action since the menu dispatches to whichever window is focused.
+ * DOM mount tests for NavigatorApp's menu-action subscription — the
+ * launcher-window mirror of the editor-window App-root triggers
+ * (`CreateProjectMenuTrigger`, `ReportBugMenuTrigger`). Both windows must
+ * react when main fires a menu action since the menu dispatches to whichever
+ * window is focused.
*
* Pins the user-visible contract: NavigatorApp's CreateProjectDialog opens
- * only after the menu action fires, and unrelated menu actions are ignored.
- * The subscription is captured via a fake bridge and invoked directly — the
- * same path main's `sendMenuActionToFocused('new-project')` drives over IPC.
+ * only after the `new-project` action fires, `report-bug` opens the
+ * system-wide ReportBugDialog, and unrelated menu actions are ignored. The
+ * subscription is captured via a fake bridge and invoked directly — the same
+ * path main's `sendMenuActionToFocused(...)` drives over IPC.
*
* Invocation: `bun run test:dom` from `packages/app/`.
*/
@@ -55,7 +57,12 @@ if (globalWithDomShims.ResizeObserver === undefined) {
const ASYNC_TIMEOUT_MS = 2000;
-type MenuActionLike = 'new-project' | 'new-doc' | 'toggle-sidebar' | 'close-active-tab-or-window';
+type MenuActionLike =
+ | 'new-project'
+ | 'new-doc'
+ | 'toggle-sidebar'
+ | 'close-active-tab-or-window'
+ | 'report-bug';
interface NavigatorBridgeStub {
bridge: OkDesktopBridge;
@@ -186,6 +193,27 @@ describe('NavigatorApp new-project menu-action subscription', () => {
expect(screen.queryByTestId('create-project-dialog') !== null).toBe(false);
});
+ test('report-bug menu action opens the system-wide ReportBugDialog', async () => {
+ const stub = makeNavigatorBridge();
+ render(<NavigatorApp bridge={stub.bridge} />);
+
+ // Let listRecent's microtask settle so the subscription useEffect runs.
+ await new Promise((r) => setTimeout(r, 0));
+ expect(screen.queryByRole('dialog')).toBeNull();
+
+ stub.fire('report-bug');
+
+ await waitFor(
+ () => {
+ expect(screen.queryByRole('dialog', { name: 'Report a bug' })).not.toBeNull();
+ },
+ { timeout: ASYNC_TIMEOUT_MS },
+ );
+ // The Navigator has no project, so the compose summary must carry the
+ // system-wide labeling rather than the project-scoped line.
+ expect(screen.getByText(/no project is open/)).not.toBeNull();
+ });
+
test('close-active-tab-or-window menu action closes the navigator window', async () => {
const closeSpy = spyOn(window, 'close').mockImplementation(() => {});
const stub = makeNavigatorBridge();
diff --git a/packages/app/src/components/NavigatorApp.tsx b/packages/app/src/components/NavigatorApp.tsx
index 71238b5f4..78b0debc7 100644
--- a/packages/app/src/components/NavigatorApp.tsx
+++ b/packages/app/src/components/NavigatorApp.tsx
@@ -47,6 +47,7 @@ import { OkIcon } from './icons/ok';
import { McpConsentDialog } from './McpConsentDialog';
import { PackCardGrid } from './PackCardGrid';
import { basenameOf } from './project-switcher-recents';
+import { ReportBugDialog } from './ReportBugDialog';
import { Badge } from './ui/badge';
import { Button } from './ui/button';
@@ -94,6 +95,7 @@ export function NavigatorApp({ bridge }: { bridge: OkDesktopBridge }) {
const [openingLabel, setOpeningLabel] = useState<string | null>(null);
const [cloneDialogOpen, setCloneDialogOpen] = useState(false);
const [createDialogOpen, setCreateDialogOpen] = useState(false);
+ const [reportBugOpen, setReportBugOpen] = useState(false);
// Starter pack chosen on the packs-forward first-run grid, plus the pack
// list. Threaded into CreateProjectDialog so it can name the pack as
// read-only context in its description and seed the fresh project with it;
@@ -198,10 +200,13 @@ export function NavigatorApp({ bridge }: { bridge: OkDesktopBridge }) {
// File → New project… (the `new-project` menu action) opens the same
// CreateProjectDialog the "Create new project" card opens. The application
// menu fires to whichever window is focused, so the Navigator must react to
- // it too — not just the editor window's App-root trigger.
+ // it too — not just the editor window's App-root trigger. Same story for
+ // Help → Report a Bug…, which here opens the report dialog scoped
+ // system-wide (the Navigator has no project).
useEffect(() => {
return bridge.onMenuAction((action) => {
if (action === 'new-project') setCreateDialogOpen(true);
+ if (action === 'report-bug') setReportBugOpen(true);
if (action === 'close-active-tab-or-window') window.close();
});
}, [bridge]);
@@ -442,6 +447,8 @@ export function NavigatorApp({ bridge }: { bridge: OkDesktopBridge }) {
packs={createPacks}
/>
+ <ReportBugDialog open={reportBugOpen} onOpenChange={setReportBugOpen} systemWide />
+
<AuthModal
open={authModalOpen}
onOpenChange={(next) => {
diff --git a/packages/app/src/components/ReportBugCrashInviteTrigger.dom.test.tsx b/packages/app/src/components/ReportBugCrashInviteTrigger.dom.test.tsx
new file mode 100644
index 000000000..56a727e12
--- /dev/null
+++ b/packages/app/src/components/ReportBugCrashInviteTrigger.dom.test.tsx
@@ -0,0 +1,182 @@
+/**
+ * DOM mount tests for ReportBugCrashInviteTrigger — the per-window host that
+ * opens ReportBugDialog's crash-invite variant when desktop main pushes a
+ * crash-detected event.
+ *
+ * The trigger reads the module-init `crash-invite-store`; these tests install
+ * the store against a fake bridge and fire the captured subscription callback
+ * directly — the same path main's `ok:bug-report:crash-detected` push drives
+ * over IPC. The buffered-delivery test pins the load-order contract: a
+ * boot-time invitation delivered before React mounts must still surface.
+ *
+ * Invocation: `bun run test:dom` from `packages/app/`.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import type { OkBugReportCrashDetectedEvent } from '@inkeep/open-knowledge-core';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { crashInviteStore } from '@/lib/crash-invite-store';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+import { ReportBugCrashInviteTrigger } from './ReportBugCrashInviteTrigger';
+
+// Radix UI primitives (shadcn Dialog) reach for DOM globals at mount — the
+// same NodeFilter/ResizeObserver hoist as the sibling trigger test.
+type WindowGlobals = { NodeFilter?: typeof NodeFilter };
+type GlobalWithDomShims = typeof globalThis &
+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };
+const globalWithDomShims = globalThis as GlobalWithDomShims;
+if (
+ globalWithDomShims.NodeFilter === undefined &&
+ globalWithDomShims.window?.NodeFilter !== undefined
+) {
+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;
+}
+if (globalWithDomShims.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ globalWithDomShims.ResizeObserver = NoopResizeObserver;
+}
+
+const ASYNC_TIMEOUT_MS = 2000;
+
+const INVITE: OkBugReportCrashDetectedEvent = {
+ eventId: 'boot:1751871600000',
+ kind: 'boot',
+ context: { dirtyShutdown: true, newMinidumps: 0 },
+};
+
+interface CrashBridgeStub {
+ bridge: OkDesktopBridge;
+ /** Deliver a crash-detected event through the captured subscription. */
+ fire(event: OkBugReportCrashDetectedEvent): void;
+ readonly acked: string[];
+}
+
+/**
+ * Fake bridge exposing just the surface the trigger and store touch:
+ * `bugReport.onCrashDetected` (subscription), `bugReport.crashAck`, and
+ * `config.mode`. The dialog's own bridge calls (create/send) are user-action
+ * driven and these tests never reach them.
+ */
+function makeCrashBridge(): CrashBridgeStub {
+ let captured: ((event: OkBugReportCrashDetectedEvent) => void) | null = null;
+ const acked: string[] = [];
+
+ const bridge = {
+ config: { mode: 'editor' },
+ bugReport: {
+ onCrashDetected: (cb: (event: OkBugReportCrashDetectedEvent) => void) => {
+ captured = cb;
+ return () => {
+ captured = null;
+ };
+ },
+ crashAck: (request: { eventId: string }) => {
+ acked.push(request.eventId);
+ return Promise.resolve({ ok: true as const });
+ },
+ },
+ } as unknown as OkDesktopBridge;
+
+ return {
+ bridge,
+ fire: (event) => {
+ // act() flushes the store-driven useSyncExternalStore update.
+ act(() => captured?.(event));
+ },
+ acked,
+ };
+}
+
+describe('ReportBugCrashInviteTrigger', () => {
+ let uninstall: (() => void) | undefined;
+
+ afterEach(() => {
+ cleanup();
+ // Detach the singleton store from the test bridge and drop any buffered
+ // invitation so state never leaks across tests.
+ uninstall?.();
+ uninstall = undefined;
+ });
+
+ test('a crash-detected push opens the crash-invite dialog', async () => {
+ const stub = makeCrashBridge();
+ uninstall = crashInviteStore.install({ bridge: stub.bridge });
+ render(<ReportBugCrashInviteTrigger bridge={stub.bridge} />);
+ expect(screen.queryByRole('dialog')).toBeNull();
+
+ stub.fire(INVITE);
+
+ await waitFor(
+ () => {
+ expect(screen.queryByRole('dialog')).not.toBeNull();
+ },
+ { timeout: ASYNC_TIMEOUT_MS },
+ );
+ expect(screen.getByText('OpenKnowledge quit unexpectedly last time.')).not.toBeNull();
+ });
+
+ test('an invitation delivered before the component mounts is buffered, not dropped', async () => {
+ const stub = makeCrashBridge();
+ uninstall = crashInviteStore.install({ bridge: stub.bridge });
+ stub.fire(INVITE);
+
+ render(<ReportBugCrashInviteTrigger bridge={stub.bridge} />);
+
+ await waitFor(
+ () => {
+ expect(screen.queryByRole('dialog')).not.toBeNull();
+ },
+ { timeout: ASYNC_TIMEOUT_MS },
+ );
+ });
+
+ test('Not now acks the crash event and closes the invitation', async () => {
+ const stub = makeCrashBridge();
+ uninstall = crashInviteStore.install({ bridge: stub.bridge });
+ render(<ReportBugCrashInviteTrigger bridge={stub.bridge} />);
+ stub.fire(INVITE);
+ await waitFor(
+ () => {
+ expect(screen.queryByRole('dialog')).not.toBeNull();
+ },
+ { timeout: ASYNC_TIMEOUT_MS },
+ );
+
+ await userEvent.click(screen.getByRole('button', { name: 'Not now' }));
+
+ await waitFor(
+ () => {
+ expect(screen.queryByRole('dialog')).toBeNull();
+ },
+ { timeout: ASYNC_TIMEOUT_MS },
+ );
+ expect(stub.acked).toEqual(['boot:1751871600000']);
+ });
+
+ test('dismissing via Escape also counts as the answer and acks', async () => {
+ const stub = makeCrashBridge();
+ uninstall = crashInviteStore.install({ bridge: stub.bridge });
+ render(<ReportBugCrashInviteTrigger bridge={stub.bridge} />);
+ stub.fire(INVITE);
+ await waitFor(
+ () => {
+ expect(screen.queryByRole('dialog')).not.toBeNull();
+ },
+ { timeout: ASYNC_TIMEOUT_MS },
+ );
+
+ await userEvent.keyboard('{Escape}');
+
+ await waitFor(
+ () => {
+ expect(screen.queryByRole('dialog')).toBeNull();
+ },
+ { timeout: ASYNC_TIMEOUT_MS },
+ );
+ expect(stub.acked).toEqual(['boot:1751871600000']);
+ });
+});
diff --git a/packages/app/src/components/ReportBugCrashInviteTrigger.tsx b/packages/app/src/components/ReportBugCrashInviteTrigger.tsx
new file mode 100644
index 000000000..6f83a67a7
--- /dev/null
+++ b/packages/app/src/components/ReportBugCrashInviteTrigger.tsx
@@ -0,0 +1,43 @@
+/**
+ * Mounts `ReportBugDialog` in its crash-invite variant when desktop main
+ * pushes a crash-detected event (abnormal renderer/child process death, or
+ * boot-time dirty-shutdown/minidump detection). Mounted once per window in
+ * `main.tsx` as a sibling of the root app — outside `AppErrorBoundary`, so an
+ * invitation still surfaces while the shell fallback is showing, and present
+ * in every window mode (main targets whichever live window can take it).
+ *
+ * The event itself is read from `crash-invite-store`, whose bridge
+ * subscription attaches at module init — boot-time invitations arrive on the
+ * window's first `did-finish-load` and must not race React's effect flush.
+ *
+ * Any close of the invitation dialog — "Not now", Escape, the ✕, or Done
+ * after a successful send — counts as the user's answer: the crash event is
+ * acked so it never re-prompts, across restarts included.
+ */
+
+import { useSyncExternalStore } from 'react';
+import { ReportBugDialog } from '@/components/ReportBugDialog';
+import { crashInviteStore } from '@/lib/crash-invite-store';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+
+export function ReportBugCrashInviteTrigger({ bridge }: { bridge: OkDesktopBridge }) {
+ const invite = useSyncExternalStore(crashInviteStore.subscribe, crashInviteStore.getSnapshot);
+
+ if (invite === null) return null;
+
+ return (
+ <ReportBugDialog
+ open
+ onOpenChange={(open) => {
+ if (open) return;
+ // Fire-and-forget by contract: crash-ack never rejects, and a decline
+ // must never surface an error. Worst case (main already tearing down)
+ // the un-acked event re-invites on the next boot.
+ void bridge.bugReport.crashAck({ eventId: invite.eventId });
+ crashInviteStore.dismiss();
+ }}
+ systemWide={bridge.config.mode === 'navigator'}
+ crashInvite={invite}
+ />
+ );
+}
diff --git a/packages/app/src/components/ReportBugDialog.dom.test.tsx b/packages/app/src/components/ReportBugDialog.dom.test.tsx
new file mode 100644
index 000000000..7308234ca
--- /dev/null
+++ b/packages/app/src/components/ReportBugDialog.dom.test.tsx
@@ -0,0 +1,584 @@
+/**
+ * ReportBugDialog state-machine tests: compose → review → send with the
+ * success, failure→email-fallback, cancel, and note-preservation paths, all
+ * against a scripted `window.okDesktop` bridge. Copy assertions pin the
+ * approved copy deck strings; the path-identity assertions pin that the zip
+ * reviewed is the zip sent.
+ *
+ * Substrate: jsdom via `bun run test:dom`.
+ */
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import type {
+ OkBugReportCrashDetectedEvent,
+ OkBugReportCreateResult,
+ OkBugReportSendMetadata,
+ OkBugReportSendResult,
+ ReportBundleSummary,
+} from '@inkeep/open-knowledge-core';
+import { act, cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (
+ <>{(value === 1 ? one : other).replace('#', String(value))}</>
+ ),
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+// Radix Dialog (focus trap) reaches for DOM globals the jsdom preload does not
+// expose on globalThis. Same hoist as CloneDialog.dom.test.tsx.
+type WindowGlobals = { NodeFilter?: typeof NodeFilter };
+type GlobalWithDomShims = typeof globalThis &
+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };
+const globalWithDomShims = globalThis as GlobalWithDomShims;
+if (
+ globalWithDomShims.NodeFilter === undefined &&
+ globalWithDomShims.window?.NodeFilter !== undefined
+) {
+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;
+}
+if (globalWithDomShims.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ globalWithDomShims.ResizeObserver = NoopResizeObserver;
+}
+
+const ZIP_PATH = '/Users/tester/.ok/bug-reports/2026-07-10T00-00-00-bugreport.zip';
+const SUMMARY: ReportBundleSummary = {
+ level: 'standard',
+ systemWide: false,
+ projectSlug: 'demo-project',
+ files: ['sysinfo.json', 'local-logs/server-current.jsonl'],
+ redactions: [],
+ redactedLineCount: 0,
+ generatedAt: '2026-07-10T00:00:00.000Z',
+};
+const CREATE_OK: OkBugReportCreateResult = {
+ ok: true,
+ zipPath: ZIP_PATH,
+ zipSizeBytes: 7130316, // renders as "6.8 MB"
+ summary: SUMMARY,
+};
+
+type CreateRequest = { level: 'standard' | 'full'; note?: string; includeCrashDump?: boolean };
+type SendRequest = { zipPath: string; metadata: OkBugReportSendMetadata };
+
+interface BridgeLog {
+ createCalls: CreateRequest[];
+ sendCalls: SendRequest[];
+ revealed: string[];
+ opened: string[];
+ clipboard: string[];
+}
+
+function installBridge(
+ handlers: {
+ create?: (request: CreateRequest) => Promise<OkBugReportCreateResult>;
+ send?: (request: SendRequest) => Promise<OkBugReportSendResult>;
+ } = {},
+): BridgeLog {
+ const log: BridgeLog = {
+ createCalls: [],
+ sendCalls: [],
+ revealed: [],
+ opened: [],
+ clipboard: [],
+ };
+ const bridge = {
+ bugReport: {
+ create: (request: CreateRequest) => {
+ log.createCalls.push(request);
+ return handlers.create ? handlers.create(request) : Promise.resolve(CREATE_OK);
+ },
+ send: (request: SendRequest) => {
+ log.sendCalls.push(request);
+ return handlers.send
+ ? handlers.send(request)
+ : Promise.resolve({ ok: true as const, reference: 'OK-8H3KQD' });
+ },
+ },
+ shell: {
+ showItemInFolder: (path: string) => {
+ log.revealed.push(path);
+ return Promise.resolve();
+ },
+ openExternal: (url: string) => {
+ log.opened.push(url);
+ return Promise.resolve();
+ },
+ },
+ clipboard: {
+ writeText: (text: string) => {
+ log.clipboard.push(text);
+ return Promise.resolve();
+ },
+ },
+ };
+ // The component reads `window.okDesktop`; the shared clipboard adapter reads
+ // `globalThis.okDesktop` — the jsdom preload keeps those objects distinct.
+ for (const host of [window, globalThis] as unknown as Array<Record<string, unknown>>) {
+ Object.defineProperty(host, 'okDesktop', { configurable: true, writable: true, value: bridge });
+ }
+ return log;
+}
+
+function clearBridge() {
+ for (const host of [window, globalThis] as unknown as Array<Record<string, unknown>>) {
+ Object.defineProperty(host, 'okDesktop', {
+ configurable: true,
+ writable: true,
+ value: undefined,
+ });
+ }
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+}
+
+async function renderDialog(
+ props: {
+ systemWide?: boolean;
+ crashContext?: import('./ReportBugDialogBody').ReportBugCrashContext;
+ crashInvite?: OkBugReportCrashDetectedEvent;
+ } = {},
+) {
+ const { ReportBugDialog } = await import('./ReportBugDialog');
+ const openChangeCalls: boolean[] = [];
+ render(
+ <ReportBugDialog open={true} onOpenChange={(next) => openChangeCalls.push(next)} {...props} />,
+ );
+ // ReportBugDialog is lazy-loaded — wait for the body chunk to resolve and
+ // mount before returning so callers' synchronous queries see the dialog.
+ await screen.findByRole('dialog');
+ return { openChangeCalls };
+}
+
+async function createReport(note?: string) {
+ if (note !== undefined) {
+ await userEvent.type(screen.getByRole('textbox', { name: /what happened/i }), note);
+ }
+ await userEvent.click(screen.getByRole('button', { name: 'Create report' }));
+ await screen.findByRole('heading', { name: 'Review your report' });
+}
+
+describe('ReportBugDialog', () => {
+ afterEach(() => {
+ cleanup();
+ clearBridge();
+ });
+
+ test('compose state offers a labeled optional note, an off-by-default diagnostics checkbox, and the privacy summary', async () => {
+ installBridge();
+ await renderDialog();
+
+ expect(screen.getByRole('dialog')).not.toBeNull();
+ expect(screen.getByRole('heading', { name: 'Report a bug' })).not.toBeNull();
+ expect(
+ screen.getByText(
+ 'Package logs and system info into a report you can review, then send it privately to the OpenKnowledge team.',
+ ),
+ ).not.toBeNull();
+
+ const noteBox = screen.getByRole('textbox', { name: /what happened\? \(optional\)/i });
+ expect(noteBox.getAttribute('placeholder')).toBe(
+ 'e.g. The editor froze after I pasted a large table',
+ );
+
+ const checkbox = screen.getByRole('checkbox', { name: 'Include detailed diagnostics' });
+ expect(checkbox.getAttribute('aria-checked')).toBe('false');
+ expect(
+ screen.getByText(
+ 'Adds telemetry, server state, and runtime info when available. Document names are anonymized.',
+ ),
+ ).not.toBeNull();
+
+ expect(
+ screen.getByText('App & system info, recent app logs, project server logs'),
+ ).not.toBeNull();
+ expect(
+ screen.getByText(
+ "Secrets like API keys and tokens are redacted automatically. You'll review the report before it's sent.",
+ ),
+ ).not.toBeNull();
+
+ expect(screen.getByRole('button', { name: 'Cancel' })).not.toBeNull();
+ expect(screen.getByRole('button', { name: 'Create report' })).not.toBeNull();
+ });
+
+ test('a system-wide report says up front that no project logs are included', async () => {
+ installBridge();
+ await renderDialog({ systemWide: true });
+
+ expect(
+ screen.getByText(
+ 'App & system info, recent app logs — no project is open, so no project logs are included.',
+ ),
+ ).not.toBeNull();
+ });
+
+ test('creating a report builds a standard bundle with the note and shows the review card for the exact zip', async () => {
+ const log = installBridge();
+ await renderDialog();
+
+ await createReport('The editor froze');
+
+ expect(log.createCalls).toEqual([{ level: 'standard', note: 'The editor froze' }]);
+ expect(
+ screen.getByText("Take a look if you'd like — this exact file is what we receive."),
+ ).not.toBeNull();
+ expect(screen.getByText('2026-07-10T00-00-00-bugreport.zip')).not.toBeNull();
+ expect(screen.getByText(/6\.8 MB · secrets redacted · 2 files/)).not.toBeNull();
+ expect(
+ screen.getByText(
+ 'Sent privately to the OpenKnowledge team, along with your note and app version. Never posted publicly.',
+ ),
+ ).not.toBeNull();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Reveal in Finder' }));
+ expect(log.revealed).toEqual([ZIP_PATH]);
+ });
+
+ test('the detailed-diagnostics checkbox requests a full-level bundle', async () => {
+ const log = installBridge();
+ await renderDialog();
+
+ await userEvent.click(screen.getByRole('checkbox', { name: 'Include detailed diagnostics' }));
+ await createReport();
+
+ expect(log.createCalls).toEqual([{ level: 'full', note: undefined }]);
+ });
+
+ test('back from review returns to compose with the note intact', async () => {
+ installBridge();
+ await renderDialog();
+ await createReport('my draft note');
+
+ await userEvent.click(screen.getByRole('button', { name: 'Back' }));
+
+ const noteBox = screen.getByRole('textbox', { name: /what happened/i });
+ expect((noteBox as HTMLTextAreaElement).value).toBe('my draft note');
+ });
+
+ test('sending uploads the reviewed zip and lands on the reference with copy and GitHub follow-up', async () => {
+ const send = deferred<OkBugReportSendResult>();
+ const log = installBridge({ send: () => send.promise });
+ const { openChangeCalls } = await renderDialog();
+ await createReport('upload me');
+
+ await userEvent.click(screen.getByRole('button', { name: 'Send report' }));
+
+ await screen.findByRole('heading', { name: 'Sending report' });
+ expect(screen.getByText('Uploading securely')).not.toBeNull();
+ // Transport-neutral announcement — the default (no intake endpoint)
+ // configuration never uploads, so the copy must not claim one.
+ expect(screen.getByText('Your report is being sent.')).not.toBeNull();
+ // Only the honest total — no fabricated transferred-bytes counter.
+ expect(screen.getByText(/6\.8 MB total/)).not.toBeNull();
+ expect(screen.queryByText(/MB of/)).toBeNull();
+ expect(screen.getByRole('progressbar')).not.toBeNull();
+ expect(
+ (screen.getByRole('button', { name: 'Send report' }) as HTMLButtonElement).disabled,
+ ).toBe(true);
+
+ await act(async () => {
+ send.resolve({ ok: true, reference: 'OK-8H3KQD' });
+ await Promise.resolve();
+ });
+
+ await screen.findByRole('heading', { name: 'Report sent — thank you' });
+ expect(log.sendCalls).toEqual([
+ {
+ zipPath: ZIP_PATH,
+ metadata: {
+ level: 'standard',
+ systemWide: false,
+ projectSlug: 'demo-project',
+ note: 'upload me',
+ },
+ },
+ ]);
+ expect(screen.getByText('OK-8H3KQD')).not.toBeNull();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Copy report reference' }));
+ await screen.findByRole('button', { name: 'Copied report reference' });
+ expect(log.clipboard).toEqual(['OK-8H3KQD']);
+
+ await userEvent.click(screen.getByRole('button', { name: 'Open GitHub issue' }));
+ expect(log.opened).toHaveLength(1);
+ expect(log.opened[0]).toContain('https://github.com/inkeep/open-knowledge/issues/new?');
+ expect(log.opened[0]).toContain('OK-8H3KQD');
+ // Privacy pin: the public GitHub prefill carries the reference in title
+ // and body only — no diagnostics, bundle-path, or attachment params may
+ // ever ride along.
+ const issueUrl = new URL(log.opened[0] ?? '');
+ expect([...issueUrl.searchParams.keys()].sort()).toEqual(['body', 'title']);
+
+ await userEvent.click(screen.getByRole('button', { name: 'Done' }));
+ expect(openChangeCalls).toEqual([false]);
+ });
+
+ test('a failed send falls back to email with the note preserved for the retry', async () => {
+ let sendAttempts = 0;
+ const log = installBridge({
+ send: () => {
+ sendAttempts += 1;
+ return sendAttempts === 1
+ ? Promise.resolve({
+ ok: false,
+ reason: 'send-failed',
+ fallback: { mailtoUrl: 'mailto:[email protected]?subject=OpenKnowledge%20bug' },
+ })
+ : Promise.resolve({ ok: true, reference: 'OK-RETRY1' });
+ },
+ });
+ await renderDialog();
+ await createReport('still my note');
+
+ await userEvent.click(screen.getByRole('button', { name: 'Send report' }));
+
+ await screen.findByRole('heading', { name: "Couldn't send the report" });
+ expect(
+ screen.getByText("Your report couldn't be sent — try again or email it instead."),
+ ).not.toBeNull();
+ const alert = screen.getByRole('alert');
+ expect(alert.textContent).toContain("The report service couldn't be reached.");
+ expect(alert.textContent).toContain(
+ 'Your report is saved on this Mac — nothing was lost. You can email it to us instead.',
+ );
+ expect(screen.getByText('2026-07-10T00-00-00-bugreport.zip')).not.toBeNull();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Reveal in Finder' }));
+ expect(log.revealed).toEqual([ZIP_PATH]);
+
+ await userEvent.click(screen.getByRole('button', { name: 'Open email draft' }));
+ expect(log.opened).toEqual(['mailto:[email protected]?subject=OpenKnowledge%20bug']);
+
+ await userEvent.click(screen.getByRole('button', { name: 'Try again' }));
+ await screen.findByRole('heading', { name: 'Report sent — thank you' });
+ expect(log.sendCalls).toHaveLength(2);
+ expect(log.sendCalls[1].zipPath).toBe(ZIP_PATH);
+ expect(log.sendCalls[1].metadata.note).toBe('still my note');
+ });
+
+ test('with no report service configured, send resolves to the email flow — no fake upload, no failure framing', async () => {
+ const log = installBridge({
+ send: () =>
+ Promise.resolve({
+ ok: false,
+ reason: 'email-draft',
+ fallback: { mailtoUrl: 'mailto:[email protected]?subject=OpenKnowledge%20bug' },
+ }),
+ });
+ await renderDialog();
+ await createReport('no intake configured');
+
+ await userEvent.click(screen.getByRole('button', { name: 'Send report' }));
+
+ await screen.findByRole('heading', { name: 'Send your report by email' });
+ expect(
+ screen.getByText(
+ 'Nothing was uploaded — the report stays on this Mac until you email it to us.',
+ ),
+ ).not.toBeNull();
+ // An informational state, not an error: no alert, no unreachable-service
+ // claim, and nothing to retry — the draft is the transport.
+ expect(screen.queryByRole('alert')).toBeNull();
+ expect(screen.queryByText(/couldn't be reached/i)).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Try again' })).toBeNull();
+ expect(screen.getByText('2026-07-10T00-00-00-bugreport.zip')).not.toBeNull();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Reveal in Finder' }));
+ expect(log.revealed).toEqual([ZIP_PATH]);
+
+ await userEvent.click(screen.getByRole('button', { name: 'Open email draft' }));
+ expect(log.opened).toEqual(['mailto:[email protected]?subject=OpenKnowledge%20bug']);
+ });
+
+ test('cancel during sending returns to review and the late result is ignored', async () => {
+ const send = deferred<OkBugReportSendResult>();
+ const { openChangeCalls } = await (async () => {
+ installBridge({ send: () => send.promise });
+ return renderDialog();
+ })();
+ await createReport();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Send report' }));
+ await screen.findByRole('heading', { name: 'Sending report' });
+
+ // Escape must not dismiss the dialog mid-upload — Cancel is the only exit.
+ await userEvent.keyboard('{Escape}');
+ expect(openChangeCalls).toEqual([]);
+
+ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ await screen.findByRole('heading', { name: 'Review your report' });
+
+ await act(async () => {
+ send.resolve({ ok: true, reference: 'OK-LATE99' });
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(screen.queryByText('OK-LATE99')).toBeNull();
+ expect(screen.getByRole('heading', { name: 'Review your report' })).not.toBeNull();
+ });
+
+ test('a crash context pre-checks detailed diagnostics and folds the context into the note on create and send', async () => {
+ const log = installBridge();
+ await renderDialog({
+ crashContext: { source: 'document view', docName: 'alpha.md', errorMessage: 'boom' },
+ });
+
+ const checkbox = screen.getByRole('checkbox', { name: 'Include detailed diagnostics' });
+ expect(checkbox.getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByText('Details about the error you just hit are included.')).not.toBeNull();
+
+ await createReport('It crashed while I typed');
+
+ expect(log.createCalls).toEqual([
+ {
+ level: 'full',
+ note: 'It crashed while I typed\n\nCrash source: document view\nDocument: alpha.md\nError: boom',
+ },
+ ]);
+
+ await userEvent.click(screen.getByRole('button', { name: 'Send report' }));
+ await screen.findByRole('heading', { name: 'Report sent — thank you' });
+ expect(log.sendCalls[0].metadata.note).toBe(
+ 'It crashed while I typed\n\nCrash source: document view\nDocument: alpha.md\nError: boom',
+ );
+ });
+
+ test('a failed create surfaces the error with the CLI fallback and stays in compose', async () => {
+ installBridge({
+ create: () => Promise.resolve({ ok: false, error: 'zip destination not writable' }),
+ });
+ await renderDialog();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Create report' }));
+
+ const alert = await screen.findByRole('alert');
+ expect(alert.textContent).toContain("Couldn't create the report");
+ expect(alert.textContent).toContain('zip destination not writable');
+ expect(alert.textContent).toContain('ok bug-report');
+ expect(screen.getByRole('heading', { name: 'Report a bug' })).not.toBeNull();
+ });
+
+ const BOOT_INVITE: OkBugReportCrashDetectedEvent = {
+ eventId: 'boot:1751871600000',
+ kind: 'boot',
+ context: { dirtyShutdown: true, newMinidumps: 1 },
+ };
+
+ test('a crash invite reskins compose: banner, crash note label, pre-checked diagnostics, off-by-default dump, Not now', async () => {
+ installBridge();
+ await renderDialog({ crashInvite: BOOT_INVITE });
+
+ expect(screen.getByText('OpenKnowledge quit unexpectedly last time.')).not.toBeNull();
+ expect(
+ screen.getByText('A report helps us find the cause. Nothing is sent until you review it.'),
+ ).not.toBeNull();
+
+ const noteBox = screen.getByRole('textbox', { name: /what were you doing\? \(optional\)/i });
+ expect(noteBox.getAttribute('placeholder')).toBe(
+ 'e.g. Switching projects while a sync was running',
+ );
+
+ expect(
+ screen
+ .getByRole('checkbox', { name: 'Include detailed diagnostics' })
+ .getAttribute('aria-checked'),
+ ).toBe('true');
+
+ const dumpBox = screen.getByRole('checkbox', { name: 'Include crash dump' });
+ expect(dumpBox.getAttribute('aria-checked')).toBe('false');
+ expect(screen.getByText(/a memory snapshot from the crash\./i)).not.toBeNull();
+ expect(screen.getByText(/can't be redacted/i)).not.toBeNull();
+
+ expect(screen.getByRole('button', { name: 'Not now' })).not.toBeNull();
+ expect(screen.queryByRole('button', { name: 'Cancel' })).toBeNull();
+ // The banner carries the consent line, so the what's-included box yields.
+ expect(screen.queryByText(/secrets like api keys and tokens are redacted/i)).toBeNull();
+ });
+
+ test('crash-invite create folds the crash details in and leaves the dump out unless opted in', async () => {
+ const log = installBridge();
+ await renderDialog({ crashInvite: BOOT_INVITE });
+
+ await userEvent.click(screen.getByRole('button', { name: 'Create report' }));
+ await screen.findByRole('heading', { name: 'Review your report' });
+
+ expect(log.createCalls).toEqual([
+ {
+ level: 'full',
+ note: 'Crash source: previous session ended without a clean quit\nCrash event: boot:1751871600000',
+ includeCrashDump: false,
+ },
+ ]);
+ });
+
+ test('checking Include crash dump opts the minidump into create', async () => {
+ const log = installBridge();
+ await renderDialog({ crashInvite: BOOT_INVITE });
+
+ await userEvent.click(screen.getByRole('checkbox', { name: 'Include crash dump' }));
+ await userEvent.click(screen.getByRole('button', { name: 'Create report' }));
+ await screen.findByRole('heading', { name: 'Review your report' });
+
+ expect(log.createCalls[0]?.includeCrashDump).toBe(true);
+ });
+
+ test('the plain compose never renders the crash-dump opt-in and never sends the flag', async () => {
+ const log = installBridge();
+ await renderDialog();
+
+ expect(screen.queryByRole('checkbox', { name: 'Include crash dump' })).toBeNull();
+
+ await createReport();
+ expect(log.createCalls).toEqual([{ level: 'standard' }]);
+ });
+
+ test('the review card qualifies the redaction claim when a raw crash dump is bundled', async () => {
+ installBridge({
+ create: () =>
+ Promise.resolve({
+ ...CREATE_OK,
+ summary: {
+ ...SUMMARY,
+ level: 'full',
+ files: [...SUMMARY.files, 'extra/renderer-crash.dmp'],
+ },
+ }),
+ });
+ await renderDialog({ crashInvite: BOOT_INVITE });
+
+ await userEvent.click(screen.getByRole('checkbox', { name: 'Include crash dump' }));
+ await userEvent.click(screen.getByRole('button', { name: 'Create report' }));
+ await screen.findByRole('heading', { name: 'Review your report' });
+
+ // The dump is copied byte-for-byte, so the last screen before send must
+ // not let "secrets redacted" stand unqualified.
+ expect(
+ screen.getByText(/6\.8 MB · secrets redacted · 3 files · crash dump not redacted/),
+ ).not.toBeNull();
+ });
+
+ test('the review card keeps the unqualified redaction claim when no crash dump is bundled', async () => {
+ installBridge();
+ await renderDialog();
+ await createReport();
+
+ expect(screen.getByText(/6\.8 MB · secrets redacted · 2 files/)).not.toBeNull();
+ expect(screen.queryByText(/crash dump not redacted/)).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/ReportBugDialog.tsx b/packages/app/src/components/ReportBugDialog.tsx
new file mode 100644
index 000000000..12de4edff
--- /dev/null
+++ b/packages/app/src/components/ReportBugDialog.tsx
@@ -0,0 +1,31 @@
+/**
+ * Report-a-bug dialog — thin lazy-loading gate. The ~800-line dialog body
+ * (phase machine, zip preview, upload-transport UI) is behind `React.lazy()`,
+ * so it only enters the bundle graph the first time the dialog is opened —
+ * keeping it out of the main app chunk (size-limit budget). Mirrors the
+ * `ConsentDialog` / `ConsentDialogBody` split.
+ */
+
+import { lazy, Suspense, useState } from 'react';
+import type { ReportBugDialogProps } from './ReportBugDialogBody';
+
+const ReportBugDialogBody = lazy(() => import('./ReportBugDialogBody'));
+
+export function ReportBugDialog(props: ReportBugDialogProps) {
+ // Pull the heavy chunk only once first opened — a ~1-frame delay on first
+ // open is worth keeping it out of first paint for a rarely-used surface.
+ // Once opened, the body stays mounted so Radix's close animation and
+ // focus-return to the trigger behave exactly as before the split.
+ const [everOpened, setEverOpened] = useState(props.open);
+ if (props.open && !everOpened) {
+ setEverOpened(true);
+ }
+ if (!everOpened) {
+ return null;
+ }
+ return (
+ <Suspense fallback={null}>
+ <ReportBugDialogBody {...props} />
+ </Suspense>
+ );
+}
diff --git a/packages/app/src/components/ReportBugDialogBody.tsx b/packages/app/src/components/ReportBugDialogBody.tsx
new file mode 100644
index 000000000..c48b06826
--- /dev/null
+++ b/packages/app/src/components/ReportBugDialogBody.tsx
@@ -0,0 +1,853 @@
+/**
+ * ReportBugDialog — the in-app "Report a bug" flow (compose → review → send).
+ *
+ * One dialog hosts six phases: compose (optional note + detail level),
+ * review (inspect the exact zip before consenting to send), sending, success
+ * (report reference + public GitHub follow-up), email (the designed
+ * no-intake default — nothing was uploaded, the prefilled draft is the
+ * transport), and failure (the same email fallback framed as an error, for
+ * uploads that were attempted and failed). The zip reviewed is byte-identical
+ * to the zip sent — `zipPath` from create is handed to send untouched.
+ *
+ * A crash-detected invitation (`crashInvite`) reskins compose — banner,
+ * "What were you doing?" label, pre-checked diagnostics, the crash-dump
+ * opt-in, a "Not now" dismiss — while review → send stay shared.
+ *
+ * Desktop-only surface: bundle creation and the upload both live in Electron
+ * main behind `window.okDesktop.bugReport`. Mount sites gate on bridge
+ * presence; without it, create degrades to the in-dialog error state.
+ */
+
+import type {
+ OkBugReportCrashDetectedEvent,
+ ReportBundleSummary,
+} from '@inkeep/open-knowledge-core';
+import { Plural, Trans, useLingui } from '@lingui/react/macro';
+import {
+ AlertCircleIcon,
+ ArchiveIcon,
+ CheckIcon,
+ FileTextIcon,
+ Loader2,
+ ShieldIcon,
+ TriangleAlertIcon,
+} from 'lucide-react';
+import { useEffect, useId, useRef, useState } from 'react';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Textarea } from '@/components/ui/textarea';
+import { scheduleClipboardWrite } from '@/lib/share/clipboard-adapter';
+
+const GITHUB_NEW_ISSUE_URL = 'https://github.com/inkeep/open-knowledge/issues/new';
+
+export interface ReportBugCrashContext {
+ /** Surface the error escaped from, e.g. 'document view' or 'app shell'. */
+ source: string;
+ /** Document that was active when the error surfaced, when known. */
+ docName?: string;
+ errorMessage?: string;
+}
+
+interface CreatedReport {
+ zipPath: string;
+ zipSizeBytes: number;
+ summary: ReportBundleSummary;
+}
+
+/**
+ * Crash details ride inside the note string so they reach the bundle's note
+ * file, the upload metadata, and the mailto fallback body through the existing
+ * IPC contract. Team-facing diagnostic text, deliberately not localized.
+ */
+function composeNote(userNote: string, contextLines: string[] | undefined): string | undefined {
+ const trimmed = userNote.trim();
+ if (contextLines === undefined) return trimmed === '' ? undefined : trimmed;
+ const context = contextLines.join('\n');
+ return trimmed === '' ? context : `${trimmed}\n\n${context}`;
+}
+
+function crashContextLines(crashContext: ReportBugCrashContext): string[] {
+ const lines = [`Crash source: ${crashContext.source}`];
+ if (crashContext.docName !== undefined) lines.push(`Document: ${crashContext.docName}`);
+ if (crashContext.errorMessage !== undefined) lines.push(`Error: ${crashContext.errorMessage}`);
+ return lines;
+}
+
+function crashInviteLines(invite: OkBugReportCrashDetectedEvent): string[] {
+ const source =
+ invite.kind === 'render-process-gone'
+ ? `renderer process crash (reason: ${invite.context.reason})`
+ : invite.kind === 'child-process-gone'
+ ? `${invite.context.processType} process crash (reason: ${invite.context.reason})`
+ : invite.context.dirtyShutdown
+ ? 'previous session ended without a clean quit'
+ : 'new crash dump found from the previous session';
+ // The event id keys the crash to main's local acknowledgment/minidump state
+ // during triage (it encodes the crashed session or dump timestamp).
+ return [`Crash source: ${source}`, `Crash event: ${invite.eventId}`];
+}
+
+type Phase =
+ | { step: 'compose'; creating: boolean; createError: string | null }
+ | { step: 'review'; report: CreatedReport }
+ | { step: 'sending'; report: CreatedReport }
+ | { step: 'success'; report: CreatedReport; reference: string }
+ | { step: 'email'; report: CreatedReport; mailtoUrl: string }
+ | { step: 'failure'; report: CreatedReport; mailtoUrl: string };
+
+const COMPOSE_IDLE: Phase = { step: 'compose', creating: false, createError: null };
+
+function formatSize(bytes: number): string {
+ if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+ if (bytes >= 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`;
+ return `${bytes} B`;
+}
+
+function zipBasename(zipPath: string): string {
+ return zipPath.split(/[\\/]/).pop() ?? zipPath;
+}
+
+/**
+ * The one artifact bundled raw is the opted-in crash minidump under `extra/`
+ * — process memory that text redaction cannot scrub. The review/email/failure
+ * cards must qualify their "secrets redacted" claim whenever one is present.
+ * The summary's file inventory, not the dialog's checkbox state, is the
+ * truth: opting in with no dump on disk adds nothing to the bundle.
+ */
+function reportIncludesRawDump(report: CreatedReport): boolean {
+ return report.summary.files.some((file) => file.startsWith('extra/'));
+}
+
+export interface ReportBugDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ /**
+ * No project is open in this window (Navigator) — the bundle will be
+ * system-wide (user-level logs + sysinfo), and the what's-included summary
+ * says so up front.
+ */
+ systemWide?: boolean;
+ /**
+ * Present when an error-boundary fallback opened the dialog. Defaults the
+ * bundle to full detail and folds the crash details into the report's note.
+ */
+ crashContext?: ReportBugCrashContext;
+ /**
+ * Present when a crash-detected invitation opened the dialog
+ * (`ReportBugCrashInviteTrigger`). Switches compose to the crash-invite
+ * variant: banner, "What were you doing?" note label, detailed diagnostics
+ * pre-checked, the crash-dump opt-in row (default off), and a "Not now"
+ * dismiss. The event's kind and id fold into the report's note.
+ */
+ crashInvite?: OkBugReportCrashDetectedEvent;
+}
+
+function ReportBugDialog({
+ open,
+ onOpenChange,
+ systemWide = false,
+ crashContext,
+ crashInvite,
+}: ReportBugDialogProps) {
+ const { t } = useLingui();
+ const [phase, setPhase] = useState<Phase>(COMPOSE_IDLE);
+ const [note, setNote] = useState('');
+ const [detailed, setDetailed] = useState(crashContext !== undefined || crashInvite !== undefined);
+ const [includeDump, setIncludeDump] = useState(false);
+ const [copied, setCopied] = useState(false);
+ const [sentFraction, setSentFraction] = useState(0);
+ // Bumped whenever the current async create/send no longer owns the dialog
+ // (cancel, close): the awaiting handler compares and drops its result.
+ const opSeqRef = useRef(0);
+ const copyResetRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ const noteId = useId();
+ const detailedId = useId();
+ const detailedHintId = useId();
+ const dumpId = useId();
+ const dumpHintId = useId();
+
+ const sending = phase.step === 'sending';
+ const noteContextLines =
+ crashContext !== undefined
+ ? crashContextLines(crashContext)
+ : crashInvite !== undefined
+ ? crashInviteLines(crashInvite)
+ : undefined;
+
+ // Fake-determinate upload progress: main exposes no byte-level progress
+ // events (the upload is one awaited IPC call), so ease toward 90% and let
+ // the terminal phase change deliver the rest — the bar never claims done.
+ useEffect(() => {
+ if (!sending) return;
+ setSentFraction(0);
+ const startedAt = Date.now();
+ const timer = setInterval(() => {
+ const elapsedSeconds = (Date.now() - startedAt) / 1000;
+ setSentFraction(Math.min(0.9, 1 - Math.exp(-elapsedSeconds / 3)));
+ }, 200);
+ return () => {
+ clearInterval(timer);
+ };
+ }, [sending]);
+
+ useEffect(() => {
+ return () => {
+ clearTimeout(copyResetRef.current);
+ };
+ }, []);
+
+ function handleOpenChange(nextOpen: boolean) {
+ // Mid-upload the footer Cancel is the only way out — swallowing Radix's
+ // Escape/outside-click close keeps the result from landing in a void.
+ if (!nextOpen && phase.step === 'sending') return;
+ if (!nextOpen) {
+ opSeqRef.current += 1;
+ // Reset the form on any concluded close (success, email draft, or upload
+ // failure) so the next open starts clean — not just on success.
+ if (phase.step === 'success' || phase.step === 'email' || phase.step === 'failure') {
+ setNote('');
+ setDetailed(crashContext !== undefined || crashInvite !== undefined);
+ setIncludeDump(false);
+ }
+ setPhase(COMPOSE_IDLE);
+ setCopied(false);
+ }
+ onOpenChange(nextOpen);
+ }
+
+ async function handleCreate() {
+ const bugReport = window.okDesktop?.bugReport;
+ if (!bugReport) {
+ setPhase({
+ step: 'compose',
+ creating: false,
+ createError: t`Bug reporting needs the OpenKnowledge desktop app.`,
+ });
+ return;
+ }
+ const seq = ++opSeqRef.current;
+ setPhase({ step: 'compose', creating: true, createError: null });
+ const result = await bugReport.create({
+ level: detailed ? 'full' : 'standard',
+ note: composeNote(note, noteContextLines),
+ // Only the crash invite ever asks for the dump — the plain compose has
+ // no opt-in surface, so it must not even send the flag.
+ ...(crashInvite !== undefined ? { includeCrashDump: includeDump } : {}),
+ });
+ if (opSeqRef.current !== seq) return;
+ if (result.ok) {
+ setPhase({
+ step: 'review',
+ report: {
+ zipPath: result.zipPath,
+ zipSizeBytes: result.zipSizeBytes,
+ summary: result.summary,
+ },
+ });
+ } else {
+ setPhase({ step: 'compose', creating: false, createError: result.error });
+ }
+ }
+
+ async function handleSend(report: CreatedReport) {
+ const bugReport = window.okDesktop?.bugReport;
+ if (!bugReport) return;
+ const seq = ++opSeqRef.current;
+ setPhase({ step: 'sending', report });
+ const result = await bugReport.send({
+ zipPath: report.zipPath,
+ metadata: {
+ level: report.summary.level,
+ systemWide: report.summary.systemWide,
+ projectSlug: report.summary.projectSlug,
+ note: composeNote(note, noteContextLines),
+ },
+ });
+ if (opSeqRef.current !== seq) return;
+ if (result.ok) {
+ setPhase({ step: 'success', report, reference: result.reference });
+ } else if (result.reason === 'email-draft') {
+ // The designed default (no intake endpoint configured): nothing was
+ // attempted and nothing failed, so the email flow renders without any
+ // failure framing.
+ setPhase({ step: 'email', report, mailtoUrl: result.fallback.mailtoUrl });
+ } else {
+ setPhase({ step: 'failure', report, mailtoUrl: result.fallback.mailtoUrl });
+ }
+ }
+
+ function handleCancelSend(report: CreatedReport) {
+ // The IPC upload has no abort path — abandon the wait and let the seq
+ // guard drop whatever it eventually resolves to.
+ opSeqRef.current += 1;
+ setPhase({ step: 'review', report });
+ }
+
+ function revealZip(zipPath: string) {
+ void window.okDesktop?.shell.showItemInFolder(zipPath);
+ }
+
+ function openExternal(url: string) {
+ void window.okDesktop?.shell.openExternal(url);
+ }
+
+ function handleCopyReference(reference: string) {
+ void scheduleClipboardWrite(reference)
+ .then(() => {
+ setCopied(true);
+ clearTimeout(copyResetRef.current);
+ copyResetRef.current = setTimeout(() => setCopied(false), 1600);
+ })
+ .catch(() => {
+ // Every clipboard path refused — the reference stays selectable text.
+ });
+ }
+
+ function handleOpenGithubIssue(reference: string) {
+ const params = new URLSearchParams({
+ title: t`Bug report ${reference}`,
+ // The reference is the only private↔public correlation key; the bundle
+ // itself never leaves the private channel.
+ body: t`Report reference: ${reference}`,
+ });
+ openExternal(`${GITHUB_NEW_ISSUE_URL}?${params}`);
+ }
+
+ const uploadPct = Math.round(sentFraction * 100);
+
+ return (
+ <Dialog open={open} onOpenChange={handleOpenChange}>
+ <DialogContent className="sm:max-w-md" showCloseButton={!sending}>
+ {phase.step === 'compose' && (
+ <>
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>Report a bug</Trans>
+ </DialogTitle>
+ {crashInvite === undefined && (
+ <DialogDescription>
+ <Trans>
+ Package logs and system info into a report you can review, then send it
+ privately to the OpenKnowledge team.
+ </Trans>
+ </DialogDescription>
+ )}
+ </DialogHeader>
+ <DialogBody className="flex flex-col gap-4">
+ {crashInvite !== undefined && (
+ <div className="flex items-start gap-2.5 rounded-md border border-chart-3/35 bg-chart-3/10 px-3 py-2.5 text-sm">
+ <TriangleAlertIcon
+ className="mt-0.5 size-4 shrink-0 text-chart-3"
+ aria-hidden="true"
+ />
+ <div>
+ <p className="font-medium">
+ <Trans>OpenKnowledge quit unexpectedly last time.</Trans>
+ </p>
+ {/* Rendered as the dialog's Description so the banner's
+ reassurance line is what screen readers announce for
+ the crash variant (no header description here). */}
+ <DialogDescription className="mt-0.5 text-xs">
+ <Trans>
+ A report helps us find the cause. Nothing is sent until you review it.
+ </Trans>
+ </DialogDescription>
+ </div>
+ </div>
+ )}
+ {phase.createError !== null && (
+ <div
+ role="alert"
+ className="flex items-start gap-2.5 rounded-md border border-destructive/35 bg-destructive/10 px-3 py-2.5 text-sm"
+ >
+ <AlertCircleIcon
+ className="mt-0.5 size-4 shrink-0 text-destructive"
+ aria-hidden="true"
+ />
+ <div>
+ <p className="font-medium">
+ <Trans>Couldn't create the report</Trans>
+ </p>
+ <p className="mt-0.5 text-xs text-muted-foreground">{phase.createError}</p>
+ <p className="mt-0.5 text-xs text-muted-foreground">
+ <Trans>
+ You can also create one from a terminal with{' '}
+ <code className="font-mono">ok bug-report</code>.
+ </Trans>
+ </p>
+ </div>
+ </div>
+ )}
+ <div className="flex flex-col gap-2">
+ <label htmlFor={noteId} className="text-sm font-medium">
+ {crashInvite !== undefined ? (
+ <Trans>What were you doing?</Trans>
+ ) : (
+ <Trans>What happened?</Trans>
+ )}{' '}
+ <span className="font-normal text-muted-foreground">
+ <Trans>(optional)</Trans>
+ </span>
+ </label>
+ <Textarea
+ id={noteId}
+ value={note}
+ onChange={(e) => setNote(e.target.value)}
+ placeholder={
+ crashInvite !== undefined
+ ? t`e.g. Switching projects while a sync was running`
+ : t`e.g. The editor froze after I pasted a large table`
+ }
+ rows={3}
+ className="resize-none"
+ disabled={phase.creating}
+ />
+ </div>
+ <div className="flex items-start gap-2.5">
+ <Checkbox
+ id={detailedId}
+ checked={detailed}
+ onCheckedChange={(value) => setDetailed(value === true)}
+ aria-describedby={detailedHintId}
+ disabled={phase.creating}
+ className="mt-0.5"
+ />
+ <div className="flex flex-col gap-0.5">
+ <label htmlFor={detailedId} className="text-sm font-medium">
+ <Trans>Include detailed diagnostics</Trans>
+ </label>
+ <p id={detailedHintId} className="text-xs text-muted-foreground">
+ <Trans>
+ Adds telemetry, server state, and runtime info when available. Document names
+ are anonymized.
+ </Trans>
+ </p>
+ </div>
+ </div>
+ {crashInvite !== undefined && (
+ <div className="flex items-start gap-2.5">
+ <Checkbox
+ id={dumpId}
+ checked={includeDump}
+ onCheckedChange={(value) => setIncludeDump(value === true)}
+ aria-describedby={dumpHintId}
+ disabled={phase.creating}
+ className="mt-0.5"
+ />
+ <div className="flex flex-col gap-0.5">
+ <label htmlFor={dumpId} className="text-sm font-medium">
+ <Trans>Include crash dump</Trans>
+ </label>
+ <p id={dumpHintId} className="text-xs text-muted-foreground">
+ <Trans>
+ A memory snapshot from the crash. It can contain document content and can't
+ be redacted — leave off unless you're comfortable sharing it.
+ </Trans>
+ </p>
+ </div>
+ </div>
+ )}
+ {crashInvite === undefined && (
+ <div className="flex flex-col gap-2 rounded-md border bg-muted/50 px-3 py-2.5 text-xs">
+ <div className="flex items-start gap-2">
+ <FileTextIcon
+ className="mt-0.5 size-3.5 shrink-0 text-muted-foreground"
+ aria-hidden="true"
+ />
+ <span>
+ {systemWide ? (
+ <Trans>
+ App & system info, recent app logs — no project is open, so no project
+ logs are included.
+ </Trans>
+ ) : (
+ <Trans>App & system info, recent app logs, project server logs</Trans>
+ )}
+ </span>
+ </div>
+ {crashContext !== undefined && (
+ <div className="flex items-start gap-2">
+ <AlertCircleIcon
+ className="mt-0.5 size-3.5 shrink-0 text-muted-foreground"
+ aria-hidden="true"
+ />
+ <span>
+ <Trans>Details about the error you just hit are included.</Trans>
+ </span>
+ </div>
+ )}
+ <div className="flex items-start gap-2 border-t pt-2 text-muted-foreground">
+ <ShieldIcon
+ className="mt-0.5 size-3.5 shrink-0 text-chart-2"
+ aria-hidden="true"
+ />
+ <span>
+ <Trans>
+ Secrets like API keys and tokens are redacted automatically. You'll review
+ the report before it's sent.
+ </Trans>
+ </span>
+ </div>
+ </div>
+ )}
+ </DialogBody>
+ <DialogFooter>
+ <Button
+ variant="ghost"
+ className="font-mono uppercase"
+ onClick={() => handleOpenChange(false)}
+ >
+ {crashInvite !== undefined ? <Trans>Not now</Trans> : <Trans>Cancel</Trans>}
+ </Button>
+ <Button onClick={() => void handleCreate()} disabled={phase.creating}>
+ {phase.creating && (
+ <Loader2
+ className="size-4 animate-spin motion-reduce:animate-none"
+ aria-hidden="true"
+ />
+ )}
+ <Trans>Create report</Trans>
+ </Button>
+ </DialogFooter>
+ </>
+ )}
+
+ {phase.step === 'review' && (
+ <>
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>Review your report</Trans>
+ </DialogTitle>
+ <DialogDescription>
+ <Trans>Take a look if you'd like — this exact file is what we receive.</Trans>
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="flex flex-col gap-4">
+ <ZipCard
+ zipPath={phase.report.zipPath}
+ zipSizeBytes={phase.report.zipSizeBytes}
+ fileCount={phase.report.summary.files.length}
+ rawDumpIncluded={reportIncludesRawDump(phase.report)}
+ onReveal={revealZip}
+ />
+ <div className="flex items-start gap-2 rounded-md border bg-muted/50 px-3 py-2.5 text-xs text-muted-foreground">
+ <ShieldIcon className="mt-0.5 size-3.5 shrink-0 text-chart-2" aria-hidden="true" />
+ <span>
+ <Trans>
+ Sent privately to the OpenKnowledge team, along with your note and app version.
+ Never posted publicly.
+ </Trans>
+ </span>
+ </div>
+ </DialogBody>
+ <DialogFooter className="sm:justify-between">
+ <Button
+ variant="ghost"
+ className="font-mono uppercase"
+ onClick={() => setPhase(COMPOSE_IDLE)}
+ >
+ <Trans>Back</Trans>
+ </Button>
+ <Button onClick={() => void handleSend(phase.report)}>
+ <Trans>Send report</Trans>
+ </Button>
+ </DialogFooter>
+ </>
+ )}
+
+ {phase.step === 'sending' && (
+ <>
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>Sending report</Trans>
+ </DialogTitle>
+ {/* Transport-neutral on purpose: in the default (no intake
+ endpoint) configuration Send never uploads — it resolves to
+ an email draft — so the announcement must not claim one. */}
+ <DialogDescription className="sr-only">
+ <Trans>Your report is being sent.</Trans>
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="flex flex-col gap-3">
+ <div role="status" className="flex items-center gap-2.5 text-sm">
+ <Loader2
+ className="size-4 shrink-0 animate-spin text-primary motion-reduce:animate-none"
+ aria-hidden="true"
+ />
+ <Trans>Uploading securely</Trans>
+ {/* No byte-level progress crosses the IPC boundary, so the only
+ honest number here is the total size. */}
+ <span className="ml-auto text-xs text-muted-foreground">
+ <Trans>{formatSize(phase.report.zipSizeBytes)} total</Trans>
+ </span>
+ </div>
+ {/* The width animation is a time-eased estimate, not real
+ transfer progress, so the machine-readable state stays
+ indeterminate (no aria-valuenow) — assistive tech must not
+ hear invented percentages. */}
+ <div
+ role="progressbar"
+ aria-label={t`Sending report`}
+ className="h-1.5 overflow-hidden rounded-full bg-secondary"
+ >
+ <div
+ className="h-full rounded-full bg-primary"
+ style={{ width: `${uploadPct}%` }}
+ />
+ </div>
+ </DialogBody>
+ <DialogFooter className="sm:justify-between">
+ <Button
+ variant="ghost"
+ className="font-mono uppercase"
+ onClick={() => handleCancelSend(phase.report)}
+ >
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button disabled>
+ <Trans>Send report</Trans>
+ </Button>
+ </DialogFooter>
+ </>
+ )}
+
+ {phase.step === 'success' && (
+ <>
+ <DialogBody>
+ <div role="status" className="flex flex-col items-center gap-2.5 py-2 text-center">
+ <div
+ className="grid size-11 place-items-center rounded-full bg-chart-2/15 text-chart-2"
+ aria-hidden="true"
+ >
+ <CheckIcon className="size-5" />
+ </div>
+ <DialogTitle>
+ <Trans>Report sent — thank you</Trans>
+ </DialogTitle>
+ <DialogDescription>
+ <Trans>We've filed it with the team and attached your logs.</Trans>
+ </DialogDescription>
+ <div className="flex items-center gap-2.5 rounded-md border border-dashed px-3.5 py-2 font-mono text-sm font-semibold tracking-wide">
+ {phase.reference}
+ <Button
+ variant="link"
+ className="h-auto p-0 font-sans text-xs font-medium"
+ // Bare "Copy" is self-describing next to the reference
+ // visually, but generic when a screen reader tabs past it.
+ // The visible text stays a prefix of the accessible name
+ // (WCAG 2.5.3 label-in-name).
+ aria-label={copied ? t`Copied report reference` : t`Copy report reference`}
+ onClick={() => handleCopyReference(phase.reference)}
+ >
+ {copied ? <Trans>Copied</Trans> : <Trans>Copy</Trans>}
+ </Button>
+ </div>
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ Want to follow along? Open a GitHub issue and mention your reference.
+ </Trans>
+ </p>
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ Or write to{' '}
+ <code className="font-mono text-xs text-foreground">[email protected]</code>
+ </Trans>
+ </p>
+ </div>
+ </DialogBody>
+ <DialogFooter className="sm:justify-center">
+ <Button
+ variant="outline"
+ className="font-mono uppercase"
+ onClick={() => handleOpenGithubIssue(phase.reference)}
+ >
+ <Trans>Open GitHub issue</Trans>
+ </Button>
+ <Button onClick={() => handleOpenChange(false)}>
+ <Trans>Done</Trans>
+ </Button>
+ </DialogFooter>
+ </>
+ )}
+
+ {phase.step === 'email' && (
+ <>
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>Send your report by email</Trans>
+ </DialogTitle>
+ {/* An informational state, not an error: with no report service
+ configured, the prefilled draft is how reports travel — no
+ upload happened, so no alert banner belongs here. */}
+ <DialogDescription>
+ <Trans>
+ Nothing was uploaded — the report stays on this Mac until you email it to us.
+ </Trans>
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="flex flex-col gap-4">
+ <ZipCard
+ zipPath={phase.report.zipPath}
+ zipSizeBytes={phase.report.zipSizeBytes}
+ fileCount={phase.report.summary.files.length}
+ rawDumpIncluded={reportIncludesRawDump(phase.report)}
+ onReveal={revealZip}
+ />
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ Attach the file in an email to{' '}
+ <code className="font-mono text-xs text-foreground">[email protected]</code>
+ </Trans>
+ </p>
+ </DialogBody>
+ <DialogFooter className="sm:justify-between">
+ <Button
+ variant="ghost"
+ className="font-mono uppercase"
+ onClick={() => handleOpenChange(false)}
+ >
+ <Trans>Close</Trans>
+ </Button>
+ <Button onClick={() => openExternal(phase.mailtoUrl)}>
+ <Trans>Open email draft</Trans>
+ </Button>
+ </DialogFooter>
+ </>
+ )}
+
+ {phase.step === 'failure' && (
+ <>
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>Couldn't send the report</Trans>
+ </DialogTitle>
+ <DialogDescription className="sr-only">
+ <Trans>Your report couldn't be sent — try again or email it instead.</Trans>
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="flex flex-col gap-4">
+ <div
+ role="alert"
+ className="flex items-start gap-2.5 rounded-md border border-destructive/35 bg-destructive/10 px-3 py-2.5 text-sm"
+ >
+ <AlertCircleIcon
+ className="mt-0.5 size-4 shrink-0 text-destructive"
+ aria-hidden="true"
+ />
+ <div>
+ <p className="font-medium">
+ <Trans>The report service couldn't be reached.</Trans>
+ </p>
+ <p className="mt-0.5 text-xs text-muted-foreground">
+ <Trans>
+ Your report is saved on this Mac — nothing was lost. You can email it to us
+ instead.
+ </Trans>
+ </p>
+ </div>
+ </div>
+ <ZipCard
+ zipPath={phase.report.zipPath}
+ zipSizeBytes={phase.report.zipSizeBytes}
+ fileCount={null}
+ rawDumpIncluded={reportIncludesRawDump(phase.report)}
+ onReveal={revealZip}
+ />
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ Attach the file in an email to{' '}
+ <code className="font-mono text-xs text-foreground">[email protected]</code>
+ </Trans>
+ </p>
+ </DialogBody>
+ <DialogFooter className="sm:justify-between">
+ <Button
+ variant="ghost"
+ className="font-mono uppercase"
+ onClick={() => handleOpenChange(false)}
+ >
+ <Trans>Close</Trans>
+ </Button>
+ <div className="flex flex-col-reverse gap-2 sm:flex-row">
+ <Button
+ variant="outline"
+ className="font-mono uppercase"
+ onClick={() => void handleSend(phase.report)}
+ >
+ <Trans>Try again</Trans>
+ </Button>
+ <Button onClick={() => openExternal(phase.mailtoUrl)}>
+ <Trans>Open email draft</Trans>
+ </Button>
+ </div>
+ </DialogFooter>
+ </>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+interface ZipCardProps {
+ zipPath: string;
+ zipSizeBytes: number;
+ /** `null` hides the file count (the failure card omits it). */
+ fileCount: number | null;
+ /** The bundle carries a raw crash dump — the redaction claim must be qualified. */
+ rawDumpIncluded: boolean;
+ onReveal: (zipPath: string) => void;
+}
+
+function ZipCard({ zipPath, zipSizeBytes, fileCount, rawDumpIncluded, onReveal }: ZipCardProps) {
+ const name = zipBasename(zipPath);
+ const sizeText = formatSize(zipSizeBytes);
+ return (
+ <div className="flex items-center gap-2.5 rounded-md border px-3 py-2.5">
+ <ArchiveIcon className="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <p className="truncate font-mono text-xs" title={name}>
+ {name}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {fileCount === null ? (
+ rawDumpIncluded ? (
+ <Trans>{sizeText} · secrets redacted · crash dump not redacted</Trans>
+ ) : (
+ <Trans>{sizeText} · secrets redacted</Trans>
+ )
+ ) : rawDumpIncluded ? (
+ <Trans>
+ {sizeText} · secrets redacted ·{' '}
+ <Plural value={fileCount} one="# file" other="# files" /> · crash dump not redacted
+ </Trans>
+ ) : (
+ <Trans>
+ {sizeText} · secrets redacted ·{' '}
+ <Plural value={fileCount} one="# file" other="# files" />
+ </Trans>
+ )}
+ </p>
+ </div>
+ <Button
+ variant="link"
+ className="h-auto shrink-0 p-0 text-xs"
+ onClick={() => onReveal(zipPath)}
+ >
+ <Trans>Reveal in Finder</Trans>
+ </Button>
+ </div>
+ );
+}
+
+// Default export lets the thin `ReportBugDialog.tsx` gate consume this body via
+// `React.lazy()`, keeping the ~800-line dialog out of the main app chunk.
+export default ReportBugDialog;
diff --git a/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsx b/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsx
new file mode 100644
index 000000000..4972fd7a7
--- /dev/null
+++ b/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsx
@@ -0,0 +1,139 @@
+/**
+ * DOM mount test for ReportBugMenuTrigger — the App-root surface that opens
+ * ReportBugDialog when main fires the `report-bug` menu action
+ * (Help → Report a Bug…).
+ *
+ * Pins the user-visible contract: the dialog is closed until the menu action
+ * fires, opens on `report-bug`, and ignores unrelated menu actions. The
+ * trigger subscribes to `bridge.onMenuAction`; this test captures the
+ * subscribed callback through a fake bridge and invokes it directly — the
+ * same path main's `sendMenuActionToFocused('report-bug')` drives over IPC.
+ *
+ * Invocation: `bun run test:dom` from `packages/app/`.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+import { ReportBugMenuTrigger } from './ReportBugMenuTrigger';
+
+// `OkMenuAction` is module-private in desktop-bridge-types.ts; mirror just the
+// members this test fires. The trigger only branches on the literal
+// 'report-bug', so an exact union is unnecessary.
+type MenuActionLike = 'report-bug' | 'new-doc' | 'toggle-sidebar';
+
+// Radix UI primitives (shadcn Dialog) reach for DOM globals at mount. The
+// broadly-needed constructors (MutationObserver) live in the shared
+// tests/dom/jsdom-preload.ts; NodeFilter (react-focus-scope) and
+// ResizeObserver (react-use-size) are hoisted locally per the sibling
+// CreateProjectMenuTrigger.dom.test.tsx.
+type WindowGlobals = { NodeFilter?: typeof NodeFilter };
+type GlobalWithDomShims = typeof globalThis &
+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };
+const globalWithDomShims = globalThis as GlobalWithDomShims;
+if (
+ globalWithDomShims.NodeFilter === undefined &&
+ globalWithDomShims.window?.NodeFilter !== undefined
+) {
+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;
+}
+if (globalWithDomShims.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ globalWithDomShims.ResizeObserver = NoopResizeObserver;
+}
+
+const ASYNC_TIMEOUT_MS = 2000;
+
+interface MenuActionBridgeStub {
+ bridge: OkDesktopBridge;
+ /** Invoke the most recently subscribed onMenuAction callback. */
+ fire(action: MenuActionLike): void;
+ readonly unsubscribeCalls: number;
+}
+
+/**
+ * Fake bridge exposing just the surface ReportBugMenuTrigger touches:
+ * `onMenuAction` (subscription). ReportBugDialog itself talks to
+ * `window.okDesktop` only on user actions (create/send), which this test
+ * never reaches — opening the compose phase needs no further bridge surface.
+ */
+function makeMenuActionBridge(): MenuActionBridgeStub {
+ let captured: ((action: MenuActionLike) => void) | null = null;
+ let unsubscribeCalls = 0;
+
+ const bridge = {
+ onMenuAction: (cb: (action: MenuActionLike) => void) => {
+ captured = cb;
+ return () => {
+ unsubscribeCalls += 1;
+ captured = null;
+ };
+ },
+ } as unknown as OkDesktopBridge;
+
+ return {
+ bridge,
+ fire: (action) => {
+ if (captured) {
+ // Wrap in act so the resulting setOpen state flush is applied before
+ // assertions run (mirrors fireEvent's internal act wrapping).
+ act(() => captured?.(action));
+ }
+ },
+ get unsubscribeCalls() {
+ return unsubscribeCalls;
+ },
+ };
+}
+
+describe('ReportBugMenuTrigger', () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('dialog is closed until the report-bug menu action fires', () => {
+ const stub = makeMenuActionBridge();
+ render(<ReportBugMenuTrigger bridge={stub.bridge} />);
+ // Radix Dialog renders nothing when closed — no portal, no dialog role.
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+
+ test('report-bug menu action opens ReportBugDialog', async () => {
+ const stub = makeMenuActionBridge();
+ render(<ReportBugMenuTrigger bridge={stub.bridge} />);
+
+ stub.fire('report-bug');
+
+ await waitFor(
+ () => {
+ expect(screen.queryByRole('dialog')).not.toBeNull();
+ },
+ { timeout: ASYNC_TIMEOUT_MS },
+ );
+ // The dialog title confirms it's the report-a-bug surface.
+ expect(screen.getByRole('dialog', { name: 'Report a bug' })).not.toBeNull();
+ });
+
+ test('unrelated menu actions do not open the dialog', async () => {
+ const stub = makeMenuActionBridge();
+ render(<ReportBugMenuTrigger bridge={stub.bridge} />);
+
+ stub.fire('new-doc');
+ stub.fire('toggle-sidebar');
+
+ // Give any erroneous open a chance to render before asserting absence.
+ await new Promise((r) => setTimeout(r, 50));
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+
+ test('unsubscribes from onMenuAction on unmount', () => {
+ const stub = makeMenuActionBridge();
+ const { unmount } = render(<ReportBugMenuTrigger bridge={stub.bridge} />);
+ expect(stub.unsubscribeCalls).toBe(0);
+ unmount();
+ expect(stub.unsubscribeCalls).toBe(1);
+ });
+});
diff --git a/packages/app/src/components/ReportBugMenuTrigger.tsx b/packages/app/src/components/ReportBugMenuTrigger.tsx
new file mode 100644
index 000000000..4c7ea4e01
--- /dev/null
+++ b/packages/app/src/components/ReportBugMenuTrigger.tsx
@@ -0,0 +1,26 @@
+/**
+ * Mounts `ReportBugDialog` and opens it when main fires the `report-bug`
+ * menu action (Help → Report a Bug…). App-root mount so the Help-menu entry
+ * works regardless of sidebar/editor state — mirroring the self-contained
+ * trigger pattern of `CreateProjectMenuTrigger`.
+ *
+ * Desktop-only: App.tsx renders it only when the desktop bridge is present
+ * (the `report-bug` menu action never fires in the web host). The Navigator
+ * window subscribes separately in `NavigatorApp` with a system-wide scope.
+ */
+
+import { useEffect, useState } from 'react';
+import { ReportBugDialog } from '@/components/ReportBugDialog';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+
+export function ReportBugMenuTrigger({ bridge }: { bridge: OkDesktopBridge }) {
+ const [open, setOpen] = useState(false);
+
+ useEffect(() => {
+ return bridge.onMenuAction((action) => {
+ if (action === 'report-bug') setOpen(true);
+ });
+ }, [bridge]);
+
+ return <ReportBugDialog open={open} onOpenChange={setOpen} />;
+}
diff --git a/packages/app/src/lib/crash-invite-store.test.ts b/packages/app/src/lib/crash-invite-store.test.ts
new file mode 100644
index 000000000..e3b3b980c
--- /dev/null
+++ b/packages/app/src/lib/crash-invite-store.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, mock, test } from 'bun:test';
+
+import type { OkBugReportCrashDetectedEvent } from '@inkeep/open-knowledge-core';
+
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+
+import { createCrashInviteStore } from './crash-invite-store';
+
+function fakeBridge(): {
+ bridge: OkDesktopBridge;
+ emit: (event: OkBugReportCrashDetectedEvent) => void;
+ subscribers: () => number;
+} {
+ const subs: ((event: OkBugReportCrashDetectedEvent) => void)[] = [];
+ const bridge = {
+ bugReport: {
+ onCrashDetected: (cb: (event: OkBugReportCrashDetectedEvent) => void) => {
+ subs.push(cb);
+ return () => {
+ const idx = subs.indexOf(cb);
+ if (idx >= 0) subs.splice(idx, 1);
+ };
+ },
+ },
+ } as unknown as OkDesktopBridge;
+ return {
+ bridge,
+ emit: (event) => {
+ for (const s of subs) s(event);
+ },
+ subscribers: () => subs.length,
+ };
+}
+
+const crashEvent: OkBugReportCrashDetectedEvent = {
+ eventId: 'crash:render:1751871600000:0',
+ kind: 'render-process-gone',
+ context: { reason: 'crashed', exitCode: 5 },
+};
+
+describe('createCrashInviteStore — install', () => {
+ test('returns undefined and is a no-op when no bridge is supplied', () => {
+ const store = createCrashInviteStore();
+ expect(store.install({ bridge: undefined })).toBeUndefined();
+ expect(store.getSnapshot()).toBeNull();
+ });
+
+ test('no-ops without throwing when the bridge omits the bugReport surface', () => {
+ const store = createCrashInviteStore();
+ // A partial bridge (test/preview mock, or a renderer paired with a main
+ // process predating the bug-report IPC) has no `bugReport` — install runs
+ // at module-init outside any error boundary, so it must no-op, not throw.
+ const partialBridge = {} as unknown as OkDesktopBridge;
+ let result: (() => void) | undefined;
+ expect(() => {
+ result = store.install({ bridge: partialBridge });
+ }).not.toThrow();
+ expect(result).toBeUndefined();
+ expect(store.getSnapshot()).toBeNull();
+ });
+
+ test('subscribes once + idempotent on a second install call', () => {
+ const fb = fakeBridge();
+ const store = createCrashInviteStore();
+ const teardown1 = store.install({ bridge: fb.bridge });
+ const teardown2 = store.install({ bridge: fb.bridge });
+ expect(typeof teardown1).toBe('function');
+ expect(typeof teardown2).toBe('function');
+ expect(fb.subscribers()).toBe(1);
+ });
+});
+
+describe('createCrashInviteStore — invitation delivery', () => {
+ test('buffers an event that arrives before any component subscribes', () => {
+ const fb = fakeBridge();
+ const store = createCrashInviteStore();
+ store.install({ bridge: fb.bridge });
+
+ fb.emit(crashEvent);
+
+ expect(store.getSnapshot()).toEqual(crashEvent);
+ });
+
+ test('notifies subscribers when an event lands', () => {
+ const fb = fakeBridge();
+ const store = createCrashInviteStore();
+ store.install({ bridge: fb.bridge });
+ const listener = mock(() => {});
+ store.subscribe(listener);
+
+ fb.emit(crashEvent);
+
+ expect(listener).toHaveBeenCalledTimes(1);
+ });
+
+ test('dismiss clears the invitation and notifies once', () => {
+ const fb = fakeBridge();
+ const store = createCrashInviteStore();
+ store.install({ bridge: fb.bridge });
+ fb.emit(crashEvent);
+ const listener = mock(() => {});
+ store.subscribe(listener);
+
+ store.dismiss();
+ store.dismiss();
+
+ expect(store.getSnapshot()).toBeNull();
+ expect(listener).toHaveBeenCalledTimes(1);
+ });
+
+ test('uninstall detaches from the bridge and drops the buffered invitation', () => {
+ const fb = fakeBridge();
+ const store = createCrashInviteStore();
+ const teardown = store.install({ bridge: fb.bridge });
+ fb.emit(crashEvent);
+
+ teardown?.();
+
+ expect(fb.subscribers()).toBe(0);
+ expect(store.getSnapshot()).toBeNull();
+ });
+});
diff --git a/packages/app/src/lib/crash-invite-store.ts b/packages/app/src/lib/crash-invite-store.ts
new file mode 100644
index 000000000..de242902d
--- /dev/null
+++ b/packages/app/src/lib/crash-invite-store.ts
@@ -0,0 +1,99 @@
+/**
+ * Renderer-side module-level store for the crash-invite event.
+ *
+ * Mirrors the `receive-store` pattern: the bridge subscription is attached at
+ * `main.tsx` module-init time (BEFORE React mounts) because main delivers a
+ * boot-time `ok:bug-report:crash-detected` on the window's first
+ * `did-finish-load`, which can beat React's effect flush — a component-mounted
+ * subscription would drop it. The `ReportBugCrashInviteTrigger` component
+ * reads via `useSyncExternalStore`.
+ *
+ * Web / CLI distribution: `bridge` is undefined and `install` is a no-op.
+ */
+
+import type { OkBugReportCrashDetectedEvent } from '@inkeep/open-knowledge-core';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+
+export interface CrashInviteStore {
+ install(opts: { bridge: OkDesktopBridge | undefined }): (() => void) | undefined;
+ getSnapshot(): OkBugReportCrashDetectedEvent | null;
+ subscribe(listener: () => void): () => void;
+ /** Drop the current invitation (the trigger clears after acking it). */
+ dismiss(): void;
+}
+
+/**
+ * Factory so each test gets a fresh store instance. Production code uses the
+ * singleton `crashInviteStore` exported below.
+ */
+export function createCrashInviteStore(): CrashInviteStore {
+ let current: OkBugReportCrashDetectedEvent | null = null;
+ const listeners = new Set<() => void>();
+ let attached = false;
+ let unsubscribeFromBridge: (() => void) | null = null;
+
+ function notify(): void {
+ for (const l of listeners) l();
+ }
+
+ function clearCurrent(): void {
+ if (current === null) return;
+ current = null;
+ notify();
+ }
+
+ return {
+ install({ bridge }): (() => void) | undefined {
+ // A partial bridge — a test/preview mock, or a renderer paired with a
+ // main process predating the bug-report IPC — may omit the `bugReport`
+ // surface (which the type declares required). This runs at module-init
+ // OUTSIDE any error boundary, so throwing on a missing surface would take
+ // down the whole renderer; no-op on absence instead, exactly like an
+ // undefined bridge.
+ const onCrashDetected = (bridge as { bugReport?: OkDesktopBridge['bugReport'] } | undefined)
+ ?.bugReport?.onCrashDetected;
+ if (typeof onCrashDetected !== 'function') return undefined;
+ if (attached) return unsubscribeFromBridge ?? undefined;
+ attached = true;
+ unsubscribeFromBridge = onCrashDetected((event) => {
+ // Main arms at most one invitation at a time, so last-wins is exact.
+ current = event;
+ notify();
+ });
+ return () => {
+ unsubscribeFromBridge?.();
+ unsubscribeFromBridge = null;
+ attached = false;
+ clearCurrent();
+ };
+ },
+
+ getSnapshot(): OkBugReportCrashDetectedEvent | null {
+ return current;
+ },
+
+ subscribe(listener): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+
+ dismiss(): void {
+ clearCurrent();
+ },
+ };
+}
+
+/** Module-level singleton — `main.tsx` installs once at boot. */
+export const crashInviteStore: CrashInviteStore = createCrashInviteStore();
+
+/**
+ * Module-init-time bridge subscription. Idempotent — HMR re-evaluation is a
+ * no-op on the second call thanks to the `attached` flag.
+ */
+export function installCrashInviteListener(opts: {
+ bridge: OkDesktopBridge | undefined;
+}): (() => void) | undefined {
+ return crashInviteStore.install(opts);
+}
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index 45c591a2e..9a8bf50c9 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -22,8 +22,14 @@ import type {
CreateNewBannerKind,
EditorId,
LocalOpOkInitResponse,
+ OkBugReportCrashAckResult,
+ OkBugReportCrashDetectedEvent,
+ OkBugReportCreateResult,
+ OkBugReportSendMetadata,
+ OkBugReportSendResult,
OkFolderState,
RecentProjectEntry,
+ ReportBundleLevel,
ShareTargetStatusResponse,
TerminalCli,
WorktreeCreateRequest,
@@ -228,7 +234,11 @@ type OkMenuAction =
// Worktree selector (worktree = window). `new-worktree` opens the
// create dialog; `switch-worktree` opens the sidebar worktree switcher.
| 'new-worktree'
- | 'switch-worktree';
+ | 'switch-worktree'
+ // Help → Report a Bug… — opens the in-app bug-report dialog. Both window
+ // types subscribe: editor windows report project-scoped, the Navigator
+ // reports system-wide.
+ | 'report-bug';
type OkUnsubscribe = () => void;
@@ -1148,6 +1158,28 @@ export interface OkDesktopBridge {
setMode(mode: 'shared' | 'local-only'): Promise<OkSharingSetModeResult>;
};
+ /**
+ * In-app "Report a bug" — `create` builds the redacted diagnostic zip
+ * (optional crash-dump opt-in via `includeCrashDump`); `send` uploads it
+ * with an email fallback; `onCrashDetected` / `crashAck` carry the
+ * crash-invite round-trip.
+ * Canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.
+ * Mirrored here per the OkDesktopBridge 3-way-mirror invariant.
+ */
+ bugReport: {
+ create(request: {
+ level: ReportBundleLevel;
+ note?: string;
+ includeCrashDump?: boolean;
+ }): Promise<OkBugReportCreateResult>;
+ send(request: {
+ zipPath: string;
+ metadata: OkBugReportSendMetadata;
+ }): Promise<OkBugReportSendResult>;
+ crashAck(request: { eventId: string }): Promise<OkBugReportCrashAckResult>;
+ onCrashDetected(cb: (event: OkBugReportCrashDetectedEvent) => void): OkUnsubscribe;
+ };
+
/**
* Filesystem probes that back the Create-new-project dialog cascade. See
* canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 729aa7506..45715b65c 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -11,6 +11,7 @@
"-3ois8": ["Hard break"],
"-5jISU": [["0", "plural", { "one": ["#", " template"], "other": ["#", " templates"] }]],
"-8PP0T": ["Match case"],
+ "-9ErB5": ["Copied report reference"],
"-K0AvT": ["Disconnect"],
"-LHLx7": ["edited template"],
"-QCLWk": ["Templates available"],
@@ -21,6 +22,9 @@
"-gdcIo": ["Auto-sync is on — your commits push and remote changes pull on intervals."],
"-i7ik4": ["Collapse burst ", ["burstNumber"], " diff"],
"-lCAuQ": ["Loading graph"],
+ "-o5XAG": [
+ "Sent privately to the OpenKnowledge team, along with your note and app version. Never posted publicly."
+ ],
"-q4abP": [
"Results capped — this workspace has more files than search can index. A missing file may be a cap artifact, not a typo."
],
@@ -35,6 +39,7 @@
"0-31GV": ["Removing"],
"00c7t0": ["Ask AI about this code block"],
"02P3hL": ["Upload failed: ", ["message"]],
+ "03wKPg": ["A report helps us find the cause. Nothing is sent until you review it."],
"04RA0-": ["Failed to enable sync — ", ["detail"]],
"04XyCH": ["Adds a managed block to ", ["0"]],
"05n5wS": ["Doc mention suggestions"],
@@ -109,6 +114,7 @@
"28B21t": ["Agent Skills"],
"29VNqC": ["Unknown error"],
"29XZXN": ["Set git identity"],
+ "2AIVbm": ["Review your report"],
"2B6eYX": ["What this checkbox changes"],
"2BBAbc": ["List"],
"2FYpfJ": ["More"],
@@ -124,12 +130,14 @@
"2hYmUH": ["[email protected]"],
"2hpdRq": ["Hide panel (", ["panelShortcutLabel"], ")"],
"2j1kfc": ["Enter a valid URL (for example https://api.openai.com/v1)."],
+ "2myNzt": ["We've filed it with the team and attached your logs."],
"2n3oDU": [
"Project-level pages ordered by inbound link count, up to ",
["FULLSCREEN_HUB_LIMIT"],
" results."
],
"2q_Q7x": ["Visibility"],
+ "2rQ8G4": ["Or write to <0>[email protected]</0>"],
"2ryd91": ["Failed to rename property"],
"2tgFCe": ["Starting clone"],
"2vIPtm": ["Open link in new tab"],
@@ -141,6 +149,11 @@
"379t2h": ["Unified diff"],
"38foVZ": ["Loading diff"],
"3BnyYc": ["This doc isn't on GitHub yet. The link won't work until it's pushed."],
+ "3DJEEt": [
+ ["sizeText"],
+ " · secrets redacted · ",
+ ["fileCount", "plural", { "one": ["#", " file"], "other": ["#", " files"] }]
+ ],
"3DTatP": ["Copy a prompt for your agent, start a blank file, or scaffold from a template."],
"3FMvls": ["A short line shown under the title in the template list."],
"3Fcb0I": ["Open graph"],
@@ -213,6 +226,7 @@
"4nj6n8": ["/api/config returned HTTP ", ["code"]],
"4rjwLG": ["Create with ", ["0"], " CLI"],
"4sKwf6": ["File already exists"],
+ "4tOxNU": ["Report sent — thank you"],
"4uNLmk": ["Pulling"],
"4v2Yyz": ["Select every visible file-tree row when focus is in the Files sidebar."],
"4xtLTl": ["Hidden folder “", ["basename"], "”"],
@@ -247,6 +261,7 @@
],
"5OTgC7": ["Open and focus the bottom Ask AI prompt composer."],
"5OqaJi": ["Enter a project name"],
+ "5PHgV2": ["You can also create one from a terminal with <0>ok bug-report</0>."],
"5QGTaA": ["Could not copy relative path"],
"5SwVv1": ["Not installed"],
"5Tk8Fb": ["Loading files"],
@@ -282,6 +297,7 @@
"5wV2qQ": ["and more"],
"5y_9lO": ["Waiting for authorization"],
"6-wLTJ": [["behind"], " behind origin"],
+ "60vpJN": ["What were you doing?"],
"62Pc08": ["Install for Claude Chat & Cowork (Desktop App)"],
"636K3K": ["Delete adjacent chip"],
"67f-3g": ["Duplicate succeeded but the sidebar may be out of date — refresh to resync"],
@@ -324,6 +340,7 @@
"6s7LXO": ["Heads up"],
"6u9LvN": [["days", "plural", { "one": ["#", " day ago"], "other": ["#", " days ago"] }]],
"6vEr3W": ["Link target"],
+ "6zzhQL": ["Send your report by email"],
"72xhRD": ["Diagram view mode"],
"74-bX-": ["A pull quote stands out from the surrounding text."],
"74eHt-": ["No file or folder selected"],
@@ -366,6 +383,7 @@
["fileName"],
") in the project root"
],
+ "89y7ar": [["sizeText"], " · secrets redacted"],
"8F1i42": ["Page not found"],
"8FqTCr": [
[
@@ -443,6 +461,7 @@
"No collab server for this worktree — run <0>ok start</0> here, or reopen the project."
],
"AB4qw9": ["New terminal"],
+ "ACCCV-": ["Nothing was uploaded — the report stays on this Mac until you email it to us."],
"AE7BY3": ["The terminal session ended."],
"AIn2Yv": [["displayName"], " CLI, ", ["hint"]],
"AItsE5": ["Open it there"],
@@ -487,6 +506,7 @@
{ "one": ["#", " file conflicted"], "other": ["#", " files conflicted"] }
]
],
+ "B7XVXd": ["Attach the file in an email to <0>[email protected]</0>"],
"BAH4qX": ["Selected graph item"],
"BBqGS9": ["Desktop"],
"BD0XSC": ["Failed to load project templates"],
@@ -523,6 +543,7 @@
"COr1Y7": [
"Pick <0>openknowledge.skill</0> from your <1>Downloads</1> folder. It enables automatically."
],
+ "CSIkhP": ["Take a look if you'd like — this exact file is what we receive."],
"CSL0l1": ["Couldn't clear the key — please try again."],
"CTJLpz": ["\"", ["trimmed"], "\" already exists here"],
"CU3AiE": ["Switching branches"],
@@ -540,6 +561,9 @@
"Ck9XRt": ["Couldn't save the key — please try again."],
"CmeH9S": ["Add property to ", ["keyName"]],
"CoHvYd": ["Moved ", ["0"], " to position ", ["1"], " of ", ["2"]],
+ "Ct7b_s": [
+ "Your report is saved on this Mac — nothing was lost. You can email it to us instead."
+ ],
"CvsD6Y": ["via ", ["viaTags"]],
"D-Oh1s": ["How to set up ", ["0"], " (opens in browser)"],
"D12vtS": ["(detached)"],
@@ -739,6 +763,7 @@
"Gp_twO": ["Local path"],
"GsBUCk": ["Loading settings"],
"Gt4gOO": ["This folder has unpushed changes. Recipients will see the last pushed version."],
+ "GuaJb-": ["Open email draft"],
"GubkSu": ["Use a starter pack"],
"GuqOb1": ["Failed to load headings"],
"Gx0VS1": ["e.g. drafts/ or *.draft.md"],
@@ -783,6 +808,7 @@
"IA6JW2": ["Detecting"],
"ICoNYz": ["You can also manage this in Settings."],
"IInnZo": ["Conflict"],
+ "IKkfn_": ["Report reference: ", ["reference"]],
"IKoTAC": ["Keep disabled"],
"IN4UX8": ["Search (", ["searchShortcut"], ")"],
"IQPyrD": ["Missing page — click to create"],
@@ -812,6 +838,7 @@
"No disconnected pages. Pages appear here only when they have no incoming and no outgoing graph edges."
],
"JE21eh": ["Symlink to ", ["targetPath"]],
+ "JJcBCm": [["0"], " total"],
"JK-Ave": ["Hide thumbnails"],
"JL3si7": ["Updating"],
"JLUTgi": ["No tags yet — author `#tagname` in any doc to populate the index."],
@@ -930,6 +957,7 @@
"M3ytY_": [
"This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
],
+ "M5_9s2": ["Sending report"],
"M5mfAe": ["Add tag"],
"M9597s": ["Preparing share URL..."],
"MCjC9A": ["Delete ", ["deleteDescriptorLabel"]],
@@ -938,6 +966,7 @@
"Insert, delete, move, copy, and indent source editor lines through CodeMirror's default keymap."
],
"MHrjPM": ["Title"],
+ "MJqRO6": ["Your report is being sent."],
"MKOVhz": ["Enable git auto-sync"],
"MQIM_Y": ["Couldn't copy. Select the URL above to copy it manually."],
"MTs6g3": ["Couldn't reconnect after server restart"],
@@ -968,6 +997,7 @@
["0"],
" — your previous version is in history if you need to restore it."
],
+ "N-eM-f": ["Details about the error you just hit are included."],
"N1KkEO": ["Jump to last tab"],
"N1YYa7": ["Loading image"],
"N1mdmS": ["This file can't be opened in the text editor."],
@@ -1011,12 +1041,14 @@
"Nx7BWE": ["Git auto-sync"],
"NxW-md": ["Resize ", ["handleKey"]],
"NzFvyK": ["Session ended — undo unavailable"],
+ "NzluOx": ["(optional)"],
"O0Z2Xr": ["Outgoing"],
"O2UpM1": ["Browse"],
"O3oNi5": ["Email"],
"O4PnDd": ["AI tool management is only available in the OpenKnowledge desktop app."],
"O6yEPk": ["Create a new OpenKnowledge project in the folder of your choice."],
"O7_W_a": ["Open with AI"],
+ "O9oQJS": ["Send report"],
"OD0FCX": ["Hidden “", ["basename"], "”"],
"ODGGlj": ["Folder name: ", ["detail"]],
"OETysD": ["No hub pages yet. Hubs appear once pages accumulate inbound graph links."],
@@ -1028,6 +1060,9 @@
"OJeiSH": ["Failed to add property"],
"OLBz-_": ["Mermaid diagram failed to render."],
"OLIKgw": ["Drag item ", ["0"], " to reorder"],
+ "OLt6sc": [
+ "Package logs and system info into a report you can review, then send it privately to the OpenKnowledge team."
+ ],
"ONPvOb": ["Loading agent activity"],
"ONgEZF": ["Loading headings for ", ["pageTarget"]],
"OOIVJo": ["Uninstalled \"", ["0"], "\" from ", ["1"]],
@@ -1037,6 +1072,7 @@
"OXb_Df": ["Settings content"],
"OYnx7O": ["Path cannot start with \"/\""],
"OZJeTZ": ["Skill"],
+ "Oawo4U": ["The report service couldn't be reached."],
"OdmsFg": ["Failed to delete item"],
"OeAl1e": ["e.g. assets/uploads"],
"OgyJSr": ["Local only"],
@@ -1091,6 +1127,7 @@
"PrJYSN": ["This folder isn't on GitHub yet. The link won't work until it's pushed."],
"PrhzDE": ["Pan up"],
"Pyp1NA": ["Restore to this point?"],
+ "PzUvDM": ["Bug report ", ["reference"]],
"Q5fqMz": ["Connection error — try again"],
"Q6hhn8": ["Preferences"],
"Q7W-mC": ["Same folder as current file"],
@@ -1188,6 +1225,7 @@
"SfxQX8": ["Writes a project-MCP config for each selected tool."],
"SgKLfA": ["Not connected to GitHub."],
"Sh3Qkg": ["No matching branches."],
+ "Si7mIR": ["Create report"],
"SiUUCS": ["Next match"],
"SkMZlS": ["Couldn't remove <0>", ["targetGitPath"], "</0>: ", ["removeGitError"]],
"Skr_7L": ["Search worktrees"],
@@ -1195,6 +1233,7 @@
"SrOuyg": ["Document panels"],
"T-654M": ["Loading PDF"],
"T0OVm7": ["The default branch is protected — pushes need a pull request."],
+ "T3j-7o": ["e.g. Switching projects while a sync was running"],
"T67A0Y": [
"Auto-sync pushes/pulls commits to your git remote on intervals and on save. Toggling on requires confirmation."
],
@@ -1219,6 +1258,9 @@
"UBv8UK": ["Delete Permanently"],
"UDFrWm": ["Checking GitHub connection..."],
"UL8A9w": ["Tag"],
+ "ULRb5t": [
+ "Adds telemetry, server state, and runtime info when available. Document names are anonymized."
+ ],
"UMrOy2": ["Skill \"", ["trimmedName"], "\" created"],
"UPjaXD": ["Couldn't duplicate \"", ["0"], "\": ", ["1"]],
"UQAp48": ["Search templates"],
@@ -1305,6 +1347,7 @@
"WALN45": ["Switch to ", ["shareBranch"]],
"WHPvOb": ["All files are hidden by view filters."],
"WL6puM": ["Path resolves outside project"],
+ "WM-NnH": ["Your report couldn't be sent — try again or email it instead."],
"WMIKXK": [
"Are you sure you want to delete ",
["targetCount"],
@@ -1328,6 +1371,7 @@
"Wgmlsw": ["Fetching"],
"Wh0im4": ["editing [[", ["realCurrentDoc"], "]]"],
"WhOsNE": ["Strikethrough"],
+ "Wi-VWy": ["Couldn't send the report"],
"WkTLN7": ["Show only markdown files"],
"WmPbvm": ["Get product updates in your inbox."],
"Wq6Wcm": ["Please enter a valid email address."],
@@ -1345,6 +1389,7 @@
"XDzAnp": ["Opens in a new tab"],
"XH30C4": ["document"],
"XJOV1Y": ["Activity"],
+ "XLfzgb": ["Want to follow along? Open a GitHub issue and mention your reference."],
"XPJ0sN": [["settingsDescriptorLabel"], " properties"],
"XPqe3B": ["Create new tag #", ["tagValue"]],
"XRuL0i": ["Create page"],
@@ -1387,6 +1432,7 @@
"YGIi_c": ["Reinstall"],
"YJ1BTp": ["A skill with that name already exists."],
"YKLP_-": ["Template renamed"],
+ "YLMBSd": ["e.g. The editor froze after I pasted a large table"],
"YPFBfr": [["detail"], " - ", ["kind"], " \"", ["createdPath"], "\" still exists on disk"],
"YSFv5w": ["No git repository — config sharing does not apply here."],
"YTLmTM": ["Remove the parent <0>.git</0> folder"],
@@ -1400,6 +1446,7 @@
"YsEYYS": [
["behind", "plural", { "one": ["#", " commit behind"], "other": ["#", " commits behind"] }]
],
+ "Yu3KMH": ["Open GitHub issue"],
"YwPUUP": ["This pack is already set up here."],
"YyXtnN": ["Underline"],
"Z1LF1M": ["Sharing a doc needs a GitHub repository. Create one for this project."],
@@ -1449,6 +1496,7 @@
"ZvzbDF": ["Add it directly to this project."],
"ZxXhLY": ["Hide Files (", ["sidebarShortcut"], ")"],
"Zz25kq": ["Show Files (", ["sidebarShortcut"], ")"],
+ "_0JUKX": ["Bug reporting needs the OpenKnowledge desktop app."],
"_5qBNl": ["AI tools & CLI"],
"_6FVBz": ["Jump to tab 1-8"],
"_7UQ7y": ["Whole word"],
@@ -1462,6 +1510,8 @@
["currentLabel"],
"</1>."
],
+ "_FLBbi": [["sizeText"], " · secrets redacted · crash dump not redacted"],
+ "_IGfXZ": ["OpenKnowledge quit unexpectedly last time."],
"_NX6gG": ["Managing project AI tools is unavailable in this build."],
"_PACVa": ["Release notes"],
"_PBJRl": ["Add at least one letter or number."],
@@ -1526,11 +1576,17 @@
],
"b4itZn": ["Working"],
"b5aNbi": ["The ", ["targetNoun"], " could not be opened — try navigating to it manually."],
+ "b6bBkz": [
+ "App & system info, recent app logs — no project is open, so no project logs are included."
+ ],
"bBE5tC": ["Detected on this machine"],
"bBcFK_": ["Open emoji picker for ", ["keyName"]],
"bD8I7O": ["Complete"],
"bGa3Fk": ["Uploading file"],
"bH382I": ["Edit this HTML — the preview updates live."],
+ "bJKq1H": [
+ "A memory snapshot from the crash. It can contain document content and can't be redacted — leave off unless you're comfortable sharing it."
+ ],
"bSD4im": ["Search worktrees and branches"],
"bS_boY": ["Replace current match"],
"bUUVED": ["Asset"],
@@ -1570,6 +1626,7 @@
"cZGNlb": ["Add another pattern"],
"cZI5AL": ["OK Desktop"],
"cZ_8zB": ["Stays on this computer."],
+ "cd5EXh": ["Report a bug"],
"cdm00A": ["No Incoming"],
"cdmk8A": ["Uncommitted changes"],
"chL5IG": ["Community"],
@@ -1589,6 +1646,7 @@
],
"d2uTPx": ["Server error (HTTP ", ["status"], ")"],
"d5rK4X": [["chars", "plural", { "one": ["char"], "other": ["chars"] }]],
+ "d7WfDG": ["Include detailed diagnostics"],
"dD7NPy": ["Outline"],
"dDpCOp": ["Rename succeeded but the sidebar may be out of date — refresh to resync"],
"dEgA5A": ["Cancel"],
@@ -1751,6 +1809,7 @@
"</1>. Your current content is already saved in the timeline — you can restore it anytime."
],
"h7FzJC": ["Link-graph response did not match expected shape."],
+ "h7jL_x": ["App & system info, recent app logs, project server logs"],
"h9QFb9": ["Skill \"", ["0"], "\" deleted"],
"hBMK4W": ["Project templates"],
"hCOLSd": [
@@ -1824,6 +1883,7 @@
"iXTp5j": ["Scope: "],
"idD8Ev": ["Saved"],
"ig5vUe": ["Failed to load file"],
+ "ii5mVn": ["Report this error"],
"iilQXA": ["Folder duplicated"],
"ijLc3m": ["Bullet list"],
"ilodsp": ["Let agents use OpenKnowledge without asking"],
@@ -1878,6 +1938,7 @@
"k4CuuV": [
"Ready-made folders and templates to get you started quickly. Select a pack to preview what gets created, then add it to your project."
],
+ "k7VziB": ["Copy report reference"],
"kCNU4q": [
"Indexing your pages — ",
["semanticIndexedCount"],
@@ -1929,6 +1990,7 @@
"l8G3S9": ["Auto-sync is off — you don't have permission to push to this repo"],
"lAiyU_": ["Only the current document uses <0>#", ["tag"], "</0>."],
"lCC_D5": ["Subscribing..."],
+ "lDqYpA": ["Include crash dump"],
"lGs_bQ": ["Page <0>*</0>"],
"lHCR4I": ["Clear the field to reset back to the default OpenAI endpoint."],
"lHwYMr": ["Server error: ", ["status"], " ", ["statusText"]],
@@ -2055,6 +2117,7 @@
"Git identity isn't set — commits use a default author. Set yours so teammates see your name."
],
"nskygk": ["Choose agent"],
+ "nwtY4N": ["Something went wrong"],
"nxlOpL": ["OpenKnowledge is using this GitHub account."],
"ny6vNn": [
"OpenKnowledge is using a GitHub account provided by the gh CLI. There's no separate OpenKnowledge credential to disconnect."
@@ -2097,6 +2160,9 @@
"You picked ~/Documents. OpenKnowledge will index every markdown file under it. If you only want to manage a sub-folder, choose a smaller scope."
],
"ogAuyr": ["Back to document view"],
+ "olTIwK": [
+ "Secrets like API keys and tokens are redacted automatically. You'll review the report before it's sent."
+ ],
"omXJcU": ["Close others"],
"optX0N": [["0"], "h ago"],
"oqB2ez": ["Previous match"],
@@ -2169,6 +2235,7 @@
"qiRoLb": ["Summarize everything I changed this week"],
"qioCwA": ["Jump to page ", ["pageNumber"]],
"qjHMHf": ["Failed to disable sync — ", ["detail"]],
+ "qmL1UG": ["Uploading securely"],
"qo4zCg": ["Path cannot contain backslashes"],
"qpQwGC": ["Describe what you're working on and the agent sets it up for you."],
"qvWGzP": ["Collapse all"],
@@ -2247,6 +2314,12 @@
"Open an additional terminal tab. With text selected, stage it in the new tab's AI input."
],
"skf5Ix": ["Indent or outdent source editor lines."],
+ "sn5BEU": [
+ ["sizeText"],
+ " · secrets redacted · ",
+ ["fileCount", "plural", { "one": ["#", " file"], "other": ["#", " files"] }],
+ " · crash dump not redacted"
+ ],
"snrVQ7": ["probe failed"],
"ssuwjF": ["Branch"],
"stlgky": [
@@ -2375,6 +2448,7 @@
"wQp1V3": ["Mirror of <0>", ["src"], "</0>"],
"wT4iQr": ["Open visual-editor find with replace controls expanded."],
"wTcjov": ["No workspace"],
+ "wVa83H": ["Couldn't create the report"],
"wXO4Tg": [["hrs"], "h ago"],
"w_Sphq": ["Attachments"],
"wbv9xO": ["Create new project"],
@@ -2471,6 +2545,7 @@
"yYR6za": ["Display text"],
"yZmvQ4": ["This project's server (v", ["0"], ") is newer than this app (v", ["1"], ")."],
"y_5CE8": ["Item ", ["0"]],
+ "y_K0Dz": ["What happened?"],
"yaPGPa": ["Open a project to manage its AI tool connections."],
"yf5r22": [
["keyName"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index f0b05ff89..39365fa8a 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -82,6 +82,10 @@ msgstr "(no id)"
msgid "(opens in new tab)"
msgstr "(opens in new tab)"
+#: src/components/ReportBugDialogBody.tsx
+msgid "(optional)"
+msgstr "(optional)"
+
#. Scope tag next to an AI tool — config is written at both project and user level
#: src/components/ConsentDialogBody.tsx
msgid "(project + user)"
@@ -154,6 +158,11 @@ msgstr "{0, plural, one {Folder} other {Folders}}"
msgid "{0} templates available"
msgstr "{0} templates available"
+#. placeholder {0}: formatSize(phase.report.zipSizeBytes)
+#: src/components/ReportBugDialogBody.tsx
+msgid "{0} total"
+msgstr "{0} total"
+
#. placeholder {0}: share.owner
#. placeholder {1}: share.repo
#. placeholder {2}: shareTargetPath(share.target)
@@ -413,6 +422,22 @@ msgstr "{settingsDescriptorLabel} properties"
msgid "{shareBranch} isn't a valid branch name."
msgstr "{shareBranch} isn't a valid branch name."
+#: src/components/ReportBugDialogBody.tsx
+msgid "{sizeText} · secrets redacted"
+msgstr "{sizeText} · secrets redacted"
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"
+msgstr "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}} · crash dump not redacted"
+msgstr "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}} · crash dump not redacted"
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "{sizeText} · secrets redacted · crash dump not redacted"
+msgstr "{sizeText} · secrets redacted · crash dump not redacted"
+
#: src/components/CreatedItemsList.tsx
msgid "{skillCount, plural, one {skill} other {skills}}"
msgstr "{skillCount, plural, one {skill} other {skills}}"
@@ -532,6 +557,10 @@ msgstr "A knowledge base that follows Google's Open Knowledge Format, a shared w
msgid "A line with a footnote<0><1>[1]</1></0> and a definition shown below."
msgstr "A line with a footnote<0><1>[1]</1></0> and a definition shown below."
+#: src/components/ReportBugDialogBody.tsx
+msgid "A memory snapshot from the crash. It can contain document content and can't be redacted — leave off unless you're comfortable sharing it."
+msgstr "A memory snapshot from the crash. It can contain document content and can't be redacted — leave off unless you're comfortable sharing it."
+
#: src/components/ShareReceiveDialog.tsx
msgid "A network problem or GitHub outage interrupted the clone."
msgstr "A network problem or GitHub outage interrupted the clone."
@@ -557,6 +586,10 @@ msgstr "A pull quote stands out from the surrounding text."
msgid "A real shell is off for this project. Turning it on runs commands with the full access of your macOS user account."
msgstr "A real shell is off for this project. Turning it on runs commands with the full access of your macOS user account."
+#: src/components/ReportBugDialogBody.tsx
+msgid "A report helps us find the cause. Nothing is sent until you review it."
+msgstr "A report helps us find the cause. Nothing is sent until you review it."
+
#: src/components/NewTemplateDialog.tsx
msgid "A reusable starting point for new documents in this folder."
msgstr "A reusable starting point for new documents in this folder."
@@ -760,6 +793,10 @@ msgstr "Adds a managed block to"
msgid "Adds a managed block to {0}"
msgstr "Adds a managed block to {0}"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Adds telemetry, server state, and runtime info when available. Document names are anonymized."
+msgstr "Adds telemetry, server state, and runtime info when available. Document names are anonymized."
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Adds the OpenKnowledge skill to the <0>Claude Desktop App</0> so it's available in Chat and Cowork sessions."
msgstr "Adds the OpenKnowledge skill to the <0>Claude Desktop App</0> so it's available in Chat and Cowork sessions."
@@ -838,6 +875,7 @@ msgstr "Already open"
msgid "Already set up — ok is available in your terminal"
msgstr "Already set up — ok is available in your terminal"
+#: src/components/AppErrorBoundary.tsx
#: src/components/DocumentErrorBoundary.tsx
msgid "An unexpected error occurred."
msgstr "An unexpected error occurred."
@@ -862,6 +900,14 @@ msgstr "Anyone can see"
msgid "API key set"
msgstr "API key set"
+#: src/components/ReportBugDialogBody.tsx
+msgid "App & system info, recent app logs — no project is open, so no project logs are included."
+msgstr "App & system info, recent app logs — no project is open, so no project logs are included."
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "App & system info, recent app logs, project server logs"
+msgstr "App & system info, recent app logs, project server logs"
+
#: src/components/CreatedItemsList.tsx
msgid "Append-only log of what changed."
msgstr "Append-only log of what changed."
@@ -933,6 +979,10 @@ msgstr "Asset reference"
msgid "Asset: {title}"
msgstr "Asset: {title}"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Attach the file in an email to <0>[email protected]</0>"
+msgstr "Attach the file in an email to <0>[email protected]</0>"
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Attachments"
msgstr "Attachments"
@@ -999,6 +1049,7 @@ msgstr "Available in every project on this computer."
msgid "Available in the OpenKnowledge desktop app. From a terminal, use<0> ok config-sharing status</0> / <1>share</1> / <2>unshare</2>."
msgstr "Available in the OpenKnowledge desktop app. From a terminal, use<0> ok config-sharing status</0> / <1>share</1> / <2>unshare</2>."
+#: src/components/ReportBugDialogBody.tsx
#: src/components/SeedDialog.tsx
msgid "Back"
msgstr "Back"
@@ -1137,6 +1188,14 @@ msgstr "Browse folder"
msgid "Browse your repos:"
msgstr "Browse your repos:"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Bug report {reference}"
+msgstr "Bug report {reference}"
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Bug reporting needs the OpenKnowledge desktop app."
+msgstr "Bug reporting needs the OpenKnowledge desktop app."
+
#: src/components/empty-state/use-create-suggestions.ts
msgid "Build a competitor research knowledge base. Start with an overview page, then add cross-linked pages for each competitor, their products and pricing, and the sources behind every claim."
msgstr "Build a competitor research knowledge base. Start with an overview page, then add cross-linked pages for each competitor, their products and pricing, and the sources behind every claim."
@@ -1196,6 +1255,7 @@ msgstr "Can't safely edit this tool's config"
#: src/components/NewTemplateDialog.tsx
#: src/components/NewWorktreeDialog.tsx
#: src/components/PublishToGitHubDialog.tsx
+#: src/components/ReportBugDialogBody.tsx
#: src/components/SeedDialog.tsx
#: src/components/settings/SearchSection.tsx
#: src/components/ShareBranchSwitchDialog.tsx
@@ -1386,6 +1446,7 @@ msgstr "Cloning..."
#: src/components/EditorTabs.tsx
#: src/components/InstallInClaudeDesktopDialog.tsx
+#: src/components/ReportBugDialogBody.tsx
#: src/components/SeedDialog.tsx
#: src/components/SubscribeForm.tsx
#: src/components/ui/dialog.tsx
@@ -1702,6 +1763,7 @@ msgstr "Convert the current block to a paragraph."
#: src/components/empty-state/CopyablePromptList.tsx
#: src/components/InstallInClaudeDesktopDialog.tsx
+#: src/components/ReportBugDialogBody.tsx
#: src/editor/extensions/CodeBlockView.tsx
msgid "Copied"
msgstr "Copied"
@@ -1720,6 +1782,10 @@ msgstr "Copied path"
msgid "Copied relative path"
msgstr "Copied relative path"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Copied report reference"
+msgstr "Copied report reference"
+
#: src/components/CopyButton.tsx
msgid "Copied!"
msgstr "Copied!"
@@ -1727,6 +1793,7 @@ msgstr "Copied!"
#: src/components/CopyButton.tsx
#: src/components/empty-state/CopyablePromptList.tsx
#: src/components/InstallInClaudeDesktopDialog.tsx
+#: src/components/ReportBugDialogBody.tsx
msgid "Copy"
msgstr "Copy"
@@ -1771,6 +1838,10 @@ msgstr "Copy path"
msgid "Copy Path"
msgstr "Copy Path"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Copy report reference"
+msgstr "Copy report reference"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Copy selected file or folder"
msgstr "Copy selected file or folder"
@@ -1950,6 +2021,10 @@ msgstr "Couldn't create skill: {0}"
msgid "Couldn't create template: {error}"
msgstr "Couldn't create template: {error}"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Couldn't create the report"
+msgstr "Couldn't create the report"
+
#: src/components/NewWorktreeDialog.tsx
msgid "Couldn't create the worktree. Try a different name."
msgstr "Couldn't create the worktree. Try a different name."
@@ -2102,6 +2177,10 @@ msgstr "Couldn't save the key — please try again."
msgid "Couldn't save the resolution for {filePath}."
msgstr "Couldn't save the resolution for {filePath}."
+#: src/components/ReportBugDialogBody.tsx
+msgid "Couldn't send the report"
+msgstr "Couldn't send the report"
+
#: src/components/handoff/EditWithAiPopover.tsx
msgid "Couldn't send the selection — please try again."
msgstr "Couldn't send the selection — please try again."
@@ -2193,6 +2272,10 @@ msgstr "Create new tag #{tagValue}"
msgid "Create page"
msgstr "Create page"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Create report"
+msgstr "Create report"
+
#: src/components/NewSkillDialog.tsx
msgid "Create skill"
msgstr "Create skill"
@@ -2415,6 +2498,10 @@ msgstr "Detached HEAD — checkout a branch to resume"
msgid "Details"
msgstr "Details"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Details about the error you just hit are included."
+msgstr "Details about the error you just hit are included."
+
#: src/components/settings/SkillTargetsPicker.tsx
msgid "Detected from the editors this project is set up for. Adjust to control where every skill installs."
msgstr "Detected from the editors this project is set up for. Adjust to control where every skill installs."
@@ -2553,6 +2640,7 @@ msgstr "Don't see <0>Skills</0>? Enable <1>Settings <2/> Capabilities <3/> Code
#: src/components/InstallInClaudeDesktopDialog.tsx
#: src/components/PublishToGitHubDialog.tsx
+#: src/components/ReportBugDialogBody.tsx
#: src/editor/extensions/JsxComponentView.tsx
#: src/editor/slash-command/items.tsx
msgid "Done"
@@ -2638,6 +2726,14 @@ msgstr "e.g. drafts/ or *.draft.md"
msgid "e.g. server.ts"
msgstr "e.g. server.ts"
+#: src/components/ReportBugDialogBody.tsx
+msgid "e.g. Switching projects while a sync was running"
+msgstr "e.g. Switching projects while a sync was running"
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "e.g. The editor froze after I pasted a large table"
+msgstr "e.g. The editor froze after I pasted a large table"
+
#: src/components/CreateProjectDialog.tsx
msgid "Each selected tool gets an OpenKnowledge MCP entry."
msgstr "Each selected tool gets an OpenKnowledge MCP entry."
@@ -3655,6 +3751,14 @@ msgstr "In a subfolder"
msgid "In the Claude Desktop App"
msgstr "In the Claude Desktop App"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Include crash dump"
+msgstr "Include crash dump"
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Include detailed diagnostics"
+msgstr "Include detailed diagnostics"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Indent or outdent list item"
msgstr "Indent or outdent list item"
@@ -4778,6 +4882,7 @@ msgstr "Not in sidebar"
msgid "Not installed"
msgstr "Not installed"
+#: src/components/ReportBugDialogBody.tsx
#: src/components/SkillsSidebarSection.tsx
#: src/lib/install-server-drift-listener.ts
msgid "Not now"
@@ -4791,6 +4896,10 @@ msgstr "Nothing set yet."
msgid "Nothing to undo on this file"
msgstr "Nothing to undo on this file"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Nothing was uploaded — the report stays on this Mac until you email it to us."
+msgstr "Nothing was uploaded — the report stays on this Mac until you email it to us."
+
#: src/editor/slash-command/component-items.tsx
msgid "Notion-style inline row for a downloadable file. Drag-drop also works."
msgstr "Notion-style inline row for a downloadable file. Drag-drop also works."
@@ -4969,6 +5078,10 @@ msgstr "Open delete confirmation for the selected file-tree items."
msgid "Open documents tagged #{chip}"
msgstr "Open documents tagged #{chip}"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Open email draft"
+msgstr "Open email draft"
+
#: src/editor/extensions/JsxComponentView.tsx
msgid "Open embedded URL in new tab"
msgstr "Open embedded URL in new tab"
@@ -4993,6 +5106,10 @@ msgstr "Open folder"
msgid "Open folder on disk"
msgstr "Open folder on disk"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Open GitHub issue"
+msgstr "Open GitHub issue"
+
#: src/components/CommandPalette.tsx
msgid "Open graph"
msgstr "Open graph"
@@ -5148,6 +5265,10 @@ msgstr "OpenKnowledge is using a GitHub account provided by the gh CLI. There's
msgid "OpenKnowledge is using this GitHub account."
msgstr "OpenKnowledge is using this GitHub account."
+#: src/components/ReportBugDialogBody.tsx
+msgid "OpenKnowledge quit unexpectedly last time."
+msgstr "OpenKnowledge quit unexpectedly last time."
+
#: src/components/ConsentDialogBody.tsx
msgid "OpenKnowledge stores its configuration and internal files inside a newly created <0>.ok</0> directory in your project root folder."
msgstr "OpenKnowledge stores its configuration and internal files inside a newly created <0>.ok</0> directory in your project root folder."
@@ -5177,6 +5298,10 @@ msgstr "or create a new file <0/>"
msgid "Or use a starter pack"
msgstr "Or use a starter pack"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Or write to <0>[email protected]</0>"
+msgstr "Or write to <0>[email protected]</0>"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Ordered list"
msgstr "Ordered list"
@@ -5218,6 +5343,10 @@ msgstr "Outline"
msgid "Owner"
msgstr "Owner"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Package logs and system info into a report you can review, then send it privately to the OpenKnowledge team."
+msgstr "Package logs and system info into a report you can review, then send it privately to the OpenKnowledge team."
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/link-path-suggestions.tsx
msgid "Page"
@@ -5847,6 +5976,24 @@ msgstr "Replace key"
msgid "Replace the active match from the replace field."
msgstr "Replace the active match from the replace field."
+#: src/components/CommandPalette.tsx
+#: src/components/ReportBugDialogBody.tsx
+msgid "Report a bug"
+msgstr "Report a bug"
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Report reference: {reference}"
+msgstr "Report reference: {reference}"
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Report sent — thank you"
+msgstr "Report sent — thank you"
+
+#: src/components/AppErrorBoundary.tsx
+#: src/components/DocumentErrorBoundary.tsx
+msgid "Report this error"
+msgstr "Report this error"
+
#: src/components/settings/AccountSection.tsx
msgid "Repositories you've already cloned may keep syncing through git's own saved credentials, even after you disconnect."
msgstr "Repositories you've already cloned may keep syncing through git's own saved credentials, even after you disconnect."
@@ -6001,6 +6148,7 @@ msgstr "Reveal in File Explorer, {hint}"
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
+#: src/components/ReportBugDialogBody.tsx
#: src/components/skill-actions.tsx
msgid "Reveal in Finder"
msgstr "Reveal in Finder"
@@ -6021,6 +6169,10 @@ msgstr "Reverts every change this agent made to <0>{docName}</0> this session ({
msgid "Review conflicts"
msgstr "Review conflicts"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Review your report"
+msgstr "Review your report"
+
#: src/editor/slash-command/items.tsx
msgid "Role"
msgstr "Role"
@@ -6186,6 +6338,10 @@ msgstr "Searching docs"
msgid "Second item"
msgstr "Second item"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Secrets like API keys and tokens are redacted automatically. You'll review the report before it's sent."
+msgstr "Secrets like API keys and tokens are redacted automatically. You'll review the report before it's sent."
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/extensions/WikiLinkPropPanel.tsx
msgid "Section <0>(optional heading anchor)</0>"
@@ -6263,10 +6419,26 @@ msgstr "Semantic search adds meaning-based ranking to the search tool so concept
msgid "Semantic search is on, but no API key is set — search falls back to keyword matching. Add one in <0>Settings → Account</0> (it's stored once for your whole machine)."
msgstr "Semantic search is on, but no API key is set — search falls back to keyword matching. Add one in <0>Settings → Account</0> (it's stored once for your whole machine)."
+#: src/components/ReportBugDialogBody.tsx
+msgid "Send report"
+msgstr "Send report"
+
#: src/components/handoff/EditWithAiPopover.tsx
msgid "Send to"
msgstr "Send to"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Send your report by email"
+msgstr "Send your report by email"
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Sending report"
+msgstr "Sending report"
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Sent privately to the OpenKnowledge team, along with your note and app version. Never posted publicly."
+msgstr "Sent privately to the OpenKnowledge team, along with your note and app version. Never posted publicly."
+
#: src/editor/slash-command/items.tsx
msgid "Separator"
msgstr "Separator"
@@ -6601,6 +6773,10 @@ msgstr "Slash commands"
msgid "Small section heading."
msgstr "Small section heading."
+#: src/components/AppErrorBoundary.tsx
+msgid "Something went wrong"
+msgstr "Something went wrong"
+
#: src/components/settings/SettingsDialogErrorBoundary.tsx
msgid "Something went wrong loading the settings panel."
msgstr "Something went wrong loading the settings panel."
@@ -6925,6 +7101,10 @@ msgstr "tag-name"
msgid "Tags matching \"{tagListQuery}\""
msgstr "Tags matching \"{tagListQuery}\""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Take a look if you'd like — this exact file is what we receive."
+msgstr "Take a look if you'd like — this exact file is what we receive."
+
#: src/components/SeedDialog.tsx
msgid "Take a piece of writing from a rough idea to a finished draft to something you're ready to share. Good for blog posts, essays, or anything you want to move through clear stages."
msgstr "Take a piece of writing from a rough idea to a finished draft to something you're ready to share. Good for blog posts, essays, or anything you want to move through clear stages."
@@ -7102,6 +7282,10 @@ msgstr "The preview blocks resources that don't meet its security rules (for exa
msgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."
msgstr "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."
+#: src/components/ReportBugDialogBody.tsx
+msgid "The report service couldn't be reached."
+msgstr "The report service couldn't be reached."
+
#: src/components/ShareReceiveDialog.tsx
msgid "The repository is private and your GitHub account doesn't have access to it."
msgstr "The repository is private and your GitHub account doesn't have access to it."
@@ -7447,8 +7631,10 @@ msgstr "Tree view options"
msgid "Try a prompt"
msgstr "Try a prompt"
+#: src/components/AppErrorBoundary.tsx
#: src/components/DocumentErrorBoundary.tsx
#: src/components/InstallInClaudeDesktopDialog.tsx
+#: src/components/ReportBugDialogBody.tsx
#: src/components/settings/AccountSection.tsx
#: src/components/ShareReceiveDialog.tsx
msgid "Try again"
@@ -7707,6 +7893,10 @@ msgstr "Uploading {keyName}"
msgid "Uploading file"
msgstr "Uploading file"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Uploading securely"
+msgstr "Uploading securely"
+
#: src/components/TimelinePanel.tsx
msgid "Upstream sync"
msgstr "Upstream sync"
@@ -7814,6 +8004,10 @@ msgstr "Visual editor table selection"
msgid "Waiting for authorization"
msgstr "Waiting for authorization"
+#: src/components/ReportBugDialogBody.tsx
+msgid "Want to follow along? Open a GitHub issue and mention your reference."
+msgstr "Want to follow along? Open a GitHub issue and mention your reference."
+
#: src/components/settings/AccountSection.tsx
msgid "We couldn't check your GitHub connection."
msgstr "We couldn't check your GitHub connection."
@@ -7830,6 +8024,10 @@ msgstr "We'll build <0>openknowledge.skill</0>, save it to <1>~/Downloads</1>, a
msgid "We'll create a repository and start syncing — no terminal needed."
msgstr "We'll create a repository and start syncing — no terminal needed."
+#: src/components/ReportBugDialogBody.tsx
+msgid "We've filed it with the team and attached your logs."
+msgstr "We've filed it with the team and attached your logs."
+
#: src/components/HelpPopover.tsx
msgid "Website"
msgstr "Website"
@@ -7850,6 +8048,10 @@ msgstr "What do you want to build?"
msgid "What gets created"
msgstr "What gets created"
+#: src/components/ReportBugDialogBody.tsx
+msgid "What happened?"
+msgstr "What happened?"
+
#: src/components/EmptyEditorState.tsx
msgid "What is a starter pack?"
msgstr "What is a starter pack?"
@@ -7876,6 +8078,10 @@ msgstr "What this changes"
msgid "What this checkbox changes"
msgstr "What this checkbox changes"
+#: src/components/ReportBugDialogBody.tsx
+msgid "What were you doing?"
+msgstr "What were you doing?"
+
#: src/components/empty-state/empty-state-copy.ts
msgid "What would you like to create?"
msgstr "What would you like to create?"
@@ -7979,6 +8185,10 @@ msgstr "writing"
msgid "yesterday"
msgstr "yesterday"
+#: src/components/ReportBugDialogBody.tsx
+msgid "You can also create one from a terminal with <0>ok bug-report</0>."
+msgstr "You can also create one from a terminal with <0>ok bug-report</0>."
+
#: src/components/TerminalGate.tsx
msgid "You can also manage this in Settings."
msgstr "You can also manage this in Settings."
@@ -8076,6 +8286,18 @@ msgstr "Your local copy is behind. Pull the latest changes, then open the link a
msgid "Your local copy of branch <0>{branch}</0> is behind. Pull the latest changes, then open the link again."
msgstr "Your local copy of branch <0>{branch}</0> is behind. Pull the latest changes, then open the link again."
+#: src/components/ReportBugDialogBody.tsx
+msgid "Your report couldn't be sent — try again or email it instead."
+msgstr "Your report couldn't be sent — try again or email it instead."
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Your report is being sent."
+msgstr "Your report is being sent."
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Your report is saved on this Mac — nothing was lost. You can email it to us instead."
+msgstr "Your report is saved on this Mac — nothing was lost. You can email it to us instead."
+
#: src/components/CloneDialog.tsx
msgid "Your repositories"
msgstr "Your repositories"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index d5a2313c1..ae2b3ee77 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -11,6 +11,7 @@
"-3ois8": ["Ĥàŕď ƀŕēàķ"],
"-5jISU": [["0", "plural", { "one": ["#", " ţēḿƥĺàţē"], "other": ["#", " ţēḿƥĺàţēś"] }]],
"-8PP0T": ["Ḿàţćĥ ćàśē"],
+ "-9ErB5": ["Ćōƥĩēď ŕēƥōŕţ ŕēƒēŕēńćē"],
"-K0AvT": ["Ďĩśćōńńēćţ"],
"-LHLx7": ["ēďĩţēď ţēḿƥĺàţē"],
"-QCLWk": ["Ţēḿƥĺàţēś àvàĩĺàƀĺē"],
@@ -21,6 +22,9 @@
"-gdcIo": ["Àũţō-śŷńć ĩś ōń — ŷōũŕ ćōḿḿĩţś ƥũśĥ àńď ŕēḿōţē ćĥàńĝēś ƥũĺĺ ōń ĩńţēŕvàĺś."],
"-i7ik4": ["Ćōĺĺàƥśē ƀũŕśţ ", ["burstNumber"], " ďĩƒƒ"],
"-lCAuQ": ["Ĺōàďĩńĝ ĝŕàƥĥ"],
+ "-o5XAG": [
+ "Śēńţ ƥŕĩvàţēĺŷ ţō ţĥē ŌƥēńĶńōŵĺēďĝē ţēàḿ, àĺōńĝ ŵĩţĥ ŷōũŕ ńōţē àńď àƥƥ vēŕśĩōń. Ńēvēŕ ƥōśţēď ƥũƀĺĩćĺŷ."
+ ],
"-q4abP": [
"Ŕēśũĺţś ćàƥƥēď — ţĥĩś ŵōŕķśƥàćē ĥàś ḿōŕē ƒĩĺēś ţĥàń śēàŕćĥ ćàń ĩńďēx. À ḿĩśśĩńĝ ƒĩĺē ḿàŷ ƀē à ćàƥ àŕţĩƒàćţ, ńōţ à ţŷƥō."
],
@@ -35,6 +39,7 @@
"0-31GV": ["Ŕēḿōvĩńĝ"],
"00c7t0": ["Àśķ ÀĨ àƀōũţ ţĥĩś ćōďē ƀĺōćķ"],
"02P3hL": ["Ũƥĺōàď ƒàĩĺēď: ", ["message"]],
+ "03wKPg": ["À ŕēƥōŕţ ĥēĺƥś ũś ƒĩńď ţĥē ćàũśē. Ńōţĥĩńĝ ĩś śēńţ ũńţĩĺ ŷōũ ŕēvĩēŵ ĩţ."],
"04RA0-": ["Ƒàĩĺēď ţō ēńàƀĺē śŷńć — ", ["detail"]],
"04XyCH": ["Àďďś à ḿàńàĝēď ƀĺōćķ ţō ", ["0"]],
"05n5wS": ["Ďōć ḿēńţĩōń śũĝĝēśţĩōńś"],
@@ -109,6 +114,7 @@
"28B21t": ["Àĝēńţ Śķĩĺĺś"],
"29VNqC": ["Ũńķńōŵń ēŕŕōŕ"],
"29XZXN": ["Śēţ ĝĩţ ĩďēńţĩţŷ"],
+ "2AIVbm": ["Ŕēvĩēŵ ŷōũŕ ŕēƥōŕţ"],
"2B6eYX": ["Ŵĥàţ ţĥĩś ćĥēćķƀōx ćĥàńĝēś"],
"2BBAbc": ["Ĺĩśţ"],
"2FYpfJ": ["Ḿōŕē"],
@@ -124,12 +130,14 @@
"2hYmUH": ["ḿŷ@ēḿàĩĺ.ćōḿ"],
"2hpdRq": ["Ĥĩďē ƥàńēĺ (", ["panelShortcutLabel"], ")"],
"2j1kfc": ["Ēńţēŕ à vàĺĩď ŨŔĹ (ƒōŕ ēxàḿƥĺē ĥţţƥś://àƥĩ.ōƥēńàĩ.ćōḿ/v1)."],
+ "2myNzt": ["Ŵē'vē ƒĩĺēď ĩţ ŵĩţĥ ţĥē ţēàḿ àńď àţţàćĥēď ŷōũŕ ĺōĝś."],
"2n3oDU": [
"ƤŕōĴēćţ-ĺēvēĺ ƥàĝēś ōŕďēŕēď ƀŷ ĩńƀōũńď ĺĩńķ ćōũńţ, ũƥ ţō ",
["FULLSCREEN_HUB_LIMIT"],
" ŕēśũĺţś."
],
"2q_Q7x": ["Vĩśĩƀĩĺĩţŷ"],
+ "2rQ8G4": ["Ōŕ ŵŕĩţē ţō <0>śũƥƥōŕţ@ĩńķēēƥ.ćōḿ</0>"],
"2ryd91": ["Ƒàĩĺēď ţō ŕēńàḿē ƥŕōƥēŕţŷ"],
"2tgFCe": ["Śţàŕţĩńĝ ćĺōńē"],
"2vIPtm": ["Ōƥēń ĺĩńķ ĩń ńēŵ ţàƀ"],
@@ -141,6 +149,11 @@
"379t2h": ["Ũńĩƒĩēď ďĩƒƒ"],
"38foVZ": ["Ĺōàďĩńĝ ďĩƒƒ"],
"3BnyYc": ["Ţĥĩś ďōć ĩśń'ţ ōń ĜĩţĤũƀ ŷēţ. Ţĥē ĺĩńķ ŵōń'ţ ŵōŕķ ũńţĩĺ ĩţ'ś ƥũśĥēď."],
+ "3DJEEt": [
+ ["sizeText"],
+ " · śēćŕēţś ŕēďàćţēď · ",
+ ["fileCount", "plural", { "one": ["#", " ƒĩĺē"], "other": ["#", " ƒĩĺēś"] }]
+ ],
"3DTatP": ["Ćōƥŷ à ƥŕōḿƥţ ƒōŕ ŷōũŕ àĝēńţ, śţàŕţ à ƀĺàńķ ƒĩĺē, ōŕ śćàƒƒōĺď ƒŕōḿ à ţēḿƥĺàţē."],
"3FMvls": ["À śĥōŕţ ĺĩńē śĥōŵń ũńďēŕ ţĥē ţĩţĺē ĩń ţĥē ţēḿƥĺàţē ĺĩśţ."],
"3Fcb0I": ["Ōƥēń ĝŕàƥĥ"],
@@ -213,6 +226,7 @@
"4nj6n8": ["/àƥĩ/ćōńƒĩĝ ŕēţũŕńēď ĤŢŢƤ ", ["code"]],
"4rjwLG": ["Ćŕēàţē ŵĩţĥ ", ["0"], " ĆĹĨ"],
"4sKwf6": ["Ƒĩĺē àĺŕēàďŷ ēxĩśţś"],
+ "4tOxNU": ["Ŕēƥōŕţ śēńţ — ţĥàńķ ŷōũ"],
"4uNLmk": ["Ƥũĺĺĩńĝ"],
"4v2Yyz": ["Śēĺēćţ ēvēŕŷ vĩśĩƀĺē ƒĩĺē-ţŕēē ŕōŵ ŵĥēń ƒōćũś ĩś ĩń ţĥē Ƒĩĺēś śĩďēƀàŕ."],
"4xtLTl": ["Ĥĩďďēń ƒōĺďēŕ “", ["basename"], "”"],
@@ -247,6 +261,7 @@
],
"5OTgC7": ["Ōƥēń àńď ƒōćũś ţĥē ƀōţţōḿ Àśķ ÀĨ ƥŕōḿƥţ ćōḿƥōśēŕ."],
"5OqaJi": ["Ēńţēŕ à ƥŕōĴēćţ ńàḿē"],
+ "5PHgV2": ["Ŷōũ ćàń àĺśō ćŕēàţē ōńē ƒŕōḿ à ţēŕḿĩńàĺ ŵĩţĥ <0>ōķ ƀũĝ-ŕēƥōŕţ</0>."],
"5QGTaA": ["Ćōũĺď ńōţ ćōƥŷ ŕēĺàţĩvē ƥàţĥ"],
"5SwVv1": ["Ńōţ ĩńśţàĺĺēď"],
"5Tk8Fb": ["Ĺōàďĩńĝ ƒĩĺēś"],
@@ -282,6 +297,7 @@
"5wV2qQ": ["àńď ḿōŕē"],
"5y_9lO": ["Ŵàĩţĩńĝ ƒōŕ àũţĥōŕĩźàţĩōń"],
"6-wLTJ": [["behind"], " ƀēĥĩńď ōŕĩĝĩń"],
+ "60vpJN": ["Ŵĥàţ ŵēŕē ŷōũ ďōĩńĝ?"],
"62Pc08": ["Ĩńśţàĺĺ ƒōŕ Ćĺàũďē Ćĥàţ & Ćōŵōŕķ (Ďēśķţōƥ Àƥƥ)"],
"636K3K": ["Ďēĺēţē àďĴàćēńţ ćĥĩƥ"],
"67f-3g": ["Ďũƥĺĩćàţē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
@@ -324,6 +340,7 @@
"6s7LXO": ["Ĥēàďś ũƥ"],
"6u9LvN": [["days", "plural", { "one": ["#", " ďàŷ àĝō"], "other": ["#", " ďàŷś àĝō"] }]],
"6vEr3W": ["Ĺĩńķ ţàŕĝēţ"],
+ "6zzhQL": ["Śēńď ŷōũŕ ŕēƥōŕţ ƀŷ ēḿàĩĺ"],
"72xhRD": ["Ďĩàĝŕàḿ vĩēŵ ḿōďē"],
"74-bX-": ["À ƥũĺĺ ǫũōţē śţàńďś ōũţ ƒŕōḿ ţĥē śũŕŕōũńďĩńĝ ţēxţ."],
"74eHt-": ["Ńō ƒĩĺē ōŕ ƒōĺďēŕ śēĺēćţēď"],
@@ -366,6 +383,7 @@
["fileName"],
") ĩń ţĥē ƥŕōĴēćţ ŕōōţ"
],
+ "89y7ar": [["sizeText"], " · śēćŕēţś ŕēďàćţēď"],
"8F1i42": ["Ƥàĝē ńōţ ƒōũńď"],
"8FqTCr": [
[
@@ -443,6 +461,7 @@
"Ńō ćōĺĺàƀ śēŕvēŕ ƒōŕ ţĥĩś ŵōŕķţŕēē — ŕũń <0>ōķ śţàŕţ</0> ĥēŕē, ōŕ ŕēōƥēń ţĥē ƥŕōĴēćţ."
],
"AB4qw9": ["Ńēŵ ţēŕḿĩńàĺ"],
+ "ACCCV-": ["Ńōţĥĩńĝ ŵàś ũƥĺōàďēď — ţĥē ŕēƥōŕţ śţàŷś ōń ţĥĩś Ḿàć ũńţĩĺ ŷōũ ēḿàĩĺ ĩţ ţō ũś."],
"AE7BY3": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď."],
"AIn2Yv": [["displayName"], " ĆĹĨ, ", ["hint"]],
"AItsE5": ["Ōƥēń ĩţ ţĥēŕē"],
@@ -487,6 +506,7 @@
{ "one": ["#", " ƒĩĺē ćōńƒĺĩćţēď"], "other": ["#", " ƒĩĺēś ćōńƒĺĩćţēď"] }
]
],
+ "B7XVXd": ["Àţţàćĥ ţĥē ƒĩĺē ĩń àń ēḿàĩĺ ţō <0>śũƥƥōŕţ@ĩńķēēƥ.ćōḿ</0>"],
"BAH4qX": ["Śēĺēćţēď ĝŕàƥĥ ĩţēḿ"],
"BBqGS9": ["Ďēśķţōƥ"],
"BD0XSC": ["Ƒàĩĺēď ţō ĺōàď ƥŕōĴēćţ ţēḿƥĺàţēś"],
@@ -523,6 +543,7 @@
"COr1Y7": [
"Ƥĩćķ <0>ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0> ƒŕōḿ ŷōũŕ <1>Ďōŵńĺōàďś</1> ƒōĺďēŕ. Ĩţ ēńàƀĺēś àũţōḿàţĩćàĺĺŷ."
],
+ "CSIkhP": ["Ţàķē à ĺōōķ ĩƒ ŷōũ'ď ĺĩķē — ţĥĩś ēxàćţ ƒĩĺē ĩś ŵĥàţ ŵē ŕēćēĩvē."],
"CSL0l1": ["Ćōũĺďń'ţ ćĺēàŕ ţĥē ķēŷ — ƥĺēàśē ţŕŷ àĝàĩń."],
"CTJLpz": ["\"", ["trimmed"], "\" àĺŕēàďŷ ēxĩśţś ĥēŕē"],
"CU3AiE": ["Śŵĩţćĥĩńĝ ƀŕàńćĥēś"],
@@ -540,6 +561,9 @@
"Ck9XRt": ["Ćōũĺďń'ţ śàvē ţĥē ķēŷ — ƥĺēàśē ţŕŷ àĝàĩń."],
"CmeH9S": ["Àďď ƥŕōƥēŕţŷ ţō ", ["keyName"]],
"CoHvYd": ["Ḿōvēď ", ["0"], " ţō ƥōśĩţĩōń ", ["1"], " ōƒ ", ["2"]],
+ "Ct7b_s": [
+ "Ŷōũŕ ŕēƥōŕţ ĩś śàvēď ōń ţĥĩś Ḿàć — ńōţĥĩńĝ ŵàś ĺōśţ. Ŷōũ ćàń ēḿàĩĺ ĩţ ţō ũś ĩńśţēàď."
+ ],
"CvsD6Y": ["vĩà ", ["viaTags"]],
"D-Oh1s": ["Ĥōŵ ţō śēţ ũƥ ", ["0"], " (ōƥēńś ĩń ƀŕōŵśēŕ)"],
"D12vtS": ["(ďēţàćĥēď)"],
@@ -739,6 +763,7 @@
"Gp_twO": ["Ĺōćàĺ ƥàţĥ"],
"GsBUCk": ["Ĺōàďĩńĝ śēţţĩńĝś"],
"Gt4gOO": ["Ţĥĩś ƒōĺďēŕ ĥàś ũńƥũśĥēď ćĥàńĝēś. Ŕēćĩƥĩēńţś ŵĩĺĺ śēē ţĥē ĺàśţ ƥũśĥēď vēŕśĩōń."],
+ "GuaJb-": ["Ōƥēń ēḿàĩĺ ďŕàƒţ"],
"GubkSu": ["Ũśē à śţàŕţēŕ ƥàćķ"],
"GuqOb1": ["Ƒàĩĺēď ţō ĺōàď ĥēàďĩńĝś"],
"Gx0VS1": ["ē.ĝ. ďŕàƒţś/ ōŕ *.ďŕàƒţ.ḿď"],
@@ -783,6 +808,7 @@
"IA6JW2": ["Ďēţēćţĩńĝ"],
"ICoNYz": ["Ŷōũ ćàń àĺśō ḿàńàĝē ţĥĩś ĩń Śēţţĩńĝś."],
"IInnZo": ["Ćōńƒĺĩćţ"],
+ "IKkfn_": ["Ŕēƥōŕţ ŕēƒēŕēńćē: ", ["reference"]],
"IKoTAC": ["Ķēēƥ ďĩśàƀĺēď"],
"IN4UX8": ["Śēàŕćĥ (", ["searchShortcut"], ")"],
"IQPyrD": ["Ḿĩśśĩńĝ ƥàĝē — ćĺĩćķ ţō ćŕēàţē"],
@@ -812,6 +838,7 @@
"Ńō ďĩśćōńńēćţēď ƥàĝēś. Ƥàĝēś àƥƥēàŕ ĥēŕē ōńĺŷ ŵĥēń ţĥēŷ ĥàvē ńō ĩńćōḿĩńĝ àńď ńō ōũţĝōĩńĝ ĝŕàƥĥ ēďĝēś."
],
"JE21eh": ["Śŷḿĺĩńķ ţō ", ["targetPath"]],
+ "JJcBCm": [["0"], " ţōţàĺ"],
"JK-Ave": ["Ĥĩďē ţĥũḿƀńàĩĺś"],
"JL3si7": ["Ũƥďàţĩńĝ"],
"JLUTgi": ["Ńō ţàĝś ŷēţ — àũţĥōŕ `#ţàĝńàḿē` ĩń àńŷ ďōć ţō ƥōƥũĺàţē ţĥē ĩńďēx."],
@@ -930,6 +957,7 @@
"M3ytY_": [
"Ţĥĩś ĺōōķś ĺĩķē à ďŕĩvē ŕōōţ (ē.ĝ., Ć:\\). Śćàƒƒōĺďĩńĝ ĥēŕē ŵĩĺĺ śćàń àń ēńţĩŕē ďŕĩvē."
],
+ "M5_9s2": ["Śēńďĩńĝ ŕēƥōŕţ"],
"M5mfAe": ["Àďď ţàĝ"],
"M9597s": ["Ƥŕēƥàŕĩńĝ śĥàŕē ŨŔĹ..."],
"MCjC9A": ["Ďēĺēţē ", ["deleteDescriptorLabel"]],
@@ -938,6 +966,7 @@
"Ĩńśēŕţ, ďēĺēţē, ḿōvē, ćōƥŷ, àńď ĩńďēńţ śōũŕćē ēďĩţōŕ ĺĩńēś ţĥŕōũĝĥ ĆōďēḾĩŕŕōŕ'ś ďēƒàũĺţ ķēŷḿàƥ."
],
"MHrjPM": ["Ţĩţĺē"],
+ "MJqRO6": ["Ŷōũŕ ŕēƥōŕţ ĩś ƀēĩńĝ śēńţ."],
"MKOVhz": ["Ēńàƀĺē ĝĩţ àũţō-śŷńć"],
"MQIM_Y": ["Ćōũĺďń'ţ ćōƥŷ. Śēĺēćţ ţĥē ŨŔĹ àƀōvē ţō ćōƥŷ ĩţ ḿàńũàĺĺŷ."],
"MTs6g3": ["Ćōũĺďń'ţ ŕēćōńńēćţ àƒţēŕ śēŕvēŕ ŕēśţàŕţ"],
@@ -968,6 +997,7 @@
["0"],
" — ŷōũŕ ƥŕēvĩōũś vēŕśĩōń ĩś ĩń ĥĩśţōŕŷ ĩƒ ŷōũ ńēēď ţō ŕēśţōŕē ĩţ."
],
+ "N-eM-f": ["Ďēţàĩĺś àƀōũţ ţĥē ēŕŕōŕ ŷōũ Ĵũśţ ĥĩţ àŕē ĩńćĺũďēď."],
"N1KkEO": ["ĵũḿƥ ţō ĺàśţ ţàƀ"],
"N1YYa7": ["Ĺōàďĩńĝ ĩḿàĝē"],
"N1mdmS": ["Ţĥĩś ƒĩĺē ćàń'ţ ƀē ōƥēńēď ĩń ţĥē ţēxţ ēďĩţōŕ."],
@@ -1011,12 +1041,14 @@
"Nx7BWE": ["Ĝĩţ àũţō-śŷńć"],
"NxW-md": ["Ŕēśĩźē ", ["handleKey"]],
"NzFvyK": ["Śēśśĩōń ēńďēď — ũńďō ũńàvàĩĺàƀĺē"],
+ "NzluOx": ["(ōƥţĩōńàĺ)"],
"O0Z2Xr": ["Ōũţĝōĩńĝ"],
"O2UpM1": ["ßŕōŵśē"],
"O3oNi5": ["Ēḿàĩĺ"],
"O4PnDd": ["ÀĨ ţōōĺ ḿàńàĝēḿēńţ ĩś ōńĺŷ àvàĩĺàƀĺē ĩń ţĥē ŌƥēńĶńōŵĺēďĝē ďēśķţōƥ àƥƥ."],
"O6yEPk": ["Ćŕēàţē à ńēŵ ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţ ĩń ţĥē ƒōĺďēŕ ōƒ ŷōũŕ ćĥōĩćē."],
"O7_W_a": ["Ōƥēń ŵĩţĥ ÀĨ"],
+ "O9oQJS": ["Śēńď ŕēƥōŕţ"],
"OD0FCX": ["Ĥĩďďēń “", ["basename"], "”"],
"ODGGlj": ["Ƒōĺďēŕ ńàḿē: ", ["detail"]],
"OETysD": ["Ńō ĥũƀ ƥàĝēś ŷēţ. Ĥũƀś àƥƥēàŕ ōńćē ƥàĝēś àććũḿũĺàţē ĩńƀōũńď ĝŕàƥĥ ĺĩńķś."],
@@ -1028,6 +1060,9 @@
"OJeiSH": ["Ƒàĩĺēď ţō àďď ƥŕōƥēŕţŷ"],
"OLBz-_": ["Ḿēŕḿàĩď ďĩàĝŕàḿ ƒàĩĺēď ţō ŕēńďēŕ."],
"OLIKgw": ["Ďŕàĝ ĩţēḿ ", ["0"], " ţō ŕēōŕďēŕ"],
+ "OLt6sc": [
+ "Ƥàćķàĝē ĺōĝś àńď śŷśţēḿ ĩńƒō ĩńţō à ŕēƥōŕţ ŷōũ ćàń ŕēvĩēŵ, ţĥēń śēńď ĩţ ƥŕĩvàţēĺŷ ţō ţĥē ŌƥēńĶńōŵĺēďĝē ţēàḿ."
+ ],
"ONPvOb": ["Ĺōàďĩńĝ àĝēńţ àćţĩvĩţŷ"],
"ONgEZF": ["Ĺōàďĩńĝ ĥēàďĩńĝś ƒōŕ ", ["pageTarget"]],
"OOIVJo": ["Ũńĩńśţàĺĺēď \"", ["0"], "\" ƒŕōḿ ", ["1"]],
@@ -1037,6 +1072,7 @@
"OXb_Df": ["Śēţţĩńĝś ćōńţēńţ"],
"OYnx7O": ["Ƥàţĥ ćàńńōţ śţàŕţ ŵĩţĥ \"/\""],
"OZJeTZ": ["Śķĩĺĺ"],
+ "Oawo4U": ["Ţĥē ŕēƥōŕţ śēŕvĩćē ćōũĺďń'ţ ƀē ŕēàćĥēď."],
"OdmsFg": ["Ƒàĩĺēď ţō ďēĺēţē ĩţēḿ"],
"OeAl1e": ["ē.ĝ. àśśēţś/ũƥĺōàďś"],
"OgyJSr": ["Ĺōćàĺ ōńĺŷ"],
@@ -1091,6 +1127,7 @@
"PrJYSN": ["Ţĥĩś ƒōĺďēŕ ĩśń'ţ ōń ĜĩţĤũƀ ŷēţ. Ţĥē ĺĩńķ ŵōń'ţ ŵōŕķ ũńţĩĺ ĩţ'ś ƥũśĥēď."],
"PrhzDE": ["Ƥàń ũƥ"],
"Pyp1NA": ["Ŕēśţōŕē ţō ţĥĩś ƥōĩńţ?"],
+ "PzUvDM": ["ßũĝ ŕēƥōŕţ ", ["reference"]],
"Q5fqMz": ["Ćōńńēćţĩōń ēŕŕōŕ — ţŕŷ àĝàĩń"],
"Q6hhn8": ["Ƥŕēƒēŕēńćēś"],
"Q7W-mC": ["Śàḿē ƒōĺďēŕ àś ćũŕŕēńţ ƒĩĺē"],
@@ -1188,6 +1225,7 @@
"SfxQX8": ["Ŵŕĩţēś à ƥŕōĴēćţ-ḾĆƤ ćōńƒĩĝ ƒōŕ ēàćĥ śēĺēćţēď ţōōĺ."],
"SgKLfA": ["Ńōţ ćōńńēćţēď ţō ĜĩţĤũƀ."],
"Sh3Qkg": ["Ńō ḿàţćĥĩńĝ ƀŕàńćĥēś."],
+ "Si7mIR": ["Ćŕēàţē ŕēƥōŕţ"],
"SiUUCS": ["Ńēxţ ḿàţćĥ"],
"SkMZlS": ["Ćōũĺďń'ţ ŕēḿōvē <0>", ["targetGitPath"], "</0>: ", ["removeGitError"]],
"Skr_7L": ["Śēàŕćĥ ŵōŕķţŕēēś"],
@@ -1195,6 +1233,7 @@
"SrOuyg": ["Ďōćũḿēńţ ƥàńēĺś"],
"T-654M": ["Ĺōàďĩńĝ ƤĎƑ"],
"T0OVm7": ["Ţĥē ďēƒàũĺţ ƀŕàńćĥ ĩś ƥŕōţēćţēď — ƥũśĥēś ńēēď à ƥũĺĺ ŕēǫũēśţ."],
+ "T3j-7o": ["ē.ĝ. Śŵĩţćĥĩńĝ ƥŕōĴēćţś ŵĥĩĺē à śŷńć ŵàś ŕũńńĩńĝ"],
"T67A0Y": [
"Àũţō-śŷńć ƥũśĥēś/ƥũĺĺś ćōḿḿĩţś ţō ŷōũŕ ĝĩţ ŕēḿōţē ōń ĩńţēŕvàĺś àńď ōń śàvē. Ţōĝĝĺĩńĝ ōń ŕēǫũĩŕēś ćōńƒĩŕḿàţĩōń."
],
@@ -1219,6 +1258,9 @@
"UBv8UK": ["Ďēĺēţē Ƥēŕḿàńēńţĺŷ"],
"UDFrWm": ["Ćĥēćķĩńĝ ĜĩţĤũƀ ćōńńēćţĩōń..."],
"UL8A9w": ["Ţàĝ"],
+ "ULRb5t": [
+ "Àďďś ţēĺēḿēţŕŷ, śēŕvēŕ śţàţē, àńď ŕũńţĩḿē ĩńƒō ŵĥēń àvàĩĺàƀĺē. Ďōćũḿēńţ ńàḿēś àŕē àńōńŷḿĩźēď."
+ ],
"UMrOy2": ["Śķĩĺĺ \"", ["trimmedName"], "\" ćŕēàţēď"],
"UPjaXD": ["Ćōũĺďń'ţ ďũƥĺĩćàţē \"", ["0"], "\": ", ["1"]],
"UQAp48": ["Śēàŕćĥ ţēḿƥĺàţēś"],
@@ -1305,6 +1347,7 @@
"WALN45": ["Śŵĩţćĥ ţō ", ["shareBranch"]],
"WHPvOb": ["Àĺĺ ƒĩĺēś àŕē ĥĩďďēń ƀŷ vĩēŵ ƒĩĺţēŕś."],
"WL6puM": ["Ƥàţĥ ŕēśōĺvēś ōũţśĩďē ƥŕōĴēćţ"],
+ "WM-NnH": ["Ŷōũŕ ŕēƥōŕţ ćōũĺďń'ţ ƀē śēńţ — ţŕŷ àĝàĩń ōŕ ēḿàĩĺ ĩţ ĩńśţēàď."],
"WMIKXK": [
"Àŕē ŷōũ śũŕē ŷōũ ŵàńţ ţō ďēĺēţē ",
["targetCount"],
@@ -1328,6 +1371,7 @@
"Wgmlsw": ["Ƒēţćĥĩńĝ"],
"Wh0im4": ["ēďĩţĩńĝ [[", ["realCurrentDoc"], "]]"],
"WhOsNE": ["Śţŕĩķēţĥŕōũĝĥ"],
+ "Wi-VWy": ["Ćōũĺďń'ţ śēńď ţĥē ŕēƥōŕţ"],
"WkTLN7": ["Śĥōŵ ōńĺŷ ḿàŕķďōŵń ƒĩĺēś"],
"WmPbvm": ["Ĝēţ ƥŕōďũćţ ũƥďàţēś ĩń ŷōũŕ ĩńƀōx."],
"Wq6Wcm": ["Ƥĺēàśē ēńţēŕ à vàĺĩď ēḿàĩĺ àďďŕēśś."],
@@ -1345,6 +1389,7 @@
"XDzAnp": ["Ōƥēńś ĩń à ńēŵ ţàƀ"],
"XH30C4": ["ďōćũḿēńţ"],
"XJOV1Y": ["Àćţĩvĩţŷ"],
+ "XLfzgb": ["Ŵàńţ ţō ƒōĺĺōŵ àĺōńĝ? Ōƥēń à ĜĩţĤũƀ ĩśśũē àńď ḿēńţĩōń ŷōũŕ ŕēƒēŕēńćē."],
"XPJ0sN": [["settingsDescriptorLabel"], " ƥŕōƥēŕţĩēś"],
"XPqe3B": ["Ćŕēàţē ńēŵ ţàĝ #", ["tagValue"]],
"XRuL0i": ["Ćŕēàţē ƥàĝē"],
@@ -1387,6 +1432,7 @@
"YGIi_c": ["Ŕēĩńśţàĺĺ"],
"YJ1BTp": ["À śķĩĺĺ ŵĩţĥ ţĥàţ ńàḿē àĺŕēàďŷ ēxĩśţś."],
"YKLP_-": ["Ţēḿƥĺàţē ŕēńàḿēď"],
+ "YLMBSd": ["ē.ĝ. Ţĥē ēďĩţōŕ ƒŕōźē àƒţēŕ Ĩ ƥàśţēď à ĺàŕĝē ţàƀĺē"],
"YPFBfr": [["detail"], " - ", ["kind"], " \"", ["createdPath"], "\" śţĩĺĺ ēxĩśţś ōń ďĩśķ"],
"YSFv5w": ["Ńō ĝĩţ ŕēƥōśĩţōŕŷ — ćōńƒĩĝ śĥàŕĩńĝ ďōēś ńōţ àƥƥĺŷ ĥēŕē."],
"YTLmTM": ["Ŕēḿōvē ţĥē ƥàŕēńţ <0>.ĝĩţ</0> ƒōĺďēŕ"],
@@ -1400,6 +1446,7 @@
"YsEYYS": [
["behind", "plural", { "one": ["#", " ćōḿḿĩţ ƀēĥĩńď"], "other": ["#", " ćōḿḿĩţś ƀēĥĩńď"] }]
],
+ "Yu3KMH": ["Ōƥēń ĜĩţĤũƀ ĩśśũē"],
"YwPUUP": ["Ţĥĩś ƥàćķ ĩś àĺŕēàďŷ śēţ ũƥ ĥēŕē."],
"YyXtnN": ["Ũńďēŕĺĩńē"],
"Z1LF1M": ["Śĥàŕĩńĝ à ďōć ńēēďś à ĜĩţĤũƀ ŕēƥōśĩţōŕŷ. Ćŕēàţē ōńē ƒōŕ ţĥĩś ƥŕōĴēćţ."],
@@ -1449,6 +1496,7 @@
"ZvzbDF": ["Àďď ĩţ ďĩŕēćţĺŷ ţō ţĥĩś ƥŕōĴēćţ."],
"ZxXhLY": ["Ĥĩďē Ƒĩĺēś (", ["sidebarShortcut"], ")"],
"Zz25kq": ["Śĥōŵ Ƒĩĺēś (", ["sidebarShortcut"], ")"],
+ "_0JUKX": ["ßũĝ ŕēƥōŕţĩńĝ ńēēďś ţĥē ŌƥēńĶńōŵĺēďĝē ďēśķţōƥ àƥƥ."],
"_5qBNl": ["ÀĨ ţōōĺś & ĆĹĨ"],
"_6FVBz": ["ĵũḿƥ ţō ţàƀ 1-8"],
"_7UQ7y": ["Ŵĥōĺē ŵōŕď"],
@@ -1462,6 +1510,8 @@
["currentLabel"],
"</1>."
],
+ "_FLBbi": [["sizeText"], " · śēćŕēţś ŕēďàćţēď · ćŕàśĥ ďũḿƥ ńōţ ŕēďàćţēď"],
+ "_IGfXZ": ["ŌƥēńĶńōŵĺēďĝē ǫũĩţ ũńēxƥēćţēďĺŷ ĺàśţ ţĩḿē."],
"_NX6gG": ["Ḿàńàĝĩńĝ ƥŕōĴēćţ ÀĨ ţōōĺś ĩś ũńàvàĩĺàƀĺē ĩń ţĥĩś ƀũĩĺď."],
"_PACVa": ["Ŕēĺēàśē ńōţēś"],
"_PBJRl": ["Àďď àţ ĺēàśţ ōńē ĺēţţēŕ ōŕ ńũḿƀēŕ."],
@@ -1526,11 +1576,17 @@
],
"b4itZn": ["Ŵōŕķĩńĝ"],
"b5aNbi": ["Ţĥē ", ["targetNoun"], " ćōũĺď ńōţ ƀē ōƥēńēď — ţŕŷ ńàvĩĝàţĩńĝ ţō ĩţ ḿàńũàĺĺŷ."],
+ "b6bBkz": [
+ "Àƥƥ & śŷśţēḿ ĩńƒō, ŕēćēńţ àƥƥ ĺōĝś — ńō ƥŕōĴēćţ ĩś ōƥēń, śō ńō ƥŕōĴēćţ ĺōĝś àŕē ĩńćĺũďēď."
+ ],
"bBE5tC": ["Ďēţēćţēď ōń ţĥĩś ḿàćĥĩńē"],
"bBcFK_": ["Ōƥēń ēḿōĴĩ ƥĩćķēŕ ƒōŕ ", ["keyName"]],
"bD8I7O": ["Ćōḿƥĺēţē"],
"bGa3Fk": ["Ũƥĺōàďĩńĝ ƒĩĺē"],
"bH382I": ["Ēďĩţ ţĥĩś ĤŢḾĹ — ţĥē ƥŕēvĩēŵ ũƥďàţēś ĺĩvē."],
+ "bJKq1H": [
+ "À ḿēḿōŕŷ śńàƥśĥōţ ƒŕōḿ ţĥē ćŕàśĥ. Ĩţ ćàń ćōńţàĩń ďōćũḿēńţ ćōńţēńţ àńď ćàń'ţ ƀē ŕēďàćţēď — ĺēàvē ōƒƒ ũńĺēśś ŷōũ'ŕē ćōḿƒōŕţàƀĺē śĥàŕĩńĝ ĩţ."
+ ],
"bSD4im": ["Śēàŕćĥ ŵōŕķţŕēēś àńď ƀŕàńćĥēś"],
"bS_boY": ["Ŕēƥĺàćē ćũŕŕēńţ ḿàţćĥ"],
"bUUVED": ["Àśśēţ"],
@@ -1570,6 +1626,7 @@
"cZGNlb": ["Àďď àńōţĥēŕ ƥàţţēŕń"],
"cZI5AL": ["ŌĶ Ďēśķţōƥ"],
"cZ_8zB": ["Śţàŷś ōń ţĥĩś ćōḿƥũţēŕ."],
+ "cd5EXh": ["Ŕēƥōŕţ à ƀũĝ"],
"cdm00A": ["Ńō Ĩńćōḿĩńĝ"],
"cdmk8A": ["Ũńćōḿḿĩţţēď ćĥàńĝēś"],
"chL5IG": ["Ćōḿḿũńĩţŷ"],
@@ -1589,6 +1646,7 @@
],
"d2uTPx": ["Śēŕvēŕ ēŕŕōŕ (ĤŢŢƤ ", ["status"], ")"],
"d5rK4X": [["chars", "plural", { "one": ["ćĥàŕ"], "other": ["ćĥàŕś"] }]],
+ "d7WfDG": ["Ĩńćĺũďē ďēţàĩĺēď ďĩàĝńōśţĩćś"],
"dD7NPy": ["Ōũţĺĩńē"],
"dDpCOp": ["Ŕēńàḿē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"dEgA5A": ["Ćàńćēĺ"],
@@ -1751,6 +1809,7 @@
"</1>. Ŷōũŕ ćũŕŕēńţ ćōńţēńţ ĩś àĺŕēàďŷ śàvēď ĩń ţĥē ţĩḿēĺĩńē — ŷōũ ćàń ŕēśţōŕē ĩţ àńŷţĩḿē."
],
"h7FzJC": ["Ĺĩńķ-ĝŕàƥĥ ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],
+ "h7jL_x": ["Àƥƥ & śŷśţēḿ ĩńƒō, ŕēćēńţ àƥƥ ĺōĝś, ƥŕōĴēćţ śēŕvēŕ ĺōĝś"],
"h9QFb9": ["Śķĩĺĺ \"", ["0"], "\" ďēĺēţēď"],
"hBMK4W": ["ƤŕōĴēćţ ţēḿƥĺàţēś"],
"hCOLSd": [
@@ -1824,6 +1883,7 @@
"iXTp5j": ["Śćōƥē: "],
"idD8Ev": ["Śàvēď"],
"ig5vUe": ["Ƒàĩĺēď ţō ĺōàď ƒĩĺē"],
+ "ii5mVn": ["Ŕēƥōŕţ ţĥĩś ēŕŕōŕ"],
"iilQXA": ["Ƒōĺďēŕ ďũƥĺĩćàţēď"],
"ijLc3m": ["ßũĺĺēţ ĺĩśţ"],
"ilodsp": ["Ĺēţ àĝēńţś ũśē ŌƥēńĶńōŵĺēďĝē ŵĩţĥōũţ àśķĩńĝ"],
@@ -1878,6 +1938,7 @@
"k4CuuV": [
"Ŕēàďŷ-ḿàďē ƒōĺďēŕś àńď ţēḿƥĺàţēś ţō ĝēţ ŷōũ śţàŕţēď ǫũĩćķĺŷ. Śēĺēćţ à ƥàćķ ţō ƥŕēvĩēŵ ŵĥàţ ĝēţś ćŕēàţēď, ţĥēń àďď ĩţ ţō ŷōũŕ ƥŕōĴēćţ."
],
+ "k7VziB": ["Ćōƥŷ ŕēƥōŕţ ŕēƒēŕēńćē"],
"kCNU4q": [
"Ĩńďēxĩńĝ ŷōũŕ ƥàĝēś — ",
["semanticIndexedCount"],
@@ -1929,6 +1990,7 @@
"l8G3S9": ["Àũţō-śŷńć ĩś ōƒƒ — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō"],
"lAiyU_": ["Ōńĺŷ ţĥē ćũŕŕēńţ ďōćũḿēńţ ũśēś <0>#", ["tag"], "</0>."],
"lCC_D5": ["Śũƀśćŕĩƀĩńĝ..."],
+ "lDqYpA": ["Ĩńćĺũďē ćŕàśĥ ďũḿƥ"],
"lGs_bQ": ["Ƥàĝē <0>*</0>"],
"lHCR4I": ["Ćĺēàŕ ţĥē ƒĩēĺď ţō ŕēśēţ ƀàćķ ţō ţĥē ďēƒàũĺţ ŌƥēńÀĨ ēńďƥōĩńţ."],
"lHwYMr": ["Śēŕvēŕ ēŕŕōŕ: ", ["status"], " ", ["statusText"]],
@@ -2055,6 +2117,7 @@
"Ĝĩţ ĩďēńţĩţŷ ĩśń'ţ śēţ — ćōḿḿĩţś ũśē à ďēƒàũĺţ àũţĥōŕ. Śēţ ŷōũŕś śō ţēàḿḿàţēś śēē ŷōũŕ ńàḿē."
],
"nskygk": ["Ćĥōōśē àĝēńţ"],
+ "nwtY4N": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ"],
"nxlOpL": ["ŌƥēńĶńōŵĺēďĝē ĩś ũśĩńĝ ţĥĩś ĜĩţĤũƀ àććōũńţ."],
"ny6vNn": [
"ŌƥēńĶńōŵĺēďĝē ĩś ũśĩńĝ à ĜĩţĤũƀ àććōũńţ ƥŕōvĩďēď ƀŷ ţĥē ĝĥ ĆĹĨ. Ţĥēŕē'ś ńō śēƥàŕàţē ŌƥēńĶńōŵĺēďĝē ćŕēďēńţĩàĺ ţō ďĩśćōńńēćţ."
@@ -2097,6 +2160,9 @@
"Ŷōũ ƥĩćķēď ~/Ďōćũḿēńţś. ŌƥēńĶńōŵĺēďĝē ŵĩĺĺ ĩńďēx ēvēŕŷ ḿàŕķďōŵń ƒĩĺē ũńďēŕ ĩţ. Ĩƒ ŷōũ ōńĺŷ ŵàńţ ţō ḿàńàĝē à śũƀ-ƒōĺďēŕ, ćĥōōśē à śḿàĺĺēŕ śćōƥē."
],
"ogAuyr": ["ßàćķ ţō ďōćũḿēńţ vĩēŵ"],
+ "olTIwK": [
+ "Śēćŕēţś ĺĩķē ÀƤĨ ķēŷś àńď ţōķēńś àŕē ŕēďàćţēď àũţōḿàţĩćàĺĺŷ. Ŷōũ'ĺĺ ŕēvĩēŵ ţĥē ŕēƥōŕţ ƀēƒōŕē ĩţ'ś śēńţ."
+ ],
"omXJcU": ["Ćĺōśē ōţĥēŕś"],
"optX0N": [["0"], "ĥ àĝō"],
"oqB2ez": ["Ƥŕēvĩōũś ḿàţćĥ"],
@@ -2169,6 +2235,7 @@
"qiRoLb": ["Śũḿḿàŕĩźē ēvēŕŷţĥĩńĝ Ĩ ćĥàńĝēď ţĥĩś ŵēēķ"],
"qioCwA": ["ĵũḿƥ ţō ƥàĝē ", ["pageNumber"]],
"qjHMHf": ["Ƒàĩĺēď ţō ďĩśàƀĺē śŷńć — ", ["detail"]],
+ "qmL1UG": ["Ũƥĺōàďĩńĝ śēćũŕēĺŷ"],
"qo4zCg": ["Ƥàţĥ ćàńńōţ ćōńţàĩń ƀàćķśĺàśĥēś"],
"qpQwGC": ["Ďēśćŕĩƀē ŵĥàţ ŷōũ'ŕē ŵōŕķĩńĝ ōń àńď ţĥē àĝēńţ śēţś ĩţ ũƥ ƒōŕ ŷōũ."],
"qvWGzP": ["Ćōĺĺàƥśē àĺĺ"],
@@ -2247,6 +2314,12 @@
"Ōƥēń àń àďďĩţĩōńàĺ ţēŕḿĩńàĺ ţàƀ. Ŵĩţĥ ţēxţ śēĺēćţēď, śţàĝē ĩţ ĩń ţĥē ńēŵ ţàƀ'ś ÀĨ ĩńƥũţ."
],
"skf5Ix": ["Ĩńďēńţ ōŕ ōũţďēńţ śōũŕćē ēďĩţōŕ ĺĩńēś."],
+ "sn5BEU": [
+ ["sizeText"],
+ " · śēćŕēţś ŕēďàćţēď · ",
+ ["fileCount", "plural", { "one": ["#", " ƒĩĺē"], "other": ["#", " ƒĩĺēś"] }],
+ " · ćŕàśĥ ďũḿƥ ńōţ ŕēďàćţēď"
+ ],
"snrVQ7": ["ƥŕōƀē ƒàĩĺēď"],
"ssuwjF": ["ßŕàńćĥ"],
"stlgky": [
@@ -2375,6 +2448,7 @@
"wQp1V3": ["Ḿĩŕŕōŕ ōƒ <0>", ["src"], "</0>"],
"wT4iQr": ["Ōƥēń vĩśũàĺ-ēďĩţōŕ ƒĩńď ŵĩţĥ ŕēƥĺàćē ćōńţŕōĺś ēxƥàńďēď."],
"wTcjov": ["Ńō ŵōŕķśƥàćē"],
+ "wVa83H": ["Ćōũĺďń'ţ ćŕēàţē ţĥē ŕēƥōŕţ"],
"wXO4Tg": [["hrs"], "ĥ àĝō"],
"w_Sphq": ["Àţţàćĥḿēńţś"],
"wbv9xO": ["Ćŕēàţē ńēŵ ƥŕōĴēćţ"],
@@ -2471,6 +2545,7 @@
"yYR6za": ["Ďĩśƥĺàŷ ţēxţ"],
"yZmvQ4": ["Ţĥĩś ƥŕōĴēćţ'ś śēŕvēŕ (v", ["0"], ") ĩś ńēŵēŕ ţĥàń ţĥĩś àƥƥ (v", ["1"], ")."],
"y_5CE8": ["Ĩţēḿ ", ["0"]],
+ "y_K0Dz": ["Ŵĥàţ ĥàƥƥēńēď?"],
"yaPGPa": ["Ōƥēń à ƥŕōĴēćţ ţō ḿàńàĝē ĩţś ÀĨ ţōōĺ ćōńńēćţĩōńś."],
"yf5r22": [
["keyName"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index e9ef21558..90e1a2e97 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -82,6 +82,10 @@ msgstr ""
msgid "(opens in new tab)"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "(optional)"
+msgstr ""
+
#. Scope tag next to an AI tool — config is written at both project and user level
#: src/components/ConsentDialogBody.tsx
msgid "(project + user)"
@@ -154,6 +158,11 @@ msgstr ""
msgid "{0} templates available"
msgstr ""
+#. placeholder {0}: formatSize(phase.report.zipSizeBytes)
+#: src/components/ReportBugDialogBody.tsx
+msgid "{0} total"
+msgstr ""
+
#. placeholder {0}: share.owner
#. placeholder {1}: share.repo
#. placeholder {2}: shareTargetPath(share.target)
@@ -413,6 +422,22 @@ msgstr ""
msgid "{shareBranch} isn't a valid branch name."
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "{sizeText} · secrets redacted"
+msgstr ""
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"
+msgstr ""
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}} · crash dump not redacted"
+msgstr ""
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "{sizeText} · secrets redacted · crash dump not redacted"
+msgstr ""
+
#: src/components/CreatedItemsList.tsx
msgid "{skillCount, plural, one {skill} other {skills}}"
msgstr ""
@@ -527,6 +552,10 @@ msgstr ""
msgid "A line with a footnote<0><1>[1]</1></0> and a definition shown below."
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "A memory snapshot from the crash. It can contain document content and can't be redacted — leave off unless you're comfortable sharing it."
+msgstr ""
+
#: src/components/ShareReceiveDialog.tsx
msgid "A network problem or GitHub outage interrupted the clone."
msgstr ""
@@ -552,6 +581,10 @@ msgstr ""
msgid "A real shell is off for this project. Turning it on runs commands with the full access of your macOS user account."
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "A report helps us find the cause. Nothing is sent until you review it."
+msgstr ""
+
#: src/components/NewTemplateDialog.tsx
msgid "A reusable starting point for new documents in this folder."
msgstr ""
@@ -755,6 +788,10 @@ msgstr ""
msgid "Adds a managed block to {0}"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Adds telemetry, server state, and runtime info when available. Document names are anonymized."
+msgstr ""
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Adds the OpenKnowledge skill to the <0>Claude Desktop App</0> so it's available in Chat and Cowork sessions."
msgstr ""
@@ -833,6 +870,7 @@ msgstr ""
msgid "Already set up — ok is available in your terminal"
msgstr ""
+#: src/components/AppErrorBoundary.tsx
#: src/components/DocumentErrorBoundary.tsx
msgid "An unexpected error occurred."
msgstr ""
@@ -857,6 +895,14 @@ msgstr ""
msgid "API key set"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "App & system info, recent app logs — no project is open, so no project logs are included."
+msgstr ""
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "App & system info, recent app logs, project server logs"
+msgstr ""
+
#: src/components/CreatedItemsList.tsx
msgid "Append-only log of what changed."
msgstr ""
@@ -928,6 +974,10 @@ msgstr ""
msgid "Asset: {title}"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Attach the file in an email to <0>[email protected]</0>"
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Attachments"
msgstr ""
@@ -994,6 +1044,7 @@ msgstr ""
msgid "Available in the OpenKnowledge desktop app. From a terminal, use<0> ok config-sharing status</0> / <1>share</1> / <2>unshare</2>."
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
#: src/components/SeedDialog.tsx
msgid "Back"
msgstr ""
@@ -1132,6 +1183,14 @@ msgstr ""
msgid "Browse your repos:"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Bug report {reference}"
+msgstr ""
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Bug reporting needs the OpenKnowledge desktop app."
+msgstr ""
+
#: src/components/empty-state/use-create-suggestions.ts
msgid "Build a competitor research knowledge base. Start with an overview page, then add cross-linked pages for each competitor, their products and pricing, and the sources behind every claim."
msgstr ""
@@ -1191,6 +1250,7 @@ msgstr ""
#: src/components/NewTemplateDialog.tsx
#: src/components/NewWorktreeDialog.tsx
#: src/components/PublishToGitHubDialog.tsx
+#: src/components/ReportBugDialogBody.tsx
#: src/components/SeedDialog.tsx
#: src/components/settings/SearchSection.tsx
#: src/components/ShareBranchSwitchDialog.tsx
@@ -1381,6 +1441,7 @@ msgstr ""
#: src/components/EditorTabs.tsx
#: src/components/InstallInClaudeDesktopDialog.tsx
+#: src/components/ReportBugDialogBody.tsx
#: src/components/SeedDialog.tsx
#: src/components/SubscribeForm.tsx
#: src/components/ui/dialog.tsx
@@ -1697,6 +1758,7 @@ msgstr ""
#: src/components/empty-state/CopyablePromptList.tsx
#: src/components/InstallInClaudeDesktopDialog.tsx
+#: src/components/ReportBugDialogBody.tsx
#: src/editor/extensions/CodeBlockView.tsx
msgid "Copied"
msgstr ""
@@ -1715,6 +1777,10 @@ msgstr ""
msgid "Copied relative path"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Copied report reference"
+msgstr ""
+
#: src/components/CopyButton.tsx
msgid "Copied!"
msgstr ""
@@ -1722,6 +1788,7 @@ msgstr ""
#: src/components/CopyButton.tsx
#: src/components/empty-state/CopyablePromptList.tsx
#: src/components/InstallInClaudeDesktopDialog.tsx
+#: src/components/ReportBugDialogBody.tsx
msgid "Copy"
msgstr ""
@@ -1766,6 +1833,10 @@ msgstr ""
msgid "Copy Path"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Copy report reference"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Copy selected file or folder"
msgstr ""
@@ -1945,6 +2016,10 @@ msgstr ""
msgid "Couldn't create template: {error}"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Couldn't create the report"
+msgstr ""
+
#: src/components/NewWorktreeDialog.tsx
msgid "Couldn't create the worktree. Try a different name."
msgstr ""
@@ -2097,6 +2172,10 @@ msgstr ""
msgid "Couldn't save the resolution for {filePath}."
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Couldn't send the report"
+msgstr ""
+
#: src/components/handoff/EditWithAiPopover.tsx
msgid "Couldn't send the selection — please try again."
msgstr ""
@@ -2188,6 +2267,10 @@ msgstr ""
msgid "Create page"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Create report"
+msgstr ""
+
#: src/components/NewSkillDialog.tsx
msgid "Create skill"
msgstr ""
@@ -2410,6 +2493,10 @@ msgstr ""
msgid "Details"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Details about the error you just hit are included."
+msgstr ""
+
#: src/components/settings/SkillTargetsPicker.tsx
msgid "Detected from the editors this project is set up for. Adjust to control where every skill installs."
msgstr ""
@@ -2548,6 +2635,7 @@ msgstr ""
#: src/components/InstallInClaudeDesktopDialog.tsx
#: src/components/PublishToGitHubDialog.tsx
+#: src/components/ReportBugDialogBody.tsx
#: src/editor/extensions/JsxComponentView.tsx
#: src/editor/slash-command/items.tsx
msgid "Done"
@@ -2633,6 +2721,14 @@ msgstr ""
msgid "e.g. server.ts"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "e.g. Switching projects while a sync was running"
+msgstr ""
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "e.g. The editor froze after I pasted a large table"
+msgstr ""
+
#: src/components/CreateProjectDialog.tsx
msgid "Each selected tool gets an OpenKnowledge MCP entry."
msgstr ""
@@ -3650,6 +3746,14 @@ msgstr ""
msgid "In the Claude Desktop App"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Include crash dump"
+msgstr ""
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Include detailed diagnostics"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Indent or outdent list item"
msgstr ""
@@ -4773,6 +4877,7 @@ msgstr ""
msgid "Not installed"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
#: src/components/SkillsSidebarSection.tsx
#: src/lib/install-server-drift-listener.ts
msgid "Not now"
@@ -4786,6 +4891,10 @@ msgstr ""
msgid "Nothing to undo on this file"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Nothing was uploaded — the report stays on this Mac until you email it to us."
+msgstr ""
+
#: src/editor/slash-command/component-items.tsx
msgid "Notion-style inline row for a downloadable file. Drag-drop also works."
msgstr ""
@@ -4964,6 +5073,10 @@ msgstr ""
msgid "Open documents tagged #{chip}"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Open email draft"
+msgstr ""
+
#: src/editor/extensions/JsxComponentView.tsx
msgid "Open embedded URL in new tab"
msgstr ""
@@ -4988,6 +5101,10 @@ msgstr ""
msgid "Open folder on disk"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Open GitHub issue"
+msgstr ""
+
#: src/components/CommandPalette.tsx
msgid "Open graph"
msgstr ""
@@ -5143,6 +5260,10 @@ msgstr ""
msgid "OpenKnowledge is using this GitHub account."
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "OpenKnowledge quit unexpectedly last time."
+msgstr ""
+
#: src/components/ConsentDialogBody.tsx
msgid "OpenKnowledge stores its configuration and internal files inside a newly created <0>.ok</0> directory in your project root folder."
msgstr ""
@@ -5172,6 +5293,10 @@ msgstr ""
msgid "Or use a starter pack"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Or write to <0>[email protected]</0>"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Ordered list"
msgstr ""
@@ -5213,6 +5338,10 @@ msgstr ""
msgid "Owner"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Package logs and system info into a report you can review, then send it privately to the OpenKnowledge team."
+msgstr ""
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/link-path-suggestions.tsx
msgid "Page"
@@ -5842,6 +5971,24 @@ msgstr ""
msgid "Replace the active match from the replace field."
msgstr ""
+#: src/components/CommandPalette.tsx
+#: src/components/ReportBugDialogBody.tsx
+msgid "Report a bug"
+msgstr ""
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Report reference: {reference}"
+msgstr ""
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Report sent — thank you"
+msgstr ""
+
+#: src/components/AppErrorBoundary.tsx
+#: src/components/DocumentErrorBoundary.tsx
+msgid "Report this error"
+msgstr ""
+
#: src/components/settings/AccountSection.tsx
msgid "Repositories you've already cloned may keep syncing through git's own saved credentials, even after you disconnect."
msgstr ""
@@ -5996,6 +6143,7 @@ msgstr ""
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
+#: src/components/ReportBugDialogBody.tsx
#: src/components/skill-actions.tsx
msgid "Reveal in Finder"
msgstr ""
@@ -6016,6 +6164,10 @@ msgstr ""
msgid "Review conflicts"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Review your report"
+msgstr ""
+
#: src/editor/slash-command/items.tsx
msgid "Role"
msgstr ""
@@ -6181,6 +6333,10 @@ msgstr ""
msgid "Second item"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Secrets like API keys and tokens are redacted automatically. You'll review the report before it's sent."
+msgstr ""
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
#: src/editor/extensions/WikiLinkPropPanel.tsx
msgid "Section <0>(optional heading anchor)</0>"
@@ -6258,10 +6414,26 @@ msgstr ""
msgid "Semantic search is on, but no API key is set — search falls back to keyword matching. Add one in <0>Settings → Account</0> (it's stored once for your whole machine)."
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Send report"
+msgstr ""
+
#: src/components/handoff/EditWithAiPopover.tsx
msgid "Send to"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Send your report by email"
+msgstr ""
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Sending report"
+msgstr ""
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Sent privately to the OpenKnowledge team, along with your note and app version. Never posted publicly."
+msgstr ""
+
#: src/editor/slash-command/items.tsx
msgid "Separator"
msgstr ""
@@ -6596,6 +6768,10 @@ msgstr ""
msgid "Small section heading."
msgstr ""
+#: src/components/AppErrorBoundary.tsx
+msgid "Something went wrong"
+msgstr ""
+
#: src/components/settings/SettingsDialogErrorBoundary.tsx
msgid "Something went wrong loading the settings panel."
msgstr ""
@@ -6920,6 +7096,10 @@ msgstr ""
msgid "Tags matching \"{tagListQuery}\""
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Take a look if you'd like — this exact file is what we receive."
+msgstr ""
+
#: src/components/SeedDialog.tsx
msgid "Take a piece of writing from a rough idea to a finished draft to something you're ready to share. Good for blog posts, essays, or anything you want to move through clear stages."
msgstr ""
@@ -7097,6 +7277,10 @@ msgstr ""
msgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "The report service couldn't be reached."
+msgstr ""
+
#: src/components/ShareReceiveDialog.tsx
msgid "The repository is private and your GitHub account doesn't have access to it."
msgstr ""
@@ -7442,8 +7626,10 @@ msgstr ""
msgid "Try a prompt"
msgstr ""
+#: src/components/AppErrorBoundary.tsx
#: src/components/DocumentErrorBoundary.tsx
#: src/components/InstallInClaudeDesktopDialog.tsx
+#: src/components/ReportBugDialogBody.tsx
#: src/components/settings/AccountSection.tsx
#: src/components/ShareReceiveDialog.tsx
msgid "Try again"
@@ -7702,6 +7888,10 @@ msgstr ""
msgid "Uploading file"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Uploading securely"
+msgstr ""
+
#: src/components/TimelinePanel.tsx
msgid "Upstream sync"
msgstr ""
@@ -7809,6 +7999,10 @@ msgstr ""
msgid "Waiting for authorization"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Want to follow along? Open a GitHub issue and mention your reference."
+msgstr ""
+
#: src/components/settings/AccountSection.tsx
msgid "We couldn't check your GitHub connection."
msgstr ""
@@ -7825,6 +8019,10 @@ msgstr ""
msgid "We'll create a repository and start syncing — no terminal needed."
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "We've filed it with the team and attached your logs."
+msgstr ""
+
#: src/components/HelpPopover.tsx
msgid "Website"
msgstr ""
@@ -7845,6 +8043,10 @@ msgstr ""
msgid "What gets created"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "What happened?"
+msgstr ""
+
#: src/components/EmptyEditorState.tsx
msgid "What is a starter pack?"
msgstr ""
@@ -7871,6 +8073,10 @@ msgstr ""
msgid "What this checkbox changes"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "What were you doing?"
+msgstr ""
+
#: src/components/empty-state/empty-state-copy.ts
msgid "What would you like to create?"
msgstr ""
@@ -7974,6 +8180,10 @@ msgstr ""
msgid "yesterday"
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "You can also create one from a terminal with <0>ok bug-report</0>."
+msgstr ""
+
#: src/components/TerminalGate.tsx
msgid "You can also manage this in Settings."
msgstr ""
@@ -8071,6 +8281,18 @@ msgstr ""
msgid "Your local copy of branch <0>{branch}</0> is behind. Pull the latest changes, then open the link again."
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Your report couldn't be sent — try again or email it instead."
+msgstr ""
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Your report is being sent."
+msgstr ""
+
+#: src/components/ReportBugDialogBody.tsx
+msgid "Your report is saved on this Mac — nothing was lost. You can email it to us instead."
+msgstr ""
+
#: src/components/CloneDialog.tsx
msgid "Your repositories"
msgstr ""
diff --git a/packages/app/src/main.tsx b/packages/app/src/main.tsx
index 96d71f4be..4e5ab7c4d 100644
--- a/packages/app/src/main.tsx
+++ b/packages/app/src/main.tsx
@@ -25,13 +25,16 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ThemeProvider } from 'next-themes';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
+import { AppErrorBoundary, CrashReportingBoundary } from '@/components/AppErrorBoundary';
import { selectDesktopRootApp } from '@/components/desktop-root-app';
+import { ReportBugCrashInviteTrigger } from '@/components/ReportBugCrashInviteTrigger';
import { Toaster } from '@/components/ui/sonner';
import { TooltipProvider } from '@/components/ui/tooltip';
// Side-effect import to load the `Window.okDesktop?` global augmentation.
import '@/lib/desktop-bridge-types';
import { installClientFetchWrapper } from '@/lib/client-fetch';
import { installConsentListener } from '@/lib/consent-store';
+import { installCrashInviteListener } from '@/lib/crash-invite-store';
// Side-effect import: loads + activates the i18n catalog before first render.
import { i18n } from '@/lib/i18n';
import { installClientLogForwarder } from '@/lib/install-client-log-forwarder';
@@ -175,6 +178,14 @@ if (typeof window !== 'undefined') {
installShareReceivedListener({ bridge: window.okDesktop });
}
+// Desktop-only: crash-detected invitations from main feeding the crash-invite
+// store. Module-init because main delivers boot-time invitations on this
+// window's first did-finish-load, which can beat React's effect flush — the
+// store buffers until ReportBugCrashInviteTrigger mounts. No-op in web/CLI.
+if (typeof window !== 'undefined') {
+ installCrashInviteListener({ bridge: window.okDesktop });
+}
+
// Desktop-only: ephemeral single-file window (`ok <file>`). Seed the doc into
// the hash BEFORE `createRoot().render()` so `NavigationHandler`'s first-mount
// read lands on the file — deterministic, no post-load `ok:deep-link` IPC to
@@ -209,7 +220,28 @@ createRoot(root).render(
disableTransitionOnChange
storageKey="ok-theme-v1"
>
- <TooltipProvider>{selectDesktopRootApp(desktopBridge)}</TooltipProvider>
+ {/*
+ * Last-resort shell boundary: catches render crashes that escape
+ * every inner boundary (per-Activity DocumentErrorBoundary, settings
+ * chunk) so an app-shell crash shows a recoverable fallback instead
+ * of unmounting the root. Inside the providers so the fallback keeps
+ * i18n + theme.
+ */}
+ <TooltipProvider>
+ <AppErrorBoundary>{selectDesktopRootApp(desktopBridge)}</AppErrorBoundary>
+ {/*
+ * Crash-invite dialog host — a sibling of the root app, outside
+ * the shell boundary, so an invitation still surfaces while the
+ * fallback is showing, in every window mode. Being outside every
+ * boundary also means a throw here would unmount the React root,
+ * so it gets its own null-fallback boundary.
+ */}
+ {desktopBridge !== undefined && (
+ <CrashReportingBoundary>
+ <ReportBugCrashInviteTrigger bridge={desktopBridge} />
+ </CrashReportingBoundary>
+ )}
+ </TooltipProvider>
{/*
* Sonner toaster for ad-hoc status/error toasts (clone dialog, file
* tree, etc.). Auto-update notices are NOT routed here — they live
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index a16527191..089b590d6 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -445,6 +445,16 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
mode: 'shared' as const,
}),
},
+ bugReport: {
+ create: async () => ({ ok: false as const, error: 'test mock' }),
+ send: async () => ({
+ ok: false as const,
+ reason: 'send-failed' as const,
+ fallback: { mailtoUrl: 'mailto:[email protected]' },
+ }),
+ crashAck: async () => ({ ok: true as const }),
+ onCrashDetected: () => () => {},
+ },
navigator: {
open: async () => {},
},
diff --git a/packages/cli/src/commands/bug-report-bundle.test.ts b/packages/cli/src/commands/bug-report-bundle.test.ts
new file mode 100644
index 000000000..53d3889ec
--- /dev/null
+++ b/packages/cli/src/commands/bug-report-bundle.test.ts
@@ -0,0 +1,258 @@
+/**
+ * Tests for the standard bug-report capture. Real disk fixtures (no fs
+ * mocks) since the module's job is filesystem-shaped; the user-level logs
+ * directory is injected so tests never touch the real `~/.ok`.
+ */
+
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { homedir, tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import {
+ collectStandardBundle,
+ defaultBugReportZipPath,
+ okBugReportsDir,
+} from './bug-report-bundle.ts';
+
+const tmpDirs: string[] = [];
+
+function makeTmpDir(prefix = 'ok-bugreport-test-'): string {
+ const dir = mkdtempSync(resolve(tmpdir(), prefix));
+ tmpDirs.push(dir);
+ return dir;
+}
+
+afterEach(() => {
+ for (const d of tmpDirs) {
+ if (existsSync(d)) rmSync(d, { recursive: true, force: true });
+ }
+ tmpDirs.length = 0;
+});
+
+function writeAt(baseDir: string, relPath: string, body: string): void {
+ const full = join(baseDir, relPath);
+ mkdirSync(dirname(full), { recursive: true });
+ writeFileSync(full, body);
+}
+
+// yazl writes; the standard parser pair is yauzl. Avoid adding it as a
+// dep for tests — use `unzip` (BSD/Linux ships it) instead.
+function listZipEntries(zipPath: string): string[] {
+ const out = execSync(`unzip -Z1 ${JSON.stringify(zipPath)}`, { encoding: 'utf-8' });
+ return out.split('\n').filter(Boolean);
+}
+
+function readZipEntry(zipPath: string, entry: string): string {
+ const extractDir = makeTmpDir('ok-bugreport-extract-');
+ execSync(
+ `unzip -q -o ${JSON.stringify(zipPath)} ${JSON.stringify(entry)} -d ${JSON.stringify(extractDir)}`,
+ );
+ return readFileSync(join(extractDir, entry), 'utf8');
+}
+
+function makeProjectDir(slug = 'bundle-proj'): string {
+ const projectDir = makeTmpDir();
+ writeAt(projectDir, '.ok/config.yml', `name: ${slug}\n`);
+ return projectDir;
+}
+
+describe('collectStandardBundle — project bundle', () => {
+ test('packages lock/spawn-error, local sink logs, and sysinfo into the zip', async () => {
+ const projectDir = makeProjectDir();
+ writeAt(projectDir, '.ok/local/server.lock', '{"pid":1234}\n');
+ writeAt(projectDir, '.ok/local/last-spawn-error.log', 'spawn failed\n');
+ writeAt(projectDir, '.ok/local/logs/server-current.jsonl', '{"level":30}\n');
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath, summary } = await collectStandardBundle({
+ projectDir,
+ redact: true,
+ outputPath,
+ });
+
+ expect(zipPath).toBe(outputPath);
+ expect(existsSync(zipPath)).toBe(true);
+ expect(summary.projectSlug).toBe('bundle-proj');
+
+ const entries = listZipEntries(zipPath);
+ expect(entries).toContain('lockdir/server.lock');
+ expect(entries).toContain('lockdir/last-spawn-error.log');
+ expect(entries).toContain('local-logs/server-current.jsonl');
+ expect(entries).toContain('sysinfo.json');
+ expect(entries).toContain('MANIFEST.json');
+ expect(entries).toContain('README.md');
+
+ const sysinfo = JSON.parse(readZipEntry(zipPath, 'sysinfo.json'));
+ expect(sysinfo.hostname).toBe('[redacted]');
+ expect(typeof sysinfo.platform).toBe('string');
+ });
+
+ test('MANIFEST.json mirrors the returned summary', async () => {
+ const projectDir = makeProjectDir();
+ writeAt(projectDir, '.ok/local/server.lock', '{"pid":1}\n');
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath, summary } = await collectStandardBundle({
+ projectDir,
+ redact: true,
+ outputPath,
+ });
+
+ const manifest = JSON.parse(readZipEntry(zipPath, 'MANIFEST.json'));
+ expect(manifest.projectSlug).toBe(summary.projectSlug);
+ expect(manifest.files).toEqual(summary.files);
+ expect(manifest.redactions).toEqual(summary.redactions);
+ expect(manifest.generatedAt).toBe(summary.generatedAt);
+ expect(summary.files).toContain('lockdir/server.lock');
+ expect(summary.files).toContain('sysinfo.json');
+ });
+
+ test('falls back to a hashed slug when .ok exists without a config name', async () => {
+ const projectDir = makeTmpDir();
+ writeAt(projectDir, '.ok/local/server.lock', '{}\n');
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { summary } = await collectStandardBundle({ projectDir, redact: true, outputPath });
+
+ expect(summary.projectSlug).toMatch(/^[0-9a-f]{12}$/);
+ });
+});
+
+describe('collectStandardBundle — redaction', () => {
+ const secret = `ghp_${'a'.repeat(40)}`;
+
+ test('scrubs a seeded secret and records the audit', async () => {
+ const projectDir = makeProjectDir();
+ writeAt(projectDir, '.ok/local/last-spawn-error.log', `token ${secret} leaked\n`);
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath, summary } = await collectStandardBundle({
+ projectDir,
+ redact: true,
+ outputPath,
+ });
+
+ const bundled = readZipEntry(zipPath, 'lockdir/last-spawn-error.log');
+ expect(bundled).not.toContain(secret);
+ expect(bundled).toContain('[REDACTED-GH-PAT]');
+
+ expect(summary.redactedLineCount).toBeGreaterThanOrEqual(1);
+ const audit = summary.redactions.find((r) => r.file === 'lockdir/last-spawn-error.log');
+ expect(audit?.patterns).toContain('github-pat');
+
+ const readme = readZipEntry(zipPath, 'README.md');
+ expect(readme).toContain('line(s) were scrubbed');
+ });
+
+ test('redact: false leaves content unmodified and the audit empty', async () => {
+ const projectDir = makeProjectDir();
+ writeAt(projectDir, '.ok/local/last-spawn-error.log', `token ${secret} leaked\n`);
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath, summary } = await collectStandardBundle({
+ projectDir,
+ redact: false,
+ outputPath,
+ });
+
+ const bundled = readZipEntry(zipPath, 'lockdir/last-spawn-error.log');
+ expect(bundled).toContain(secret);
+ expect(summary.redactions).toEqual([]);
+ expect(summary.redactedLineCount).toBe(0);
+
+ const readme = readZipEntry(zipPath, 'README.md');
+ expect(readme).toContain('Redaction was disabled');
+ expect(readme).not.toContain('safe to attach');
+ });
+});
+
+describe('collectStandardBundle — user-level logs', () => {
+ test('includes .log and rotated .log.N files, skipping other extensions', async () => {
+ const userLogsDir = makeTmpDir();
+ writeFileSync(join(userLogsDir, 'desktop.log'), 'line\n');
+ writeFileSync(join(userLogsDir, 'desktop.log.1'), 'rotated\n');
+ writeFileSync(join(userLogsDir, 'notes.txt'), 'not a log\n');
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath } = await collectStandardBundle({ redact: true, outputPath, userLogsDir });
+
+ const entries = listZipEntries(zipPath);
+ expect(entries).toContain('logs/desktop.log');
+ expect(entries).toContain('logs/desktop.log.1');
+ expect(entries).not.toContain('logs/notes.txt');
+ });
+
+ test('narrows user logs to those mentioning the project slug when any match', async () => {
+ const userLogsDir = makeTmpDir();
+ writeFileSync(join(userLogsDir, 'match.log'), '{"project":"bundle-proj"}\n');
+ writeFileSync(join(userLogsDir, 'other.log'), '{"project":"someone-else"}\n');
+ const projectDir = makeProjectDir('bundle-proj');
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath } = await collectStandardBundle({
+ projectDir,
+ redact: true,
+ outputPath,
+ userLogsDir,
+ });
+
+ const entries = listZipEntries(zipPath);
+ expect(entries).toContain('logs/match.log');
+ expect(entries).not.toContain('logs/other.log');
+ });
+
+ test('keeps every user log when none mention the project slug', async () => {
+ const userLogsDir = makeTmpDir();
+ writeFileSync(join(userLogsDir, 'a.log'), 'no slug here\n');
+ writeFileSync(join(userLogsDir, 'b.log'), 'none here either\n');
+ const projectDir = makeProjectDir('bundle-proj');
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath } = await collectStandardBundle({
+ projectDir,
+ redact: true,
+ outputPath,
+ userLogsDir,
+ });
+
+ const entries = listZipEntries(zipPath);
+ expect(entries).toContain('logs/a.log');
+ expect(entries).toContain('logs/b.log');
+ });
+});
+
+describe('collectStandardBundle — system-wide (no projectDir)', () => {
+ test('captures user logs + sysinfo only, with a null slug', async () => {
+ const userLogsDir = makeTmpDir();
+ writeFileSync(join(userLogsDir, 'desktop.log'), 'line\n');
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath, summary } = await collectStandardBundle({
+ redact: true,
+ outputPath,
+ userLogsDir,
+ });
+
+ expect(summary.projectSlug).toBeNull();
+ const entries = listZipEntries(zipPath);
+ expect(entries).toEqual(
+ expect.arrayContaining(['logs/desktop.log', 'sysinfo.json', 'MANIFEST.json', 'README.md']),
+ );
+ expect(entries.some((e) => e.startsWith('lockdir/'))).toBe(false);
+ expect(entries.some((e) => e.startsWith('local-logs/'))).toBe(false);
+
+ const readme = readZipEntry(zipPath, 'README.md');
+ expect(readme).toContain('Project: (unscoped)');
+ });
+});
+
+describe('defaultBugReportZipPath', () => {
+ test('derives ~/.ok/bug-reports/<timestamp>-bugreport.zip with : and . replaced', () => {
+ const path = defaultBugReportZipPath(new Date('2026-07-10T01:02:03.456Z'));
+ expect(path).toBe(
+ join(homedir(), '.ok', 'bug-reports', '2026-07-10T01-02-03-456Z-bugreport.zip'),
+ );
+ expect(okBugReportsDir()).toBe(join(homedir(), '.ok', 'bug-reports'));
+ });
+});
diff --git a/packages/cli/src/commands/bug-report-bundle.ts b/packages/cli/src/commands/bug-report-bundle.ts
new file mode 100644
index 000000000..9f09049fe
--- /dev/null
+++ b/packages/cli/src/commands/bug-report-bundle.ts
@@ -0,0 +1,420 @@
+/**
+ * Standard bug-report capture — the `ok bug-report` content set (user-level
+ * logs, per-project lock/spawn-error files, local sink logs, sysinfo) packaged
+ * into a redacted zip. Extracted from `bug-report.ts` for the same reason as
+ * `bug-report-redact.ts`: `bug-report.ts` imports `cli.ts`, which parses argv
+ * at module load, so it can't be imported by tests or by Electron main.
+ * Desktop calls this in-process instead of shelling out to the CLI.
+ *
+ * CLI-facing concerns (stdout path echo, stderr redaction notice, Finder
+ * reveal) stay in `bug-report.ts` — this module only collects and packages.
+ */
+
+import { execSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';
+import { freemem, homedir, type as osType, platform, release, totalmem, uptime } from 'node:os';
+import { basename, dirname, join, resolve } from 'node:path';
+import type { BundleManifest, BundleRedaction } from '@inkeep/open-knowledge-core';
+import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';
+import type { ZipFile } from 'yazl';
+// Keep this import type-only: `diagnose/bundle.ts` imports from this module
+// too, so a value import in either direction would form a runtime cycle.
+import type { DesktopMetadata } from '../diagnose/bundle.ts';
+import { redactContent, SECRET_PATTERN_NAMES } from './bug-report-redact.ts';
+
+/**
+ * Where `ok bug-report` (and the desktop report flow) write bundles by
+ * default. A function, not a module-level constant: `homedir()` is
+ * env-sensitive, and freezing it at import time makes the value depend on
+ * module load order (test processes mutate HOME).
+ */
+export function okBugReportsDir(): string {
+ return join(homedir(), '.ok', 'bug-reports');
+}
+
+export function defaultBugReportZipPath(now: Date = new Date()): string {
+ const timestamp = now.toISOString().replace(/[:.]/g, '-');
+ return join(okBugReportsDir(), `${timestamp}-bugreport.zip`);
+}
+
+/** Structural subset of a pino logger, so callers outside the CLI can inject their own. */
+export interface BundleLogger {
+ info(payload: Record<string, unknown>, message: string): void;
+ warn(payload: Record<string, unknown>, message: string): void;
+}
+
+/** File copied byte-for-byte into the bundle under `extra/` — never text-scrubbed. */
+export interface BundleExtraFile {
+ sourcePath: string;
+ /** Zip entry name under `extra/`; defaults to the source file's basename. */
+ zipName?: string;
+}
+
+export interface CollectStandardBundleOptions {
+ /**
+ * Project directory whose `.ok/local` artifacts (lock/spawn-error, local
+ * sink logs) are captured and whose slug scopes the user-log filter. Omit
+ * for a system-wide bundle: user-level logs + sysinfo only.
+ */
+ projectDir?: string;
+ /** Apply the secret-pattern scrub to every bundled file. */
+ redact: boolean;
+ /** Zip destination; parent directories are created as needed. */
+ outputPath: string;
+ /** Override the user-level logs directory (defaults to `~/.ok/logs`). */
+ userLogsDir?: 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/`. */
+ extraFiles?: BundleExtraFile[];
+ /**
+ * Desktop host metadata recorded in `sysinfo.json` (and, through it, the
+ * manifest). `null`/omitted reads as "not an Electron host" — mirroring the
+ * full-level bundle's `host.desktop: null` convention.
+ */
+ desktop?: DesktopMetadata | null;
+ logger?: BundleLogger;
+}
+
+interface StandardBundleSummary {
+ projectSlug: string | null;
+ /** Zip entry names of the captured content files (mirrors MANIFEST.json `files`). */
+ files: string[];
+ /** Per-file redaction audit (mirrors MANIFEST.json `redactions`). */
+ redactions: BundleRedaction[];
+ /** Total lines scrubbed across all files. */
+ redactedLineCount: number;
+ generatedAt: string;
+}
+
+export interface StandardBundleResult {
+ zipPath: string;
+ summary: StandardBundleSummary;
+}
+
+export function resolveProjectSlug(cwd: string, logger?: BundleLogger): string | null {
+ const configPath = join(cwd, '.ok', 'config.yml');
+ if (existsSync(configPath)) {
+ try {
+ const content = readFileSync(configPath, 'utf8');
+ const nameMatch = content.match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);
+ if (nameMatch?.[1]) return nameMatch[1];
+ } catch (err) {
+ // A malformed/unreadable .ok/config.yml falls back to a path-hash slug
+ // (or null), but log it so a missing/wrong project slug in the bundle is
+ // diagnosable rather than silent — same rationale as resolveContentDir.
+ logger?.warn(
+ { configPath, err: err instanceof Error ? err.message : String(err) },
+ 'bug-report: failed to read .ok/config.yml for project slug; using path-hash fallback',
+ );
+ }
+ }
+
+ if (existsSync(join(cwd, '.ok'))) {
+ return createHash('sha256').update(resolve(cwd)).digest('hex').slice(0, 12);
+ }
+
+ return null;
+}
+
+function collectSysinfo(): Record<string, unknown> {
+ const info: Record<string, unknown> = {
+ timestamp: new Date().toISOString(),
+ platform: platform(),
+ osType: osType(),
+ osRelease: release(),
+ hostname: '[redacted]',
+ uptime: uptime(),
+ freeMem: freemem(),
+ totalMem: totalmem(),
+ nodeVersion: process.version,
+ bunVersion: process.versions.bun ?? null,
+ v8Version: process.versions.v8 ?? null,
+ pid: process.pid,
+ };
+
+ try {
+ const ver = execSync(
+ 'sw_vers -productVersion 2>/dev/null',
+ withHiddenWindowsConsole({ encoding: 'utf8' }),
+ ).trim();
+ info.macosVersion = ver;
+ } catch {}
+
+ try {
+ const pkgPath = join(__dirname, '..', '..', 'package.json');
+ if (existsSync(pkgPath)) {
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
+ info.okVersion = pkg.version;
+ }
+ } catch {}
+
+ return info;
+}
+
+function collectLogs(projectSlug: string | null, logsDir: string): { files: string[] } {
+ if (!existsSync(logsDir)) return { files: [] };
+
+ let files = readdirSync(logsDir)
+ .filter((f) => f.endsWith('.log') || /\.log\.\d+$/.test(f))
+ .map((f) => join(logsDir, f));
+
+ if (projectSlug && files.length > 0) {
+ const filtered = files.filter((f) => {
+ try {
+ const content = readFileSync(f, 'utf8');
+ return content.includes(`"project":"${projectSlug}"`);
+ } catch {
+ return true;
+ }
+ });
+ if (filtered.length > 0) files = filtered;
+ }
+
+ return { files };
+}
+
+function collectLockDir(cwd: string): { files: string[] } {
+ const lockDir = join(cwd, '.ok', 'local');
+ if (!existsSync(lockDir)) return { files: [] };
+
+ const candidates = ['server.lock', 'last-spawn-error.log'];
+ const found = candidates.map((f) => join(lockDir, f)).filter((f) => existsSync(f));
+
+ return { files: found };
+}
+
+// Server-side diagnostic logs from the runtime pino file sink — including the
+// `renderer` subsystem fed by the web client-log ingest (`/api/client-logs`).
+// Path + filenames mirror `logsCurrentPath`/`logsPreviousPath` in
+// `packages/server/src/telemetry-file-sink.ts`; hardcoded here so the CLI
+// bug-report path doesn't pull in the server module graph.
+function collectLocalSinkLogs(cwd: string): { files: string[] } {
+ const logsDir = join(cwd, '.ok', 'local', 'logs');
+ if (!existsSync(logsDir)) return { files: [] };
+
+ const candidates = ['server-current.jsonl', 'server-prev.jsonl'];
+ const found = candidates.map((f) => join(logsDir, f)).filter((f) => existsSync(f));
+
+ return { files: found };
+}
+
+function addTextEntry(args: {
+ zipfile: ZipFile;
+ name: string;
+ content: string;
+ redact: boolean;
+ bundleFiles: string[];
+ redactions: BundleRedaction[];
+}): void {
+ if (args.redact) {
+ const { redacted, patterns, lineCount } = redactContent(args.content);
+ args.zipfile.addBuffer(Buffer.from(redacted, 'utf8'), args.name);
+ args.bundleFiles.push(args.name);
+ if (patterns.length > 0) {
+ args.redactions.push({ file: args.name, lineCount, patterns });
+ }
+ } else {
+ args.zipfile.addBuffer(Buffer.from(args.content, 'utf8'), args.name);
+ args.bundleFiles.push(args.name);
+ }
+}
+
+function addContentFiles(args: {
+ zipfile: ZipFile;
+ files: string[];
+ prefix: string;
+ redact: boolean;
+ bundleFiles: string[];
+ redactions: BundleRedaction[];
+ logger?: BundleLogger;
+}): void {
+ for (const file of args.files) {
+ try {
+ addTextEntry({
+ zipfile: args.zipfile,
+ name: `${args.prefix}/${basename(file)}`,
+ content: readFileSync(file, 'utf8'),
+ redact: args.redact,
+ bundleFiles: args.bundleFiles,
+ redactions: args.redactions,
+ });
+ } catch (err) {
+ // A file we listed but can't read is dropped rather than aborting the
+ // whole report; log it so the omission is diagnosable — the bundled
+ // MANIFEST lists only what was written, never what was skipped.
+ args.logger?.warn(
+ { file, prefix: args.prefix, err: err instanceof Error ? err.message : String(err) },
+ 'bug-report: skipped unreadable file',
+ );
+ }
+ }
+}
+
+/**
+ * Collect the standard bug-report content set and write it as a zip to
+ * `outputPath`. Returns the zip path plus a summary mirroring the bundled
+ * MANIFEST.json (file inventory + redaction audit).
+ */
+export async function collectStandardBundle(
+ opts: CollectStandardBundleOptions,
+): Promise<StandardBundleResult> {
+ const { redact, outputPath, logger } = opts;
+ const userLogsDir = opts.userLogsDir ?? join(homedir(), '.ok', 'logs');
+ const projectSlug = opts.projectDir ? resolveProjectSlug(opts.projectDir, logger) : null;
+
+ mkdirSync(dirname(outputPath), { recursive: true });
+
+ logger?.info({ projectSlug }, 'gathering diagnostic data');
+
+ const sysinfo = collectSysinfo();
+ // Always present so a recipient can distinguish "not an Electron host"
+ // (null) from a bundle predating the field (absent).
+ sysinfo.desktop = opts.desktop ?? null;
+ const { files: logFiles } = collectLogs(projectSlug, userLogsDir);
+ const { files: lockFiles } = opts.projectDir ? collectLockDir(opts.projectDir) : { files: [] };
+ const { files: localSinkFiles } = opts.projectDir
+ ? collectLocalSinkLogs(opts.projectDir)
+ : { files: [] };
+
+ logger?.info(
+ {
+ logFileCount: logFiles.length,
+ lockFileCount: lockFiles.length,
+ localSinkFileCount: localSinkFiles.length,
+ },
+ 'files collected',
+ );
+
+ const redactions: BundleRedaction[] = [];
+ const bundleFiles: string[] = [];
+
+ const { ZipFile } = await import('yazl');
+ const zipfile = new ZipFile();
+
+ addContentFiles({
+ zipfile,
+ files: logFiles,
+ prefix: 'logs',
+ redact,
+ bundleFiles,
+ redactions,
+ logger,
+ });
+ addContentFiles({
+ zipfile,
+ files: lockFiles,
+ prefix: 'lockdir',
+ redact,
+ bundleFiles,
+ redactions,
+ logger,
+ });
+ addContentFiles({
+ zipfile,
+ files: localSinkFiles,
+ prefix: 'local-logs',
+ redact,
+ bundleFiles,
+ redactions,
+ logger,
+ });
+
+ for (const extra of opts.extraFiles ?? []) {
+ try {
+ // Raw bytes on purpose: extras are binary payloads (crash minidumps)
+ // that the text scrub would corrupt.
+ const raw = readFileSync(extra.sourcePath);
+ const name = `extra/${extra.zipName ?? basename(extra.sourcePath)}`;
+ zipfile.addBuffer(raw, name);
+ bundleFiles.push(name);
+ } catch (err) {
+ // Unlike the best-effort log/lock sources, an extra is an artifact the
+ // user explicitly opted into sharing — its absence must be traceable,
+ // not silent.
+ logger?.warn(
+ { sourcePath: extra.sourcePath, err },
+ 'extra file unreadable; omitted from bundle',
+ );
+ }
+ }
+
+ if (opts.note) {
+ addTextEntry({
+ zipfile,
+ name: 'note.txt',
+ content: opts.note,
+ redact,
+ bundleFiles,
+ redactions,
+ });
+ }
+
+ const sysinfoJson = JSON.stringify(sysinfo, null, 2);
+ zipfile.addBuffer(Buffer.from(sysinfoJson, 'utf8'), 'sysinfo.json');
+ bundleFiles.push('sysinfo.json');
+
+ const manifest: BundleManifest = {
+ generatedAt: new Date().toISOString(),
+ disciplineVersion: '1.0.0',
+ projectSlug,
+ files: bundleFiles,
+ redactions,
+ sysinfo: sysinfo as Record<string, import('@inkeep/open-knowledge-core').Loggable>,
+ };
+ zipfile.addBuffer(Buffer.from(JSON.stringify(manifest, null, 2), 'utf8'), 'MANIFEST.json');
+
+ const totalRedacted = redactions.reduce((sum, r) => sum + r.lineCount, 0);
+ const readme = [
+ '# Bug Report Bundle',
+ '',
+ `Generated: ${manifest.generatedAt}`,
+ `Project: ${projectSlug ?? '(unscoped)'}`,
+ `Discipline version: ${manifest.disciplineVersion}`,
+ '',
+ '## Contents',
+ '',
+ ...bundleFiles.map((f) => `- ${f}`),
+ '',
+ '## Privacy',
+ '',
+ ...(redact
+ ? [
+ 'This bundle was auto-redacted before packaging.',
+ `Patterns checked: ${SECRET_PATTERN_NAMES.join(', ')}`,
+ totalRedacted > 0
+ ? `${totalRedacted} line(s) were scrubbed across ${redactions.length} file(s).`
+ : 'No redactions were needed.',
+ 'See MANIFEST.json for the full redaction audit report.',
+ '',
+ 'This bundle is safe to attach to a GitHub issue.',
+ ]
+ : ['Redaction was disabled for this bundle; file contents are unmodified.']),
+ ].join('\n');
+ zipfile.addBuffer(Buffer.from(readme, 'utf8'), 'README.md');
+
+ zipfile.end();
+ const output = createWriteStream(outputPath);
+ zipfile.outputStream.pipe(output);
+ await new Promise<void>((resolvePromise, reject) => {
+ output.on('close', resolvePromise);
+ output.on('error', reject);
+ });
+
+ logger?.info(
+ { bundlePath: outputPath, fileCount: bundleFiles.length, redactionCount: totalRedacted },
+ 'bundle written',
+ );
+
+ return {
+ zipPath: outputPath,
+ summary: {
+ projectSlug,
+ files: bundleFiles,
+ redactions,
+ redactedLineCount: totalRedacted,
+ generatedAt: manifest.generatedAt,
+ },
+ };
+}
diff --git a/packages/cli/src/commands/bug-report.ts b/packages/cli/src/commands/bug-report.ts
index f26436a69..c684b473c 100644
--- a/packages/cli/src/commands/bug-report.ts
+++ b/packages/cli/src/commands/bug-report.ts
@@ -1,261 +1,10 @@
-import { spawn as childSpawn, execSync } from 'node:child_process';
-import { createHash } from 'node:crypto';
-import { createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';
-import { freemem, homedir, type as osType, platform, release, totalmem, uptime } from 'node:os';
-import { basename, join, resolve } from 'node:path';
-import type { BundleManifest, BundleRedaction } from '@inkeep/open-knowledge-core';
+import { spawn as childSpawn } from 'node:child_process';
+import { platform } from 'node:os';
import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import { getCliLogger } from '../cli.ts';
-import { redactContent, SECRET_PATTERN_NAMES } from './bug-report-redact.ts';
-
-const OK_LOGS_DIR = join(homedir(), '.ok', 'logs');
-const OK_BUGS_DIR = join(homedir(), '.ok', 'bug-reports');
-
-function resolveProjectSlug(cwd: string): string | null {
- const configPath = join(cwd, '.ok', 'config.yml');
- if (existsSync(configPath)) {
- try {
- const content = readFileSync(configPath, 'utf8');
- const nameMatch = content.match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);
- if (nameMatch?.[1]) return nameMatch[1];
- } catch {}
- }
-
- if (existsSync(join(cwd, '.ok'))) {
- return createHash('sha256').update(resolve(cwd)).digest('hex').slice(0, 12);
- }
-
- return null;
-}
-
-function collectSysinfo(): Record<string, unknown> {
- const info: Record<string, unknown> = {
- timestamp: new Date().toISOString(),
- platform: platform(),
- osType: osType(),
- osRelease: release(),
- hostname: '[redacted]',
- uptime: uptime(),
- freeMem: freemem(),
- totalMem: totalmem(),
- nodeVersion: process.version,
- bunVersion: process.versions.bun ?? null,
- v8Version: process.versions.v8 ?? null,
- pid: process.pid,
- };
-
- try {
- const ver = execSync(
- 'sw_vers -productVersion 2>/dev/null',
- withHiddenWindowsConsole({ encoding: 'utf8' }),
- ).trim();
- info.macosVersion = ver;
- } catch {}
-
- try {
- const pkgPath = join(__dirname, '..', '..', 'package.json');
- if (existsSync(pkgPath)) {
- const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
- info.okVersion = pkg.version;
- }
- } catch {}
-
- return info;
-}
-
-function collectLogs(projectSlug: string | null): { files: string[]; dir: string } {
- if (!existsSync(OK_LOGS_DIR)) return { files: [], dir: OK_LOGS_DIR };
-
- let files = readdirSync(OK_LOGS_DIR)
- .filter((f) => f.endsWith('.log') || /\.log\.\d+$/.test(f))
- .map((f) => join(OK_LOGS_DIR, f));
-
- if (projectSlug && files.length > 0) {
- const filtered = files.filter((f) => {
- try {
- const content = readFileSync(f, 'utf8');
- return content.includes(`"project":"${projectSlug}"`);
- } catch {
- return true;
- }
- });
- if (filtered.length > 0) files = filtered;
- }
-
- return { files, dir: OK_LOGS_DIR };
-}
-
-function collectLockDir(cwd: string): { files: string[]; dir: string | null } {
- const lockDir = join(cwd, '.ok', 'local');
- if (!existsSync(lockDir)) return { files: [], dir: null };
-
- const candidates = ['server.lock', 'last-spawn-error.log'];
- const found = candidates.map((f) => join(lockDir, f)).filter((f) => existsSync(f));
-
- return { files: found, dir: lockDir };
-}
-
-// Server-side diagnostic logs from the runtime pino file sink — including the
-// `renderer` subsystem fed by the web client-log ingest (`/api/client-logs`).
-// Path + filenames mirror `logsCurrentPath`/`logsPreviousPath` in
-// `packages/server/src/telemetry-file-sink.ts`; hardcoded here so the CLI
-// bug-report path doesn't pull in the server module graph.
-function collectLocalSinkLogs(cwd: string): { files: string[]; dir: string | null } {
- const logsDir = join(cwd, '.ok', 'local', 'logs');
- if (!existsSync(logsDir)) return { files: [], dir: null };
-
- const candidates = ['server-current.jsonl', 'server-prev.jsonl'];
- const found = candidates.map((f) => join(logsDir, f)).filter((f) => existsSync(f));
-
- return { files: found, dir: logsDir };
-}
-
-async function createBundle(opts: {
- projectSlug: string | null;
- cwd: string;
- noReveal: boolean;
-}): Promise<string> {
- const log = getCliLogger();
- mkdirSync(OK_BUGS_DIR, { recursive: true });
-
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
- const zipName = `${timestamp}-bugreport.zip`;
- const zipPath = join(OK_BUGS_DIR, zipName);
-
- log?.info({ projectSlug: opts.projectSlug }, 'gathering diagnostic data');
-
- const sysinfo = collectSysinfo();
- const { files: logFiles } = collectLogs(opts.projectSlug);
- const { files: lockFiles } = collectLockDir(opts.cwd);
- const { files: localSinkFiles } = collectLocalSinkLogs(opts.cwd);
-
- log?.info(
- {
- logFileCount: logFiles.length,
- lockFileCount: lockFiles.length,
- localSinkFileCount: localSinkFiles.length,
- },
- 'files collected',
- );
-
- const redactions: BundleRedaction[] = [];
- const bundleFiles: string[] = [];
-
- const { ZipFile } = await import('yazl');
- const zipfile = new ZipFile();
-
- for (const logFile of logFiles) {
- try {
- const raw = readFileSync(logFile, 'utf8');
- const { redacted, patterns, lineCount } = redactContent(raw);
- const name = `logs/${basename(logFile)}`;
- zipfile.addBuffer(Buffer.from(redacted, 'utf8'), name);
- bundleFiles.push(name);
- if (patterns.length > 0) {
- redactions.push({ file: name, lineCount, patterns });
- }
- } catch {}
- }
-
- for (const lockFile of lockFiles) {
- try {
- const raw = readFileSync(lockFile, 'utf8');
- const { redacted, patterns, lineCount } = redactContent(raw);
- const name = `lockdir/${basename(lockFile)}`;
- zipfile.addBuffer(Buffer.from(redacted, 'utf8'), name);
- bundleFiles.push(name);
- if (patterns.length > 0) {
- redactions.push({ file: name, lineCount, patterns });
- }
- } catch {}
- }
-
- for (const localSinkFile of localSinkFiles) {
- try {
- const raw = readFileSync(localSinkFile, 'utf8');
- const { redacted, patterns, lineCount } = redactContent(raw);
- const name = `local-logs/${basename(localSinkFile)}`;
- zipfile.addBuffer(Buffer.from(redacted, 'utf8'), name);
- bundleFiles.push(name);
- if (patterns.length > 0) {
- redactions.push({ file: name, lineCount, patterns });
- }
- } catch {}
- }
-
- const sysinfoJson = JSON.stringify(sysinfo, null, 2);
- zipfile.addBuffer(Buffer.from(sysinfoJson, 'utf8'), 'sysinfo.json');
- bundleFiles.push('sysinfo.json');
-
- const manifest: BundleManifest = {
- generatedAt: new Date().toISOString(),
- disciplineVersion: '1.0.0',
- projectSlug: opts.projectSlug,
- files: bundleFiles,
- redactions,
- sysinfo: sysinfo as Record<string, import('@inkeep/open-knowledge-core').Loggable>,
- };
- zipfile.addBuffer(Buffer.from(JSON.stringify(manifest, null, 2), 'utf8'), 'MANIFEST.json');
-
- const totalRedacted = redactions.reduce((sum, r) => sum + r.lineCount, 0);
- const readme = [
- '# Bug Report Bundle',
- '',
- `Generated: ${manifest.generatedAt}`,
- `Project: ${opts.projectSlug ?? '(unscoped)'}`,
- `Discipline version: ${manifest.disciplineVersion}`,
- '',
- '## Contents',
- '',
- ...bundleFiles.map((f) => `- ${f}`),
- '',
- '## Privacy',
- '',
- 'This bundle was auto-redacted before packaging.',
- `Patterns checked: ${SECRET_PATTERN_NAMES.join(', ')}`,
- totalRedacted > 0
- ? `${totalRedacted} line(s) were scrubbed across ${redactions.length} file(s).`
- : 'No redactions were needed.',
- 'See MANIFEST.json for the full redaction audit report.',
- '',
- 'This bundle is safe to attach to a GitHub issue.',
- ].join('\n');
- zipfile.addBuffer(Buffer.from(readme, 'utf8'), 'README.md');
-
- zipfile.end();
- const output = createWriteStream(zipPath);
- zipfile.outputStream.pipe(output);
- await new Promise<void>((resolve, reject) => {
- output.on('close', resolve);
- output.on('error', reject);
- });
-
- log?.info(
- { bundlePath: zipPath, fileCount: bundleFiles.length, redactionCount: totalRedacted },
- 'bundle written',
- );
-
- process.stdout.write(`${zipPath}\n`);
-
- if (totalRedacted > 0) {
- process.stderr.write(
- `ok bug-report: ${totalRedacted} line(s) auto-redacted across ${redactions.length} file(s)\n`,
- );
- }
-
- if (!opts.noReveal && platform() === 'darwin') {
- try {
- childSpawn(
- '/usr/bin/open',
- ['-R', zipPath],
- withHiddenWindowsConsole({ detached: true, stdio: 'ignore' as const }),
- ).unref();
- } catch {}
- }
-
- return zipPath;
-}
+import { collectReportBundle } from '../report-bundle.ts';
+import { defaultBugReportZipPath } from './bug-report-bundle.ts';
export function bugReportCommand(): Command {
return new Command('bug-report')
@@ -263,15 +12,32 @@ export function bugReportCommand(): Command {
.option('--reveal', 'Reveal the bundle in Finder (default: true)', true)
.option('--no-reveal', 'Do not reveal the bundle in Finder')
.action(async (opts: { reveal: boolean }) => {
- const cwd = process.cwd();
- const projectSlug = resolveProjectSlug(cwd);
-
try {
- await createBundle({
- projectSlug,
- cwd,
- noReveal: !opts.reveal,
+ const { zipPath, summary } = await collectReportBundle({
+ level: 'standard',
+ projectDir: process.cwd(),
+ redact: true,
+ outputPath: defaultBugReportZipPath(),
+ logger: getCliLogger(),
});
+
+ process.stdout.write(`${zipPath}\n`);
+
+ if (summary.redactedLineCount > 0) {
+ process.stderr.write(
+ `ok bug-report: ${summary.redactedLineCount} line(s) auto-redacted across ${summary.redactions.length} file(s)\n`,
+ );
+ }
+
+ if (opts.reveal && platform() === 'darwin') {
+ try {
+ childSpawn(
+ '/usr/bin/open',
+ ['-R', zipPath],
+ withHiddenWindowsConsole({ detached: true, stdio: 'ignore' as const }),
+ ).unref();
+ } catch {}
+ }
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
process.stderr.write(`ok bug-report: failed — ${msg}\n`);
diff --git a/packages/cli/src/diagnose/bundle.test.ts b/packages/cli/src/diagnose/bundle.test.ts
index f4051975d..89d0247f4 100644
--- a/packages/cli/src/diagnose/bundle.test.ts
+++ b/packages/cli/src/diagnose/bundle.test.ts
@@ -7,7 +7,16 @@
*/
import { afterEach, describe, expect, test } from 'bun:test';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { ZipFile } from 'yazl';
@@ -604,3 +613,42 @@ describe('collectBundle — manifest.telemetry.localSink cascade', () => {
collected.cleanup();
});
});
+
+// ---------------------------------------------------------------------------
+// Staging cleanup on a mid-staging throw
+// ---------------------------------------------------------------------------
+
+describe('collectBundle — staging cleanup on throw', () => {
+ test('a mid-staging throw removes the staging dir instead of stranding staged copies', async () => {
+ const marker = `staging-leak-${randomUUID()}`;
+ const contentDir = makeTmpDir();
+ // Staged before `readRuntime` runs, so by the time the injected failure
+ // fires, this bundle's bytes already sit in the tmpdir staging area.
+ writeAt(contentDir, '.ok/local/logs/server-current.jsonl', `{"msg":"${marker}"}\n`);
+
+ await expect(
+ collectBundle({
+ contentDir,
+ deps: makeDeterministicDeps({
+ readRuntime: () => {
+ throw new Error('runtime probe failed');
+ },
+ }),
+ }),
+ ).rejects.toThrow('runtime probe failed');
+
+ // Content-marker scan instead of a directory diff: concurrently running
+ // suites also create `ok-bundle-*` staging dirs, but only this bundle can
+ // contain the marker.
+ const candidates = readdirSync(tmpdir()).filter((d) => d.startsWith('ok-bundle-'));
+ for (const dir of candidates) {
+ let staged = '';
+ try {
+ staged = readFileSync(join(tmpdir(), dir, 'logs', 'server-current.jsonl'), 'utf-8');
+ } catch {
+ // Another suite's staging dir (different layout, or already cleaned).
+ }
+ expect(staged).not.toContain(marker);
+ }
+ });
+});
diff --git a/packages/cli/src/diagnose/bundle.ts b/packages/cli/src/diagnose/bundle.ts
index 35918fe28..16e522989 100644
--- a/packages/cli/src/diagnose/bundle.ts
+++ b/packages/cli/src/diagnose/bundle.ts
@@ -28,6 +28,7 @@ import {
} from 'node:fs';
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 {
DEFAULT_LOGS_MAX_BYTES,
DEFAULT_SPANS_MAX_BYTES,
@@ -36,6 +37,8 @@ import {
import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';
import { parse as parseYaml } from 'yaml';
import { ZipFile } from 'yazl';
+import type { BundleExtraFile, BundleLogger } from '../commands/bug-report-bundle.ts';
+import { redactContent } from '../commands/bug-report-redact.ts';
import { PACKAGE_VERSION } from '../constants.ts';
import { type RedactStagedBundleResult, redactStagedBundle } from './bundle-redact.ts';
@@ -47,12 +50,14 @@ import { type RedactStagedBundleResult, redactStagedBundle } from './bundle-reda
// (`collected.manifest.X` / `collected.summary.X`). They stay file-local for
// now; consumers (the deferred `/report-bug` skill) can index into the public
// types — e.g., `CollectedBundle['manifest']['files'][number]` — without
-// needing to import each interface by name.
+// needing to import each interface by name. `DesktopMetadata` is the one
+// exception: it is exported as the value type of the `readDesktopEnv` seam so
+// `collectReportBundle` callers (the desktop app) can inject host metadata.
/** Schema version pinned at 1 for v1 bundles. */
type BundleSchemaVersion = 1;
-interface DesktopMetadata {
+export interface DesktopMetadata {
electronVersion: string;
packaged: boolean;
channel: string;
@@ -72,6 +77,13 @@ interface BundleFileEntry {
lines: number;
}
+interface BundleSecretScrub {
+ /** Per-file audit (zip-relative paths) — only files where a pattern matched. */
+ redactions: SecretScrubEntry[];
+ /** Total lines scrubbed across all files. */
+ redactedLineCount: number;
+}
+
interface BundleRedaction {
applied: boolean;
/**
@@ -90,6 +102,12 @@ interface BundleRedaction {
* those hashes.
*/
docNameCollisions?: Record<string, string[]>;
+ /**
+ * Audit of the secret-pattern scrub (the `ok bug-report` scrub applied to
+ * the staged copies). Present only when the collector ran with
+ * `scrubSecrets`.
+ */
+ secretScrub?: BundleSecretScrub;
}
type BundleServerStatus = 'running' | 'not-running';
@@ -158,6 +176,20 @@ export interface CollectBundleOpts {
* staged copies.
*/
redact?: boolean;
+ /**
+ * Apply the bug-report secret-pattern scrub to every staged text file
+ * (.jsonl/.json/.txt/.log/.lock). Staged copies only — originals on disk
+ * are untouched. Audit lands in `manifest.redaction.secretScrub`.
+ */
+ scrubSecrets?: boolean;
+ /** User note staged verbatim as `note.txt` at the bundle root. */
+ note?: string;
+ /**
+ * Files copied byte-for-byte under `extra/` (e.g. an opted-in crash
+ * minidump). Staged after the secret scrub — binary payloads must never be
+ * text-scrubbed.
+ */
+ extraFiles?: BundleExtraFile[];
/** Test-injectable dependencies — every field defaults to a real-system implementation. */
deps?: CollectBundleDeps;
}
@@ -188,6 +220,8 @@ export interface CollectBundleDeps {
* 'false'` in production — exposed for tests so the gate is observable.
*/
isOtlpPushEnabled?: () => boolean;
+ /** Sink for collection-quality warnings (e.g. an opted-in extra file that vanished). Absent means silent. */
+ logger?: BundleLogger;
}
interface BundleSummary {
@@ -315,7 +349,7 @@ function defaultReadShadowHead(contentDir: string): string | null {
return result.stdout ?? '';
}
-function defaultReadDesktopEnv(): DesktopMetadata | null {
+export function defaultReadDesktopEnv(): DesktopMetadata | null {
const electronVersion = process.env.OK_DESKTOP_VERSION;
const packagedRaw = process.env.OK_DESKTOP_PACKAGED;
const channel = process.env.OK_DESKTOP_CHANNEL;
@@ -492,6 +526,30 @@ function shouldCountLines(relPath: string): boolean {
return LINE_COUNTED_EXTENSIONS.has(relPath.slice(lastDot));
}
+const SECRET_SCRUB_EXTENSIONS = new Set(['.jsonl', '.json', '.txt', '.log', '.lock']);
+
+function isSecretScrubbable(relPath: string): boolean {
+ const lastDot = relPath.lastIndexOf('.');
+ if (lastDot === -1) return false;
+ return SECRET_SCRUB_EXTENSIONS.has(relPath.slice(lastDot));
+}
+
+function scrubStagedSecrets(stagingDir: string): BundleSecretScrub {
+ const redactions: SecretScrubEntry[] = [];
+ for (const absPath of walkStagedFiles(stagingDir)) {
+ const relPath = relativeZipPath(stagingDir, absPath);
+ if (!isSecretScrubbable(relPath)) continue;
+ const { redacted, patterns, lineCount } = redactContent(readFileSync(absPath, 'utf-8'));
+ if (patterns.length === 0) continue;
+ writeFileSync(absPath, redacted);
+ redactions.push({ file: relPath, lineCount, patterns });
+ }
+ return {
+ redactions,
+ redactedLineCount: redactions.reduce((sum, r) => sum + r.lineCount, 0),
+ };
+}
+
function relativeZipPath(stagingDir: string, absPath: string): string {
return relative(stagingDir, absPath).split(sep).join('/');
}
@@ -518,139 +576,147 @@ export async function collectBundle(opts: CollectBundleOpts): Promise<CollectedB
const isOtlpPushEnabled = deps.isOtlpPushEnabled ?? defaultIsOtlpPushEnabled;
const stagingDir = mkdtempSync(join(tmpdir(), 'ok-bundle-'));
- mkdirSync(join(stagingDir, 'telemetry'), { recursive: true });
- mkdirSync(join(stagingDir, 'logs'), { recursive: true });
- mkdirSync(join(stagingDir, 'state'), { recursive: true });
-
- stageFileIfPresent(spansCurrentPath(projectDir), join(stagingDir, 'telemetry', SPANS_CURRENT));
- stageFileIfPresent(spansPreviousPath(projectDir), join(stagingDir, 'telemetry', SPANS_PREVIOUS));
- stageFileIfPresent(logsCurrentPath(projectDir), join(stagingDir, 'logs', LOGS_CURRENT));
- stageFileIfPresent(logsPreviousPath(projectDir), join(stagingDir, 'logs', LOGS_PREVIOUS));
-
- // Server lock + status + agent presence.
- const lockDir = join(projectDir, '.ok', 'local');
- const lockPath = join(lockDir, 'server.lock');
- let serverStatus: BundleServerStatus = 'not-running';
- let serverStatusReason = 'no server.lock';
- let lockPort: number | null = null;
-
- if (existsSync(lockPath)) {
- stageFileIfPresent(lockPath, join(stagingDir, 'state', 'server.lock'));
- try {
- const lockContent = readFileSync(lockPath, 'utf-8');
- const lock = JSON.parse(lockContent) as { port?: number };
- if (typeof lock.port === 'number') {
- lockPort = lock.port;
+ try {
+ mkdirSync(join(stagingDir, 'telemetry'), { recursive: true });
+ mkdirSync(join(stagingDir, 'logs'), { recursive: true });
+ mkdirSync(join(stagingDir, 'state'), { recursive: true });
+
+ stageFileIfPresent(spansCurrentPath(projectDir), join(stagingDir, 'telemetry', SPANS_CURRENT));
+ stageFileIfPresent(
+ spansPreviousPath(projectDir),
+ join(stagingDir, 'telemetry', SPANS_PREVIOUS),
+ );
+ stageFileIfPresent(logsCurrentPath(projectDir), join(stagingDir, 'logs', LOGS_CURRENT));
+ stageFileIfPresent(logsPreviousPath(projectDir), join(stagingDir, 'logs', LOGS_PREVIOUS));
+
+ // Server lock + status + agent presence.
+ const lockDir = join(projectDir, '.ok', 'local');
+ const lockPath = join(lockDir, 'server.lock');
+ let serverStatus: BundleServerStatus = 'not-running';
+ let serverStatusReason = 'no server.lock';
+ let lockPort: number | null = null;
+
+ if (existsSync(lockPath)) {
+ stageFileIfPresent(lockPath, join(stagingDir, 'state', 'server.lock'));
+ try {
+ const lockContent = readFileSync(lockPath, 'utf-8');
+ const lock = JSON.parse(lockContent) as { port?: number };
+ if (typeof lock.port === 'number') {
+ lockPort = lock.port;
+ } else {
+ serverStatusReason = 'lock present but no port';
+ }
+ } catch {
+ serverStatusReason = 'lock present but unparseable';
+ }
+ }
+
+ if (lockPort !== null) {
+ const presence = await fetchAgentPresence(lockPort);
+ if (presence !== null) {
+ writeFileSync(join(stagingDir, 'state', 'agent-presence.json'), presence);
+ serverStatus = 'running';
+ serverStatusReason = '';
} else {
- serverStatusReason = 'lock present but no port';
+ serverStatusReason = `agent-presence endpoint at :${lockPort} unreachable`;
}
- } catch {
- serverStatusReason = 'lock present but unparseable';
}
- }
- if (lockPort !== null) {
- const presence = await fetchAgentPresence(lockPort);
- if (presence !== null) {
- writeFileSync(join(stagingDir, 'state', 'agent-presence.json'), presence);
- serverStatus = 'running';
- serverStatusReason = '';
- } else {
- serverStatusReason = `agent-presence endpoint at :${lockPort} unreachable`;
+ // Shadow-repo head — best effort.
+ const shadowHead = readShadowHead(contentDir);
+ if (shadowHead !== null) {
+ writeFileSync(join(stagingDir, 'state', 'shadow-head.txt'), shadowHead);
}
- }
- // Shadow-repo head — best effort.
- const shadowHead = readShadowHead(contentDir);
- if (shadowHead !== null) {
- writeFileSync(join(stagingDir, 'state', 'shadow-head.txt'), shadowHead);
- }
+ // last-spawn-error.log (Electron host writes this when a spawn fails).
+ stageFileIfPresent(
+ join(lockDir, 'last-spawn-error.log'),
+ join(stagingDir, 'state', 'last-spawn-error.log'),
+ );
- // last-spawn-error.log (Electron host writes this when a spawn fails).
- stageFileIfPresent(
- join(lockDir, 'last-spawn-error.log'),
- join(stagingDir, 'state', 'last-spawn-error.log'),
- );
+ // Runtime + desktop block.
+ const runtime = readRuntime();
+ const desktop = readDesktopEnv();
+ const runtimeJson = {
+ ok: {
+ version: okVersion(),
+ nodeVersion: runtime.nodeVersion,
+ platform: runtime.platform,
+ arch: runtime.arch,
+ },
+ host: { desktop },
+ };
+ writeFileSync(
+ join(stagingDir, 'state', 'runtime.json'),
+ `${JSON.stringify(runtimeJson, null, 2)}\n`,
+ );
- // Runtime + desktop block.
- const runtime = readRuntime();
- const desktop = readDesktopEnv();
- const runtimeJson = {
- ok: {
- version: okVersion(),
- nodeVersion: runtime.nodeVersion,
- platform: runtime.platform,
- arch: runtime.arch,
- },
- host: { desktop },
- };
- writeFileSync(
- join(stagingDir, 'state', 'runtime.json'),
- `${JSON.stringify(runtimeJson, null, 2)}\n`,
- );
+ const statusBody =
+ serverStatus === 'running' ? 'running\n' : `not-running (${serverStatusReason})\n`;
+ writeFileSync(join(stagingDir, 'state', 'server-status.txt'), statusBody);
- const statusBody =
- serverStatus === 'running' ? 'running\n' : `not-running (${serverStatusReason})\n`;
- writeFileSync(join(stagingDir, 'state', 'server-status.txt'), statusBody);
+ // process/ — only when caller hands us a pre-collected dir.
+ if (opts.processDir && existsSync(opts.processDir)) {
+ const processDest = join(stagingDir, 'process');
+ mkdirSync(processDest, { recursive: true });
+ cpSync(opts.processDir, processDest, { recursive: true });
+ }
- // process/ — only when caller hands us a pre-collected dir.
- if (opts.processDir && existsSync(opts.processDir)) {
- const processDest = join(stagingDir, 'process');
- mkdirSync(processDest, { recursive: true });
- cpSync(opts.processDir, processDest, { recursive: true });
- }
+ // Apply redaction to the staged copies BEFORE the file inventory walk so
+ // the recorded bytes/lines reflect post-redaction state. Originals on disk
+ // are not touched — only the staged copies in stagingDir. The redactor
+ // returns the inverse map for the manifest.
+ let redactionResult: RedactStagedBundleResult | null = null;
+ if (opts.redact === true) {
+ redactionResult = redactStagedBundle({ stagingDir, contentDir });
+ }
- // Apply redaction to the staged copies BEFORE the file inventory walk so
- // the recorded bytes/lines reflect post-redaction state. Originals on disk
- // are not touched — only the staged copies in stagingDir. The redactor
- // returns the inverse map for the manifest.
- let redactionResult: RedactStagedBundleResult | null = null;
- if (opts.redact === true) {
- redactionResult = redactStagedBundle({ stagingDir, contentDir });
- }
+ // Staged before the scrub so a secret pasted into the note gets caught too.
+ if (opts.note) {
+ writeFileSync(join(stagingDir, 'note.txt'), opts.note);
+ }
- // Manifest. Config lookup uses projectDir (where `.ok/config.yml` lives)
- // rather than contentDir — when `content.dir != '.'`, these differ and
- // contentDir wouldn't contain the project config file.
- const localSink = resolveLocalSinkBlock(projectDir);
- const stagedFiles = walkStagedFiles(stagingDir);
- const files: BundleFileEntry[] = [];
- let totalBytes = 0;
- let docNameCount = 0;
- for (const absPath of stagedFiles) {
- const relPath = relativeZipPath(stagingDir, absPath);
- const bytes = statSync(absPath).size;
- const lines = shouldCountLines(relPath) ? countLines(absPath) : 0;
- files.push({ path: relPath, bytes, lines });
- totalBytes += bytes;
- if (relPath.startsWith('telemetry/') && shouldCountLines(relPath)) {
- docNameCount += countDocNameOccurrences(absPath);
+ let secretScrub: BundleSecretScrub | null = null;
+ if (opts.scrubSecrets === true) {
+ secretScrub = scrubStagedSecrets(stagingDir);
+ }
+
+ for (const extra of opts.extraFiles ?? []) {
+ const staged = stageFileIfPresent(
+ extra.sourcePath,
+ join(stagingDir, 'extra', extra.zipName ?? basename(extra.sourcePath)),
+ );
+ if (!staged) {
+ // Unlike the availability-gated telemetry/log sources, an extra is an
+ // artifact the user explicitly opted into sharing (e.g. a crash
+ // minidump) — its absence must be traceable, not silent.
+ deps.logger?.warn(
+ { sourcePath: extra.sourcePath },
+ 'extra file missing; omitted from bundle',
+ );
+ }
+ }
+
+ // Manifest. Config lookup uses projectDir (where `.ok/config.yml` lives)
+ // rather than contentDir — when `content.dir != '.'`, these differ and
+ // contentDir wouldn't contain the project config file.
+ const localSink = resolveLocalSinkBlock(projectDir);
+ const stagedFiles = walkStagedFiles(stagingDir);
+ const files: BundleFileEntry[] = [];
+ let totalBytes = 0;
+ let docNameCount = 0;
+ for (const absPath of stagedFiles) {
+ const relPath = relativeZipPath(stagingDir, absPath);
+ const bytes = statSync(absPath).size;
+ const lines = shouldCountLines(relPath) ? countLines(absPath) : 0;
+ files.push({ path: relPath, bytes, lines });
+ totalBytes += bytes;
+ if (relPath.startsWith('telemetry/') && shouldCountLines(relPath)) {
+ docNameCount += countDocNameOccurrences(absPath);
+ }
}
- }
- const manifest: BundleManifest = {
- schemaVersion: 1,
- createdAt: now().toISOString(),
- ok: {
- version: okVersion(),
- nodeVersion: runtime.nodeVersion,
- platform: runtime.platform,
- arch: runtime.arch,
- },
- host: { desktop },
- contentDir: {
- // pathSha256 stays as the SHA-256 of the original absolute path — it's
- // a stable correlation identifier for the recipient. The absolutePath
- // string itself is masked when redaction is on so the bundle doesn't
- // leak the user's home directory layout.
- pathSha256: hashContentDirPath(contentDir),
- absolutePath: redactionResult !== null ? '<CONTENT_DIR>' : contentDir,
- },
- telemetry: {
- localSink,
- otlpPushEnabled: isOtlpPushEnabled(),
- },
- redaction:
+ const redaction: BundleRedaction =
redactionResult !== null
? Object.keys(redactionResult.docNameCollisions).length > 0
? {
@@ -659,50 +725,85 @@ export async function collectBundle(opts: CollectBundleOpts): Promise<CollectedB
docNameCollisions: redactionResult.docNameCollisions,
}
: { applied: true, docNameMapSidecar: null }
- : { applied: false, docNameMapSidecar: null },
- serverStatus,
- files,
- };
-
- writeFileSync(join(stagingDir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
-
- // contentDirVisible scan runs AFTER manifest write so it doesn't include
- // the manifest's own `absolutePath` field — the user's prompt cares about
- // JSONLs + state files where the path bleeds in via spans / logs / lock
- // metadata, not the recipient-facing inventory.
- const contentDirVisible = stagedFiles.some((absPath) => {
- try {
- return readFileSync(absPath, 'utf-8').includes(contentDir);
- } catch {
- // Binary file (cpuprofile, dmp) — skip the substring scan.
- return false;
+ : { applied: false, docNameMapSidecar: null };
+ if (secretScrub !== null) {
+ redaction.secretScrub = secretScrub;
}
- });
- const summary: BundleSummary = {
- totalBytes,
- fileCount: files.length,
- docNameCount,
- contentDirVisible,
- redacted: redactionResult !== null,
- };
+ const manifest: BundleManifest = {
+ schemaVersion: 1,
+ createdAt: now().toISOString(),
+ ok: {
+ version: okVersion(),
+ nodeVersion: runtime.nodeVersion,
+ platform: runtime.platform,
+ arch: runtime.arch,
+ },
+ host: { desktop },
+ contentDir: {
+ // pathSha256 stays as the SHA-256 of the original absolute path — it's
+ // a stable correlation identifier for the recipient. The absolutePath
+ // string itself is masked when redaction is on so the bundle doesn't
+ // leak the user's home directory layout.
+ pathSha256: hashContentDirPath(contentDir),
+ absolutePath: redactionResult !== null ? '<CONTENT_DIR>' : contentDir,
+ },
+ telemetry: {
+ localSink,
+ otlpPushEnabled: isOtlpPushEnabled(),
+ },
+ redaction,
+ serverStatus,
+ files,
+ };
- let cleaned = false;
- const cleanup = (): void => {
- if (cleaned) return;
- cleaned = true;
- rmSync(stagingDir, { recursive: true, force: true });
- };
+ writeFileSync(join(stagingDir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
+
+ // contentDirVisible scan runs AFTER manifest write so it doesn't include
+ // the manifest's own `absolutePath` field — the user's prompt cares about
+ // JSONLs + state files where the path bleeds in via spans / logs / lock
+ // metadata, not the recipient-facing inventory.
+ const contentDirVisible = stagedFiles.some((absPath) => {
+ try {
+ return readFileSync(absPath, 'utf-8').includes(contentDir);
+ } catch {
+ // Binary file (cpuprofile, dmp) — skip the substring scan.
+ return false;
+ }
+ });
- const redactionMapPayload =
- redactionResult !== null
- ? {
- docNameMap: redactionResult.docNameMap,
- docNameCollisions: redactionResult.docNameCollisions,
- }
- : null;
+ const summary: BundleSummary = {
+ totalBytes,
+ fileCount: files.length,
+ docNameCount,
+ contentDirVisible,
+ redacted: redactionResult !== null,
+ };
+
+ let cleaned = false;
+ const cleanup = (): void => {
+ if (cleaned) return;
+ cleaned = true;
+ rmSync(stagingDir, { recursive: true, force: true });
+ };
+
+ const redactionMapPayload =
+ redactionResult !== null
+ ? {
+ docNameMap: redactionResult.docNameMap,
+ docNameCollisions: redactionResult.docNameCollisions,
+ }
+ : null;
- return { stagingDir, manifest, summary, redactionMapPayload, cleanup };
+ return { stagingDir, manifest, summary, redactionMapPayload, cleanup };
+ } catch (err) {
+ // The cleanup handle only exists on the returned value, so a throw during
+ // staging is the one path where nobody else can release the tmpdir — and
+ // what would be stranded there are copies of logs and telemetry that may
+ // not have been redacted yet.
+ rmSync(stagingDir, { recursive: true, force: true });
+ throw err;
+ }
}
// ---------------------------------------------------------------------------
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 5cf1c39e0..78f4a9bf8 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -16,6 +16,15 @@ export {
makeLazyProbeTokenStore,
type TokenStore,
} from './auth/token-store.ts';
+export {
+ type BundleExtraFile,
+ type BundleLogger,
+ defaultBugReportZipPath,
+} from './commands/bug-report-bundle.ts';
+// The bug-report secret scrub — shared with the desktop send path so the
+// note travelling in upload metadata / the mailto body gets the same
+// treatment as the note.txt copy inside the bundle.
+export { redactContent } from './commands/bug-report-redact.ts';
export {
ALL_EDITOR_IDS,
buildManagedServerEntry,
@@ -120,6 +129,15 @@ export {
removeProjectSkill,
writeProjectSkill,
} from './integrations/write-project-skill.ts';
+// Leveled bug-report capture — shared by `ok bug-report` and the desktop
+// report-a-bug flow so the two stay in lockstep.
+export {
+ type CollectReportBundleOptions,
+ collectReportBundle,
+ type ReportBundleLevel,
+ type ReportBundleResult,
+ type ReportBundleSummary,
+} from './report-bundle.ts';
export {
addOkPathsToGitExclude,
type ExcludeWriteResult,
diff --git a/packages/cli/src/report-bundle.test.ts b/packages/cli/src/report-bundle.test.ts
new file mode 100644
index 000000000..f2ed52e12
--- /dev/null
+++ b/packages/cli/src/report-bundle.test.ts
@@ -0,0 +1,473 @@
+/**
+ * Tests for the leveled report-bundle entry. Real disk fixtures (no fs
+ * mocks) matching the bug-report-bundle conventions: injected userLogsDir
+ * keeps tests off the real `~/.ok`, and zip verification shells out to
+ * `unzip` rather than adding a parser dep.
+ */
+
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { collectReportBundle as collectReportBundleFromIndex } from './index.ts';
+import { collectReportBundle } from './report-bundle.ts';
+
+const tmpDirs: string[] = [];
+
+function makeTmpDir(prefix = 'ok-report-test-'): string {
+ const dir = mkdtempSync(resolve(tmpdir(), prefix));
+ tmpDirs.push(dir);
+ return dir;
+}
+
+afterEach(() => {
+ for (const d of tmpDirs) {
+ if (existsSync(d)) rmSync(d, { recursive: true, force: true });
+ }
+ tmpDirs.length = 0;
+});
+
+function writeAt(baseDir: string, relPath: string, body: string | Buffer): void {
+ const full = join(baseDir, relPath);
+ mkdirSync(dirname(full), { recursive: true });
+ writeFileSync(full, body);
+}
+
+function listZipEntries(zipPath: string): string[] {
+ const out = execSync(`unzip -Z1 ${JSON.stringify(zipPath)}`, { encoding: 'utf-8' });
+ return out.split('\n').filter(Boolean);
+}
+
+function readZipEntry(zipPath: string, entry: string): string {
+ return readZipEntryBuffer(zipPath, entry).toString('utf-8');
+}
+
+function readZipEntryBuffer(zipPath: string, entry: string): Buffer {
+ const extractDir = makeTmpDir('ok-report-extract-');
+ execSync(
+ `unzip -q -o ${JSON.stringify(zipPath)} ${JSON.stringify(entry)} -d ${JSON.stringify(extractDir)}`,
+ );
+ return readFileSync(join(extractDir, entry));
+}
+
+const SECRET = `ghp_${'a'.repeat(40)}`;
+
+function makeStandardProjectDir(slug = 'report-proj'): string {
+ const projectDir = makeTmpDir();
+ writeAt(projectDir, '.ok/config.yml', `name: ${slug}\n`);
+ writeAt(projectDir, '.ok/local/server.lock', '{"pid":1234}\n');
+ writeAt(projectDir, '.ok/local/last-spawn-error.log', 'spawn failed\n');
+ writeAt(projectDir, '.ok/local/logs/server-current.jsonl', '{"level":30}\n');
+ return projectDir;
+}
+
+/** A project with telemetry + log sinks but no shadow repo and no server lock. */
+function makeFullProjectDir(slug = 'full-proj'): string {
+ const projectDir = makeTmpDir();
+ writeAt(projectDir, '.ok/config.yml', `name: ${slug}\n`);
+ const span = JSON.stringify({
+ name: 'doc.write',
+ attributes: [{ key: 'doc.name', value: { stringValue: 'secret-notes/plan' } }],
+ });
+ const leak = JSON.stringify({ msg: `token ${SECRET}` });
+ writeAt(projectDir, '.ok/local/telemetry/spans-current.jsonl', `${span}\n${leak}\n`);
+ writeAt(projectDir, '.ok/local/logs/server-current.jsonl', '{"level":30,"msg":"boot"}\n');
+ return projectDir;
+}
+
+describe('collectReportBundle — standard level', () => {
+ test('packages the bug-report content set with level metadata in the summary', async () => {
+ const projectDir = makeStandardProjectDir();
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath, summary } = await collectReportBundle({
+ level: 'standard',
+ projectDir,
+ redact: true,
+ outputPath,
+ });
+
+ expect(zipPath).toBe(outputPath);
+ expect(existsSync(zipPath)).toBe(true);
+ const entries = listZipEntries(zipPath);
+ expect(entries).toContain('lockdir/server.lock');
+ expect(entries).toContain('lockdir/last-spawn-error.log');
+ expect(entries).toContain('local-logs/server-current.jsonl');
+ expect(entries).toContain('sysinfo.json');
+ expect(entries).toContain('MANIFEST.json');
+ expect(summary.level).toBe('standard');
+ expect(summary.systemWide).toBe(false);
+ expect(summary.projectSlug).toBe('report-proj');
+ expect(summary.files).toContain('lockdir/server.lock');
+ });
+
+ test('persists the note as note.txt, scrubbed and audited when redact is on', async () => {
+ const projectDir = makeStandardProjectDir();
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath, summary } = await collectReportBundle({
+ level: 'standard',
+ projectDir,
+ note: `crashed right after I pasted ${SECRET}`,
+ redact: true,
+ outputPath,
+ });
+
+ const note = readZipEntry(zipPath, 'note.txt');
+ expect(note).not.toContain(SECRET);
+ expect(note).toContain('[REDACTED-GH-PAT]');
+ const manifest = JSON.parse(readZipEntry(zipPath, 'MANIFEST.json'));
+ expect(manifest.files).toContain('note.txt');
+ expect(summary.files).toContain('note.txt');
+ const audit = summary.redactions.find((r) => r.file === 'note.txt');
+ expect(audit?.patterns).toContain('github-pat');
+ expect(summary.redactedLineCount).toBeGreaterThanOrEqual(1);
+ });
+
+ test('includes extra files byte-for-byte under extra/, never scrubbed', async () => {
+ const projectDir = makeStandardProjectDir();
+ const sourceDir = makeTmpDir();
+ const minidump = Buffer.concat([
+ Buffer.from([0x4d, 0x44, 0x4d, 0x50, 0x00, 0xff, 0xfe]),
+ Buffer.from(SECRET),
+ Buffer.from([0x00, 0x01, 0x02]),
+ ]);
+ writeAt(sourceDir, 'crash.dmp', minidump);
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath, summary } = await collectReportBundle({
+ level: 'standard',
+ projectDir,
+ redact: true,
+ outputPath,
+ extraFiles: [{ sourcePath: join(sourceDir, 'crash.dmp') }],
+ });
+
+ const bundled = readZipEntryBuffer(zipPath, 'extra/crash.dmp');
+ expect(bundled.equals(minidump)).toBe(true);
+ expect(summary.files).toContain('extra/crash.dmp');
+ });
+
+ test('produces a system-wide bundle when projectDir is omitted', async () => {
+ const userLogsDir = makeTmpDir();
+ writeAt(userLogsDir, 'cli.log', 'started\n');
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath, summary } = await collectReportBundle({
+ level: 'standard',
+ redact: true,
+ outputPath,
+ userLogsDir,
+ });
+
+ const entries = listZipEntries(zipPath);
+ expect(entries).toContain('logs/cli.log');
+ expect(entries).toContain('sysinfo.json');
+ expect(entries.some((e) => e.startsWith('lockdir/'))).toBe(false);
+ expect(summary.systemWide).toBe(true);
+ expect(summary.projectSlug).toBeNull();
+ });
+});
+
+describe('collectReportBundle — full level', () => {
+ test('produces the diagnose superset and omits unavailable pieces without error', async () => {
+ const projectDir = makeFullProjectDir();
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath, summary } = await collectReportBundle({
+ level: 'full',
+ projectDir,
+ redact: true,
+ outputPath,
+ });
+
+ const entries = listZipEntries(zipPath);
+ expect(entries).toContain('manifest.json');
+ expect(entries).toContain('telemetry/spans-current.jsonl');
+ expect(entries).toContain('logs/server-current.jsonl');
+ expect(entries).toContain('state/runtime.json');
+ expect(entries).toContain('state/server-status.txt');
+ // No shadow repo and no server lock in the fixture: both pieces are
+ // omitted, and the bundled manifest inventory reflects the omission.
+ expect(entries).not.toContain('state/shadow-head.txt');
+ expect(entries).not.toContain('state/server.lock');
+ expect(entries).not.toContain('state/agent-presence.json');
+ const manifest = JSON.parse(readZipEntry(zipPath, 'manifest.json'));
+ expect(manifest.schemaVersion).toBe(1);
+ expect(manifest.serverStatus).toBe('not-running');
+ const paths = manifest.files.map((f: { path: string }) => f.path);
+ expect(paths).not.toContain('state/shadow-head.txt');
+ expect(summary.level).toBe('full');
+ expect(summary.systemWide).toBe(false);
+ expect(summary.projectSlug).toBe('full-proj');
+ expect(summary.files).toEqual(paths);
+ });
+
+ test('omits telemetry entirely when the sink has never written', async () => {
+ const projectDir = makeTmpDir();
+ writeAt(projectDir, '.ok/config.yml', 'name: bare-proj\n');
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath } = await collectReportBundle({
+ level: 'full',
+ projectDir,
+ redact: true,
+ outputPath,
+ });
+
+ const entries = listZipEntries(zipPath);
+ expect(entries.some((e) => e.startsWith('telemetry/'))).toBe(false);
+ expect(entries).toContain('manifest.json');
+ });
+
+ test('scrubs seeded secrets, hashes doc names, and reports the audit', async () => {
+ const projectDir = makeFullProjectDir();
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath, summary } = await collectReportBundle({
+ level: 'full',
+ projectDir,
+ redact: true,
+ outputPath,
+ });
+
+ const spans = readZipEntry(zipPath, 'telemetry/spans-current.jsonl');
+ expect(spans).not.toContain(SECRET);
+ expect(spans).toContain('[REDACTED-GH-PAT]');
+ expect(spans).not.toContain('secret-notes/plan');
+ expect(spans).toContain('doc:');
+ const manifest = JSON.parse(readZipEntry(zipPath, 'manifest.json'));
+ expect(manifest.redaction.applied).toBe(true);
+ const scrub = manifest.redaction.secretScrub;
+ expect(scrub.redactions.map((r: { file: string }) => r.file)).toContain(
+ 'telemetry/spans-current.jsonl',
+ );
+ expect(summary.redactions).toEqual(scrub.redactions);
+ expect(summary.redactedLineCount).toBe(scrub.redactedLineCount);
+ expect(summary.redactedLineCount).toBeGreaterThanOrEqual(1);
+ // Inverse doc-name map lands as a sidecar next to the zip, never inside.
+ expect(existsSync(join(dirname(outputPath), 'report.docnames.json'))).toBe(true);
+ expect(listZipEntries(zipPath)).not.toContain('report.docnames.json');
+ });
+
+ test('redact: false leaves content unmodified with an empty audit', async () => {
+ const projectDir = makeFullProjectDir();
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath, summary } = await collectReportBundle({
+ level: 'full',
+ projectDir,
+ redact: false,
+ outputPath,
+ });
+
+ const spans = readZipEntry(zipPath, 'telemetry/spans-current.jsonl');
+ expect(spans).toContain(SECRET);
+ expect(spans).toContain('secret-notes/plan');
+ const manifest = JSON.parse(readZipEntry(zipPath, 'manifest.json'));
+ expect(manifest.redaction.applied).toBe(false);
+ expect(manifest.redaction.secretScrub).toBeUndefined();
+ expect(summary.redactions).toEqual([]);
+ expect(summary.redactedLineCount).toBe(0);
+ });
+
+ test('persists the note and extra files, creating output parents as needed', async () => {
+ const projectDir = makeFullProjectDir();
+ const sourceDir = makeTmpDir();
+ const minidump = Buffer.concat([
+ Buffer.from([0x4d, 0x44, 0x4d, 0x50, 0x00, 0xff]),
+ Buffer.from(SECRET),
+ ]);
+ writeAt(sourceDir, 'crash.dmp', minidump);
+ const outputPath = join(makeTmpDir(), 'nested', 'sub', 'report.zip');
+
+ const { zipPath, summary } = await collectReportBundle({
+ level: 'full',
+ projectDir,
+ note: 'Editor froze after paste',
+ redact: true,
+ outputPath,
+ extraFiles: [{ sourcePath: join(sourceDir, 'crash.dmp') }],
+ });
+
+ expect(readZipEntry(zipPath, 'note.txt')).toBe('Editor froze after paste');
+ const bundled = readZipEntryBuffer(zipPath, 'extra/crash.dmp');
+ expect(bundled.equals(minidump)).toBe(true);
+ const manifest = JSON.parse(readZipEntry(zipPath, 'manifest.json'));
+ const paths = manifest.files.map((f: { path: string }) => f.path);
+ expect(paths).toContain('note.txt');
+ expect(paths).toContain('extra/crash.dmp');
+ expect(summary.files).toContain('note.txt');
+ expect(summary.files).toContain('extra/crash.dmp');
+ });
+
+ test('scrubs a secret pasted into the note', async () => {
+ const projectDir = makeFullProjectDir();
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath, summary } = await collectReportBundle({
+ level: 'full',
+ projectDir,
+ note: `it broke after ${SECRET}`,
+ redact: true,
+ outputPath,
+ });
+
+ const note = readZipEntry(zipPath, 'note.txt');
+ expect(note).not.toContain(SECRET);
+ expect(note).toContain('[REDACTED-GH-PAT]');
+ expect(summary.redactions.some((r) => r.file === 'note.txt')).toBe(true);
+ });
+
+ test('falls back to the system-wide standard set when no project is in scope', async () => {
+ const userLogsDir = makeTmpDir();
+ writeAt(userLogsDir, 'cli.log', 'started\n');
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath, summary } = await collectReportBundle({
+ level: 'full',
+ redact: true,
+ outputPath,
+ userLogsDir,
+ });
+
+ const entries = listZipEntries(zipPath);
+ expect(entries).toContain('MANIFEST.json');
+ expect(entries).toContain('sysinfo.json');
+ expect(entries).toContain('logs/cli.log');
+ expect(entries).not.toContain('manifest.json');
+ expect(summary.level).toBe('full');
+ expect(summary.systemWide).toBe(true);
+ expect(summary.projectSlug).toBeNull();
+ });
+
+ test('resolves content.dir from the project config for the full capture', async () => {
+ const projectDir = makeTmpDir();
+ writeAt(projectDir, '.ok/config.yml', 'name: split-proj\ncontent:\n dir: docs\n');
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath } = await collectReportBundle({
+ level: 'full',
+ projectDir,
+ redact: false,
+ outputPath,
+ });
+
+ const manifest = JSON.parse(readZipEntry(zipPath, 'manifest.json'));
+ expect(manifest.contentDir.absolutePath).toBe(resolve(projectDir, 'docs'));
+ });
+});
+
+describe('collectReportBundle — desktop metadata seam', () => {
+ const DESKTOP = { electronVersion: '1.2.3', packaged: true, channel: 'latest' };
+
+ test('injected desktop metadata lands in the standard sysinfo and manifest', async () => {
+ const projectDir = makeStandardProjectDir();
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath } = await collectReportBundle({
+ level: 'standard',
+ projectDir,
+ redact: true,
+ outputPath,
+ readDesktopEnv: () => DESKTOP,
+ });
+
+ expect(JSON.parse(readZipEntry(zipPath, 'sysinfo.json')).desktop).toEqual(DESKTOP);
+ expect(JSON.parse(readZipEntry(zipPath, 'MANIFEST.json')).sysinfo.desktop).toEqual(DESKTOP);
+ });
+
+ test('injected desktop metadata lands in the full runtime block', async () => {
+ const projectDir = makeFullProjectDir();
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath } = await collectReportBundle({
+ level: 'full',
+ projectDir,
+ redact: false,
+ outputPath,
+ readDesktopEnv: () => DESKTOP,
+ });
+
+ expect(JSON.parse(readZipEntry(zipPath, 'state/runtime.json')).host.desktop).toEqual(DESKTOP);
+ });
+
+ test('a null seam records desktop: null at the standard level (not an Electron host)', async () => {
+ const projectDir = makeStandardProjectDir();
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath } = await collectReportBundle({
+ level: 'standard',
+ projectDir,
+ redact: true,
+ outputPath,
+ readDesktopEnv: () => null,
+ });
+
+ expect(JSON.parse(readZipEntry(zipPath, 'sysinfo.json')).desktop).toBeNull();
+ });
+});
+
+describe('collectReportBundle — opted-in extras that cannot be staged', () => {
+ function makeRecordingLogger() {
+ const warnings: Array<{ payload: Record<string, unknown>; message: string }> = [];
+ return {
+ logger: {
+ info: () => {},
+ warn: (payload: Record<string, unknown>, message: string) => {
+ warnings.push({ payload, message });
+ },
+ },
+ warnings,
+ };
+ }
+
+ test('standard level warns when an extra is unreadable and still builds the bundle', async () => {
+ const projectDir = makeStandardProjectDir();
+ const outputPath = join(makeTmpDir(), 'report.zip');
+ const missingDump = join(makeTmpDir(), 'vanished.dmp');
+ const { logger, warnings } = makeRecordingLogger();
+
+ const { zipPath, summary } = await collectReportBundle({
+ level: 'standard',
+ projectDir,
+ redact: true,
+ outputPath,
+ extraFiles: [{ sourcePath: missingDump }],
+ logger,
+ });
+
+ expect(existsSync(zipPath)).toBe(true);
+ expect(summary.files.some((f) => f.startsWith('extra/'))).toBe(false);
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]?.payload.sourcePath).toBe(missingDump);
+ });
+
+ test('full level warns when an extra is missing on disk and still builds the bundle', async () => {
+ const projectDir = makeFullProjectDir();
+ const outputPath = join(makeTmpDir(), 'report.zip');
+ const missingDump = join(makeTmpDir(), 'vanished.dmp');
+ const { logger, warnings } = makeRecordingLogger();
+
+ const { zipPath, summary } = await collectReportBundle({
+ level: 'full',
+ projectDir,
+ redact: true,
+ outputPath,
+ extraFiles: [{ sourcePath: missingDump }],
+ logger,
+ });
+
+ expect(existsSync(zipPath)).toBe(true);
+ expect(summary.files.some((f) => f.startsWith('extra/'))).toBe(false);
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]?.payload.sourcePath).toBe(missingDump);
+ });
+});
+
+describe('collectReportBundle — package surface', () => {
+ test('is exported from the package index', () => {
+ expect(collectReportBundleFromIndex).toBe(collectReportBundle);
+ });
+});
diff --git a/packages/cli/src/report-bundle.ts b/packages/cli/src/report-bundle.ts
new file mode 100644
index 000000000..51d0c5474
--- /dev/null
+++ b/packages/cli/src/report-bundle.ts
@@ -0,0 +1,190 @@
+/**
+ * Leveled bug-report capture — the one entry shared by the `ok bug-report`
+ * CLI command and the desktop report-a-bug flow, so the two stay in lockstep.
+ * `standard` wraps the bug-report capture; `full` wraps the diagnose bundle
+ * collector (`diagnose/bundle.ts`) two-step contract.
+ */
+
+import { existsSync, mkdirSync, readFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import type {
+ ReportBundleLevel as CoreReportBundleLevel,
+ ReportBundleSummary as CoreReportBundleSummary,
+} from '@inkeep/open-knowledge-core';
+import { parse as parseYaml } from 'yaml';
+import {
+ type BundleExtraFile,
+ type BundleLogger,
+ collectStandardBundle,
+ resolveProjectSlug,
+} from './commands/bug-report-bundle.ts';
+import {
+ collectBundle,
+ type DesktopMetadata,
+ defaultReadDesktopEnv,
+ writeBundle,
+} from './diagnose/bundle.ts';
+import { isObject } from './utils/is-object.ts';
+
+// The level + summary types live in core so the desktop bridge contract's
+// per-package copies (core / desktop / app renderer) can all name the same
+// types; aliased here (not `export ... from` — that re-export form trips a
+// rolldown-plugin-dts chunk bug) so this module stays the CLI's one public
+// entry for the leveled capture.
+export type ReportBundleLevel = CoreReportBundleLevel;
+export type ReportBundleSummary = CoreReportBundleSummary;
+
+export interface CollectReportBundleOptions {
+ level: ReportBundleLevel;
+ /**
+ * Project root (where `.ok/` lives). Omit for a system-wide bundle:
+ * user-level logs + sysinfo only.
+ */
+ projectDir?: string;
+ /** Free-text user note included as `note.txt`. */
+ note?: string;
+ /** Apply redaction (secret-pattern scrub at both levels; doc-name anonymization at `full`). */
+ redact: boolean;
+ /** Zip destination; parent directories are created as needed. */
+ outputPath: string;
+ /** Files included byte-for-byte under `extra/` (e.g. an opted-in minidump) — never scrubbed. */
+ extraFiles?: BundleExtraFile[];
+ /** Override the user-level logs directory (standard-level test seam). */
+ userLogsDir?: 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
+ * file that could not be staged).
+ */
+ logger?: BundleLogger;
+ /**
+ * Host (desktop) metadata source for the bundle's runtime/sysinfo blocks.
+ * Defaults to reading the `OK_DESKTOP_*` env block, so CLI invocations are
+ * unchanged; the desktop app injects its typed metadata here directly
+ * instead of mutating `process.env` (which would leak into any child later
+ * spawned with the main process's env). Returning `null` means "not an
+ * Electron host" and is recorded as such at both levels.
+ */
+ readDesktopEnv?: () => DesktopMetadata | null;
+}
+
+export interface ReportBundleResult {
+ zipPath: string;
+ summary: ReportBundleSummary;
+}
+
+/**
+ * Read `content.dir` from the project config, falling back to the project
+ * root. Deliberately fail-open (no throw on a missing/corrupt config): a
+ * broken config may be the very problem being reported, and the capture must
+ * still succeed.
+ */
+function resolveContentDir(projectDir: string, logger?: BundleLogger): string {
+ const configPath = join(projectDir, '.ok', 'config.yml');
+ if (existsSync(configPath)) {
+ try {
+ const parsed: unknown = parseYaml(readFileSync(configPath, 'utf-8'));
+ const content = isObject(parsed) ? parsed.content : undefined;
+ const dir = isObject(content) ? content.dir : undefined;
+ if (typeof dir === 'string' && dir.length > 0) {
+ return resolve(projectDir, dir);
+ }
+ } catch (err) {
+ // A malformed or unreadable .ok/config.yml falls back to the project
+ // root (the bundle should still succeed), but log it so a wrong
+ // content-dir in the resulting bundle is diagnosable, not silent.
+ logger?.warn(
+ { configPath, err: err instanceof Error ? err.message : String(err) },
+ 'bug-report: failed to read .ok/config.yml; falling back to project root as content dir',
+ );
+ }
+ }
+ return resolve(projectDir);
+}
+
+async function collectFullBundle(
+ opts: CollectReportBundleOptions,
+ projectDir: string,
+ readDesktopEnv: () => DesktopMetadata | null,
+): Promise<ReportBundleResult> {
+ const collected = await collectBundle({
+ contentDir: resolveContentDir(projectDir, opts.logger),
+ projectDir,
+ redact: opts.redact,
+ scrubSecrets: opts.redact,
+ note: opts.note,
+ extraFiles: opts.extraFiles,
+ deps: { readDesktopEnv, logger: opts.logger },
+ });
+ try {
+ mkdirSync(dirname(opts.outputPath), { recursive: true });
+ await writeBundle({ collected, outputPath: opts.outputPath });
+ const scrub = collected.manifest.redaction.secretScrub;
+ return {
+ zipPath: opts.outputPath,
+ summary: {
+ level: 'full',
+ systemWide: false,
+ projectSlug: resolveProjectSlug(projectDir, opts.logger),
+ files: collected.manifest.files.map((f) => f.path),
+ redactions: scrub?.redactions ?? [],
+ redactedLineCount: scrub?.redactedLineCount ?? 0,
+ generatedAt: collected.manifest.createdAt,
+ },
+ };
+ } finally {
+ collected.cleanup();
+ }
+}
+
+/**
+ * Collect a bug-report bundle at the requested detail level and write it as
+ * a zip to `outputPath`.
+ *
+ * - `standard`: the `ok bug-report` content set — user-level logs,
+ * per-project lock/spawn-error + local sink logs, sysinfo. No git/server
+ * dependency.
+ * - `full`: the `ok diagnose bundle` superset — adds telemetry spans, live
+ * server state, runtime metadata, and doc-name anonymization.
+ * Availability-gated: pieces whose source is missing (no running server,
+ * no shadow repo, no telemetry sink) are omitted without error, and the
+ * bundled manifest inventory reflects what was actually included.
+ *
+ * Every full-only artifact is project-scoped, so without a `projectDir` both
+ * levels produce the same system-wide bundle.
+ *
+ * With `redact` on, the secret-pattern scrub applies at both levels; the
+ * full level additionally hashes doc names and masks the content-dir path
+ * (inverse map written as a sidecar next to the zip, never inside it).
+ */
+export async function collectReportBundle(
+ opts: CollectReportBundleOptions,
+): Promise<ReportBundleResult> {
+ const { projectDir } = opts;
+ const readDesktopEnv = opts.readDesktopEnv ?? defaultReadDesktopEnv;
+ if (opts.level === 'full' && projectDir !== undefined) {
+ return collectFullBundle(opts, projectDir, readDesktopEnv);
+ }
+ const { zipPath, summary } = await collectStandardBundle({
+ projectDir,
+ redact: opts.redact,
+ outputPath: opts.outputPath,
+ userLogsDir: opts.userLogsDir,
+ logger: opts.logger,
+ note: opts.note,
+ extraFiles: opts.extraFiles,
+ desktop: readDesktopEnv(),
+ });
+ return {
+ zipPath,
+ summary: {
+ level: opts.level,
+ systemWide: projectDir === undefined,
+ projectSlug: summary.projectSlug,
+ files: summary.files,
+ redactions: summary.redactions,
+ redactedLineCount: summary.redactedLineCount,
+ generatedAt: summary.generatedAt,
+ },
+ };
+}
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 5eefd0da2..2ecdeedf0 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -17,6 +17,14 @@ import type {
WorktreeListResult,
} from './git/worktree-selector-model.ts';
import type { TerminalCli } from './handoff/terminal-launch.ts';
+import type {
+ OkBugReportCrashAckResult,
+ OkBugReportCrashDetectedEvent,
+ OkBugReportCreateResult,
+ OkBugReportSendMetadata,
+ OkBugReportSendResult,
+ ReportBundleLevel,
+} from './logger-types.ts';
import type { LocalOpOkInitResponse } from './schemas/api/local-op.ts';
import type {
BranchInfoResponse,
@@ -97,7 +105,11 @@ type OkMenuAction =
// create dialog; `switch-worktree` opens the sidebar worktree switcher.
// Both delegate to the renderer's ProjectSwitcher surface.
| 'new-worktree'
- | 'switch-worktree';
+ | 'switch-worktree'
+ // Help → Report a Bug… — opens the in-app bug-report dialog. Both window
+ // types subscribe: editor windows report project-scoped, the Navigator
+ // reports system-wide.
+ | 'report-bug';
/**
* Unsubscribe closure returned from `onProjectSwitched` / `onMenuAction`.
@@ -1332,6 +1344,28 @@ export interface OkDesktopBridge {
setMode(mode: 'shared' | 'local-only'): Promise<OkSharingSetModeResult>;
};
+ /**
+ * In-app "Report a bug" — `create` builds the redacted diagnostic zip
+ * (optional crash-dump opt-in via `includeCrashDump`); `send` uploads it
+ * with an email fallback; `onCrashDetected` / `crashAck` carry the
+ * crash-invite round-trip.
+ * Canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.
+ * Mirrored here per the OkDesktopBridge 3-way-mirror invariant.
+ */
+ bugReport: {
+ create(request: {
+ level: ReportBundleLevel;
+ note?: string;
+ includeCrashDump?: boolean;
+ }): Promise<OkBugReportCreateResult>;
+ send(request: {
+ zipPath: string;
+ metadata: OkBugReportSendMetadata;
+ }): Promise<OkBugReportSendResult>;
+ crashAck(request: { eventId: string }): Promise<OkBugReportCrashAckResult>;
+ onCrashDetected(cb: (event: OkBugReportCrashDetectedEvent) => void): OkUnsubscribe;
+ };
+
/**
* Filesystem probes that back the Create-new-project dialog cascade. See
* canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 9e51fac12..7282d9edf 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -25,6 +25,14 @@ export type {
Loggable,
LogLevel,
LogPayload,
+ OkBugReportCrashAckResult,
+ OkBugReportCrashDetectedEvent,
+ OkBugReportCreateResult,
+ OkBugReportSendFallbackReason,
+ OkBugReportSendMetadata,
+ OkBugReportSendResult,
+ ReportBundleLevel,
+ ReportBundleSummary,
SerializedError,
SerializedErrorTruncation,
} from './logger-types.ts';
diff --git a/packages/core/src/logger-types.ts b/packages/core/src/logger-types.ts
index 220ae3539..b0a94a05d 100644
--- a/packages/core/src/logger-types.ts
+++ b/packages/core/src/logger-types.ts
@@ -50,3 +50,122 @@ export interface BundleManifest {
readonly redactions: BundleRedaction[];
readonly sysinfo: Record<string, Loggable>;
}
+
+/**
+ * Detail level for a bug-report bundle: `standard` is the `ok bug-report`
+ * content set (logs + lock/spawn-error + local sink logs + sysinfo); `full`
+ * is the diagnose superset (adds telemetry, server state, runtime metadata),
+ * availability-gated by what exists at capture time.
+ *
+ * Lives in core (not the CLI package that implements the capture) so the
+ * desktop bridge contract's three per-package copies can all name the same
+ * type — the app renderer and core cannot depend on the CLI package.
+ */
+export type ReportBundleLevel = 'standard' | 'full';
+
+/** Summary of a collected bug-report bundle, mirroring its bundled manifest. */
+export interface ReportBundleSummary {
+ level: ReportBundleLevel;
+ /** True when no project was in scope — the bundle carries user-level logs + sysinfo only. */
+ systemWide: boolean;
+ projectSlug: string | null;
+ /** Zip entry names of the captured content files (mirrors the bundled manifest inventory). */
+ files: string[];
+ /** Per-file secret-scrub audit (empty when redaction was off or nothing matched). */
+ redactions: BundleRedaction[];
+ /** Total lines scrubbed across all files. */
+ redactedLineCount: number;
+ generatedAt: string;
+}
+
+/**
+ * Result of the desktop `ok:bug-report:dispatch` create operation. Never
+ * thrown across the IPC boundary — every failure mode is discriminated so the
+ * report dialog can render its failure state.
+ */
+export type OkBugReportCreateResult =
+ | {
+ ok: true;
+ zipPath: string;
+ /**
+ * On-disk size of the produced zip. Carried on the result rather than
+ * the summary because the summary mirrors the bundled manifest, which
+ * cannot know the final size of the archive that contains it.
+ */
+ zipSizeBytes: number;
+ summary: ReportBundleSummary;
+ }
+ | { ok: false; error: string };
+
+/**
+ * Report metadata the renderer supplies with a send operation — the user's
+ * note plus the system summary the preceding create yielded. Main enriches
+ * it with host facts (app version, platform) before it reaches the intake
+ * wire or the fallback email body; the renderer never sources those.
+ */
+export interface OkBugReportSendMetadata {
+ level: ReportBundleLevel;
+ /** True when the bundle was system-wide (no project open at capture). */
+ systemWide: boolean;
+ projectSlug: string | null;
+ note?: string;
+}
+
+/**
+ * Why a send operation resolved to the email fallback instead of an upload
+ * reference. `email-draft` is the designed default, not a failure: no intake
+ * endpoint is configured, no network request was made, and the prefilled
+ * draft IS the transport — the dialog shows an email flow, not an error.
+ * `send-failed` covers real failures: a configured upload that was attempted
+ * and refused (offline, timeout, rejection at any step), or a request the
+ * handler refused outright (malformed payload, zip outside the bug-reports
+ * root).
+ */
+export type OkBugReportSendFallbackReason = 'email-draft' | 'send-failed';
+
+/**
+ * Result of the desktop `ok:bug-report:dispatch` send operation. Success
+ * carries the intake service's report reference. Everything else resolves to
+ * the email fallback — a prefilled mailto the dialog offers in place of the
+ * upload — with `reason` discriminating the designed no-intake email path
+ * from a genuine send failure. Never thrown across the IPC boundary.
+ */
+export type OkBugReportSendResult =
+ | { ok: true; reference: string }
+ | { ok: false; reason: OkBugReportSendFallbackReason; fallback: { mailtoUrl: string } };
+
+/**
+ * A crash signal detected by desktop main, pushed to the renderer over the
+ * `ok:bug-report:crash-detected` event channel as an invitation to file a
+ * report — never an automatic send. `eventId` keys the acknowledgment
+ * round-trip: the renderer acks over `ok:bug-report:dispatch`
+ * (`kind: 'crash-ack'`) and main persists the id so one crash event never
+ * prompts twice, across restarts included.
+ *
+ * Lives in core for the same reason as the sibling bug-report types: the
+ * desktop bridge contract's per-package copies must all name one type.
+ */
+export type OkBugReportCrashDetectedEvent =
+ | {
+ eventId: string;
+ kind: 'render-process-gone';
+ context: { reason: string; exitCode?: number };
+ }
+ | {
+ eventId: string;
+ kind: 'child-process-gone';
+ context: { reason: string; processType: string; name?: string; exitCode?: number };
+ }
+ | {
+ eventId: string;
+ /** Boot-time detection: the previous session left a dirty-shutdown sentinel or fresh minidumps. */
+ kind: 'boot';
+ context: { dirtyShutdown: boolean; newMinidumps: number };
+ };
+
+/**
+ * Result of the desktop `ok:bug-report:dispatch` crash-ack operation. Never
+ * thrown across the IPC boundary; the only failure mode is a malformed
+ * renderer payload.
+ */
+export type OkBugReportCrashAckResult = { ok: true } | { ok: false; error: string };
diff --git a/packages/desktop/src/main/crash-detection.test.ts b/packages/desktop/src/main/crash-detection.test.ts
new file mode 100644
index 000000000..e2ee483bc
--- /dev/null
+++ b/packages/desktop/src/main/crash-detection.test.ts
@@ -0,0 +1,339 @@
+/**
+ * Crash-detection pipeline tests: injected signal sources, a fake renderer
+ * push, and tmpdir-backed sentinel/store/minidump paths — the same
+ * injectable-deps posture as the sibling IPC handler tests. The clock is a
+ * deterministic advancing fake so sentinel boot ids, ack baselines, and
+ * seeded minidump mtimes are all comparable without wall-clock races.
+ */
+
+import { afterEach, describe, expect, test } from 'bun:test';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ utimesSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import type { OkBugReportCrashDetectedEvent } from '@inkeep/open-knowledge-core';
+import {
+ type CrashDetectionDeps,
+ createCrashDetection,
+ startLocalCrashReporter,
+} from './crash-detection.ts';
+
+const tmpDirs: string[] = [];
+
+afterEach(() => {
+ for (const dir of tmpDirs.splice(0)) {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+const silentLogger = {
+ info: () => {},
+ warn: () => {},
+};
+
+interface Rig {
+ deps: CrashDetectionDeps;
+ emitted: OkBugReportCrashDetectedEvent[];
+ /** Flip to false to simulate "no live renderer window can take the event". */
+ setRendererAvailable(available: boolean): void;
+ /** Advance and return the fake clock (10s per tick). */
+ tick(): Date;
+ dir: string;
+}
+
+function makeRig(): Rig {
+ const dir = mkdtempSync(resolve(tmpdir(), 'ok-crash-detection-'));
+ tmpDirs.push(dir);
+ const emitted: OkBugReportCrashDetectedEvent[] = [];
+ let rendererAvailable = true;
+ let clockMs = Date.parse('2026-07-10T00:00:00.000Z');
+ return {
+ dir,
+ emitted,
+ setRendererAvailable(available: boolean) {
+ rendererAvailable = available;
+ },
+ tick() {
+ clockMs += 10_000;
+ return new Date(clockMs);
+ },
+ deps: {
+ sentinelPath: join(dir, 'user-data', 'bug-report-dirty-shutdown.json'),
+ ackStorePath: join(dir, 'user-data', 'bug-report-crash-acks.json'),
+ crashDumpsDir: join(dir, 'crash-dumps'),
+ emit(event) {
+ if (!rendererAvailable) return false;
+ emitted.push(event);
+ return true;
+ },
+ now: () => {
+ clockMs += 10_000;
+ return new Date(clockMs);
+ },
+ logger: silentLogger,
+ },
+ };
+}
+
+/** Seed a minidump whose mtime is pinned to the fake clock's timeline. */
+function seedMinidump(rig: Rig, relPath: string, at: Date): void {
+ const dumpPath = join(rig.deps.crashDumpsDir, relPath);
+ mkdirSync(dirname(dumpPath), { recursive: true });
+ writeFileSync(dumpPath, 'minidump-bytes');
+ utimesSync(dumpPath, at, at);
+}
+
+describe('runtime process-gone invitations', () => {
+ test('abnormal renderer death arms one report invitation', () => {
+ const rig = makeRig();
+ const detection = createCrashDetection(rig.deps);
+
+ detection.handleRenderProcessGone({ reason: 'crashed', exitCode: 5 });
+
+ expect(rig.emitted).toHaveLength(1);
+ const event = rig.emitted[0];
+ expect(event?.kind).toBe('render-process-gone');
+ expect(event?.eventId).toBeTruthy();
+ if (event?.kind === 'render-process-gone') {
+ expect(event.context.reason).toBe('crashed');
+ expect(event.context.exitCode).toBe(5);
+ }
+ });
+
+ test('routine process teardown never invites', () => {
+ const rig = makeRig();
+ const detection = createCrashDetection(rig.deps);
+
+ for (const reason of ['clean-exit', 'killed', 'abnormal-exit']) {
+ detection.handleRenderProcessGone({ reason });
+ detection.handleChildProcessGone({ type: 'Utility', reason });
+ }
+
+ expect(rig.emitted).toHaveLength(0);
+ });
+
+ test('abnormal child-process death invites with the child identity', () => {
+ const rig = makeRig();
+ const detection = createCrashDetection(rig.deps);
+
+ detection.handleChildProcessGone({ type: 'GPU', reason: 'oom', exitCode: 1 });
+
+ expect(rig.emitted).toHaveLength(1);
+ const event = rig.emitted[0];
+ expect(event?.kind).toBe('child-process-gone');
+ if (event?.kind === 'child-process-gone') {
+ expect(event.context.processType).toBe('GPU');
+ expect(event.context.reason).toBe('oom');
+ }
+ });
+
+ test('a second crash stays silent while one invitation is unanswered, and invites again after ack', () => {
+ const rig = makeRig();
+ const detection = createCrashDetection(rig.deps);
+
+ detection.handleRenderProcessGone({ reason: 'crashed' });
+ detection.handleRenderProcessGone({ reason: 'crashed' });
+ expect(rig.emitted).toHaveLength(1);
+
+ const first = rig.emitted[0];
+ if (!first) throw new Error('expected a first invitation');
+ detection.ack(first.eventId);
+
+ detection.handleRenderProcessGone({ reason: 'oom' });
+ expect(rig.emitted).toHaveLength(2);
+ expect(rig.emitted[1]?.eventId).not.toBe(first.eventId);
+ });
+
+ test('with no live renderer the invitation waits and delivers exactly once on renderer-ready', () => {
+ const rig = makeRig();
+ const detection = createCrashDetection(rig.deps);
+
+ rig.setRendererAvailable(false);
+ detection.handleRenderProcessGone({ reason: 'crashed' });
+ expect(rig.emitted).toHaveLength(0);
+
+ rig.setRendererAvailable(true);
+ detection.notifyRendererReady();
+ expect(rig.emitted).toHaveLength(1);
+
+ detection.notifyRendererReady();
+ expect(rig.emitted).toHaveLength(1);
+ });
+});
+
+describe('boot-time detection', () => {
+ test('a dirty shutdown invites once at the next boot, delivered on renderer-ready', () => {
+ const rig = makeRig();
+
+ const sessionA = createCrashDetection(rig.deps);
+ expect(sessionA.detectBootCrash()).toBeNull();
+ // Session A ends without markCleanQuit — a crash leaves its sentinel behind.
+
+ const sessionB = createCrashDetection(rig.deps);
+ const armed = sessionB.detectBootCrash();
+ expect(armed?.kind).toBe('boot');
+ if (armed?.kind === 'boot') {
+ expect(armed.context.dirtyShutdown).toBe(true);
+ expect(armed.context.newMinidumps).toBe(0);
+ }
+
+ // Boot events wait for the first ready renderer instead of racing window load.
+ expect(rig.emitted).toHaveLength(0);
+ sessionB.notifyRendererReady();
+ expect(rig.emitted).toHaveLength(1);
+ sessionB.notifyRendererReady();
+ expect(rig.emitted).toHaveLength(1);
+ });
+
+ test('a clean quit clears the sentinel and the next boot stays silent', () => {
+ const rig = makeRig();
+
+ const sessionA = createCrashDetection(rig.deps);
+ sessionA.detectBootCrash();
+ expect(existsSync(rig.deps.sentinelPath)).toBe(true);
+ sessionA.markCleanQuit();
+ expect(existsSync(rig.deps.sentinelPath)).toBe(false);
+
+ const sessionB = createCrashDetection(rig.deps);
+ expect(sessionB.detectBootCrash()).toBeNull();
+ sessionB.notifyRendererReady();
+ expect(rig.emitted).toHaveLength(0);
+ });
+
+ test('an acknowledged boot event never re-prompts, but a later crash prompts as a new event', () => {
+ const rig = makeRig();
+
+ const sessionA = createCrashDetection(rig.deps);
+ sessionA.detectBootCrash();
+ // Session A crashes.
+
+ const sessionB = createCrashDetection(rig.deps);
+ const first = sessionB.detectBootCrash();
+ if (!first) throw new Error('expected a boot invitation after the dirty shutdown');
+ sessionB.ack(first.eventId);
+ expect(readFileSync(rig.deps.ackStorePath, 'utf8')).toContain(first.eventId);
+ sessionB.markCleanQuit();
+
+ const sessionC = createCrashDetection(rig.deps);
+ expect(sessionC.detectBootCrash()).toBeNull();
+ // Session C crashes too — a genuinely new event, so the next boot invites again.
+
+ const sessionD = createCrashDetection(rig.deps);
+ const second = sessionD.detectBootCrash();
+ expect(second?.kind).toBe('boot');
+ expect(second?.eventId).not.toBe(first.eventId);
+ });
+
+ test('minidumps predating the store never invite; a fresh one does, and ack retires it', () => {
+ const rig = makeRig();
+ seedMinidump(rig, 'pending/ancient.dmp', new Date('2026-07-09T00:00:00.000Z'));
+
+ const sessionA = createCrashDetection(rig.deps);
+ expect(sessionA.detectBootCrash()).toBeNull();
+ sessionA.markCleanQuit();
+
+ seedMinidump(rig, 'pending/fresh.dmp', rig.tick());
+ const sessionB = createCrashDetection(rig.deps);
+ const armed = sessionB.detectBootCrash();
+ expect(armed?.kind).toBe('boot');
+ if (armed?.kind === 'boot') {
+ expect(armed.context.dirtyShutdown).toBe(false);
+ expect(armed.context.newMinidumps).toBe(1);
+ }
+ if (!armed) throw new Error('expected a minidump-driven boot invitation');
+ sessionB.ack(armed.eventId);
+ sessionB.markCleanQuit();
+
+ const sessionC = createCrashDetection(rig.deps);
+ expect(sessionC.detectBootCrash()).toBeNull();
+ });
+
+ test('a corrupt acknowledgment store fails open to a fresh baseline', () => {
+ const rig = makeRig();
+ mkdirSync(dirname(rig.deps.ackStorePath), { recursive: true });
+ writeFileSync(rig.deps.ackStorePath, 'not json{');
+ seedMinidump(rig, 'pending/old.dmp', new Date('2026-07-09T00:00:00.000Z'));
+
+ const detection = createCrashDetection(rig.deps);
+ expect(detection.detectBootCrash()).toBeNull();
+
+ const rewritten: unknown = JSON.parse(readFileSync(rig.deps.ackStorePath, 'utf8'));
+ expect((rewritten as { ackedEventIds: string[] }).ackedEventIds).toEqual([]);
+ });
+
+ test('an unreadable sentinel still counts as a dirty shutdown', () => {
+ const rig = makeRig();
+ mkdirSync(dirname(rig.deps.sentinelPath), { recursive: true });
+ writeFileSync(rig.deps.sentinelPath, 'torn-write-not-json');
+
+ const detection = createCrashDetection(rig.deps);
+ const armed = detection.detectBootCrash();
+ expect(armed?.kind).toBe('boot');
+ if (armed?.kind === 'boot') {
+ expect(armed.context.dirtyShutdown).toBe(true);
+ }
+ });
+});
+
+describe('newest un-acked minidump lookup', () => {
+ test('returns the newest dump past the ack baseline, and none once acked', () => {
+ const rig = makeRig();
+ const detection = createCrashDetection(rig.deps);
+ const older = rig.tick();
+ const newer = rig.tick();
+ seedMinidump(rig, 'pending/older.dmp', older);
+ seedMinidump(rig, 'completed/newer.dmp', newer);
+
+ expect(detection.newestMinidumpPath()).toBe(
+ join(rig.deps.crashDumpsDir, 'completed', 'newer.dmp'),
+ );
+
+ detection.ack('boot:some-earlier-event');
+ expect(detection.newestMinidumpPath()).toBeNull();
+ });
+
+ test('dumps already covered by the fresh-install baseline never surface', () => {
+ const rig = makeRig();
+ seedMinidump(rig, 'pending/historic.dmp', new Date(Date.parse('2026-07-09T00:00:00.000Z')));
+ const detection = createCrashDetection(rig.deps);
+
+ expect(detection.newestMinidumpPath()).toBeNull();
+ });
+
+ test('a crash-dumps dir Crashpad has not created yet reads as no dump', () => {
+ const rig = makeRig();
+ const detection = createCrashDetection(rig.deps);
+
+ expect(detection.newestMinidumpPath()).toBeNull();
+ });
+});
+
+describe('process-level invariants', () => {
+ test('crash detection registers no userland uncaughtException handler', () => {
+ const rig = makeRig();
+ const detection = createCrashDetection(rig.deps);
+ detection.detectBootCrash();
+ detection.handleRenderProcessGone({ reason: 'crashed' });
+ detection.notifyRendererReady();
+
+ expect(process.listenerCount('uncaughtException')).toBe(0);
+ });
+
+ test('the crash reporter starts local-only, with upload disabled', () => {
+ const calls: Array<{ uploadToServer: boolean }> = [];
+ startLocalCrashReporter({
+ start(options) {
+ calls.push(options);
+ },
+ });
+
+ expect(calls).toEqual([{ uploadToServer: false }]);
+ });
+});
diff --git a/packages/desktop/src/main/crash-detection.ts b/packages/desktop/src/main/crash-detection.ts
new file mode 100644
index 000000000..c05d6b5be
--- /dev/null
+++ b/packages/desktop/src/main/crash-detection.ts
@@ -0,0 +1,434 @@
+/**
+ * First-party crash detection for the desktop main process. Three signal
+ * sources feed one invitation pipeline:
+ *
+ * - Electron's `crashReporter` runs with `uploadToServer: false` — Crashpad
+ * writes native-crash minidumps to `app.getPath('crashDumps')` and
+ * nothing ever leaves the machine (standing policy: first-party only, no
+ * vendor crash SDKs).
+ * - `render-process-gone` / `child-process-gone` signals, filtered to
+ * genuine crash reasons, invite a report while the app is still running.
+ * - A boot-time scan pairs a dirty-shutdown sentinel (written each boot,
+ * removed on clean quit) with a minidump-freshness check to catch
+ * main-process/native crashes that leave no live-session signal.
+ *
+ * Every detection only ever *invites*: the renderer opens the report dialog
+ * and the user decides; nothing is sent automatically. Each crash event
+ * prompts at most once — delivery is once per event, at most one invitation
+ * is armed at a time, and acknowledgments persist (userData JSON) so an
+ * acked event never re-prompts across restarts.
+ *
+ * Deliberately absent: a userland `uncaughtException` handler. Electron
+ * defers its main-process crash dialog to such a handler whenever one exists
+ * (see `process-safety-net.ts`) — the boot-time sentinel/minidump scan is how
+ * main-process crashes are covered instead.
+ *
+ * Electron-free by construction (paths, clock, and the renderer push are all
+ * injected) so the whole pipeline is testable without a live app.
+ */
+
+import {
+ type Dirent,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from 'node:fs';
+import { dirname, join } from 'node:path';
+import type { OkBugReportCrashDetectedEvent } from '@inkeep/open-knowledge-core';
+
+/**
+ * Process-gone reasons that read as genuine crashes. `clean-exit` and
+ * `killed` are routine teardown (window closed mid-load, OS/user kill);
+ * `abnormal-exit` is a managed child exiting nonzero — those children own
+ * their failure UX (e.g. the server utility's spawn-error surface), so a
+ * report prompt for each would nag.
+ */
+const CRASH_REASONS = new Set(['crashed', 'oom', 'launch-failed', 'integrity-failure']);
+
+/**
+ * Acked ids older than the store's minidump baseline can never fire again,
+ * so the list only needs to outlive a plausible burst of distinct events.
+ */
+const MAX_ACKED_EVENT_IDS = 50;
+
+/** Crashpad nests dumps (`pending/`, `completed/`, `new/`) — walk a bounded depth. */
+const MINIDUMP_SCAN_DEPTH = 3;
+
+interface CrashLogger {
+ info(payload: Record<string, unknown>, msg: string): void;
+ warn(payload: Record<string, unknown>, msg: string): void;
+}
+
+/** Persisted acknowledgment state (userData JSON). */
+interface CrashAckStore {
+ ackedEventIds: string[];
+ /** Minidumps at or older than this instant are considered already handled. */
+ minidumpBaselineAt: string;
+}
+
+export interface CrashDetectionDeps {
+ /** Dirty-shutdown sentinel — written each boot, removed on clean quit. */
+ sentinelPath: string;
+ /** Acknowledgment store (JSON) recording which crash events the user already saw. */
+ ackStorePath: string;
+ /** Electron's `app.getPath('crashDumps')`; scanned for fresh `.dmp` files. */
+ crashDumpsDir: string;
+ /**
+ * Push one crash-detected event to a live renderer. Returns false when no
+ * renderer could take it — the event stays armed and is re-offered on the
+ * next `notifyRendererReady`.
+ */
+ emit(event: OkBugReportCrashDetectedEvent): boolean;
+ now(): Date;
+ logger: CrashLogger;
+}
+
+export interface CrashDetection {
+ /**
+ * Boot-time scan: reads the previous session's sentinel and the minidump
+ * directory, arms at most one boot invitation (unless already acked), then
+ * writes this session's sentinel. Returns what it armed, for callers'
+ * logging; delivery waits for `notifyRendererReady`.
+ */
+ detectBootCrash(): OkBugReportCrashDetectedEvent | null;
+ /** Clean-quit path: removes the sentinel so the next boot reads as clean. */
+ markCleanQuit(): void;
+ handleRenderProcessGone(details: { reason: string; exitCode?: number }): void;
+ handleChildProcessGone(details: {
+ type: string;
+ reason: string;
+ exitCode?: number;
+ name?: string;
+ }): void;
+ /** A renderer finished loading — deliver the armed invitation if one is waiting. */
+ notifyRendererReady(): void;
+ /** Persist an acknowledgment so the event never re-prompts, and disarm it. */
+ ack(eventId: string): void;
+ /**
+ * Absolute path of the newest minidump not yet covered by an acknowledgment
+ * (strictly newer than the ack baseline) — the dump belonging to whatever
+ * crash the user is currently invited to report. Null when the un-acked
+ * crash left no dump (e.g. dirty shutdown without a native crash) or every
+ * dump is already acked. Minidumps carry raw process memory that text
+ * redaction cannot scrub, so bundle inclusion must stay behind the report
+ * dialog's explicit opt-in that calls this.
+ */
+ newestMinidumpPath(): string | null;
+}
+
+/**
+ * Start Electron's crash reporter in local-only mode: Crashpad collects
+ * minidumps on disk and uploads nothing. Isolated behind this wrapper so the
+ * no-upload contract is pinned by a unit test rather than trusted to a call
+ * site nothing exercises.
+ */
+export function startLocalCrashReporter(reporter: {
+ start(options: { uploadToServer: boolean }): void;
+}): void {
+ reporter.start({ uploadToServer: false });
+}
+
+function isFileMissingError(err: unknown): boolean {
+ return (
+ typeof err === 'object' && err !== null && (err as NodeJS.ErrnoException).code === 'ENOENT'
+ );
+}
+
+function parseAckStore(raw: string): CrashAckStore | null {
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (typeof parsed !== 'object' || parsed === null) return null;
+ const p = parsed as Record<string, unknown>;
+ if (!Array.isArray(p.ackedEventIds)) return null;
+ if (!p.ackedEventIds.every((id): id is string => typeof id === 'string')) return null;
+ if (typeof p.minidumpBaselineAt !== 'string') return null;
+ if (!Number.isFinite(Date.parse(p.minidumpBaselineAt))) return null;
+ return { ackedEventIds: p.ackedEventIds, minidumpBaselineAt: p.minidumpBaselineAt };
+ } catch {
+ return null;
+ }
+}
+
+interface MinidumpEntry {
+ path: string;
+ mtimeMs: number;
+}
+
+/** Collect `.dmp` files under `dir` with mtimes, tolerating a dir Crashpad hasn't created yet. */
+function collectMinidumpEntries(dir: string, depth: number, out: MinidumpEntry[]): void {
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const entryPath = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (depth > 0) collectMinidumpEntries(entryPath, depth - 1, out);
+ continue;
+ }
+ if (!entry.name.endsWith('.dmp')) continue;
+ try {
+ out.push({ path: entryPath, mtimeMs: statSync(entryPath).mtimeMs });
+ } catch {
+ // Raced with Crashpad's own upload/cleanup rotation — skip the entry.
+ }
+ }
+}
+
+export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {
+ /** The one invitation in flight; a new signal while this is unacked stays silent. */
+ let active: { event: OkBugReportCrashDetectedEvent; delivered: boolean } | null = null;
+ let runtimeSeq = 0;
+
+ let storeNeedsInit = false;
+ let store: CrashAckStore;
+ {
+ let parsed: CrashAckStore | null = null;
+ try {
+ parsed = parseAckStore(readFileSync(deps.ackStorePath, 'utf8'));
+ } catch {
+ // Missing on first run; unreadable otherwise — both re-baseline below.
+ }
+ if (parsed === null) {
+ // Fresh baseline: minidumps that predate this store (from before the
+ // feature existed, or from before the store was lost) never prompt.
+ store = { ackedEventIds: [], minidumpBaselineAt: deps.now().toISOString() };
+ storeNeedsInit = true;
+ } else {
+ store = parsed;
+ }
+ }
+
+ function persistStore(): void {
+ try {
+ mkdirSync(dirname(deps.ackStorePath), { recursive: true });
+ writeFileSync(deps.ackStorePath, `${JSON.stringify(store)}\n`);
+ } catch (err) {
+ // Detection stays usable in-session even when userData is unwritable;
+ // only the cross-restart memory degrades.
+ deps.logger.warn(
+ {
+ event: 'crash-detection.store-write-failed',
+ cause: err instanceof Error ? err.message : String(err),
+ },
+ 'could not persist crash acknowledgment state',
+ );
+ }
+ }
+
+ function tryDeliver(): void {
+ if (active === null || active.delivered) return;
+ if (deps.emit(active.event)) {
+ active.delivered = true;
+ }
+ }
+
+ /**
+ * Arm an invitation without delivering — boot events wait for the first
+ * renderer-ready signal, runtime events follow up with `tryDeliver`.
+ * Returns false when a prior invitation is still unanswered (new signals
+ * stay silent rather than stacking prompts).
+ */
+ function armInvite(event: OkBugReportCrashDetectedEvent): boolean {
+ if (active !== null) {
+ deps.logger.info(
+ {
+ event: 'crash-detection.suppressed',
+ eventId: event.eventId,
+ pendingEventId: active.event.eventId,
+ },
+ 'crash invitation already pending — new signal stays silent',
+ );
+ return false;
+ }
+ active = { event, delivered: false };
+ return true;
+ }
+
+ return {
+ detectBootCrash(): OkBugReportCrashDetectedEvent | null {
+ const detectedAt = deps.now();
+
+ let sentinelPresent = false;
+ let sentinelRaw: string | null = null;
+ try {
+ sentinelRaw = readFileSync(deps.sentinelPath, 'utf8');
+ sentinelPresent = true;
+ } catch (err) {
+ // A non-ENOENT read failure still means the file exists — the
+ // previous session did not clean-quit.
+ sentinelPresent = !isFileMissingError(err);
+ }
+ let prevBootId: string | null = null;
+ if (sentinelRaw !== null) {
+ try {
+ const parsed: unknown = JSON.parse(sentinelRaw);
+ const bootId = (parsed as Record<string, unknown> | null)?.bootId;
+ if (typeof bootId === 'string' && bootId !== '') prevBootId = bootId;
+ } catch {
+ // Torn write from the crashed session — presence alone is the signal.
+ }
+ }
+
+ const dumpEntries: MinidumpEntry[] = [];
+ collectMinidumpEntries(deps.crashDumpsDir, MINIDUMP_SCAN_DEPTH, dumpEntries);
+ const baselineMs = Date.parse(store.minidumpBaselineAt);
+ const newDumps = dumpEntries.filter((e) => e.mtimeMs > baselineMs).map((e) => e.mtimeMs);
+
+ let armed: OkBugReportCrashDetectedEvent | null = null;
+ if (sentinelPresent || newDumps.length > 0) {
+ // Sentinel-derived ids stay stable for the same crashed session, so an
+ // ack survives even if detection runs again before this boot rewrites
+ // the sentinel. The dump-only and unreadable-sentinel fallbacks only
+ // need in-session stability — the sentinel is replaced below either way.
+ const eventId = sentinelPresent
+ ? `boot:${prevBootId ?? `unreadable:${detectedAt.getTime()}`}`
+ : `boot:dump:${Math.max(...newDumps)}`;
+ if (!store.ackedEventIds.includes(eventId)) {
+ const event: OkBugReportCrashDetectedEvent = {
+ eventId,
+ kind: 'boot',
+ context: { dirtyShutdown: sentinelPresent, newMinidumps: newDumps.length },
+ };
+ if (armInvite(event)) {
+ armed = event;
+ deps.logger.info(
+ {
+ event: 'crash-detection.boot',
+ eventId,
+ dirtyShutdown: sentinelPresent,
+ newMinidumps: newDumps.length,
+ },
+ 'previous session ended uncleanly — arming report invitation',
+ );
+ }
+ }
+ }
+
+ if (storeNeedsInit) {
+ persistStore();
+ storeNeedsInit = false;
+ }
+
+ try {
+ mkdirSync(dirname(deps.sentinelPath), { recursive: true });
+ writeFileSync(
+ deps.sentinelPath,
+ `${JSON.stringify({ bootId: String(detectedAt.getTime()), startedAt: detectedAt.toISOString() })}\n`,
+ );
+ } catch (err) {
+ deps.logger.warn(
+ {
+ event: 'crash-detection.sentinel-write-failed',
+ cause: err instanceof Error ? err.message : String(err),
+ },
+ 'could not arm the dirty-shutdown sentinel',
+ );
+ }
+
+ return armed;
+ },
+
+ markCleanQuit(): void {
+ try {
+ rmSync(deps.sentinelPath, { force: true });
+ } catch (err) {
+ deps.logger.warn(
+ {
+ event: 'crash-detection.sentinel-clear-failed',
+ cause: err instanceof Error ? err.message : String(err),
+ },
+ 'could not clear the dirty-shutdown sentinel — next boot may prompt spuriously',
+ );
+ }
+ },
+
+ handleRenderProcessGone(details): void {
+ if (!CRASH_REASONS.has(details.reason)) return;
+ deps.logger.warn(
+ {
+ event: 'crash-detection.render-process-gone',
+ reason: details.reason,
+ exitCode: details.exitCode,
+ },
+ 'renderer process died abnormally',
+ );
+ if (
+ armInvite({
+ eventId: `crash:render:${deps.now().getTime()}:${runtimeSeq++}`,
+ kind: 'render-process-gone',
+ context: {
+ reason: details.reason,
+ ...(details.exitCode !== undefined ? { exitCode: details.exitCode } : {}),
+ },
+ })
+ ) {
+ tryDeliver();
+ }
+ },
+
+ handleChildProcessGone(details): void {
+ if (!CRASH_REASONS.has(details.reason)) return;
+ deps.logger.warn(
+ {
+ event: 'crash-detection.child-process-gone',
+ processType: details.type,
+ reason: details.reason,
+ exitCode: details.exitCode,
+ },
+ 'child process died abnormally',
+ );
+ if (
+ armInvite({
+ eventId: `crash:child:${deps.now().getTime()}:${runtimeSeq++}`,
+ kind: 'child-process-gone',
+ context: {
+ reason: details.reason,
+ processType: details.type,
+ ...(details.name !== undefined ? { name: details.name } : {}),
+ ...(details.exitCode !== undefined ? { exitCode: details.exitCode } : {}),
+ },
+ })
+ ) {
+ tryDeliver();
+ }
+ },
+
+ notifyRendererReady(): void {
+ tryDeliver();
+ },
+
+ ack(eventId: string): void {
+ if (!store.ackedEventIds.includes(eventId)) {
+ store.ackedEventIds.push(eventId);
+ if (store.ackedEventIds.length > MAX_ACKED_EVENT_IDS) {
+ store.ackedEventIds.splice(0, store.ackedEventIds.length - MAX_ACKED_EVENT_IDS);
+ }
+ }
+ // Advancing the baseline marks this crash's minidumps as handled, so the
+ // boot-time scan never re-invites for an event the user already answered.
+ store.minidumpBaselineAt = deps.now().toISOString();
+ persistStore();
+ if (active?.event.eventId === eventId) {
+ active = null;
+ }
+ },
+
+ newestMinidumpPath(): string | null {
+ const entries: MinidumpEntry[] = [];
+ collectMinidumpEntries(deps.crashDumpsDir, MINIDUMP_SCAN_DEPTH, entries);
+ const baselineMs = Date.parse(store.minidumpBaselineAt);
+ let newest: MinidumpEntry | null = null;
+ for (const entry of entries) {
+ if (entry.mtimeMs <= baselineMs) continue;
+ if (newest === null || entry.mtimeMs > newest.mtimeMs) newest = entry;
+ }
+ return newest === null ? null : newest.path;
+ },
+ };
+}
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index b3b1fc4d8..3efed611b 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -40,12 +40,13 @@ import {
writeFileSync,
} from 'node:fs';
import { createServer as createHttpServer } from 'node:http';
-import { homedir as osHomedir, hostname as osHostname } from 'node:os';
+import { homedir as osHomedir, hostname as osHostname, release as osRelease } from 'node:os';
import { basename, dirname, join } from 'node:path';
import {
ALL_EDITOR_IDS,
addOkPathsToGitExclude,
classifyExistingMcpEntry,
+ defaultBugReportZipPath,
detectInstalledEditors,
EDITOR_TARGETS,
getOkArtifactPaths,
@@ -107,6 +108,7 @@ import {
app,
BrowserWindow,
clipboard,
+ crashReporter,
dialog,
autoUpdater as electronAutoUpdater,
ipcMain,
@@ -166,6 +168,11 @@ import {
runLoginShellProbe,
} from './claude-readiness.ts';
import { requestUserConsent, walkExceedsCap } from './consent-dialog.ts';
+import {
+ type CrashDetection,
+ createCrashDetection,
+ startLocalCrashReporter,
+} from './crash-detection.ts';
import {
CreateNewProjectError,
folderState,
@@ -207,6 +214,11 @@ import { readCanonicalGitHubRemoteUrl } from './git-remote.ts';
import { formatInstanceAppName, resolveInstanceLabel } from './instance-identity.ts';
import { deriveInstanceUserDataDir } from './instance-isolation.ts';
import { registerIntegrationsSettings } from './integrations-settings.ts';
+import {
+ handleBugReportCrashAck,
+ handleBugReportCreate,
+ handleBugReportSend,
+} from './ipc/bug-report.ts';
import { handleBuildAndOpen, handleDetectClaudeDesktop } from './ipc/install-skill.ts';
import {
createLocalOpState,
@@ -903,6 +915,13 @@ let debugIpc: DebugIpcHandle | null = null;
* when the wiring no-ops (marker present, dev mode, non-macOS, etc.).
*/
let mcpWiringHandle: RunMcpWiringHandle | null = null;
+/**
+ * First-party crash detection (local-only crash reporter, process-gone
+ * listeners, boot-time dirty-shutdown/minidump scan). Created at the top of
+ * `bootPrimaryInstance`; null only in the duplicate-instance and driver-smoke
+ * boot paths, which never prompt.
+ */
+let crashDetection: CrashDetection | null = null;
/**
* Active-editor target snapshot pushed by the renderer via
@@ -2183,6 +2202,7 @@ async function runApplicationMenuRefresh(): Promise<void> {
if (!target) return;
target.webContents.executeJavaScript("window.location.hash = '#settings'; undefined");
},
+ onReportBug: () => sendMenuActionToFocused('report-bug'),
// App-menu / Help-menu "Check for Updates…" entries fire this. Returns
// void: the menu doesn't surface in-flight progress; the existing
// `update-available` / `update-not-available` electron-updater events
@@ -3526,6 +3546,11 @@ function registerIpcHandlers() {
{
platform: process.platform,
projectPath: callerProjectPath,
+ // The bug-report zip lives in `~/.ok/bug-reports/`, outside every
+ // project, so the review/failure card's Reveal would otherwise be
+ // refused (`out-of-project`, or `no-project-bound` from a Navigator
+ // window). This dir is main-derived, not renderer-influenced.
+ allowedRoots: [dirname(defaultBugReportZipPath())],
showItemInFolder: (p) => shell.showItemInFolder(p),
},
path,
@@ -3761,6 +3786,50 @@ function registerIpcHandlers() {
return handleSharingSetMode(ctx.projectPath, mode);
});
+ // In-app bug reporting — build the redacted diagnostic bundle for the
+ // sender window's project, upload a reviewed bundle to the private intake,
+ // or acknowledge a crash-detected invitation. Unlike the sibling
+ // project-scoped channels, a window with no project context (Navigator) is
+ // NOT refused: the bundle degrades to system-wide (user logs + sysinfo),
+ // labeled via `summary.systemWide`.
+ handle('ok:bug-report:dispatch', async (event, request) => {
+ if (request.kind === 'crash-ack') {
+ return handleBugReportCrashAck(
+ { ackCrashEvent: (eventId) => crashDetection?.ack(eventId) },
+ request,
+ );
+ }
+ if (request.kind === 'send') {
+ return handleBugReportSend(
+ {
+ intakeBaseUrl: process.env.OK_BUG_REPORT_INTAKE_URL,
+ appVersion: app.getVersion(),
+ platform: `${process.platform} ${osRelease()}`,
+ // Same containment root the Reveal handler whitelists above — only
+ // zips `create` produced may be read and uploaded.
+ bugReportsRoot: dirname(defaultBugReportZipPath()),
+ },
+ request,
+ );
+ }
+ const win = BrowserWindow.fromWebContents(event.sender);
+ const ctx =
+ win && wm ? wm.getContextForBrowserWindow(win as unknown as BrowserWindowLike) : null;
+ return handleBugReportCreate(
+ {
+ projectDir: ctx?.projectPath ?? null,
+ desktopMeta: {
+ version: app.getVersion(),
+ packaged: app.isPackaged,
+ channel: channelFromVersion(app.getVersion()),
+ },
+ newestMinidumpPath: () => crashDetection?.newestMinidumpPath() ?? null,
+ logger: getLogger('bug-report'),
+ },
+ request,
+ );
+ });
+
handle('ok:project:list-recent', async () => {
// Enrich each present recent with its git-worktree relationship so the
// renderer can nest linked worktrees under their main project. Each present
@@ -4835,11 +4904,62 @@ function bootPrimaryInstance(): void {
'desktop main process starting',
);
+ // Crash handling is strictly local: Crashpad writes minidumps under
+ // `app.getPath('crashDumps')` and uploads nothing. Started before any
+ // window so every child process inherits coverage, then the boot-time scan
+ // arms a report invitation if the previous session ended uncleanly. NO
+ // userland `uncaughtException` handler is involved anywhere in this
+ // pipeline — see process-safety-net.ts for why one must never be added.
+ startLocalCrashReporter(crashReporter);
+ crashDetection = createCrashDetection({
+ sentinelPath: join(app.getPath('userData'), 'bug-report-dirty-shutdown.json'),
+ ackStorePath: join(app.getPath('userData'), 'bug-report-crash-acks.json'),
+ crashDumpsDir: app.getPath('crashDumps'),
+ // Deliver to one live window — focused first — and report undeliverable
+ // so the invitation waits for the next renderer-ready signal instead of
+ // dropping (at boot, or when the only window is the one that crashed).
+ emit: (event) => {
+ const focused = BrowserWindow.getFocusedWindow();
+ const candidates = focused
+ ? [focused, ...BrowserWindow.getAllWindows()]
+ : BrowserWindow.getAllWindows();
+ for (const win of candidates) {
+ const contents = win.webContents;
+ if (contents.isDestroyed() || contents.isCrashed() || contents.isLoading()) continue;
+ sendToRenderer(contents, 'ok:bug-report:crash-detected', event);
+ return true;
+ }
+ return false;
+ },
+ now: () => new Date(),
+ logger: getLogger('crash-detection'),
+ });
+ crashDetection.detectBootCrash();
+ app.on('child-process-gone', (_event, details) => {
+ crashDetection?.handleChildProcessGone(details);
+ });
+
// Capture renderer console output into the desktop pino log
// (`~/.ok/logs/desktop.<date>.log`, bundled by `ok bug-report`). Registered
// before `whenReady` so every window's webContents is covered from creation.
app.on('web-contents-created', (_event, contents) => {
attachRendererConsoleCapture(contents);
+ contents.on('render-process-gone', (_e, details) => {
+ crashDetection?.handleRenderProcessGone(details);
+ });
+ // A freshly-loaded renderer can take a waiting crash invitation (boot
+ // events detect before any window exists; delivery must not race load).
+ // Both `did-finish-load` AND `did-stop-loading` retry delivery: a boot
+ // invite's `emit` skips a window that is `isLoading()`, and for a sole
+ // editor window whose `did-finish-load` fires while a follow-on load is
+ // still in flight, `did-finish-load` alone never retries once the window
+ // settles — the invitation would stay armed but undelivered. `did-stop-
+ // loading` is that missing "load settled" signal. `notifyRendererReady`
+ // is idempotent (guarded by the delivered flag), so the extra call is a
+ // no-op once delivered.
+ const retryDelivery = () => crashDetection?.notifyRendererReady();
+ contents.on('did-finish-load', retryDelivery);
+ contents.on('did-stop-loading', retryDelivery);
});
// Assistive-tech flips (e.g. VoiceOver, NVDA attach/detach) fan out to every window so
@@ -5607,6 +5727,9 @@ function bootPrimaryInstance(): void {
// after each call makes subsequent will-quit re-entrances no-ops.
app.on('will-quit', () => {
getLogger('lifecycle').info({}, 'will-quit');
+ // A quit that reaches here was orderly — clear the dirty-shutdown
+ // sentinel so the next boot doesn't read this session as a crash.
+ crashDetection?.markCleanQuit();
// Reap every window's PTY host first so no user shell / spawn-helper
// outlives the app. Idempotent (clears the map; a second pass no-ops).
terminalReaper?.killAll();
diff --git a/packages/desktop/src/main/ipc-handlers.showItemInFolder.test.ts b/packages/desktop/src/main/ipc-handlers.showItemInFolder.test.ts
new file mode 100644
index 000000000..85fb15b74
--- /dev/null
+++ b/packages/desktop/src/main/ipc-handlers.showItemInFolder.test.ts
@@ -0,0 +1,103 @@
+/**
+ * `showItemInFolder` containment: the reveal gate admits paths under the
+ * caller's project OR an explicit trusted `allowedRoots` entry (the
+ * `~/.ok/bug-reports/` dir the report dialog reveals from), and refuses
+ * everything else.
+ *
+ * Regression guard: before `allowedRoots`, the report dialog's "Reveal in
+ * Finder" was silently refused for every bug-report zip — the zip lives
+ * outside every project, so an editor window hit `out-of-project` and a
+ * Navigator window hit `no-project-bound`.
+ */
+import { describe, expect, test } from 'bun:test';
+import { join } from 'node:path';
+import { showItemInFolder } from './ipc-handlers.ts';
+
+const BUG_REPORTS = '/Users/tester/.ok/bug-reports';
+const PROJECT = '/Users/tester/projects/demo';
+
+describe('showItemInFolder — allowedRoots for bug-report zips', () => {
+ test('editor window (project bound) reveals a bug-report zip via allowedRoots', () => {
+ const zip = join(BUG_REPORTS, '2026-07-10T00-00-00-bugreport.zip');
+ const revealed: string[] = [];
+ const outcome = showItemInFolder(
+ {
+ platform: 'darwin',
+ projectPath: PROJECT,
+ allowedRoots: [BUG_REPORTS],
+ showItemInFolder: (p) => revealed.push(p),
+ },
+ zip,
+ );
+ expect(outcome).toEqual({ ok: true });
+ expect(revealed).toEqual([zip]);
+ });
+
+ test('Navigator window (no project) still reveals a bug-report zip via allowedRoots', () => {
+ const zip = join(BUG_REPORTS, 'report.zip');
+ const revealed: string[] = [];
+ const outcome = showItemInFolder(
+ {
+ platform: 'darwin',
+ projectPath: undefined,
+ allowedRoots: [BUG_REPORTS],
+ showItemInFolder: (p) => revealed.push(p),
+ },
+ zip,
+ );
+ expect(outcome).toEqual({ ok: true });
+ expect(revealed).toEqual([zip]);
+ });
+
+ test('a project file is still revealed (unchanged behavior)', () => {
+ const file = join(PROJECT, 'notes.md');
+ const revealed: string[] = [];
+ const outcome = showItemInFolder(
+ {
+ platform: 'darwin',
+ projectPath: PROJECT,
+ allowedRoots: [BUG_REPORTS],
+ showItemInFolder: (p) => revealed.push(p),
+ },
+ file,
+ );
+ expect(outcome).toEqual({ ok: true });
+ expect(revealed).toEqual([file]);
+ });
+
+ test('an arbitrary out-of-project, out-of-allowed path is still refused', () => {
+ const revealed: string[] = [];
+ const outcome = showItemInFolder(
+ {
+ platform: 'darwin',
+ projectPath: PROJECT,
+ allowedRoots: [BUG_REPORTS],
+ showItemInFolder: (p) => revealed.push(p),
+ },
+ '/etc/passwd',
+ );
+ expect(outcome).toEqual({ ok: false, reason: 'out-of-project' });
+ expect(revealed).toEqual([]);
+ });
+
+ test('without allowedRoots, a bug-report zip is refused (the pre-fix regression)', () => {
+ const zip = join(BUG_REPORTS, 'report.zip');
+ const revealed: string[] = [];
+ const outcome = showItemInFolder(
+ { platform: 'darwin', projectPath: PROJECT, showItemInFolder: (p) => revealed.push(p) },
+ zip,
+ );
+ expect(outcome).toEqual({ ok: false, reason: 'out-of-project' });
+ expect(revealed).toEqual([]);
+ });
+
+ test('Navigator window with no project and no allowedRoots refuses', () => {
+ const revealed: string[] = [];
+ const outcome = showItemInFolder(
+ { platform: 'darwin', projectPath: undefined, showItemInFolder: (p) => revealed.push(p) },
+ join(BUG_REPORTS, 'report.zip'),
+ );
+ expect(outcome).toEqual({ ok: false, reason: 'no-project-bound' });
+ expect(revealed).toEqual([]);
+ });
+});
diff --git a/packages/desktop/src/main/ipc-handlers.ts b/packages/desktop/src/main/ipc-handlers.ts
index 05b2c5f8c..1072a38f4 100644
--- a/packages/desktop/src/main/ipc-handlers.ts
+++ b/packages/desktop/src/main/ipc-handlers.ts
@@ -10,7 +10,7 @@
*/
import { execFile } from 'node:child_process';
-import { join, posix as pathPosix, win32 as pathWin32 } from 'node:path';
+import { join } from 'node:path';
import {
createOsProbe,
type ExecFileLike,
@@ -20,6 +20,11 @@ import {
resolveCursorSpawnInvocation,
} from '@inkeep/open-knowledge-server';
import type { HandoffStatsLine, SpawnOutcome } from '../shared/ipc-channels.ts';
+import { isPathWithinProject, validateSpawnPath } from './path-containment.ts';
+
+// Re-exported so the sole remaining consumer (asset-allowlist.ts) keeps its
+// import site; the implementations live in the leaf module.
+export { isPathWithinProject, validateSpawnPath };
const DEFAULT_PROBE_TIMEOUT_MS = 2000;
const WHICH_TIMEOUT_MS = 500;
@@ -197,81 +202,6 @@ interface SpawnCursorDeps {
// transports — same redirect logic runs in `POST /api/spawn-cursor` and in
// this Electron IPC `spawnCursor`, so a future fix only needs one edit.
-/** Reject non-absolute paths, null bytes, and empties. Shared with tests. */
-export function validateSpawnPath(path: string, platform: NodeJS.Platform): boolean {
- if (!path || typeof path !== 'string') return false;
- if (path.includes('\0')) return false;
- if (platform === 'win32') {
- // Match `C:\…`, `C:/…`, or UNC `\\server\share\…`.
- return /^([a-zA-Z]:[\\/]|\\\\)/.test(path);
- }
- // POSIX (darwin / linux) — absolute paths start with `/`.
- return path.startsWith('/');
-}
-
-/**
- * Resolve both paths canonically and verify `path` lies at or under
- * `projectPath`. Returns false on invalid inputs or boundary escape.
- *
- * Uses `path/posix` or `path/win32` explicitly instead of the host default so
- * Windows inputs resolve correctly on a POSIX dev runner under test, and
- * production behavior follows the caller's platform regardless of Node's
- * runtime `path` module.
- *
- * On Windows, also rejects when the two paths don't share a canonical root
- * (drive letter or `\\server\share` for UNC, `\\?\…` / `\\.\…` for device
- * namespaces). Without that check, `path.win32.relative()` returns the
- * absolute "to" path when roots differ — and the rel-shape probes below
- * miss the UNC / device-prefix forms because they don't begin with a drive
- * letter. Root comparison is case-insensitive (Windows filesystem semantics).
- *
- * Lexical comparison only — does not resolve symlinks. A symlink inside
- * `projectPath` that targets a path outside (e.g. `<proj>/notes -> /etc`)
- * passes this check; the OS will follow it at use time.
- *
- * **Logical sibling of `isPathWithinDir` in `@inkeep/open-knowledge-server`.**
- * Both implement the same containment algorithm; the desktop version is
- * retained because its test suite exercises edge cases this file uniquely
- * cares about (Electron `showItemInFolder` UNC + device-namespace handling).
- * If the two versions ever drift, consolidate by re-exporting one as the
- * other — they share a security contract.
- */
-export function isPathWithinProject(
- userPath: string,
- projectPath: string,
- platform: NodeJS.Platform,
-): boolean {
- if (!validateSpawnPath(userPath, platform)) return false;
- if (!validateSpawnPath(projectPath, platform)) return false;
- const p = platform === 'win32' ? pathWin32 : pathPosix;
- try {
- const canonicalUser = p.resolve(userPath);
- const canonicalProject = p.resolve(projectPath);
- if (platform === 'win32') {
- const userRoot = p.parse(canonicalUser).root.toLowerCase();
- const projectRoot = p.parse(canonicalProject).root.toLowerCase();
- if (!userRoot || !projectRoot || userRoot !== projectRoot) return false;
- }
- if (canonicalUser === canonicalProject) return true;
- const rel = p.relative(canonicalProject, canonicalUser);
- // `relative` returns `..` / `..\foo` / `../foo` when `userPath` escapes
- // the project root, or an absolute form when roots differ on Windows.
- if (rel === '' || rel === '.') return true;
- if (rel === '..' || rel.startsWith(`..${p.sep}`)) return false;
- // Defense-in-depth — the root check above already rejects cross-root,
- // but if a future code path introduces another way for `rel` to come
- // back absolute (drive `D:\…`, UNC `\\server\…`, device `\\?\…`,
- // `\\.\…`), refuse it here.
- if (platform === 'win32' && (/^[a-zA-Z]:[\\/]/.test(rel) || rel.startsWith('\\\\'))) {
- return false;
- }
- if (platform !== 'win32' && rel.startsWith('/')) return false;
- return true;
- } catch {
- return false;
- }
-}
-
// Cursor binary discovery (`whichCursorReal`) is now imported from
// `@inkeep/open-knowledge-server` as `resolveCursorBinaryDefault`. Both
// transports — this file's Electron IPC and the server's
@@ -347,21 +277,30 @@ type ShowItemInFolderOutcome =
/** Injected deps for `showItemInFolder` — the electron `shell.showItemInFolder` and platform/projectPath. */
interface ShowItemInFolderDeps {
readonly platform: NodeJS.Platform;
- /** Caller window's project directory; if omitted, validation refuses any path. */
+ /** Caller window's project directory; if omitted, only `allowedRoots` paths are permitted. */
readonly projectPath: string | undefined;
+ /**
+ * Extra trusted roots the path may lie under besides the project — for
+ * main-produced artifacts that legitimately live outside any project (the
+ * bug-report zip in `~/.ok/bug-reports/`). These are constant, main-derived
+ * directories, never renderer-influenced, so admitting them keeps the
+ * containment guarantee that bounds a compromised renderer.
+ */
+ readonly allowedRoots?: readonly string[];
/** Wraps `electron.shell.showItemInFolder`. Replaceable in tests. */
readonly showItemInFolder: (path: string) => void;
}
/**
* Reveal the given path in the OS file manager. The path must be absolute,
- * free of null bytes, and lie at or under `deps.projectPath` — otherwise the
- * call is refused. Bounds a renderer compromise from steering the OS file
- * manager at arbitrary filesystem locations. Same defense pattern as
- * `spawnCursor`.
+ * free of null bytes, and lie at or under `deps.projectPath` OR one of
+ * `deps.allowedRoots` — otherwise the call is refused. Bounds a renderer
+ * compromise from steering the OS file manager at arbitrary filesystem
+ * locations. Same defense pattern as `spawnCursor`.
*
- * When `projectPath` is undefined (e.g. Navigator window with no bound
- * project), refuses every path — the only safe default.
+ * A window with no bound project (Navigator) can still reveal an
+ * `allowedRoots` path; only when neither the project nor any allowed root
+ * contains the path is the reveal refused.
*/
export function showItemInFolder(
deps: ShowItemInFolderDeps,
@@ -370,11 +309,16 @@ export function showItemInFolder(
if (!validateSpawnPath(path, deps.platform)) {
return { ok: false, reason: 'invalid-format' };
}
- if (deps.projectPath === undefined) {
- return { ok: false, reason: 'no-project-bound' };
- }
- if (!isPathWithinProject(path, deps.projectPath, deps.platform)) {
- return { ok: false, reason: 'out-of-project' };
+ const withinAllowedRoot = (deps.allowedRoots ?? []).some((root) =>
+ isPathWithinProject(path, root, deps.platform),
+ );
+ if (!withinAllowedRoot) {
+ if (deps.projectPath === undefined) {
+ return { ok: false, reason: 'no-project-bound' };
+ }
+ if (!isPathWithinProject(path, deps.projectPath, deps.platform)) {
+ return { ok: false, reason: 'out-of-project' };
+ }
}
deps.showItemInFolder(path);
return { ok: true };
diff --git a/packages/desktop/src/main/ipc/bug-report.test.ts b/packages/desktop/src/main/ipc/bug-report.test.ts
new file mode 100644
index 000000000..f1c9e53fa
--- /dev/null
+++ b/packages/desktop/src/main/ipc/bug-report.test.ts
@@ -0,0 +1,1098 @@
+/**
+ * IPC handler tests for the `ok:bug-report:dispatch` create operation.
+ *
+ * Exercise the pure handler directly against tmpdir-backed fixtures with the
+ * real `collectReportBundle` (no capture mocks) — zip contents are the
+ * observable contract. The IPC wrapping in main/index.ts is one createHandler
+ * call whose ctx-resolution behavior is shared with every project-scoped IPC
+ * and covered by the existing main-side siblings.
+ *
+ * HOME and the `OK_DESKTOP_*` block are snapshot/restored around every test:
+ * bun runs all test files in one process, so an unrestored env mutation here
+ * becomes a load-order-dependent failure in another suite.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { execFileSync, execSync } from 'node:child_process';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ symlinkSync,
+ truncateSync,
+ utimesSync,
+ writeFileSync,
+} from 'node:fs';
+import { createServer, type Server } from 'node:http';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { createCrashDetection } from '../crash-detection.ts';
+import { handleShellOpenExternal } from '../shell-allowlist.ts';
+import {
+ type BugReportCreateDeps,
+ type BugReportSendDeps,
+ handleBugReportCrashAck,
+ handleBugReportCreate,
+ handleBugReportSend,
+ MAX_UPLOAD_ZIP_BYTES,
+ parseTransportSafeUrl,
+} from './bug-report.ts';
+
+const tmpDirs: string[] = [];
+
+function makeTmpDir(prefix = 'ok-bugreport-ipc-'): string {
+ const dir = mkdtempSync(resolve(tmpdir(), prefix));
+ tmpDirs.push(dir);
+ return dir;
+}
+
+const ENV_KEYS = [
+ 'HOME',
+ 'OK_DESKTOP_VERSION',
+ 'OK_DESKTOP_PACKAGED',
+ 'OK_DESKTOP_CHANNEL',
+] as const;
+let envSnapshot: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>> = {};
+
+beforeEach(() => {
+ envSnapshot = {};
+ for (const key of ENV_KEYS) envSnapshot[key] = process.env[key];
+});
+
+afterEach(() => {
+ for (const key of ENV_KEYS) {
+ const value = envSnapshot[key];
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ for (const d of tmpDirs) {
+ if (existsSync(d)) rmSync(d, { recursive: true, force: true });
+ }
+ tmpDirs.length = 0;
+});
+
+function writeAt(baseDir: string, relPath: string, body: string): void {
+ const full = join(baseDir, relPath);
+ mkdirSync(dirname(full), { recursive: true });
+ writeFileSync(full, body);
+}
+
+function listZipEntries(zipPath: string): string[] {
+ const out = execSync(`unzip -Z1 ${JSON.stringify(zipPath)}`, { encoding: 'utf-8' });
+ return out.split('\n').filter(Boolean);
+}
+
+function readZipEntry(zipPath: string, entry: string): string {
+ const extractDir = makeTmpDir('ok-bugreport-ipc-extract-');
+ execSync(
+ `unzip -q -o ${JSON.stringify(zipPath)} ${JSON.stringify(entry)} -d ${JSON.stringify(extractDir)}`,
+ );
+ return readFileSync(join(extractDir, entry), 'utf8');
+}
+
+/** Raw-bytes sibling of `readZipEntry` for entries that must not be decoded (minidumps). */
+function readZipEntryBytes(zipPath: string, entry: string): Buffer {
+ const extractDir = makeTmpDir('ok-bugreport-ipc-extract-');
+ execSync(
+ `unzip -q -o ${JSON.stringify(zipPath)} ${JSON.stringify(entry)} -d ${JSON.stringify(extractDir)}`,
+ );
+ return readFileSync(join(extractDir, entry));
+}
+
+function makeProjectDir(slug = 'ipc-proj'): string {
+ const projectDir = makeTmpDir();
+ writeAt(projectDir, '.ok/config.yml', `name: ${slug}\n`);
+ return projectDir;
+}
+
+const DESKTOP_META = { version: '0.9.9-test.1', packaged: false, channel: 'beta' };
+
+function makeDeps(overrides: Partial<BugReportCreateDeps> = {}): BugReportCreateDeps {
+ return {
+ projectDir: null,
+ desktopMeta: DESKTOP_META,
+ outputPath: join(makeTmpDir(), 'report.zip'),
+ userLogsDir: makeTmpDir(),
+ ...overrides,
+ };
+}
+
+describe('handleBugReportCreate — project bundle', () => {
+ test('builds the zip at the returned path with the project content set and the note', async () => {
+ const projectDir = makeProjectDir();
+ writeAt(projectDir, '.ok/local/server.lock', '{"pid":1234}\n');
+ writeAt(projectDir, '.ok/local/logs/server-current.jsonl', '{"level":30}\n');
+ const deps = makeDeps({ projectDir });
+
+ const result = await handleBugReportCreate(deps, {
+ kind: 'create',
+ level: 'standard',
+ note: 'it crashed while saving',
+ });
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ expect(result.zipPath).toBe(deps.outputPath as string);
+ expect(existsSync(result.zipPath)).toBe(true);
+ expect(result.zipSizeBytes).toBe(statSync(result.zipPath).size);
+ expect(result.zipSizeBytes).toBeGreaterThan(0);
+ expect(result.summary.level).toBe('standard');
+ expect(result.summary.systemWide).toBe(false);
+ expect(result.summary.projectSlug).toBe('ipc-proj');
+
+ const entries = listZipEntries(result.zipPath);
+ expect(entries).toContain('lockdir/server.lock');
+ expect(entries).toContain('local-logs/server-current.jsonl');
+ expect(entries).toContain('sysinfo.json');
+ expect(entries).toContain('note.txt');
+ expect(readZipEntry(result.zipPath, 'note.txt')).toContain('it crashed while saving');
+ });
+
+ test('rejects a create request whose note exceeds the length ceiling', async () => {
+ const deps = makeDeps({ projectDir: makeProjectDir() });
+
+ const result = await handleBugReportCreate(deps, {
+ kind: 'create',
+ level: 'standard',
+ note: 'x'.repeat(32_769),
+ });
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error).toBe('invalid-request');
+ });
+
+ test('redacts a seeded secret in the bundled copy and audits it in the summary', async () => {
+ const secret = 'sk-ant-api03-abcdefghijklmnopqrstuvwx';
+ const projectDir = makeProjectDir();
+ writeAt(projectDir, '.ok/local/logs/server-current.jsonl', `{"msg":"key ${secret}"}\n`);
+ const deps = makeDeps({ projectDir });
+
+ const result = await handleBugReportCreate(deps, { kind: 'create', level: 'standard' });
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ const bundled = readZipEntry(result.zipPath, 'local-logs/server-current.jsonl');
+ expect(bundled).not.toContain(secret);
+ expect(bundled).toContain('[REDACTED-ANTHROPIC]');
+ expect(result.summary.redactions.length).toBeGreaterThan(0);
+ expect(result.summary.redactedLineCount).toBeGreaterThan(0);
+ });
+
+ test('full level stamps the desktop host metadata into the bundle runtime block', async () => {
+ const projectDir = makeProjectDir();
+ const deps = makeDeps({ projectDir });
+ // A canary in the env proves the metadata travels the typed collector
+ // seam — the collector must never fall back to `OK_DESKTOP_*`.
+ process.env.OK_DESKTOP_VERSION = 'env-canary-must-not-be-read';
+ process.env.OK_DESKTOP_PACKAGED = '1';
+ process.env.OK_DESKTOP_CHANNEL = 'env-canary';
+
+ const result = await handleBugReportCreate(deps, { kind: 'create', level: 'full' });
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ expect(result.summary.level).toBe('full');
+ const runtime = JSON.parse(readZipEntry(result.zipPath, 'state/runtime.json'));
+ expect(runtime.host.desktop).toEqual({
+ electronVersion: DESKTOP_META.version,
+ packaged: false,
+ channel: 'beta',
+ });
+ });
+
+ test('standard level records the desktop host metadata in sysinfo and the manifest', async () => {
+ const projectDir = makeProjectDir();
+ const deps = makeDeps({ projectDir });
+
+ const result = await handleBugReportCreate(deps, { kind: 'create', level: 'standard' });
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ const expected = {
+ electronVersion: DESKTOP_META.version,
+ packaged: false,
+ channel: 'beta',
+ };
+ expect(JSON.parse(readZipEntry(result.zipPath, 'sysinfo.json')).desktop).toEqual(expected);
+ expect(JSON.parse(readZipEntry(result.zipPath, 'MANIFEST.json')).sysinfo.desktop).toEqual(
+ expected,
+ );
+ });
+
+ test('create leaves process.env free of OK_DESKTOP_* — metadata is injected, never stamped', async () => {
+ delete process.env.OK_DESKTOP_VERSION;
+ delete process.env.OK_DESKTOP_PACKAGED;
+ delete process.env.OK_DESKTOP_CHANNEL;
+ const deps = makeDeps({ projectDir: makeProjectDir() });
+
+ const result = await handleBugReportCreate(deps, { kind: 'create', level: 'full' });
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ expect(process.env.OK_DESKTOP_VERSION).toBeUndefined();
+ expect(process.env.OK_DESKTOP_PACKAGED).toBeUndefined();
+ expect(process.env.OK_DESKTOP_CHANNEL).toBeUndefined();
+ });
+});
+
+describe('handleBugReportCreate — no project (system-wide)', () => {
+ test('null projectDir degrades to a labeled system-wide bundle of user logs + sysinfo', async () => {
+ const userLogsDir = makeTmpDir();
+ writeFileSync(join(userLogsDir, 'desktop.log'), 'renderer line\n');
+ const deps = makeDeps({ projectDir: null, userLogsDir });
+
+ const result = await handleBugReportCreate(deps, { kind: 'create', level: 'standard' });
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ expect(result.summary.systemWide).toBe(true);
+ expect(result.summary.projectSlug).toBeNull();
+
+ const entries = listZipEntries(result.zipPath);
+ expect(entries).toContain('logs/desktop.log');
+ expect(entries).toContain('sysinfo.json');
+ expect(entries.some((e) => e.startsWith('lockdir/'))).toBe(false);
+ expect(entries.some((e) => e.startsWith('local-logs/'))).toBe(false);
+ });
+
+ test('defaults the destination to ~/.ok/bug-reports/<timestamp>-bugreport.zip', () => {
+ // Bun resolves `os.homedir()` at process launch, so the default path can
+ // only be steered hermetically by a subprocess launched with a fake HOME
+ // (mutating `process.env.HOME` in this process would not take, and the
+ // real `~/.ok` must never be touched by tests).
+ const fakeHome = makeTmpDir('ok-bugreport-home-');
+ const userLogsDir = makeTmpDir();
+ const driverDir = makeTmpDir('ok-bugreport-driver-');
+ const handlerPath = resolve(import.meta.dirname, 'bug-report.ts');
+ writeFileSync(
+ join(driverDir, 'driver.ts'),
+ [
+ `import { handleBugReportCreate } from ${JSON.stringify(handlerPath)};`,
+ 'const result = await handleBugReportCreate(',
+ ` { projectDir: null, desktopMeta: ${JSON.stringify(DESKTOP_META)}, userLogsDir: ${JSON.stringify(userLogsDir)} },`,
+ " { kind: 'create', level: 'standard' },",
+ ');',
+ 'console.log(JSON.stringify(result));',
+ ].join('\n'),
+ );
+
+ const stdout = execFileSync(process.execPath, [join(driverDir, 'driver.ts')], {
+ env: { ...process.env, HOME: fakeHome },
+ encoding: 'utf-8',
+ });
+ const lines = stdout.trim().split('\n');
+ const result = JSON.parse(lines[lines.length - 1] ?? '') as Awaited<
+ ReturnType<typeof handleBugReportCreate>
+ >;
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ expect(dirname(result.zipPath)).toBe(join(fakeHome, '.ok', 'bug-reports'));
+ expect(result.zipPath.endsWith('-bugreport.zip')).toBe(true);
+ expect(existsSync(result.zipPath)).toBe(true);
+ });
+});
+
+interface RecordedRequest {
+ method: string;
+ path: string;
+ headers: Record<string, string | string[] | undefined>;
+ body: Buffer;
+}
+
+interface IntakeStub {
+ url: string;
+ requests: RecordedRequest[];
+ stop(): Promise<void>;
+}
+
+const SIGNED_HEADERS = {
+ 'x-signed-token': 'sig-verbatim-123',
+ 'cache-control': 'private, immutable',
+};
+
+const stubServers: Server[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ stubServers.map((server) => new Promise<void>((done) => server.close(() => done()))),
+ );
+ stubServers.length = 0;
+});
+
+/**
+ * Local HTTP stub implementing the intake + signed-upload contract: mint at
+ * POST /api/bug-report (upload URL points back at the stub), direct PUT at
+ * /upload/dest, completion at POST /api/bug-report/complete. Override
+ * per-step status/body to force each failure mode.
+ */
+function startIntakeStub(
+ overrides: {
+ mintStatus?: number;
+ mintBody?: unknown;
+ /** Record the mint request but never respond — for the timeout path. */
+ stallMint?: boolean;
+ putStatus?: number;
+ /** Record the PUT (body fully received) but never respond. */
+ stallPut?: boolean;
+ completeStatus?: number;
+ completeBody?: unknown;
+ /** Record the completion request but never respond. */
+ stallComplete?: boolean;
+ } = {},
+): Promise<IntakeStub> {
+ const requests: RecordedRequest[] = [];
+ let url = '';
+ const server = createServer((req, res) => {
+ const chunks: Buffer[] = [];
+ req.on('data', (chunk) => chunks.push(chunk as Buffer));
+ req.on('end', () => {
+ const method = req.method ?? '';
+ const path = req.url ?? '';
+ requests.push({ method, path, headers: { ...req.headers }, body: Buffer.concat(chunks) });
+ const respond = (status: number, payload: unknown) => {
+ res.writeHead(status, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(payload));
+ };
+ if (method === 'POST' && path === '/api/bug-report') {
+ if (overrides.stallMint === true) return;
+ respond(
+ overrides.mintStatus ?? 200,
+ overrides.mintBody ?? {
+ uploadUrl: `${url}/upload/dest`,
+ assetUrl: 'https://uploads.example.invalid/asset/dest',
+ headers: SIGNED_HEADERS,
+ },
+ );
+ } else if (method === 'PUT' && path === '/upload/dest') {
+ if (overrides.stallPut === true) return;
+ const putStatus = overrides.putStatus ?? 200;
+ if (putStatus >= 300 && putStatus < 400) {
+ // A redirecting storage endpoint — the client must refuse to chase it.
+ res.writeHead(putStatus, { location: `${url}/redirected` });
+ res.end();
+ } else {
+ respond(putStatus, {});
+ }
+ } else if (method === 'POST' && path === '/api/bug-report/complete') {
+ if (overrides.stallComplete === true) return;
+ respond(
+ overrides.completeStatus ?? 200,
+ overrides.completeBody ?? { reference: 'OK-1042' },
+ );
+ } else {
+ respond(404, { error: 'unexpected request' });
+ }
+ });
+ });
+ stubServers.push(server);
+ return new Promise((done, fail) => {
+ server.once('error', fail);
+ server.listen(0, '127.0.0.1', () => {
+ const address = server.address();
+ if (address === null || typeof address === 'string') {
+ fail(new Error('stub bound without a port'));
+ return;
+ }
+ url = `http://127.0.0.1:${address.port}`;
+ done({ url, requests, stop: () => new Promise((d) => server.close(() => d())) });
+ });
+ });
+}
+
+const SEND_HOST = { appVersion: '0.9.9-test.1', platform: 'darwin 25.4.0' };
+
+/** Fake `~/.ok/bug-reports/` — the containment root send validates against. */
+function makeBugReportsRoot(): string {
+ return makeTmpDir('ok-bugreport-root-');
+}
+
+function makeSendDeps(
+ intakeBaseUrl: string | undefined,
+ bugReportsRoot: string,
+): BugReportSendDeps {
+ return { intakeBaseUrl, bugReportsRoot, ...SEND_HOST };
+}
+
+const SEND_METADATA = {
+ level: 'standard' as const,
+ systemWide: false,
+ projectSlug: 'ipc-proj',
+ note: 'the editor froze',
+};
+
+/** Non-UTF-8 byte pattern so the PUT byte-identity assertion is meaningful. */
+function makeZipFixture(bugReportsRoot: string): string {
+ const bytes = Buffer.alloc(2048);
+ for (let i = 0; i < bytes.length; i++) bytes[i] = (i * 37 + 11) % 256;
+ const zipPath = join(bugReportsRoot, 'report.zip');
+ writeFileSync(zipPath, bytes);
+ return zipPath;
+}
+
+/** Deps plus a zip fixture placed inside the deps' containment root. */
+function makeSendRig(intakeBaseUrl: string | undefined): {
+ deps: BugReportSendDeps;
+ zipPath: string;
+} {
+ const bugReportsRoot = makeBugReportsRoot();
+ return {
+ deps: makeSendDeps(intakeBaseUrl, bugReportsRoot),
+ zipPath: makeZipFixture(bugReportsRoot),
+ };
+}
+
+describe('handleBugReportSend — upload happy path', () => {
+ test('runs mint, direct PUT with verbatim signed headers, and completion, returning the reference', async () => {
+ const stub = await startIntakeStub();
+ const { deps, zipPath } = makeSendRig(stub.url);
+
+ const result = await handleBugReportSend(deps, {
+ kind: 'send',
+ zipPath,
+ metadata: SEND_METADATA,
+ });
+
+ expect(result).toEqual({ ok: true, reference: 'OK-1042' });
+
+ expect(stub.requests.map((r) => `${r.method} ${r.path}`)).toEqual([
+ 'POST /api/bug-report',
+ 'PUT /upload/dest',
+ 'POST /api/bug-report/complete',
+ ]);
+
+ const [mint, put, complete] = stub.requests;
+ expect(mint?.headers['content-type']).toBe('application/json');
+ expect(JSON.parse(mint?.body.toString('utf8') ?? '')).toEqual({
+ filename: 'report.zip',
+ sizeBytes: 2048,
+ contentType: 'application/zip',
+ metadata: { ...SEND_METADATA, ...SEND_HOST },
+ });
+
+ expect(put?.headers['x-signed-token']).toBe('sig-verbatim-123');
+ expect(put?.headers['cache-control']).toBe('private, immutable');
+ expect(put?.headers['content-type']).toBe('application/zip');
+ expect(put?.body.equals(readFileSync(zipPath))).toBe(true);
+
+ expect(JSON.parse(complete?.body.toString('utf8') ?? '')).toEqual({
+ assetUrl: 'https://uploads.example.invalid/asset/dest',
+ metadata: { ...SEND_METADATA, ...SEND_HOST },
+ });
+ });
+});
+
+describe('handleBugReportSend — zip path containment', () => {
+ test('a zipPath outside the bug-reports root is refused before any read or network attempt', async () => {
+ const stub = await startIntakeStub();
+ const bugReportsRoot = makeBugReportsRoot();
+ const outsideZip = makeZipFixture(makeTmpDir('ok-bugreport-outside-'));
+
+ const result = await handleBugReportSend(makeSendDeps(stub.url, bugReportsRoot), {
+ kind: 'send',
+ zipPath: outsideZip,
+ metadata: SEND_METADATA,
+ });
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected refusal');
+ // A refusal is a failure, never the designed email-draft path.
+ expect(result.reason).toBe('send-failed');
+ // Generic fallback only — the refused path must not be echoed into the draft.
+ expect(result.fallback.mailtoUrl).not.toContain(encodeURIComponent(outsideZip));
+ expect(result.fallback.mailtoUrl.startsWith('mailto:[email protected]?')).toBe(true);
+ expect(stub.requests).toHaveLength(0);
+ });
+
+ test('a traversal escape through the root is refused', async () => {
+ const stub = await startIntakeStub();
+ const bugReportsRoot = makeBugReportsRoot();
+
+ const result = await handleBugReportSend(makeSendDeps(stub.url, bugReportsRoot), {
+ kind: 'send',
+ zipPath: `${bugReportsRoot}/../escape.zip`,
+ metadata: SEND_METADATA,
+ });
+
+ expect(result.ok).toBe(false);
+ expect(stub.requests).toHaveLength(0);
+ });
+
+ test('a relative zipPath is refused', async () => {
+ const stub = await startIntakeStub();
+ const bugReportsRoot = makeBugReportsRoot();
+
+ const result = await handleBugReportSend(makeSendDeps(stub.url, bugReportsRoot), {
+ kind: 'send',
+ zipPath: 'report.zip',
+ metadata: SEND_METADATA,
+ });
+
+ expect(result.ok).toBe(false);
+ expect(stub.requests).toHaveLength(0);
+ });
+
+ test('a symlink inside the bug-reports root that targets a file outside is refused', async () => {
+ const stub = await startIntakeStub();
+ const bugReportsRoot = makeBugReportsRoot();
+ // Lexically contained, canonically escaping — only the realpath check
+ // stands between this link and reading (then uploading) the target.
+ const outsideZip = makeZipFixture(makeTmpDir('ok-bugreport-outside-'));
+ const linkPath = join(bugReportsRoot, 'escape-link.zip');
+ symlinkSync(outsideZip, linkPath);
+
+ const result = await handleBugReportSend(makeSendDeps(stub.url, bugReportsRoot), {
+ kind: 'send',
+ zipPath: linkPath,
+ metadata: SEND_METADATA,
+ });
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected refusal');
+ expect(result.fallback.mailtoUrl).not.toContain(encodeURIComponent(linkPath));
+ expect(stub.requests).toHaveLength(0);
+ });
+});
+
+describe('handleBugReportSend — transport hardening', () => {
+ test('a stalled mint request hits the timeout ceiling and falls back', async () => {
+ const stub = await startIntakeStub({ stallMint: true });
+ const rig = makeSendRig(stub.url);
+
+ const result = await handleBugReportSend(
+ { ...rig.deps, timeouts: { mintMs: 50 } },
+ { kind: 'send', zipPath: rig.zipPath, metadata: SEND_METADATA },
+ );
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected fallback');
+ expect(result.fallback.mailtoUrl.startsWith('mailto:[email protected]?')).toBe(true);
+ expect(stub.requests.map((r) => `${r.method} ${r.path}`)).toEqual(['POST /api/bug-report']);
+ });
+
+ test('a stalled PUT hits the upload timeout ceiling and falls back before completion', async () => {
+ const stub = await startIntakeStub({ stallPut: true });
+ const rig = makeSendRig(stub.url);
+
+ const result = await handleBugReportSend(
+ { ...rig.deps, timeouts: { putMs: 50 } },
+ { kind: 'send', zipPath: rig.zipPath, metadata: SEND_METADATA },
+ );
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected fallback');
+ expect(stub.requests.map((r) => `${r.method} ${r.path}`)).toEqual([
+ 'POST /api/bug-report',
+ 'PUT /upload/dest',
+ ]);
+ });
+
+ test('a stalled completion request hits the timeout ceiling and falls back', async () => {
+ const stub = await startIntakeStub({ stallComplete: true });
+ const rig = makeSendRig(stub.url);
+
+ const result = await handleBugReportSend(
+ { ...rig.deps, timeouts: { completeMs: 50 } },
+ { kind: 'send', zipPath: rig.zipPath, metadata: SEND_METADATA },
+ );
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected fallback');
+ expect(stub.requests.map((r) => `${r.method} ${r.path}`)).toEqual([
+ 'POST /api/bug-report',
+ 'PUT /upload/dest',
+ 'POST /api/bug-report/complete',
+ ]);
+ });
+
+ test('a completion 503 falls back after all three requests fired', async () => {
+ const stub = await startIntakeStub({ completeStatus: 503 });
+ const rig = makeSendRig(stub.url);
+
+ const result = await handleBugReportSend(rig.deps, {
+ kind: 'send',
+ zipPath: rig.zipPath,
+ metadata: SEND_METADATA,
+ });
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected fallback');
+ expect(stub.requests.map((r) => `${r.method} ${r.path}`)).toEqual([
+ 'POST /api/bug-report',
+ 'PUT /upload/dest',
+ 'POST /api/bug-report/complete',
+ ]);
+ });
+
+ test('a PUT redirect is treated as failure and never followed', async () => {
+ const stub = await startIntakeStub({ putStatus: 302 });
+ const rig = makeSendRig(stub.url);
+
+ const result = await handleBugReportSend(rig.deps, {
+ kind: 'send',
+ zipPath: rig.zipPath,
+ metadata: SEND_METADATA,
+ });
+
+ expect(result.ok).toBe(false);
+ // Neither the redirect target nor the completion endpoint is touched.
+ expect(stub.requests.map((r) => `${r.method} ${r.path}`)).toEqual([
+ 'POST /api/bug-report',
+ 'PUT /upload/dest',
+ ]);
+ });
+
+ test('a non-loopback http intake URL is refused and falls back', async () => {
+ const rig = makeSendRig('http://intake.example.invalid');
+
+ const result = await handleBugReportSend(rig.deps, {
+ kind: 'send',
+ zipPath: rig.zipPath,
+ metadata: SEND_METADATA,
+ });
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected fallback');
+ expect(result.fallback.mailtoUrl).toContain(encodeURIComponent(rig.zipPath));
+ });
+
+ test('a mint response naming a non-loopback http upload URL is refused before any bytes are PUT', async () => {
+ const stub = await startIntakeStub({
+ mintBody: {
+ uploadUrl: 'http://uploads.example.invalid/dest',
+ assetUrl: 'https://uploads.example.invalid/asset/dest',
+ headers: SIGNED_HEADERS,
+ },
+ });
+ const rig = makeSendRig(stub.url);
+
+ const result = await handleBugReportSend(rig.deps, {
+ kind: 'send',
+ zipPath: rig.zipPath,
+ metadata: SEND_METADATA,
+ });
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected fallback');
+ // The bundle bytes get the same transport gate as the intake base: the
+ // minted cleartext destination is refused with no PUT ever attempted.
+ expect(stub.requests.map((r) => `${r.method} ${r.path}`)).toEqual(['POST /api/bug-report']);
+ });
+
+ test('a zip over the upload size ceiling is refused before any read or network attempt', async () => {
+ const stub = await startIntakeStub();
+ const bugReportsRoot = makeBugReportsRoot();
+ const zipPath = join(bugReportsRoot, 'huge.zip');
+ // Sparse file: stat reports a logical size over the ceiling without the
+ // test actually writing 256 MiB.
+ writeFileSync(zipPath, 'zip');
+ truncateSync(zipPath, MAX_UPLOAD_ZIP_BYTES + 1);
+
+ const result = await handleBugReportSend(makeSendDeps(stub.url, bugReportsRoot), {
+ kind: 'send',
+ zipPath,
+ metadata: SEND_METADATA,
+ });
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected refusal');
+ // The renderer sees the ordinary failure screen with the email fallback.
+ expect(result.reason).toBe('send-failed');
+ expect(result.fallback.mailtoUrl.startsWith('mailto:[email protected]?')).toBe(true);
+ expect(stub.requests).toHaveLength(0);
+ });
+
+ test('parseTransportSafeUrl admits https anywhere and http only on loopback', () => {
+ expect(parseTransportSafeUrl('https://openknowledge.ai')).not.toBeNull();
+ expect(parseTransportSafeUrl('http://127.0.0.1:8080')).not.toBeNull();
+ expect(parseTransportSafeUrl('http://localhost:8080')).not.toBeNull();
+ expect(parseTransportSafeUrl('http://[::1]:8080')).not.toBeNull();
+ expect(parseTransportSafeUrl('http://intake.example.com')).toBeNull();
+ expect(parseTransportSafeUrl('ftp://openknowledge.ai')).toBeNull();
+ expect(parseTransportSafeUrl('not a url')).toBeNull();
+ });
+});
+
+describe('handleBugReportSend — note redaction off the bundle path', () => {
+ const SECRET = 'sk-ant-api03-abcdefghijklmnopqrstuvwx';
+
+ test('a secret in the note is scrubbed from the mint and completion metadata', async () => {
+ const stub = await startIntakeStub();
+ const rig = makeSendRig(stub.url);
+
+ const result = await handleBugReportSend(rig.deps, {
+ kind: 'send',
+ zipPath: rig.zipPath,
+ metadata: { ...SEND_METADATA, note: `it broke right after I pasted ${SECRET}` },
+ });
+
+ expect(result).toEqual({ ok: true, reference: 'OK-1042' });
+ const [mint, , complete] = stub.requests;
+ for (const body of [mint?.body, complete?.body]) {
+ const wire = JSON.parse(body?.toString('utf8') ?? '') as {
+ metadata: { note?: string };
+ };
+ expect(wire.metadata.note).toContain('[REDACTED-ANTHROPIC]');
+ expect(wire.metadata.note).not.toContain(SECRET);
+ }
+ });
+
+ test('a secret in the note is scrubbed from the mailto fallback body', async () => {
+ const rig = makeSendRig(undefined);
+
+ const result = await handleBugReportSend(rig.deps, {
+ kind: 'send',
+ zipPath: rig.zipPath,
+ metadata: { ...SEND_METADATA, note: `my key is ${SECRET}` },
+ });
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected fallback');
+ expect(result.fallback.mailtoUrl).toContain(encodeURIComponent('[REDACTED-ANTHROPIC]'));
+ expect(result.fallback.mailtoUrl).not.toContain(encodeURIComponent(SECRET));
+ // The zip path itself stays verbatim — the user needs it to attach the file.
+ expect(result.fallback.mailtoUrl).toContain(encodeURIComponent(rig.zipPath));
+ });
+});
+
+describe('handleBugReportSend — email fallback', () => {
+ test('unconfigured endpoint resolves to the email-draft path with the exact prefilled mailto, which clears the openExternal gate', async () => {
+ const { deps, zipPath } = makeSendRig(undefined);
+
+ const result = await handleBugReportSend(deps, {
+ kind: 'send',
+ zipPath,
+ metadata: SEND_METADATA,
+ });
+
+ const expectedBody = [
+ 'the editor froze',
+ '',
+ 'Please attach the report file saved at:',
+ zipPath,
+ '',
+ 'App version: 0.9.9-test.1',
+ 'Platform: darwin 25.4.0',
+ 'Project: ipc-proj',
+ 'Detail level: standard',
+ ].join('\n');
+ const expectedMailto = `mailto:[email protected]?subject=${encodeURIComponent(
+ 'OpenKnowledge bug report (v0.9.9-test.1)',
+ )}&body=${encodeURIComponent(expectedBody)}`;
+ // `email-draft`, not `send-failed`: no intake is configured, so this is
+ // the designed transport, and the dialog must not render a failure.
+ expect(result).toEqual({
+ ok: false,
+ reason: 'email-draft',
+ fallback: { mailtoUrl: expectedMailto },
+ });
+ if (result.ok) throw new Error('expected fallback');
+
+ const opened: string[] = [];
+ const openExternal = handleShellOpenExternal({
+ openExternal: async (url) => {
+ opened.push(url);
+ },
+ });
+ await openExternal(result.fallback.mailtoUrl);
+ expect(opened).toEqual([expectedMailto]);
+ });
+
+ test('a mint rejection (oversize 413) falls back with the note preserved, after only the mint request', async () => {
+ const stub = await startIntakeStub({ mintStatus: 413 });
+
+ const rig = makeSendRig(stub.url);
+ const result = await handleBugReportSend(rig.deps, {
+ kind: 'send',
+ zipPath: rig.zipPath,
+ metadata: SEND_METADATA,
+ });
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected fallback');
+ // A real attempted-and-refused upload — distinct from the email-draft path.
+ expect(result.reason).toBe('send-failed');
+ expect(result.fallback.mailtoUrl).toContain(encodeURIComponent('the editor froze'));
+ expect(stub.requests.map((r) => `${r.method} ${r.path}`)).toEqual(['POST /api/bug-report']);
+ });
+
+ test('a network error (endpoint unreachable) falls back instead of throwing', async () => {
+ const stub = await startIntakeStub();
+ await stub.stop();
+
+ const rig = makeSendRig(stub.url);
+ const result = await handleBugReportSend(rig.deps, {
+ kind: 'send',
+ zipPath: rig.zipPath,
+ metadata: SEND_METADATA,
+ });
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected fallback');
+ expect(result.fallback.mailtoUrl.startsWith('mailto:[email protected]?')).toBe(true);
+ });
+
+ test('a failed PUT falls back and never fires the completion call', async () => {
+ const stub = await startIntakeStub({ putStatus: 500 });
+
+ const rig = makeSendRig(stub.url);
+ const result = await handleBugReportSend(rig.deps, {
+ kind: 'send',
+ zipPath: rig.zipPath,
+ metadata: SEND_METADATA,
+ });
+
+ expect(result.ok).toBe(false);
+ // No accepted-but-lost state: a report is only filed with its bundle
+ // attached, so a failed upload must leave the completion endpoint untouched.
+ expect(stub.requests.map((r) => `${r.method} ${r.path}`)).toEqual([
+ 'POST /api/bug-report',
+ 'PUT /upload/dest',
+ ]);
+ });
+
+ test('a malformed mint response (missing uploadUrl) falls back', async () => {
+ const stub = await startIntakeStub({ mintBody: { assetUrl: 'x', headers: {} } });
+
+ const rig = makeSendRig(stub.url);
+ const result = await handleBugReportSend(rig.deps, {
+ kind: 'send',
+ zipPath: rig.zipPath,
+ metadata: SEND_METADATA,
+ });
+
+ expect(result.ok).toBe(false);
+ expect(stub.requests.map((r) => `${r.method} ${r.path}`)).toEqual(['POST /api/bug-report']);
+ });
+
+ test('a completion response without a reference falls back', async () => {
+ const stub = await startIntakeStub({ completeBody: { filed: true } });
+
+ const rig = makeSendRig(stub.url);
+ const result = await handleBugReportSend(rig.deps, {
+ kind: 'send',
+ zipPath: rig.zipPath,
+ metadata: SEND_METADATA,
+ });
+
+ expect(result.ok).toBe(false);
+ expect(stub.requests).toHaveLength(3);
+ });
+
+ test('a malformed renderer payload falls back to a generic mailto without touching the network', async () => {
+ const stub = await startIntakeStub();
+
+ const rig = makeSendRig(stub.url);
+ const result = await handleBugReportSend(rig.deps, {
+ kind: 'send',
+ zipPath: rig.zipPath,
+ metadata: { ...SEND_METADATA, level: 'verbose' },
+ } as unknown as Parameters<typeof handleBugReportSend>[1]);
+
+ const degenerateBody = ['App version: 0.9.9-test.1', 'Platform: darwin 25.4.0'].join('\n');
+ expect(result).toEqual({
+ ok: false,
+ reason: 'send-failed',
+ fallback: {
+ mailtoUrl: `mailto:[email protected]?subject=${encodeURIComponent(
+ 'OpenKnowledge bug report (v0.9.9-test.1)',
+ )}&body=${encodeURIComponent(degenerateBody)}`,
+ },
+ });
+ expect(stub.requests).toHaveLength(0);
+ });
+});
+
+describe('handleBugReportCreate — crash-dump opt-in', () => {
+ test('includeCrashDump bundles the newest minidump byte-for-byte under extra/', async () => {
+ const dumpPath = join(makeTmpDir(), 'renderer-crash.dmp');
+ // Non-UTF-8 payload wrapping a would-be-redacted token: the dump must
+ // arrive byte-identical — minidumps are copied raw, never text-scrubbed.
+ const dumpBytes = Buffer.concat([
+ Buffer.from([0x4d, 0x44, 0x4d, 0x50, 0x00, 0xff, 0xfe, 0x01]),
+ Buffer.from('sk-ant-api03-abcdefghijklmnopqrstuvwx'),
+ Buffer.from([0x00, 0x9c]),
+ ]);
+ writeFileSync(dumpPath, dumpBytes);
+ const deps = makeDeps({ newestMinidumpPath: () => dumpPath });
+
+ const result = await handleBugReportCreate(deps, {
+ kind: 'create',
+ level: 'standard',
+ includeCrashDump: true,
+ });
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ expect(listZipEntries(result.zipPath)).toContain('extra/renderer-crash.dmp');
+ expect(readZipEntryBytes(result.zipPath, 'extra/renderer-crash.dmp').equals(dumpBytes)).toBe(
+ true,
+ );
+ });
+
+ test('without the opt-in no minidump is included even when one exists', async () => {
+ const dumpPath = join(makeTmpDir(), 'renderer-crash.dmp');
+ writeFileSync(dumpPath, 'dump-bytes');
+ const deps = makeDeps({ newestMinidumpPath: () => dumpPath });
+
+ const result = await handleBugReportCreate(deps, { kind: 'create', level: 'standard' });
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ expect(listZipEntries(result.zipPath).some((e) => e.startsWith('extra/'))).toBe(false);
+ });
+
+ test('opting in with no relevant dump on disk still builds the bundle', async () => {
+ const deps = makeDeps({ newestMinidumpPath: () => null });
+
+ const result = await handleBugReportCreate(deps, {
+ kind: 'create',
+ level: 'standard',
+ includeCrashDump: true,
+ });
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ expect(listZipEntries(result.zipPath).some((e) => e.startsWith('extra/'))).toBe(false);
+ });
+
+ test('an opted-in dump that vanished before staging is warned about, never dropped silently', async () => {
+ const vanishedDump = join(makeTmpDir(), 'already-cleaned.dmp');
+ const warnings: Array<{ payload: Record<string, unknown>; message: string }> = [];
+ const deps = makeDeps({
+ newestMinidumpPath: () => vanishedDump,
+ logger: {
+ info: () => {},
+ warn: (payload, message) => {
+ warnings.push({ payload, message });
+ },
+ },
+ });
+
+ const result = await handleBugReportCreate(deps, {
+ kind: 'create',
+ level: 'standard',
+ includeCrashDump: true,
+ });
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ expect(listZipEntries(result.zipPath).some((e) => e.startsWith('extra/'))).toBe(false);
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]?.payload.sourcePath).toBe(vanishedDump);
+ });
+
+ test('a non-boolean includeCrashDump is refused as invalid-request', async () => {
+ const deps = makeDeps({ newestMinidumpPath: () => '/never-read.dmp' });
+
+ const result = await handleBugReportCreate(deps, {
+ kind: 'create',
+ level: 'standard',
+ includeCrashDump: 'yes',
+ } as unknown as Parameters<typeof handleBugReportCreate>[1]);
+
+ expect(result).toEqual({ ok: false, error: 'invalid-request' });
+ });
+});
+
+describe('handleBugReportCreate — failure modes', () => {
+ test('an unwritable destination maps to a discriminated error instead of throwing', async () => {
+ const blockerFile = join(makeTmpDir(), 'not-a-dir');
+ writeFileSync(blockerFile, 'occupied\n');
+ const deps = makeDeps({ outputPath: join(blockerFile, 'report.zip') });
+
+ const result = await handleBugReportCreate(deps, { kind: 'create', level: 'standard' });
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected failure');
+ expect(result.error.length).toBeGreaterThan(0);
+ });
+
+ test('a malformed renderer payload is refused as invalid-request', async () => {
+ const deps = makeDeps();
+
+ const result = await handleBugReportCreate(deps, {
+ kind: 'create',
+ level: 'verbose',
+ } as unknown as Parameters<typeof handleBugReportCreate>[1]);
+
+ expect(result).toEqual({ ok: false, error: 'invalid-request' });
+ });
+});
+
+describe('handleBugReportCrashAck', () => {
+ /**
+ * Real crash-detection instance over tmpdir paths with a deterministic
+ * advancing clock, so the ack round-trip is proven against the persisted
+ * store rather than a recording double.
+ */
+ function makeCrashDetectionRig() {
+ const dir = makeTmpDir('ok-bugreport-crashack-');
+ let clockMs = Date.parse('2026-07-10T00:00:00.000Z');
+ const deps = {
+ sentinelPath: join(dir, 'sentinel.json'),
+ ackStorePath: join(dir, 'crash-acks.json'),
+ crashDumpsDir: join(dir, 'dumps'),
+ emit: () => true,
+ now: () => {
+ clockMs += 10_000;
+ return new Date(clockMs);
+ },
+ logger: { info: () => {}, warn: () => {} },
+ };
+ const seedMinidump = (relPath: string): void => {
+ const dumpPath = join(deps.crashDumpsDir, relPath);
+ mkdirSync(dirname(dumpPath), { recursive: true });
+ writeFileSync(dumpPath, 'minidump-bytes');
+ clockMs += 10_000;
+ const at = new Date(clockMs);
+ utimesSync(dumpPath, at, at);
+ };
+ return { deps, seedMinidump };
+ }
+
+ test('a crash-ack round-trip retires the crash event across restarts', () => {
+ const { deps, seedMinidump } = makeCrashDetectionRig();
+
+ const sessionA = createCrashDetection(deps);
+ expect(sessionA.detectBootCrash()).toBeNull();
+ sessionA.markCleanQuit();
+
+ seedMinidump('pending/native.dmp');
+
+ const sessionB = createCrashDetection(deps);
+ const invited = sessionB.detectBootCrash();
+ if (!invited) throw new Error('expected a boot invitation for the fresh minidump');
+ sessionB.markCleanQuit();
+
+ // Unanswered, the same crash re-invites on the next boot...
+ const sessionC = createCrashDetection(deps);
+ expect(sessionC.detectBootCrash()?.eventId).toBe(invited.eventId);
+
+ // ...until the renderer's ack lands through the dispatch surface.
+ const ackResult = handleBugReportCrashAck(
+ { ackCrashEvent: (eventId) => sessionC.ack(eventId) },
+ { kind: 'crash-ack', eventId: invited.eventId },
+ );
+ expect(ackResult).toEqual({ ok: true });
+ sessionC.markCleanQuit();
+
+ const sessionD = createCrashDetection(deps);
+ expect(sessionD.detectBootCrash()).toBeNull();
+ });
+
+ test('a malformed renderer payload is refused and never touches the acknowledgment store', () => {
+ const acked: string[] = [];
+ const deps = { ackCrashEvent: (eventId: string) => acked.push(eventId) };
+ const malformed = [
+ { kind: 'crash-ack' },
+ { kind: 'crash-ack', eventId: '' },
+ { kind: 'crash-ack', eventId: 42 },
+ { kind: 'ack', eventId: 'crash:render:1:0' },
+ null,
+ ];
+
+ for (const request of malformed) {
+ const result = handleBugReportCrashAck(
+ deps,
+ request as unknown as Parameters<typeof handleBugReportCrashAck>[1],
+ );
+ expect(result).toEqual({ ok: false, error: 'invalid-request' });
+ }
+
+ // The handler's contract: malformed renderer input never mutates the store.
+ expect(acked).toEqual([]);
+ });
+});
diff --git a/packages/desktop/src/main/ipc/bug-report.ts b/packages/desktop/src/main/ipc/bug-report.ts
new file mode 100644
index 000000000..1c6a59d42
--- /dev/null
+++ b/packages/desktop/src/main/ipc/bug-report.ts
@@ -0,0 +1,626 @@
+/**
+ * IPC handler implementation for the in-app "Report a bug" flow.
+ *
+ * Single channel `ok:bug-report:dispatch` with discriminated args, following
+ * the `ok:sharing:dispatch` precedent so the whole report-a-bug surface costs
+ * one hand-rolled channel slot. The surface carries three operations:
+ * - `create` — build the redacted diagnostic zip via the CLI package's
+ * leveled `collectReportBundle` (no subprocess), scoped to the sender
+ * window's project or system-wide when the window has no project.
+ * - `send` — upload a previously created zip to the private intake
+ * endpoint; every failure degrades to a prefilled email fallback.
+ * - `crash-ack` — persist that the user answered (or dismissed) a
+ * crash-detected invitation so the same crash event never re-prompts.
+ *
+ * Project scoping: main resolves the sender window's project via the
+ * window-manager context; the renderer never passes a project path.
+ */
+
+import { readFile, realpath, stat } from 'node:fs/promises';
+import { basename } from 'node:path';
+import {
+ type BundleLogger,
+ collectReportBundle,
+ defaultBugReportZipPath,
+ redactContent,
+} from '@inkeep/open-knowledge';
+import type {
+ OkBugReportCrashAckResult,
+ OkBugReportCreateResult,
+ OkBugReportSendMetadata,
+ OkBugReportSendResult,
+ ReportBundleLevel,
+} from '@inkeep/open-knowledge-core';
+import { logIpcError } from '../ipc-log.ts';
+import { isPathWithinProject } from '../path-containment.ts';
+import type { UpdateChannel } from '../state-store.ts';
+
+export interface OkBugReportCreateRequest {
+ kind: 'create';
+ level: ReportBundleLevel;
+ /** Free-text user note bundled as `note.txt` (secret-scrubbed like every text entry). */
+ note?: string;
+ /**
+ * Crash-invite opt-in: copy the newest un-acked crash minidump into the
+ * bundle under `extra/`, raw. Minidumps carry process memory that text
+ * redaction cannot scrub, so absence (the default) must always mean no
+ * dump — only the dialog's explicit checkbox sets this.
+ */
+ includeCrashDump?: boolean;
+}
+
+export interface OkBugReportSendRequest {
+ kind: 'send';
+ /** Zip produced by a prior `create` — the exact file the user reviewed is what uploads. */
+ zipPath: string;
+ metadata: OkBugReportSendMetadata;
+}
+
+export interface OkBugReportCrashAckRequest {
+ kind: 'crash-ack';
+ /** `eventId` from the `ok:bug-report:crash-detected` push being answered. */
+ eventId: string;
+}
+
+/** Every operation the `ok:bug-report:dispatch` channel carries. */
+export type OkBugReportRequest =
+ | OkBugReportCreateRequest
+ | OkBugReportSendRequest
+ | OkBugReportCrashAckRequest;
+
+/**
+ * Host metadata handed to the bundle collector through its typed
+ * `readDesktopEnv` seam. Never routed via `process.env`: the main process is
+ * long-lived, and env mutations would leak `OK_DESKTOP_*` into every child
+ * later spawned with `env: process.env` (e.g. a server respawn).
+ */
+interface BugReportDesktopMeta {
+ /** App version (`app.getVersion()`). */
+ version: string;
+ /** Packaged build vs dev run (`app.isPackaged`). */
+ packaged: boolean;
+ /** Update channel implied by the build version (`channelFromVersion`). */
+ channel: UpdateChannel;
+}
+
+export interface BugReportCreateDeps {
+ /** Sender window's project root; `null` (Navigator, no project) degrades to a system-wide bundle. */
+ projectDir: string | null;
+ desktopMeta: BugReportDesktopMeta;
+ /** Zip destination override; defaults to `~/.ok/bug-reports/<timestamp>-bugreport.zip`. */
+ outputPath?: string;
+ /** User-level logs directory override (standard-level test seam). */
+ userLogsDir?: string;
+ /**
+ * Crash-detection lookup for the newest un-acked minidump (wired from
+ * `CrashDetection.newestMinidumpPath`). Only consulted when the renderer
+ * opted in via `includeCrashDump`; absent or returning null simply omits
+ * the dump.
+ */
+ newestMinidumpPath?: () => string | null;
+ /**
+ * Sink for the collector's warnings — most importantly an opted-in crash
+ * dump that could not be staged, which must be traceable rather than a
+ * silent omission from the bundle.
+ */
+ logger?: BundleLogger;
+}
+
+/**
+ * `createHandler` casts renderer args without runtime enforcement, so the
+ * payload is re-validated here before any filesystem work.
+ */
+/**
+ * Ceiling on the free-text note the renderer may hand to `create`/`send`. A
+ * genuine "what happened?" note is a sentence or two; this refuses an abusive
+ * or compromised renderer stuffing megabytes of text through the typed IPC
+ * boundary (the note is embedded in the zip and the mailto fallback).
+ */
+const MAX_NOTE_LENGTH = 32_768;
+
+/** A note is valid when absent, or a string within the length ceiling. */
+function isValidNote(note: unknown): boolean {
+ return note === undefined || (typeof note === 'string' && note.length <= MAX_NOTE_LENGTH);
+}
+
+function isCreateRequest(request: unknown): request is OkBugReportCreateRequest {
+ if (typeof request !== 'object' || request === null) return false;
+ const r = request as Record<string, unknown>;
+ return (
+ r.kind === 'create' &&
+ (r.level === 'standard' || r.level === 'full') &&
+ isValidNote(r.note) &&
+ (r.includeCrashDump === undefined || typeof r.includeCrashDump === 'boolean')
+ );
+}
+
+/**
+ * Build the redacted bug-report bundle for the `create` operation. Never
+ * throws — every failure mode maps to the discriminated `{ok: false}` result
+ * so the report dialog can render its failure state.
+ */
+export async function handleBugReportCreate(
+ deps: BugReportCreateDeps,
+ request: OkBugReportCreateRequest,
+): Promise<OkBugReportCreateResult> {
+ if (!isCreateRequest(request)) {
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:bug-report:dispatch',
+ reason: 'invalid-request',
+ handler: 'handleBugReportCreate',
+ });
+ return { ok: false, error: 'invalid-request' };
+ }
+ const minidumpPath =
+ request.includeCrashDump === true ? (deps.newestMinidumpPath?.() ?? null) : null;
+ try {
+ 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(),
+ userLogsDir: deps.userLogsDir,
+ extraFiles: minidumpPath === null ? undefined : [{ sourcePath: minidumpPath }],
+ logger: deps.logger,
+ readDesktopEnv: () => ({
+ electronVersion: deps.desktopMeta.version,
+ packaged: deps.desktopMeta.packaged,
+ channel: deps.desktopMeta.channel,
+ }),
+ });
+ const { size: zipSizeBytes } = await stat(zipPath);
+ return { ok: true, zipPath, zipSizeBytes, summary };
+ } catch (err) {
+ // Environmental failure at the fs boundary (unwritable destination, disk
+ // full, unreadable project artifacts) — the producer can't enforce these
+ // preconditions, and the channel's contract is a discriminated result.
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:bug-report:dispatch',
+ reason: 'bundle-failed',
+ handler: 'handleBugReportCreate',
+ cause: err,
+ });
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+const SUPPORT_EMAIL = '[email protected]';
+
+export interface BugReportSendDeps {
+ /**
+ * Intake endpoint origin (e.g. `https://openknowledge.ai`), from
+ * `OK_BUG_REPORT_INTAKE_URL`. Absent means the endpoint is not deployed or
+ * not configured — the designed default: send makes no network attempt and
+ * resolves to the email fallback with `reason: 'email-draft'`, which the
+ * dialog renders as the email flow rather than a failure.
+ */
+ intakeBaseUrl: string | undefined;
+ /** App version (`app.getVersion()`), stamped into the report metadata by main. */
+ appVersion: string;
+ /** Human-readable OS line (e.g. `darwin 25.4.0`), stamped by main. */
+ platform: string;
+ /**
+ * Containment root for the renderer-supplied `zipPath` — the bug-reports
+ * directory `create` writes into (main-derived, never renderer-influenced).
+ * `send` both reads and transmits the file off-device, so it gets the same
+ * renderer-path bound every sibling filesystem-touching channel enforces
+ * (`showItemInFolder` allowedRoots, `spawnCursor`, `trashItem`).
+ */
+ bugReportsRoot: string;
+ /** Transport-timeout overrides (test seam; defaults 30s mint/complete, 120s PUT). */
+ timeouts?: Partial<BugReportUploadTimeouts>;
+}
+
+/**
+ * Per-step ceilings so a hung intake or storage endpoint cannot park the IPC
+ * handler (and the in-memory zip bytes) forever — the dialog's Cancel only
+ * abandons the renderer-side wait, never the main-side socket. The PUT gets
+ * the long ceiling because it carries the whole bundle.
+ */
+interface BugReportUploadTimeouts {
+ mintMs: number;
+ putMs: number;
+ completeMs: number;
+}
+
+const MINT_TIMEOUT_MS = 30_000;
+const PUT_TIMEOUT_MS = 120_000;
+const COMPLETE_TIMEOUT_MS = 30_000;
+
+/**
+ * Ceiling on the zip size `send` will buffer into main-process memory for the
+ * PUT. Real bundles sit in the tens of MB (the log/span sinks are size-capped)
+ * plus an optional minidump; 256 MiB refuses a pathological zip before the
+ * read can exhaust the process, degrading to the email fallback instead.
+ */
+export const MAX_UPLOAD_ZIP_BYTES = 256 * 1024 * 1024;
+
+/**
+ * Admit a report-transport URL — the intake base or a minted upload URL —
+ * only when transport-safe: `https:` anywhere, or plain `http:` strictly on
+ * loopback hosts (local stubs and dev). Anything else would ship the report
+ * bytes — possibly a memory-carrying minidump — in cleartext to a MITM-able
+ * endpoint.
+ *
+ * Transport encryption is ALL this gate enforces. Any `https:` destination
+ * passes, loopback / link-local / RFC-1918 literals included — there is no
+ * internal-host (SSRF-style) filtering here, and none is claimed: the intake
+ * base is operator config and the minted URL comes from that operator's
+ * service, so destination trust rests with the config, not this parser.
+ */
+export function parseTransportSafeUrl(raw: string): URL | null {
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ return null;
+ }
+ if (url.protocol === 'https:') return url;
+ const loopback =
+ url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]';
+ return url.protocol === 'http:' && loopback ? url : null;
+}
+
+function isSendRequest(request: unknown): request is OkBugReportSendRequest {
+ if (typeof request !== 'object' || request === null) return false;
+ const r = request as Record<string, unknown>;
+ if (r.kind !== 'send' || typeof r.zipPath !== 'string') return false;
+ if (typeof r.metadata !== 'object' || r.metadata === null) return false;
+ const m = r.metadata as Record<string, unknown>;
+ return (
+ (m.level === 'standard' || m.level === 'full') &&
+ typeof m.systemWide === 'boolean' &&
+ (m.projectSlug === null || typeof m.projectSlug === 'string') &&
+ isValidNote(m.note)
+ );
+}
+
+/**
+ * Prefilled draft to the support inbox: the note plus the system summary,
+ * with the zip path so the user knows which file to attach — the draft never
+ * inlines bundle contents. Total over partial input so the degenerate
+ * invalid-request path still yields a working mailto.
+ */
+function buildBugReportMailto(args: {
+ appVersion: string;
+ platform: string;
+ metadata?: OkBugReportSendMetadata;
+ zipPath?: string;
+}): string {
+ const subject = `OpenKnowledge bug report (v${args.appVersion})`;
+ const lines: string[] = [];
+ if (args.metadata?.note) lines.push(args.metadata.note, '');
+ if (args.zipPath) lines.push('Please attach the report file saved at:', args.zipPath, '');
+ lines.push(`App version: ${args.appVersion}`, `Platform: ${args.platform}`);
+ if (args.metadata) {
+ const project =
+ args.metadata.projectSlug ??
+ (args.metadata.systemWide ? 'none (system-wide report)' : '(unnamed project)');
+ lines.push(`Project: ${project}`, `Detail level: ${args.metadata.level}`);
+ }
+ const body = lines.join('\n');
+ return `mailto:${SUPPORT_EMAIL}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
+}
+
+/** Metadata JSON as it crosses to the intake endpoint — renderer summary + host facts. */
+interface BugReportWireMetadata extends OkBugReportSendMetadata {
+ appVersion: string;
+ platform: string;
+}
+
+interface BugReportMintResponse {
+ uploadUrl: string;
+ assetUrl: string;
+ /** Signed-upload headers the PUT must carry verbatim. */
+ headers: Record<string, string>;
+}
+
+/** Cross-network response bodies are untrusted bytes — re-parse before use. */
+function parseMintResponse(payload: unknown): BugReportMintResponse | null {
+ if (typeof payload !== 'object' || payload === null) return null;
+ const p = payload as Record<string, unknown>;
+ if (typeof p.uploadUrl !== 'string' || typeof p.assetUrl !== 'string') return null;
+ if (typeof p.headers !== 'object' || p.headers === null) return null;
+ const headers: Record<string, string> = {};
+ for (const [key, value] of Object.entries(p.headers)) {
+ if (typeof value !== 'string') return null;
+ headers[key] = value;
+ }
+ return { uploadUrl: p.uploadUrl, assetUrl: p.assetUrl, headers };
+}
+
+function parseCompletionReference(payload: unknown): string | null {
+ if (typeof payload !== 'object' || payload === null) return null;
+ const reference = (payload as Record<string, unknown>).reference;
+ return typeof reference === 'string' && reference !== '' ? reference : null;
+}
+
+type BugReportUploadOutcome =
+ | { ok: true; reference: string }
+ | { ok: false; reason: string; cause?: unknown };
+
+/**
+ * Two-step client upload (mint → direct PUT → completion), keeping the zip
+ * bytes out of the intake function body: the endpoint mints a short-lived
+ * signed upload URL, the client PUTs the bytes straight to storage with the
+ * signed headers verbatim, then the completion call files the report and
+ * returns its reference. The completion POST only fires after a successful
+ * PUT — an accepted report always has its bundle attached.
+ */
+async function uploadBugReport(
+ baseUrl: string,
+ zipPath: string,
+ metadata: BugReportWireMetadata,
+ timeouts?: Partial<BugReportUploadTimeouts>,
+): Promise<BugReportUploadOutcome> {
+ const base = parseTransportSafeUrl(baseUrl);
+ if (base === null) {
+ // The rejected value is operator config, never a user secret — logging
+ // it is what makes a misconfigured intake diagnosable.
+ return { ok: false, reason: 'intake-url-rejected', cause: `rejected intake URL: ${baseUrl}` };
+ }
+ // Re-packed as a plain Uint8Array — fetch's BodyInit typing rejects
+ // Buffer's ArrayBufferLike backing.
+ let zipBytes: Uint8Array<ArrayBuffer>;
+ try {
+ const { size } = await stat(zipPath);
+ if (size > MAX_UPLOAD_ZIP_BYTES) {
+ return {
+ ok: false,
+ reason: 'zip-oversize',
+ cause: `zip is ${size} bytes (ceiling ${MAX_UPLOAD_ZIP_BYTES})`,
+ };
+ }
+ const raw = await readFile(zipPath);
+ zipBytes = new Uint8Array(raw.byteLength);
+ zipBytes.set(raw);
+ } catch (err) {
+ return { ok: false, reason: 'zip-unreadable', cause: err };
+ }
+ let step: 'mint' | 'upload' | 'complete' = 'mint';
+ try {
+ const mintRes = await fetch(new URL('/api/bug-report', base), {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ filename: basename(zipPath),
+ sizeBytes: zipBytes.byteLength,
+ contentType: 'application/zip',
+ metadata,
+ }),
+ redirect: 'manual',
+ signal: AbortSignal.timeout(timeouts?.mintMs ?? MINT_TIMEOUT_MS),
+ });
+ if (!mintRes.ok) return { ok: false, reason: `mint-rejected: ${mintRes.status}` };
+ const mint = parseMintResponse(await mintRes.json().catch(() => null));
+ if (mint === null) return { ok: false, reason: 'mint-malformed' };
+ // The minted URL is the channel that carries the actual bundle bytes, so
+ // it gets the same transport gate as the operator-configured base — a
+ // misconfigured or compromised intake must not be able to downgrade the
+ // PUT to cleartext. Encryption only: the gate does not restrict which
+ // https host the mint may name.
+ if (parseTransportSafeUrl(mint.uploadUrl) === null) {
+ return {
+ ok: false,
+ reason: 'upload-url-rejected',
+ cause: `rejected upload URL: ${mint.uploadUrl}`,
+ };
+ }
+
+ step = 'upload';
+ const putRes = await fetch(mint.uploadUrl, {
+ method: 'PUT',
+ // Minted values win over the baseline content-type when they overlap —
+ // the signed-URL contract requires its headers untransformed.
+ headers: { 'content-type': 'application/zip', ...mint.headers },
+ body: zipBytes,
+ // Never chase a redirect with the signed request: following would
+ // replay the signed headers and the bundle bytes to a location the
+ // mint response didn't name.
+ redirect: 'manual',
+ signal: AbortSignal.timeout(timeouts?.putMs ?? PUT_TIMEOUT_MS),
+ });
+ // `redirect: 'manual'` surfaces the un-followed redirect either as the
+ // raw 3xx or as an opaque-redirect response (status 0), depending on
+ // runtime — classify both apart from an ordinary status rejection.
+ if (
+ putRes.type === 'opaqueredirect' ||
+ putRes.status === 0 ||
+ (putRes.status >= 300 && putRes.status < 400)
+ ) {
+ return { ok: false, reason: 'upload-redirected' };
+ }
+ if (!putRes.ok) return { ok: false, reason: `upload-rejected: ${putRes.status}` };
+
+ step = 'complete';
+ const completeRes = await fetch(new URL('/api/bug-report/complete', base), {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ assetUrl: mint.assetUrl, metadata }),
+ redirect: 'manual',
+ signal: AbortSignal.timeout(timeouts?.completeMs ?? COMPLETE_TIMEOUT_MS),
+ });
+ if (!completeRes.ok) return { ok: false, reason: `complete-rejected: ${completeRes.status}` };
+ const reference = parseCompletionReference(await completeRes.json().catch(() => null));
+ if (reference === null) return { ok: false, reason: 'complete-malformed' };
+ return { ok: true, reference };
+ } catch (err) {
+ // Offline, DNS failure, refused connection — or a timeout ceiling firing
+ // on a hung endpoint. `AbortError` is classified as a timeout alongside
+ // `TimeoutError` because runtimes disagree on which name an
+ // `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.
+ const timedOut =
+ err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError');
+ return { ok: false, reason: timedOut ? `${step}-timeout` : 'network-error', cause: err };
+ }
+}
+
+/**
+ * Upload the reviewed zip for the `send` operation. Never throws — every
+ * non-success maps to the discriminated `{ok: false}` result whose fallback
+ * mailto the dialog offers instead, with `reason: 'email-draft'` reserved for
+ * the designed no-intake path (no network attempted, not a failure).
+ */
+export async function handleBugReportSend(
+ deps: BugReportSendDeps,
+ request: OkBugReportSendRequest,
+): Promise<OkBugReportSendResult> {
+ const hostFacts = { appVersion: deps.appVersion, platform: deps.platform };
+ if (!isSendRequest(request)) {
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:bug-report:dispatch',
+ reason: 'invalid-request',
+ handler: 'handleBugReportSend',
+ });
+ return {
+ ok: false,
+ reason: 'send-failed',
+ fallback: { mailtoUrl: buildBugReportMailto(hostFacts) },
+ };
+ }
+ // A compromised renderer must not be able to steer main into reading (and
+ // uploading) arbitrary user-readable files: only zips inside the
+ // main-owned bug-reports directory — the sole place `create` writes — may
+ // leave the machine. Refused paths get the generic fallback so the
+ // untrusted path is not echoed back into the email draft. The lexical
+ // check is a cheap pre-filter; the canonical (realpath) check below is
+ // what holds, because a symlink planted inside the root passes lexically
+ // and the OS follows it at read time (same order as `trashItem`).
+ if (!isPathWithinProject(request.zipPath, deps.bugReportsRoot, process.platform)) {
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:bug-report:dispatch',
+ reason: 'zip-path-escape',
+ handler: 'handleBugReportSend',
+ });
+ return {
+ ok: false,
+ reason: 'send-failed',
+ fallback: { mailtoUrl: buildBugReportMailto(hostFacts) },
+ };
+ }
+ let canonicalZipPath: string;
+ try {
+ // The root canonicalizes alongside the zip so a symlinked ancestor of
+ // the root itself (macOS `/var` → `/private/var`) can't read as escape.
+ const canonicalRoot = await realpath(deps.bugReportsRoot);
+ canonicalZipPath = await realpath(request.zipPath);
+ if (!isPathWithinProject(canonicalZipPath, canonicalRoot, process.platform)) {
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:bug-report:dispatch',
+ reason: 'zip-path-escape',
+ handler: 'handleBugReportSend',
+ });
+ return {
+ ok: false,
+ reason: 'send-failed',
+ fallback: { mailtoUrl: buildBugReportMailto(hostFacts) },
+ };
+ }
+ } catch (err) {
+ // Realpath failure means the zip (or the root) is gone from disk — the
+ // draft still helps, but there is no file to read or upload.
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:bug-report:dispatch',
+ reason: 'zip-unresolvable',
+ handler: 'handleBugReportSend',
+ cause: err,
+ });
+ return {
+ ok: false,
+ reason: 'send-failed',
+ fallback: { mailtoUrl: buildBugReportMailto(hostFacts) },
+ };
+ }
+ // The compose UI promises automatic secret redaction. The note inside the
+ // zip is scrubbed by the bundle collector; these are the two copies that
+ // travel OUTSIDE the zip (upload metadata JSON, mailto body), so they get
+ // the same scrub. Only the note — the zipPath line must stay verbatim so
+ // the user can find the file to attach.
+ const scrubbedNote =
+ request.metadata.note === undefined ? undefined : redactContent(request.metadata.note).redacted;
+ const metadata: OkBugReportSendMetadata = {
+ level: request.metadata.level,
+ systemWide: request.metadata.systemWide,
+ projectSlug: request.metadata.projectSlug,
+ ...(scrubbedNote !== undefined ? { note: scrubbedNote } : {}),
+ };
+ const fallback = {
+ mailtoUrl: buildBugReportMailto({
+ ...hostFacts,
+ metadata,
+ zipPath: request.zipPath,
+ }),
+ };
+ if (!deps.intakeBaseUrl) {
+ // The designed default, not an error: no intake endpoint means the email
+ // draft is the transport and no network request was ever attempted. The
+ // distinct reason lets the dialog render an email flow, never a failure
+ // screen. Still logged for observability of which path sends take.
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:bug-report:dispatch',
+ reason: 'intake-unconfigured',
+ handler: 'handleBugReportSend',
+ });
+ return { ok: false, reason: 'email-draft', fallback };
+ }
+ const wireMetadata: BugReportWireMetadata = { ...metadata, ...hostFacts };
+ const outcome = await uploadBugReport(
+ deps.intakeBaseUrl,
+ canonicalZipPath,
+ wireMetadata,
+ deps.timeouts,
+ );
+ if (outcome.ok) return { ok: true, reference: outcome.reference };
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:bug-report:dispatch',
+ reason: outcome.reason,
+ handler: 'handleBugReportSend',
+ cause: outcome.cause,
+ });
+ return { ok: false, reason: 'send-failed', fallback };
+}
+
+export interface BugReportCrashAckDeps {
+ /** Crash-detection persistence — records the id so the event never re-prompts. */
+ ackCrashEvent(eventId: string): void;
+}
+
+function isCrashAckRequest(request: unknown): request is OkBugReportCrashAckRequest {
+ if (typeof request !== 'object' || request === null) return false;
+ const r = request as Record<string, unknown>;
+ return r.kind === 'crash-ack' && typeof r.eventId === 'string' && r.eventId !== '';
+}
+
+/**
+ * Acknowledge a crash-detected invitation for the `crash-ack` operation.
+ * Malformed renderer input must never touch the acknowledgment store — the
+ * validator gates the only mutation.
+ */
+export function handleBugReportCrashAck(
+ deps: BugReportCrashAckDeps,
+ request: OkBugReportCrashAckRequest,
+): OkBugReportCrashAckResult {
+ if (!isCrashAckRequest(request)) {
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:bug-report:dispatch',
+ reason: 'invalid-request',
+ handler: 'handleBugReportCrashAck',
+ });
+ return { ok: false, error: 'invalid-request' };
+ }
+ deps.ackCrashEvent(request.eventId);
+ return { ok: true };
+}
diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.ts
index 0468f6caa..77017200b 100644
--- a/packages/desktop/src/main/menu.ts
+++ b/packages/desktop/src/main/menu.ts
@@ -13,7 +13,7 @@
* - Project menu (Save Version, Version History, Reveal .ok/, Trust Project)
* - File → Clone from GitHub…
* - View → Graph / Timeline / Backlinks / Outline toggles
- * - Help menu (Documentation, Report Issue, Check for updates)
+ * - Help → Documentation
*
* The menu is rebuilt on recent-projects changes so the Recent project submenu
* stays current without us reaching into Electron's menu-item mutation API
@@ -97,6 +97,14 @@ export interface MenuDeps {
* mounted there — same precedent as `openInstallSkillDialog`.
*/
openSettings?(): void;
+ /**
+ * Help → Report a Bug… click handler — fires the `report-bug` menu action
+ * to the focused renderer, which opens the in-app report dialog (editor
+ * windows and the Navigator both subscribe). Optional for the same reason
+ * as `openInstallSkillDialog` — unit tests build the menu without wiring
+ * it; the item itself always renders.
+ */
+ onReportBug?(): void;
/**
* "Check for updates…" click handler — fires an out-of-cadence
* `autoUpdater.checkForUpdates()` via the `ok:update:check-now` IPC.
@@ -766,6 +774,10 @@ export function buildMenuTemplate(deps: MenuDeps): MenuItemConstructorOptions[]
label: 'OpenKnowledge on GitHub',
click: () => deps.openExternalUrl('https://github.com/inkeep/open-knowledge'),
},
+ {
+ label: 'Report a Bug…',
+ click: () => deps.onReportBug?.(),
+ },
// Cross-platform "Check for updates…" — Windows/Linux convention
// is to place this in Help, since those platforms have no
// application menu. macOS users get the Apple-HIG-canonical
diff --git a/packages/desktop/src/main/path-containment.test.ts b/packages/desktop/src/main/path-containment.test.ts
new file mode 100644
index 000000000..c9433d886
--- /dev/null
+++ b/packages/desktop/src/main/path-containment.test.ts
@@ -0,0 +1,152 @@
+/**
+ * Containment-primitive tests. The module is platform-parameterized (explicit
+ * `path/posix` / `path/win32`) precisely so the Windows semantics — drive
+ * roots, UNC shares, `\\?\` / `\\.\` device namespaces — can be exercised on
+ * the POSIX runners that build and test the desktop app today. Nothing in
+ * production executes the win32 branches yet (desktop is macOS-only), so this
+ * suite is their only coverage.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import { isPathWithinDir } from '@inkeep/open-knowledge-server';
+import { isPathWithinProject, validateSpawnPath } from './path-containment.ts';
+
+describe('validateSpawnPath — posix', () => {
+ test('accepts absolute paths and rejects relative, empty, and NUL-carrying input', () => {
+ expect(validateSpawnPath('/proj/file.zip', 'darwin')).toBe(true);
+ expect(validateSpawnPath('proj/file.zip', 'darwin')).toBe(false);
+ expect(validateSpawnPath('./file.zip', 'linux')).toBe(false);
+ expect(validateSpawnPath('', 'darwin')).toBe(false);
+ expect(validateSpawnPath('/proj/fi\0le.zip', 'darwin')).toBe(false);
+ });
+});
+
+describe('validateSpawnPath — win32', () => {
+ test('accepts drive-letter (either separator) and UNC forms', () => {
+ expect(validateSpawnPath('C:\\proj\\file.zip', 'win32')).toBe(true);
+ expect(validateSpawnPath('C:/proj/file.zip', 'win32')).toBe(true);
+ expect(validateSpawnPath('\\\\server\\share\\file.zip', 'win32')).toBe(true);
+ });
+
+ test('rejects relative, posix-absolute, empty, and NUL-carrying input', () => {
+ expect(validateSpawnPath('proj\\file.zip', 'win32')).toBe(false);
+ expect(validateSpawnPath('/proj/file.zip', 'win32')).toBe(false);
+ expect(validateSpawnPath('', 'win32')).toBe(false);
+ expect(validateSpawnPath('C:\\proj\\fi\0le.zip', 'win32')).toBe(false);
+ });
+});
+
+describe('isPathWithinProject — posix', () => {
+ test('admits the root itself and nested children', () => {
+ expect(isPathWithinProject('/proj', '/proj', 'darwin')).toBe(true);
+ expect(isPathWithinProject('/proj/file.zip', '/proj', 'darwin')).toBe(true);
+ expect(isPathWithinProject('/proj/a/b/file.zip', '/proj', 'darwin')).toBe(true);
+ });
+
+ test('rejects dot-dot escapes, even when lexically prefixed by the root', () => {
+ expect(isPathWithinProject('/proj/../etc/passwd', '/proj', 'darwin')).toBe(false);
+ expect(isPathWithinProject('/proj/a/../../etc', '/proj', 'linux')).toBe(false);
+ });
+
+ test('rejects the sibling-prefix collision', () => {
+ expect(isPathWithinProject('/proj-evil/file.zip', '/proj', 'darwin')).toBe(false);
+ });
+
+ test('rejects relative input on either side', () => {
+ expect(isPathWithinProject('file.zip', '/proj', 'darwin')).toBe(false);
+ expect(isPathWithinProject('/proj/file.zip', 'proj', 'darwin')).toBe(false);
+ });
+});
+
+describe('isPathWithinProject — win32', () => {
+ test('admits the root itself and nested children, with either or mixed separators', () => {
+ expect(isPathWithinProject('C:\\proj', 'C:\\proj', 'win32')).toBe(true);
+ expect(isPathWithinProject('C:\\proj\\file.zip', 'C:\\proj', 'win32')).toBe(true);
+ expect(isPathWithinProject('C:/proj/sub/file.zip', 'C:\\proj', 'win32')).toBe(true);
+ });
+
+ test('drive roots compare case-insensitively', () => {
+ expect(isPathWithinProject('c:\\proj\\file.zip', 'C:\\proj', 'win32')).toBe(true);
+ });
+
+ test('rejects dot-dot escapes and the sibling-prefix collision', () => {
+ expect(isPathWithinProject('C:\\proj\\..\\windows\\evil.zip', 'C:\\proj', 'win32')).toBe(false);
+ expect(isPathWithinProject('C:\\proj-evil\\file.zip', 'C:\\proj', 'win32')).toBe(false);
+ });
+
+ test('rejects a drive-letter mismatch', () => {
+ // Without the canonical-root check, `path.win32.relative` returns the
+ // absolute "to" path for cross-drive inputs and the `..`-shape probes
+ // never fire — this is the case the root comparison exists for.
+ expect(isPathWithinProject('D:\\proj\\file.zip', 'C:\\proj', 'win32')).toBe(false);
+ });
+
+ test('admits within a UNC share and rejects share or server mismatches', () => {
+ expect(
+ isPathWithinProject('\\\\server\\share\\dir\\file.zip', '\\\\server\\share\\dir', 'win32'),
+ ).toBe(true);
+ expect(
+ isPathWithinProject('\\\\server\\share2\\file.zip', '\\\\server\\share\\dir', 'win32'),
+ ).toBe(false);
+ expect(
+ isPathWithinProject('\\\\server2\\share\\file.zip', '\\\\server\\share\\dir', 'win32'),
+ ).toBe(false);
+ });
+
+ test('rejects a UNC path against a drive-letter root', () => {
+ expect(isPathWithinProject('\\\\server\\share\\file.zip', 'C:\\proj', 'win32')).toBe(false);
+ });
+
+ test('rejects device-namespace paths against a drive-letter root', () => {
+ // `\\?\C:\proj\...` names the same file as `C:\proj\...` but carries a
+ // distinct canonical root (`\\?\C:\`), so it must not read as contained.
+ expect(isPathWithinProject('\\\\?\\C:\\proj\\file.zip', 'C:\\proj', 'win32')).toBe(false);
+ expect(isPathWithinProject('\\\\.\\pipe\\ok-pipe', 'C:\\proj', 'win32')).toBe(false);
+ });
+});
+
+describe('isPathWithinProject — parity with the server isPathWithinDir', () => {
+ // The two functions implement one security contract from independent copies
+ // (see the module header's consolidation note). This matrix pins them to
+ // identical verdicts so a fix or hardening applied to only one of them
+ // fails here instead of drifting silently. Lexical, symlink-free vectors
+ // only — neither implementation resolves symlinks.
+ const PARITY_VECTORS: Array<[userPath: string, root: string, platform: NodeJS.Platform]> = [
+ // POSIX: root itself, nested children, dot-dot escapes, sibling prefix.
+ ['/proj', '/proj', 'darwin'],
+ ['/proj/file.zip', '/proj', 'darwin'],
+ ['/proj/a/b/file.zip', '/proj', 'linux'],
+ ['/proj/../etc/passwd', '/proj', 'darwin'],
+ ['/proj/a/../../etc', '/proj', 'linux'],
+ ['/proj-evil/file.zip', '/proj', 'darwin'],
+ // Malformed inputs: relative on either side, empty, NUL byte.
+ ['file.zip', '/proj', 'darwin'],
+ ['/proj/file.zip', 'proj', 'darwin'],
+ ['', '/proj', 'darwin'],
+ ['/proj/fi\0le.zip', '/proj', 'darwin'],
+ // Windows: drive letters (either separator, case-insensitive roots),
+ // dot-dot escapes, cross-drive, UNC shares, device namespaces.
+ ['C:\\proj', 'C:\\proj', 'win32'],
+ ['C:\\proj\\file.zip', 'C:\\proj', 'win32'],
+ ['C:/proj/sub/file.zip', 'C:\\proj', 'win32'],
+ ['c:\\proj\\file.zip', 'C:\\proj', 'win32'],
+ ['C:\\proj\\..\\windows\\evil.zip', 'C:\\proj', 'win32'],
+ ['C:\\proj-evil\\file.zip', 'C:\\proj', 'win32'],
+ ['D:\\proj\\file.zip', 'C:\\proj', 'win32'],
+ ['\\\\server\\share\\dir\\file.zip', '\\\\server\\share\\dir', 'win32'],
+ ['\\\\server\\share2\\file.zip', '\\\\server\\share\\dir', 'win32'],
+ ['\\\\server2\\share\\file.zip', '\\\\server\\share\\dir', 'win32'],
+ ['\\\\server\\share\\file.zip', 'C:\\proj', 'win32'],
+ ['\\\\?\\C:\\proj\\file.zip', 'C:\\proj', 'win32'],
+ ['\\\\.\\pipe\\ok-pipe', 'C:\\proj', 'win32'],
+ ['/proj/file.zip', 'C:\\proj', 'win32'],
+ ];
+
+ for (const [userPath, root, platform] of PARITY_VECTORS) {
+ test(`${platform}: ${JSON.stringify(userPath)} vs ${JSON.stringify(root)}`, () => {
+ expect(isPathWithinProject(userPath, root, platform)).toBe(
+ isPathWithinDir(userPath, root, platform),
+ );
+ });
+ }
+});
diff --git a/packages/desktop/src/main/path-containment.ts b/packages/desktop/src/main/path-containment.ts
new file mode 100644
index 000000000..7d28e3e18
--- /dev/null
+++ b/packages/desktop/src/main/path-containment.ts
@@ -0,0 +1,97 @@
+/**
+ * Renderer-path containment primitives shared by every IPC handler that acts
+ * on a renderer-supplied filesystem path (`spawnCursor`, `showItemInFolder`,
+ * `trashItem`, asset opens, bug-report send). Lives in its own leaf module —
+ * importing only `node:path` — so validation-only consumers don't drag in the
+ * rest of the handler surface (and its `@inkeep/open-knowledge-server`
+ * dependency, which several sibling test suites replace via `mock.module`).
+ */
+
+import { posix as pathPosix, win32 as pathWin32 } from 'node:path';
+
+/** Reject non-absolute paths, null bytes, and empties. Shared with tests. */
+export function validateSpawnPath(path: string, platform: NodeJS.Platform): boolean {
+ if (!path || typeof path !== 'string') return false;
+ if (path.includes('\0')) return false;
+ if (platform === 'win32') {
+ // Match `C:\…`, `C:/…`, or UNC `\\server\share\…`.
+ return /^([a-zA-Z]:[\\/]|\\\\)/.test(path);
+ }
+ // POSIX (darwin / linux) — absolute paths start with `/`.
+ return path.startsWith('/');
+}
+
+/**
+ * Resolve both paths canonically and verify `path` lies at or under
+ * `projectPath`. Returns false on invalid inputs or boundary escape.
+ *
+ * Uses `path/posix` or `path/win32` explicitly instead of the host default so
+ * Windows inputs resolve correctly on a POSIX dev runner under test, and
+ * production behavior follows the caller's platform regardless of Node's
+ * runtime `path` module.
+ *
+ * On Windows, also rejects when the two paths don't share a canonical root
+ * (drive letter or `\\server\share` for UNC, `\\?\…` / `\\.\…` for device
+ * namespaces). Without that check, `path.win32.relative()` returns the
+ * absolute "to" path when roots differ — and the rel-shape probes below
+ * miss the UNC / device-prefix forms because they don't begin with a drive
+ * letter. Root comparison is case-insensitive (Windows filesystem semantics).
+ *
+ * Lexical comparison only — does not resolve symlinks. A symlink inside
+ * `projectPath` that targets a path outside (e.g. `<proj>/notes -> /etc`)
+ * passes this check; the OS will follow it at use time.
+ *
+ * **Logical sibling of `isPathWithinDir` in `@inkeep/open-knowledge-server`.**
+ * Both implement the same containment algorithm; the desktop version is
+ * retained because its test suite exercises edge cases this file uniquely
+ * cares about (Electron `showItemInFolder` UNC + device-namespace handling).
+ * If the two versions ever drift, consolidate by re-exporting one as the
+ * other — they share a security contract. A parity matrix in
+ * `path-containment.test.ts` pins the two to identical verdicts.
+ */
+export function isPathWithinProject(
+ userPath: string,
+ projectPath: string,
+ platform: NodeJS.Platform,
+): boolean {
+ if (!validateSpawnPath(userPath, platform)) return false;
+ if (!validateSpawnPath(projectPath, platform)) return false;
+ const p = platform === 'win32' ? pathWin32 : pathPosix;
+ try {
+ const canonicalUser = p.resolve(userPath);
+ const canonicalProject = p.resolve(projectPath);
+ if (platform === 'win32') {
+ const userRoot = p.parse(canonicalUser).root.toLowerCase();
+ const projectRoot = p.parse(canonicalProject).root.toLowerCase();
+ if (!userRoot || !projectRoot || userRoot !== projectRoot) return false;
+ }
+ if (canonicalUser === canonicalProject) return true;
+ const rel = p.relative(canonicalProject, canonicalUser);
+ // `relative` returns `..` / `..\foo` / `../foo` when `userPath` escapes
+ // the project root, or an absolute form when roots differ on Windows.
+ if (rel === '' || rel === '.') return true;
+ if (rel === '..' || rel.startsWith(`..${p.sep}`)) return false;
+ // Defense-in-depth — the root check above already rejects cross-root,
+ // but if a future code path introduces another way for `rel` to come
+ // back absolute (drive `D:\…`, UNC `\\server\…`, device `\\?\…`,
+ // `\\.\…`), refuse it here.
+ if (platform === 'win32' && (/^[a-zA-Z]:[\\/]/.test(rel) || rel.startsWith('\\\\'))) {
+ return false;
+ }
+ if (platform !== 'win32' && rel.startsWith('/')) return false;
+ return true;
+ } catch (err) {
+ // path.resolve / path.parse are total on inputs that pass the shape
+ // checks above — a throw here is unexpected (corrupted unicode, a
+ // Node-internals regression). Warn so an engineer debugging an
+ // unexplained containment refusal sees the root cause instead of
+ // investigating a phantom path-escape — same semantics as
+ // `isPathWithinDir` in `@inkeep/open-knowledge-server`.
+ // Deliberate `console.warn` rather than the pino desktop logger (the
+ // AGENTS.md default): this is a dependency-free leaf containment util
+ // shared with contexts that inject no logger, mirroring the logger-free
+ // server `isPathWithinDir` it must stay verdict-compatible with.
+ console.warn('[path-containment] unexpected path-resolution error:', err);
+ return false;
+ }
+}
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index cc45a1907..77f0a82d4 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -20,6 +20,12 @@
*/
import type {
+ OkBugReportCrashAckResult,
+ OkBugReportCrashDetectedEvent,
+ OkBugReportCreateResult,
+ OkBugReportSendMetadata,
+ OkBugReportSendResult,
+ ReportBundleLevel,
WorktreeCreateRequest,
WorktreeCreateResult,
WorktreeListResult,
@@ -474,6 +480,39 @@ const bridge: OkDesktopBridge = {
},
},
+ bugReport: {
+ // The `kind` discriminant is added here so the renderer surface stays
+ // per-operation while the wire stays one consolidated channel
+ // (`ok:bug-report:dispatch`), respecting the hand-rolled-channel cap.
+ // Each method knows its operation, so it casts the union result to its
+ // own arm (the worktree-dispatch precedent).
+ create: (request: { level: ReportBundleLevel; note?: string; includeCrashDump?: boolean }) =>
+ invoke('ok:bug-report:dispatch', {
+ kind: 'create',
+ level: request.level,
+ note: request.note,
+ includeCrashDump: request.includeCrashDump,
+ }) as Promise<OkBugReportCreateResult>,
+ send: (request: { zipPath: string; metadata: OkBugReportSendMetadata }) =>
+ invoke('ok:bug-report:dispatch', {
+ kind: 'send',
+ zipPath: request.zipPath,
+ metadata: request.metadata,
+ }) as Promise<OkBugReportSendResult>,
+ crashAck: (request: { eventId: string }) =>
+ invoke('ok:bug-report:dispatch', {
+ kind: 'crash-ack',
+ eventId: request.eventId,
+ }) as Promise<OkBugReportCrashAckResult>,
+ onCrashDetected(cb: (event: OkBugReportCrashDetectedEvent) => void) {
+ const listener = (_event: IpcRendererEvent, event: OkBugReportCrashDetectedEvent) =>
+ cb(event);
+ // biome-ignore lint/plugin/no-loosely-typed-webcontents-ipc: preload-side subscription wrapper (precedent #14)
+ ipcRenderer.on('ok:bug-report:crash-detected', listener);
+ return () => ipcRenderer.removeListener('ok:bug-report:crash-detected', listener);
+ },
+ },
+
fs: {
defaultProjectsRoot: () => invoke('ok:fs:default-projects-root'),
folderState: (path: string) => invoke('ok:fs:folder-state', path),
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index 6116bec2f..b04867680 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -24,7 +24,13 @@ import type {
CreateNewBannerKind,
EditorId,
LocalOpOkInitResponse,
+ OkBugReportCrashAckResult,
+ OkBugReportCrashDetectedEvent,
+ OkBugReportCreateResult,
+ OkBugReportSendMetadata,
+ OkBugReportSendResult,
OkFolderState,
+ ReportBundleLevel,
ShareTargetStatusResponse,
TerminalCli,
WorktreeCreateRequest,
@@ -221,7 +227,11 @@ export type OkMenuAction =
// Worktree selector (worktree = window). `new-worktree` opens the
// create dialog; `switch-worktree` opens the sidebar worktree switcher.
| 'new-worktree'
- | 'switch-worktree';
+ | 'switch-worktree'
+ // Help → Report a Bug… — opens the in-app bug-report dialog. Both window
+ // types subscribe: editor windows report project-scoped, the Navigator
+ // reports system-wide.
+ | 'report-bug';
/** Returned by `onProjectSwitched` / `onMenuAction`. Call to detach the listener. */
type OkUnsubscribe = () => void;
@@ -1536,6 +1546,40 @@ export interface OkDesktopBridge {
setMode(mode: 'shared' | 'local-only'): Promise<OkSharingSetModeResult>;
};
+ /**
+ * In-app "Report a bug" — `create` builds the redacted diagnostic zip for
+ * the sender window's project (system-wide when the window has no project,
+ * labeled via `summary.systemWide`) under `~/.ok/bug-reports/`, folding in
+ * the newest un-acked crash minidump only when `includeCrashDump` is set
+ * (the crash invite's explicit opt-in — minidumps carry raw memory no text
+ * redaction can scrub); `send` uploads the reviewed zip to the private
+ * intake endpoint when one is configured, otherwise resolving to the
+ * prefilled email fallback (`fallback.mailtoUrl`) — `reason` discriminates
+ * the designed no-intake email path (`'email-draft'`, no network attempted)
+ * from a real upload failure (`'send-failed'`), so the dialog only renders
+ * an error for the latter. `onCrashDetected` delivers main's crash-detected invitations
+ * (the `ok:bug-report:crash-detected` push; boot events arrive on the first
+ * renderer that finishes loading, so subscribe at module init) and
+ * `crashAck` records the user's answer so one crash event never re-prompts,
+ * restarts included. Backed by `ok:bug-report:dispatch` (one consolidated
+ * channel, discriminated on `kind`, per the `ok:sharing:dispatch`
+ * precedent). Never rejects on capture or upload failure — the results are
+ * discriminated.
+ */
+ bugReport: {
+ create(request: {
+ level: ReportBundleLevel;
+ note?: string;
+ includeCrashDump?: boolean;
+ }): Promise<OkBugReportCreateResult>;
+ send(request: {
+ zipPath: string;
+ metadata: OkBugReportSendMetadata;
+ }): Promise<OkBugReportSendResult>;
+ crashAck(request: { eventId: string }): Promise<OkBugReportCrashAckResult>;
+ onCrashDetected(cb: (event: OkBugReportCrashDetectedEvent) => void): OkUnsubscribe;
+ };
+
/**
* Filesystem probes that back the Create-new-project dialog cascade. The
* find-enclosing-* probes are read-only and mirror the pure helpers in
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index 04c6de2a8..d689b6756 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -30,7 +30,7 @@
* existing channels is preferred over net-new hand-rolled channels until
* that migration lands.
*
- * Count is 82 (ratchet cap 82). The 74→75 bump reconciled a merge collision:
+ * Count is 83 (ratchet cap 83). The 74→75 bump reconciled a merge collision:
* the worktree selector (`ok:worktree:dispatch`) and the terminal-controls PR
* (`ok:terminal:cli-installed-map`) each landed in the base tree's single free
* slot concurrently. The 75→76 bump then unioned in the desktop
@@ -44,6 +44,9 @@
* sender window's project). The 79→81 bump added terminal-tab reload-survival
* (`ok:pty:set-meta` + `ok:pty:set-order`) — two slots, following the `ok:pty:*`
* one-channel-per-operation design rather than a dispatch fold. The 81→82 bump
+ * added the in-app report-a-bug surface (`ok:bug-report:dispatch`, a
+ * discriminated fold per the sharing-dispatch precedent; later report
+ * operations widen its payload rather than adding channels). The 82→83 bump
* added the terminal clickable-links out-of-project reveal
* (`ok:shell:reveal-external`): a distinct trust boundary from `reveal-asset`
* (uncontained + dialog-gated), so it could not fold onto it. Full rationale in
@@ -56,6 +59,9 @@ import type {
CreateNewBannerKind,
EditorId,
LocalOpOkInitResponse,
+ OkBugReportCrashAckResult,
+ OkBugReportCreateResult,
+ OkBugReportSendResult,
OkFolderState,
ShareTargetStatusResponse,
TerminalCli,
@@ -69,6 +75,7 @@ import type {
PackId,
ScaffoldPlan,
} from '@inkeep/open-knowledge-server';
+import type { OkBugReportRequest } from '../main/ipc/bug-report.ts';
import type { BuildAndOpenResult } from '../main/ipc/install-skill.ts';
import type { SeedApplyResult, SeedListPacksResult, SeedPlanResult } from '../main/ipc/seed.ts';
import type { KeyringSmokeResult } from '../utility/keyring-smoke.ts';
@@ -796,6 +803,28 @@ export interface RequestChannels {
args: [request: { kind: 'status' } | { kind: 'set-mode'; mode: 'shared' | 'local-only' }];
result: OkSharingResult;
};
+ /**
+ * In-app "Report a bug" — one consolidated discriminated channel (the
+ * `ok:sharing:dispatch` precedent) so the whole report surface costs a
+ * single hand-rolled slot; report operations widen this payload instead of
+ * adding channels.
+ * - `{kind: 'create', level, note?, includeCrashDump?}` → build the
+ * redacted diagnostic zip for the sender window's project (system-wide
+ * when the sender has no project context) under `~/.ok/bug-reports/`;
+ * the crash-dump flag is the crash invite's explicit opt-in.
+ * - `{kind: 'send', zipPath, metadata}` → upload the reviewed zip to the
+ * private intake endpoint; any failure (endpoint unconfigured included)
+ * degrades to a prefilled email fallback.
+ * - `{kind: 'crash-ack', eventId}` → persist that the user answered a
+ * `ok:bug-report:crash-detected` invitation so that crash event never
+ * re-prompts, across restarts included.
+ * Never throws — every failure mode is discriminated so the dialog can
+ * render it; each preload method casts the union result to its own arm.
+ */
+ 'ok:bug-report:dispatch': {
+ args: [request: OkBugReportRequest];
+ result: OkBugReportCreateResult | OkBugReportSendResult | OkBugReportCrashAckResult;
+ };
/** Read the LRU-capped recent-projects list from app state. */
'ok:project:list-recent': { args: []; result: RecentProject[] };
/** Remove one project from the persisted recent-projects list. Does not delete files. */
diff --git a/packages/desktop/src/shared/ipc-events.ts b/packages/desktop/src/shared/ipc-events.ts
index bf0f21764..fa35abb15 100644
--- a/packages/desktop/src/shared/ipc-events.ts
+++ b/packages/desktop/src/shared/ipc-events.ts
@@ -14,6 +14,7 @@
* wrapper files by a lint rule.
*/
+import type { OkBugReportCrashDetectedEvent } from '@inkeep/open-knowledge-core';
import type {
OkDesktopConfig,
OkLocalOpAuthEvent,
@@ -291,4 +292,15 @@ export interface EventChannels {
* xterm's `screenReaderMode` in place.
*/
'ok:accessibility:changed': { payload: { screenReaderActive: boolean } };
+ /**
+ * Main → one renderer inviting a bug report for a detected crash: a
+ * renderer/child process death mid-session, or a boot-time dirty-shutdown /
+ * fresh-minidump detection. Fired at most once per crash event, to a single
+ * live window; boot-time events wait for the first renderer-ready signal
+ * instead of racing window load. Invitation only — nothing is captured or
+ * sent until the user acts. The renderer answers over
+ * `ok:bug-report:dispatch` (`kind: 'crash-ack'`); an acked event id never
+ * fires again, across restarts included.
+ */
+ 'ok:bug-report:crash-detected': { payload: OkBugReportCrashDetectedEvent };
}
diff --git a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
index f3f44c605..7d968e8ea 100644
--- a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
+++ b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
@@ -312,7 +312,27 @@ const CHANNELS_SRC = readFileSync(SRC_PATH, 'utf-8');
* single channel over two distinct operations against a namespace that
* deliberately keeps each PTY operation on its own channel.
*
- * Bumped from 81 to 82 for the terminal clickable-links out-of-project reveal
+ * Bumped from 81 to 82 for the in-app "Report a bug" surface:
+ *
+ * - `ok:bug-report:dispatch` — builds the redacted diagnostic zip for the
+ * sender window's project (system-wide when the window has no project)
+ * via the CLI package's leveled `collectReportBundle`, in-process. Main
+ * owns it because the inputs are main-process state: the window-manager
+ * project context, `app.getVersion()`/`app.isPackaged`/the update
+ * channel (stamped as `OK_DESKTOP_*` metadata), and the `~/.ok/bug-reports/`
+ * write. A single discriminated channel per the `ok:sharing:dispatch`
+ * precedent: the report surface's upload (`send`) and crash-ack
+ * operations widen this channel's payload — the preferred
+ * payload-widening path — instead of adding channels, so the whole
+ * surface costs one slot. Could not fold into any existing channel: no
+ * diagnostics/reporting surface exists — `ok:shell:*` is scoped to
+ * asset reveal/open, `ok:update:*` to the updater lifecycle, and the
+ * `ok:project:*` reads carry unrelated schemas. New `ok:bug-report:*`
+ * namespace, single member. The typed-ipc migration remains the
+ * committed end state; scoped exception with the `ipc-channels.ts`
+ * header commitment updated in lock-step.
+ *
+ * Bumped from 82 to 83 for the terminal clickable-links out-of-project reveal
* (`ok:shell:reveal-external`): when a terminal link points at an existing file
* OUTSIDE the window's project, main pops a "reveal in Finder?" confirmation and
* reveals on confirm. It is a distinct trust boundary from `ok:shell:reveal-asset`
@@ -321,7 +341,7 @@ const CHANNELS_SRC = readFileSync(SRC_PATH, 'utf-8');
* opposite security contracts. Single member; the typed-ipc migration remains the
* committed end state, with the `ipc-channels.ts` header updated in lock-step.
*/
-const REQUEST_CHANNEL_CAP = 82;
+const REQUEST_CHANNEL_CAP = 83;
/**
* Extract the body of an interface block by name. Returns the substring
diff --git a/packages/desktop/tests/integration/m1-smoke.test.ts b/packages/desktop/tests/integration/m1-smoke.test.ts
index 9f4eef9fa..2b69baf28 100644
--- a/packages/desktop/tests/integration/m1-smoke.test.ts
+++ b/packages/desktop/tests/integration/m1-smoke.test.ts
@@ -599,10 +599,10 @@ describe('M1 smoke', () => {
expect(coreMembers.size).toBeGreaterThan(0);
expect(appMembers.size).toBeGreaterThan(0);
// 26 + 2 worktree actions (`new-worktree`, `switch-worktree`) for the
- // worktree selector (worktree = window) + 3 sidebar visibility toggles
- // (`toggle-show-ok-folders`, `toggle-show-only-markdown-files`,
- // `toggle-show-skills-section`).
- expect(desktopMembers.size).toBe(31);
+ // worktree selector (worktree = window) + `report-bug` (Help menu) + 3
+ // sidebar visibility toggles (`toggle-show-ok-folders`,
+ // `toggle-show-only-markdown-files`, `toggle-show-skills-section`).
+ expect(desktopMembers.size).toBe(32);
expect(desktopMembers).toEqual(coreMembers);
expect(desktopMembers).toEqual(appMembers);
// Pin the visibility toggles explicitly: a bare count check wouldn't
@@ -613,6 +613,7 @@ describe('M1 smoke', () => {
expect(desktopMembers.has('toggle-show-skills-section')).toBe(true);
expect(desktopMembers.has('new-worktree')).toBe(true);
expect(desktopMembers.has('switch-worktree')).toBe(true);
+ expect(desktopMembers.has('report-bug')).toBe(true);
});
test('M1 invariant: EntryPoint / OkProjectEntryPoint literal-union drift catcher', async () => {
diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.ts
index 7e0e7b5d4..acaf75841 100644
--- a/packages/desktop/tests/main/menu.test.ts
+++ b/packages/desktop/tests/main/menu.test.ts
@@ -383,6 +383,29 @@ describe('buildMenuTemplate', () => {
});
});
+ describe('Report a Bug… menu item', () => {
+ test('always renders in the Help menu, even without the dep wired', () => {
+ // Unlike Check for updates… (capability-gated on the updater handle),
+ // the report flow is always available — the item renders with default
+ // deps and clicking it is a safe no-op.
+ const template = buildMenuTemplate(makeDeps());
+ const helpMenu = template.find((t) => t.label === 'Help');
+ const sub = helpMenu?.submenu as MenuItemConstructorOptions[] | undefined;
+ if (!sub) throw new Error('Help submenu missing');
+ expect(sub.find((i) => i.label === 'Report a Bug…')).toBeDefined();
+ });
+
+ test('click dispatches deps.onReportBug()', () => {
+ const onReportBug = mock(() => {});
+ const deps = makeDeps({ onReportBug });
+ const template = buildMenuTemplate(deps);
+ const item = findByLabel(template, 'Report a Bug…');
+ if (!item || typeof item.click !== 'function') throw new Error('Report a Bug… click missing');
+ (item.click as () => void)();
+ expect(onReportBug).toHaveBeenCalledTimes(1);
+ });
+ });
+
describe('Uninstall OpenKnowledge… menu item', () => {
test('omitted entirely when onUninstall dep is undefined', () => {
const template = buildMenuTemplate(makeDeps());
diff --git a/packages/desktop/tests/smoke/report-bug.e2e.ts b/packages/desktop/tests/smoke/report-bug.e2e.ts
new file mode 100644
index 000000000..7f9d06105
--- /dev/null
+++ b/packages/desktop/tests/smoke/report-bug.e2e.ts
@@ -0,0 +1,171 @@
+/**
+ * Report-a-bug entry-point smoke — drives the real Electron build through
+ * both entry points (Help menu, ⌘K command palette) into the shared
+ * ReportBugDialog, then through compose → create → review against the real
+ * main-process bundling pipeline.
+ *
+ * This is the live-wire complement to the bun tiers, which mock at the
+ * `window.okDesktop` bridge seam on the renderer side and at injected deps
+ * on the main side. Here the whole chain is real: native menu click handler
+ * → `ok:menu-action` push → preload bridge → dialog mount, and the dialog's
+ * `bugReport.create` invoke → dispatch handler → `collectReportBundle` →
+ * zip on disk under the test-isolated `~/.ok/bug-reports/`.
+ *
+ * The Help-menu drive calls `MenuItem.click()` programmatically via
+ * `app.evaluate` — Playwright cannot click native macOS menu chrome. The
+ * programmatic click fires the exact handler wired in `menu.ts`, so
+ * everything from the click handler down is the production path; only the
+ * OS-level mouse event on the native menu bar is simulated.
+ *
+ * Send and Reveal stay unexercised here by design: Send needs the intake
+ * endpoint (ships separately; absent here), and Reveal opens a real Finder
+ * window on the host running the suite.
+ *
+ * Skip gates mirror consent-dialog.e2e.ts — opt-in via OK_DESKTOP_E2E_SMOKE=1,
+ * darwin-only, and build-must-exist.
+ */
+
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ realpathSync,
+ statSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import type { Page } from '@playwright/test';
+import { _electron as electron } from '@playwright/test';
+import { expect, test } from './_helpers/smoke-test';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const MAIN_ENTRY = resolve(__dirname, '..', '..', 'out', 'main', 'index.js');
+
+const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';
+const DARWIN = process.platform === 'darwin';
+const BUILD_EXISTS = existsSync(MAIN_ENTRY);
+
+test.describe('Report-a-bug entry points', () => {
+ test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');
+ test.skip(!DARWIN, 'Smoke harness is darwin-only.');
+ test.skip(
+ !BUILD_EXISTS,
+ `Main build missing at ${MAIN_ENTRY} — run "bun run build:desktop" first.`,
+ );
+
+ test('Help menu and palette open the dialog; create lands a zip shown in review', async ({
+ captureStderrFor,
+ }) => {
+ // Isolated HOME: the create handler writes to `~/.ok/bug-reports/` via a
+ // call-time homedir() lookup, so launching with HOME pointed at a tmpdir
+ // keeps the real `~/.ok` untouched. Realpath per the consent-dialog
+ // precedent (macOS tmpdir() is a symlink into /private/var/folders).
+ const tmpHome = realpathSync(mkdtempSync(join(tmpdir(), 'ok-report-bug-home-')));
+ const projectDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-report-bug-project-')));
+ mkdirSync(join(projectDir, '.ok'), { recursive: true });
+ writeFileSync(join(projectDir, '.ok', 'config.yml'), "content:\n dir: '.'\n");
+ writeFileSync(join(projectDir, 'start.md'), '# Start\n\nSeed document.\n');
+
+ // Already-consented project restored via lastOpenedProject → the app
+ // boots straight into an editor window (no Navigator/consent detour).
+ const userDataDir = join(tmpHome, 'electron-userdata');
+ mkdirSync(userDataDir, { recursive: true });
+ writeFileSync(
+ join(userDataDir, 'state.json'),
+ JSON.stringify({
+ recentProjects: [
+ { path: projectDir, name: 'Report Bug Smoke', lastOpenedAt: new Date().toISOString() },
+ ],
+ lastOpenedProject: projectDir,
+ versionPendingInstall: null,
+ lastSeenVersion: null,
+ lastSuccessfulCheckAt: null,
+ stuckHintShown: false,
+ }),
+ );
+
+ const app = await electron.launch({
+ args: [MAIN_ENTRY, `--user-data-dir=${userDataDir}`],
+ timeout: 30_000,
+ env: {
+ ...process.env,
+ HOME: tmpHome,
+ OK_DESKTOP_E2E_SMOKE: '1',
+ },
+ });
+ captureStderrFor(app, { cleanupDirs: [tmpHome, projectDir] });
+
+ let editorPage: Page | undefined;
+ await expect(async () => {
+ for (const page of app.windows()) {
+ const mode = await page
+ .evaluate(() => window.okDesktop?.config?.mode)
+ .catch(() => undefined);
+ if (mode === 'editor') {
+ editorPage = page;
+ return;
+ }
+ }
+ throw new Error('editor window not ready yet');
+ }).toPass({ timeout: 30_000 });
+ if (!editorPage) throw new Error('editor window vanished after readiness poll');
+ const page = editorPage;
+
+ // App-mounted gate: menu actions delivered before the renderer attaches
+ // its onMenuAction subscription are dropped, so wait for stable App UI
+ // (the sidebar toolbar) before driving the menu.
+ await expect(page.getByRole('button', { name: 'New file' })).toBeVisible({ timeout: 30_000 });
+
+ // Entry point 1 — Help menu. Label lookup walks every top-level submenu
+ // rather than assuming the Help menu's resolved label/role shape.
+ await app.evaluate(({ Menu }) => {
+ const appMenu = Menu.getApplicationMenu();
+ for (const top of appMenu?.items ?? []) {
+ const item = top.submenu?.items.find((candidate) => candidate.label === 'Report a Bug…');
+ if (item) {
+ item.click();
+ return;
+ }
+ }
+ throw new Error('Report a Bug… menu item not found in any submenu');
+ });
+ const composeDialog = page.getByRole('dialog', { name: 'Report a bug' });
+ await expect(composeDialog).toBeVisible({ timeout: 10_000 });
+ await page.keyboard.press('Escape');
+ await expect(composeDialog).not.toBeVisible();
+
+ // Entry point 2 — ⌘K palette → "Report a bug" command.
+ await page.keyboard.press('Meta+k');
+ const paletteRow = page.getByTestId('command-palette-report-bug');
+ await expect(paletteRow).toBeVisible({ timeout: 10_000 });
+ await paletteRow.click();
+ await expect(composeDialog).toBeVisible({ timeout: 10_000 });
+
+ // Compose → create. The note rides into the bundle; typing it here
+ // exercises the same field the crash variants relabel.
+ await composeDialog
+ .getByRole('textbox', { name: /What happened/ })
+ .fill('Report-a-bug smoke note');
+ await composeDialog.getByRole('button', { name: 'Create report' }).click();
+
+ // Review: the dialog title flips per phase, and the card shows the
+ // exact produced zip. Bundle creation runs the real capture pipeline,
+ // so give it the generous end of the poll budget.
+ const reviewDialog = page.getByRole('dialog', { name: 'Review your report' });
+ await expect(reviewDialog).toBeVisible({ timeout: 30_000 });
+ await expect(reviewDialog.getByText(/secrets redacted/)).toBeVisible();
+ await expect(reviewDialog.getByRole('button', { name: 'Send report' })).toBeVisible();
+
+ // The zip landed in the isolated home and the review card names it.
+ const reportsDir = join(tmpHome, '.ok', 'bug-reports');
+ const zips = readdirSync(reportsDir).filter((name) => name.endsWith('.zip'));
+ expect(zips).toHaveLength(1);
+ const zipName = zips[0];
+ expect(zipName).toMatch(/-bugreport\.zip$/);
+ expect(statSync(join(reportsDir, zipName)).size).toBeGreaterThan(0);
+ await expect(reviewDialog.getByTitle(zipName)).toBeVisible();
+ });
+});
diff --git a/packages/server/src/spawn-cursor-api.ts b/packages/server/src/spawn-cursor-api.ts
index da8d4f039..df163e810 100644
--- a/packages/server/src/spawn-cursor-api.ts
+++ b/packages/server/src/spawn-cursor-api.ts
@@ -394,7 +394,7 @@ export function resolveCursorSpawnInvocation(
* platform. Lexical comparison only (no symlink resolution); a symlink inside
* `contentDir` that targets outside (`<dir>/notes -> /etc`) passes here, and
* the OS will follow it at use time. Same constraint as
- * `isPathWithinProject` in `packages/desktop/src/main/ipc-handlers.ts`.
+ * `isPathWithinProject` in `packages/desktop/src/main/path-containment.ts`.
*/
export function isPathWithinDir(
userPath: string,