Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): bug report retry list (#2674)

Andrew Mikofalvyfeaa3fd622a4
diff --git a/.changeset/bug-report-retry-list.md b/.changeset/bug-report-retry-list.md
new file mode 100644
index 000000000..0a2a6f2c8
--- /dev/null
+++ b/.changeset/bug-report-retry-list.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Report a bug now keeps a history of your reports so a send that fails (or a dialog you closed) no longer means starting over. Each report you generate is saved with its last-known state, and you can find it again from a new "Bug report history" command in the palette or from a "Previous reports" section in the Report a bug dialog. From the list you can retry sending an existing report without regenerating it, reveal its file in Finder, or delete it. Retry re-sends the exact bundle you already made, so a report that failed the first time can reach the team on the next try, and the history survives closing the dialog and restarting the app.
+
+Reports are also cleaned up automatically. Once a report is confirmed sent, its (potentially large) zip is reclaimed from disk while a lightweight record of the send is kept, and unsent reports are bounded so old bundles do not pile up. The most recent report you have not sent is never removed. Everything stays on your Mac, redaction is unchanged, and reports are only ever sent when you choose to send them.
diff --git a/packages/app/src/components/BugReportHistory.dom.test.tsx b/packages/app/src/components/BugReportHistory.dom.test.tsx
new file mode 100644
index 000000000..60da290e5
--- /dev/null
+++ b/packages/app/src/components/BugReportHistory.dom.test.tsx
@@ -0,0 +1,291 @@
+/**
+ * BugReportHistoryList DOM tests: the persisted report list renders rows with
+ * state badges, an empty state with the Report-a-bug CTA, a degraded unknown
+ * row, and the Retry / Reveal / Delete actions dispatching the right bridge
+ * calls (Retry reconstructs the send metadata from the row).
+ *
+ * Substrate: jsdom via `pnpm run test:dom`.
+ */
+import type { OkBugReportListRow, OkBugReportSendResult } from '@inkeep/open-knowledge-core';
+import * as actualLinguiMacro from '@lingui/react/macro';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+// Superset factory: spreading the real module keeps every export the component
+// tree may reach for, so a sibling suite mocking the same specifier in the same
+// worker can't be left with a hole.
+vi.doMock('@lingui/react/macro', () => ({
+ ...actualLinguiMacro,
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: renderLinguiTemplate,
+ i18n: { date: (value: Date) => value.toISOString() },
+ }),
+}));
+
+// Radix (Collapsible in the sibling disclosure) reaches for DOM globals the
+// jsdom preload does not expose on globalThis. Same hoist as the dialog test.
+type WindowGlobals = { NodeFilter?: typeof NodeFilter };
+type GlobalWithDomShims = typeof globalThis &
+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };
+const globalWithDomShims = globalThis as GlobalWithDomShims;
+if (globalWithDomShims.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ globalWithDomShims.ResizeObserver = NoopResizeObserver;
+}
+
+// Imported after the macro mock so the component binds to the shim.
+const { BugReportHistoryList, BugReportPreviousReports } = await import('./BugReportHistory');
+
+interface BridgeLog {
+ listCalls: number;
+ sendCalls: { zipPath: string; metadata: unknown }[];
+ deleteCalls: string[];
+ revealed: string[];
+ opened: string[];
+}
+
+function installBridge(handlers: {
+ reports: OkBugReportListRow[] | (() => OkBugReportListRow[]);
+ send?: () => Promise<OkBugReportSendResult>;
+}): BridgeLog {
+ const log: BridgeLog = {
+ listCalls: 0,
+ sendCalls: [],
+ deleteCalls: [],
+ revealed: [],
+ opened: [],
+ };
+ const bridge = {
+ bugReport: {
+ list: () => {
+ log.listCalls += 1;
+ const reports =
+ typeof handlers.reports === 'function' ? handlers.reports() : handlers.reports;
+ return Promise.resolve({ ok: true as const, reports });
+ },
+ send: (request: { zipPath: string; metadata: unknown }) => {
+ log.sendCalls.push(request);
+ return handlers.send
+ ? handlers.send()
+ : Promise.resolve({ ok: true as const, reference: 'OK-9' });
+ },
+ delete: (id: string) => {
+ log.deleteCalls.push(id);
+ return Promise.resolve({ ok: true as const });
+ },
+ },
+ shell: {
+ showItemInFolder: (path: string) => {
+ log.revealed.push(path);
+ return Promise.resolve();
+ },
+ openExternal: (url: string) => {
+ log.opened.push(url);
+ return 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 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 makeRow(overrides: Partial<OkBugReportListRow> & { id: string }): OkBugReportListRow {
+ return {
+ createdAt: '2026-07-15T18:30:00.000Z',
+ bundleLevel: 'standard',
+ state: 'generated',
+ zipBytes: 4096,
+ zipDeleted: false,
+ zipExists: true,
+ systemWide: false,
+ projectSlug: 'demo',
+ attemptsCount: 0,
+ zipPath: `/Users/tester/.ok/bug-reports/${overrides.id}`,
+ retryable: true,
+ degraded: false,
+ ...overrides,
+ };
+}
+
+afterEach(() => {
+ cleanup();
+ clearBridge();
+});
+
+describe('BugReportHistoryList', () => {
+ test('renders each report with its state badge, reference, and failure reason', async () => {
+ installBridge({
+ reports: [
+ makeRow({
+ id: 'a-bugreport.zip',
+ state: 'sent',
+ reference: 'OK-42',
+ zipDeleted: true,
+ zipExists: false,
+ retryable: false,
+ }),
+ makeRow({
+ id: 'b-bugreport.zip',
+ state: 'upload-failed',
+ lastError: { reason: 'complete-rejected: 503', at: 'x' },
+ }),
+ ],
+ });
+
+ render(<BugReportHistoryList />);
+
+ expect(await screen.findByText('Sent')).toBeDefined();
+ expect(screen.getByText('OK-42')).toBeDefined();
+ expect(screen.getByText('Failed')).toBeDefined();
+ expect(screen.getByText('complete-rejected: 503')).toBeDefined();
+ });
+
+ test('shows the empty state with a Report-a-bug CTA that fires the callback', async () => {
+ installBridge({ reports: [] });
+ let cta = 0;
+
+ render(<BugReportHistoryList onReportABug={() => (cta += 1)} />);
+
+ expect(await screen.findByText('No bug reports yet.')).toBeDefined();
+ await userEvent.click(screen.getByRole('button', { name: 'Report a bug' }));
+ expect(cta).toBe(1);
+ });
+
+ test('a degraded row renders as Unknown without breaking the list', async () => {
+ installBridge({
+ reports: [
+ makeRow({
+ id: 'c-bugreport.zip',
+ state: 'unknown',
+ degraded: true,
+ bundleLevel: 'unknown',
+ }),
+ ],
+ });
+
+ render(<BugReportHistoryList />);
+ expect(await screen.findByText('Unknown')).toBeDefined();
+ });
+
+ test('Retry resends the existing bundle with reconstructed send metadata', async () => {
+ const log = installBridge({
+ reports: [
+ makeRow({
+ id: 'd-bugreport.zip',
+ state: 'upload-failed',
+ bundleLevel: 'full',
+ systemWide: true,
+ projectSlug: null,
+ lastError: { reason: 'offline', at: 'x' },
+ }),
+ ],
+ });
+
+ render(<BugReportHistoryList />);
+ await userEvent.click(await screen.findByRole('button', { name: 'Retry' }));
+
+ expect(log.sendCalls).toHaveLength(1);
+ expect(log.sendCalls[0]).toEqual({
+ zipPath: '/Users/tester/.ok/bug-reports/d-bugreport.zip',
+ metadata: { level: 'full', systemWide: true, projectSlug: null },
+ });
+ });
+
+ test('a retry that resolves to the email-draft path opens the prefilled draft', async () => {
+ const log = installBridge({
+ reports: [makeRow({ id: 'e-bugreport.zip', state: 'upload-failed' })],
+ send: async () => ({
+ ok: false as const,
+ reason: 'email-draft' as const,
+ fallback: { mailtoUrl: 'mailto:[email protected]?subject=x' },
+ }),
+ });
+
+ render(<BugReportHistoryList />);
+ await userEvent.click(await screen.findByRole('button', { name: 'Retry' }));
+
+ expect(log.opened).toEqual(['mailto:[email protected]?subject=x']);
+ });
+
+ test('Reveal opens the zip location and Delete removes by id', async () => {
+ const log = installBridge({
+ reports: [makeRow({ id: 'f-bugreport.zip', state: 'generated' })],
+ });
+
+ render(<BugReportHistoryList />);
+ await userEvent.click(await screen.findByLabelText('Reveal in Finder'));
+ expect(log.revealed).toEqual(['/Users/tester/.ok/bug-reports/f-bugreport.zip']);
+
+ await userEvent.click(screen.getByLabelText('Delete report'));
+ expect(log.deleteCalls).toEqual(['f-bugreport.zip']);
+ });
+
+ test('renders an error state when the bridge is absent', async () => {
+ clearBridge();
+ render(<BugReportHistoryList />);
+ expect(await screen.findByText("Couldn't load your bug reports.")).toBeDefined();
+ });
+});
+
+describe('BugReportPreviousReports', () => {
+ test('renders nothing when there is no history to disclose', async () => {
+ const log = installBridge({ reports: [] });
+
+ const { container } = render(<BugReportPreviousReports />);
+ await waitFor(() => {
+ expect(log.listCalls).toBeGreaterThan(0);
+ });
+
+ // An empty history must not put an empty disclosure in the compose step.
+ expect(container.textContent).toBe('');
+ });
+
+ test('discloses the count collapsed, and the rows once expanded', async () => {
+ installBridge({
+ reports: [
+ makeRow({ id: 'a-bugreport.zip', state: 'upload-failed' }),
+ makeRow({ id: 'b-bugreport.zip', state: 'generated' }),
+ ],
+ });
+
+ render(<BugReportPreviousReports />);
+ const trigger = await screen.findByRole('button', { name: /Previous reports/ });
+ expect(trigger.textContent).toContain('(2)');
+ // Collapsed: the trigger is the only affordance, no report actions yet.
+ expect(screen.queryByLabelText('Reveal in Finder')).toBeNull();
+
+ await userEvent.click(trigger);
+
+ expect(await screen.findAllByLabelText('Reveal in Finder')).toHaveLength(2);
+ });
+
+ test('renders nothing when the bridge is absent', async () => {
+ clearBridge();
+ const { container } = render(<BugReportPreviousReports />);
+ // Unlike the standalone list, the compose-step disclosure stays silent on a
+ // load failure rather than showing an error inside the report form.
+ await waitFor(() => {
+ expect(container.textContent).toBe('');
+ });
+ });
+});
diff --git a/packages/app/src/components/BugReportHistory.tsx b/packages/app/src/components/BugReportHistory.tsx
new file mode 100644
index 000000000..518e40b6e
--- /dev/null
+++ b/packages/app/src/components/BugReportHistory.tsx
@@ -0,0 +1,337 @@
+/**
+ * Bug-report history — the persisted list of previously generated reports and
+ * their last-known state, backed by `window.okDesktop.bugReport.list()`.
+ *
+ * Two surfaces share the same list + actions:
+ * - `BugReportHistoryList` — the standalone body (command-palette entry). Shows
+ * a loading / error / empty (with a "Report a bug" CTA) / rows state.
+ * - `BugReportPreviousReports` — the collapsible "Previous reports" disclosure
+ * inside the Report Bug dialog's compose step; renders nothing until there
+ * is at least one prior report, so it never clutters the compose flow.
+ *
+ * State is shown as an inline status badge (modeless — no nested dialogs), and
+ * per-row actions are Retry (resend the existing bundle without regenerating),
+ * Reveal (open the zip in Finder), and Delete. The surface is deliberately
+ * lightweight (a transient posture), not a management console. Desktop-only —
+ * the callers gate on `window.okDesktop`.
+ */
+
+import type { OkBugReportListRow } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { ChevronDownIcon, FolderOpenIcon, Loader2, RotateCwIcon, Trash2Icon } from 'lucide-react';
+import { useEffect, useState } from 'react';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
+
+type PendingAction = 'retrying' | 'deleting';
+type HistoryStatus = 'loading' | 'ready' | 'error';
+
+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`;
+}
+
+/**
+ * Fetch the report history on mount and expose the per-row actions. Retry
+ * resends the persisted bundle via the existing `send` path (reconstructing the
+ * send metadata from the row); on the no-intake email-draft path it opens the
+ * prefilled draft. Every action reloads the list afterward so the row's badge
+ * reflects the new on-disk state.
+ */
+function useReportHistory() {
+ const [status, setStatus] = useState<HistoryStatus>('loading');
+ const [reports, setReports] = useState<OkBugReportListRow[]>([]);
+ const [pending, setPending] = useState<Record<string, PendingAction>>({});
+
+ async function load() {
+ const bugReport = window.okDesktop?.bugReport;
+ if (!bugReport) {
+ setStatus('error');
+ return;
+ }
+ try {
+ const result = await bugReport.list();
+ if (result.ok) {
+ setReports(result.reports);
+ setStatus('ready');
+ } else {
+ setStatus('error');
+ }
+ } catch {
+ setStatus('error');
+ }
+ }
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: load the history once on mount; the action handlers reload imperatively
+ useEffect(() => {
+ void load();
+ }, []);
+
+ function clearPending(id: string) {
+ setPending((prev) => {
+ if (!(id in prev)) return prev;
+ const next = { ...prev };
+ delete next[id];
+ return next;
+ });
+ }
+
+ async function retry(row: OkBugReportListRow) {
+ const bugReport = window.okDesktop?.bugReport;
+ if (!bugReport || !row.retryable) return;
+ setPending((prev) => ({ ...prev, [row.id]: 'retrying' }));
+ // `send` is contract-safe (never rejects); the `.catch` is belt-and-suspenders
+ // so a transport-layer IPC failure still clears the spinner and reloads.
+ const result = await bugReport
+ .send({
+ zipPath: row.zipPath,
+ metadata: {
+ level: row.bundleLevel === 'unknown' ? 'standard' : row.bundleLevel,
+ systemWide: row.systemWide,
+ projectSlug: row.projectSlug,
+ },
+ })
+ .catch(() => null);
+ // The designed no-intake path: nothing uploaded, so hand the user the
+ // prefilled email draft (the same behavior the dialog's Send has).
+ if (result && !result.ok && result.reason === 'email-draft') {
+ void window.okDesktop?.shell.openExternal(result.fallback.mailtoUrl);
+ }
+ await load();
+ clearPending(row.id);
+ }
+
+ async function remove(row: OkBugReportListRow) {
+ const bugReport = window.okDesktop?.bugReport;
+ if (!bugReport) return;
+ setPending((prev) => ({ ...prev, [row.id]: 'deleting' }));
+ await bugReport.delete(row.id).catch(() => undefined);
+ await load();
+ clearPending(row.id);
+ }
+
+ function reveal(row: OkBugReportListRow) {
+ void window.okDesktop?.shell.showItemInFolder(row.zipPath);
+ }
+
+ return { status, reports, pending, retry, remove, reveal };
+}
+
+function StateBadge({ state }: { state: OkBugReportListRow['state'] }) {
+ switch (state) {
+ case 'sent':
+ return (
+ <Badge variant="primary">
+ <Trans>Sent</Trans>
+ </Badge>
+ );
+ case 'upload-failed':
+ return (
+ <Badge variant="destructive">
+ <Trans>Failed</Trans>
+ </Badge>
+ );
+ case 'uploading':
+ return (
+ <Badge variant="warning">
+ <Trans>Sending</Trans>
+ </Badge>
+ );
+ case 'email-drafted':
+ return (
+ <Badge variant="secondary">
+ <Trans>Emailed</Trans>
+ </Badge>
+ );
+ case 'generated':
+ return (
+ <Badge variant="gray">
+ <Trans>Not sent</Trans>
+ </Badge>
+ );
+ default:
+ return (
+ <Badge variant="outline">
+ <Trans>Unknown</Trans>
+ </Badge>
+ );
+ }
+}
+
+function ReportRow({
+ row,
+ pending,
+ onRetry,
+ onReveal,
+ onDelete,
+}: {
+ row: OkBugReportListRow;
+ pending: PendingAction | undefined;
+ onRetry: (row: OkBugReportListRow) => void;
+ onReveal: (row: OkBugReportListRow) => void;
+ onDelete: (row: OkBugReportListRow) => void;
+}) {
+ const { t } = useLingui();
+ const busy = pending !== undefined;
+ const when =
+ row.createdAt === ''
+ ? t`Unknown date`
+ : new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(
+ new Date(row.createdAt),
+ );
+ return (
+ <div className="flex items-start gap-2.5 rounded-md border px-3 py-2.5">
+ <div className="min-w-0 flex-1 space-y-1">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <StateBadge state={row.state} />
+ {row.bundleLevel !== 'unknown' ? <Badge variant="gray">{row.bundleLevel}</Badge> : null}
+ <span className="truncate text-1sm text-muted-foreground">{when}</span>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {row.state === 'sent' && row.reference !== undefined ? (
+ <Trans>
+ Reference <span className="font-mono text-foreground">{row.reference}</span>
+ </Trans>
+ ) : row.state === 'upload-failed' && row.lastError !== undefined ? (
+ <span className="text-destructive">{row.lastError.reason}</span>
+ ) : (
+ <span>{formatSize(row.zipBytes)}</span>
+ )}
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ {row.retryable ? (
+ <Button variant="outline" size="xs" disabled={busy} onClick={() => onRetry(row)}>
+ {pending === 'retrying' ? (
+ <Loader2 className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ ) : (
+ <RotateCwIcon aria-hidden="true" />
+ )}
+ <Trans>Retry</Trans>
+ </Button>
+ ) : null}
+ {row.zipExists ? (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ disabled={busy}
+ aria-label={t`Reveal in Finder`}
+ onClick={() => onReveal(row)}
+ >
+ <FolderOpenIcon aria-hidden="true" />
+ </Button>
+ ) : null}
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ disabled={busy}
+ aria-label={t`Delete report`}
+ onClick={() => onDelete(row)}
+ >
+ {pending === 'deleting' ? (
+ <Loader2 className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ ) : (
+ <Trash2Icon aria-hidden="true" />
+ )}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function ReportRows({
+ reports,
+ pending,
+ retry,
+ remove,
+ reveal,
+}: ReturnType<typeof useReportHistory>) {
+ return (
+ <div className="flex flex-col gap-2">
+ {reports.map((row) => (
+ <ReportRow
+ key={row.id}
+ row={row}
+ pending={pending[row.id]}
+ onRetry={retry}
+ onReveal={reveal}
+ onDelete={remove}
+ />
+ ))}
+ </div>
+ );
+}
+
+/**
+ * Standalone history body — loading / error / empty (with a "Report a bug" CTA
+ * for someone who opened the history meaning to file a report) / the report
+ * rows. Used by the command-palette "Bug report history" entry.
+ */
+export function BugReportHistoryList({ onReportABug }: { onReportABug?: () => void }) {
+ const history = useReportHistory();
+
+ if (history.status === 'loading') {
+ return (
+ <div role="status" className="flex items-center gap-2.5 py-6 text-sm text-muted-foreground">
+ <Loader2 className="size-4 animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ <Trans>Loading your reports</Trans>
+ </div>
+ );
+ }
+ if (history.status === 'error') {
+ return (
+ <p className="py-6 text-sm text-muted-foreground">
+ <Trans>Couldn't load your bug reports.</Trans>
+ </p>
+ );
+ }
+ if (history.reports.length === 0) {
+ return (
+ <div className="flex flex-col items-center gap-3 py-6 text-center">
+ <p className="text-sm text-muted-foreground">
+ <Trans>No bug reports yet.</Trans>
+ </p>
+ {onReportABug ? (
+ <Button onClick={onReportABug}>
+ <Trans>Report a bug</Trans>
+ </Button>
+ ) : null}
+ </div>
+ );
+ }
+ return <ReportRows {...history} />;
+}
+
+/**
+ * The "Previous reports" disclosure for the Report Bug dialog's compose step.
+ * Renders nothing until at least one prior report exists, so the compose flow
+ * stays clean when there is no history to show.
+ */
+export function BugReportPreviousReports() {
+ const [open, setOpen] = useState(false);
+ const history = useReportHistory();
+
+ if (history.status !== 'ready' || history.reports.length === 0) return null;
+
+ return (
+ <Collapsible open={open} onOpenChange={setOpen}>
+ <CollapsibleTrigger asChild>
+ <Button variant="ghost" size="sm" className="h-auto w-full justify-between px-0 py-1">
+ <span className="text-sm font-medium">
+ <Trans>Previous reports</Trans>{' '}
+ <span className="font-normal text-muted-foreground">({history.reports.length})</span>
+ </span>
+ <ChevronDownIcon
+ className={`transition-transform motion-reduce:transition-none ${open ? 'rotate-180' : ''}`}
+ aria-hidden="true"
+ />
+ </Button>
+ </CollapsibleTrigger>
+ <CollapsibleContent className="pt-2">
+ <ReportRows {...history} />
+ </CollapsibleContent>
+ </Collapsible>
+ );
+}
diff --git a/packages/app/src/components/BugReportHistoryDialog.tsx b/packages/app/src/components/BugReportHistoryDialog.tsx
new file mode 100644
index 000000000..cba8ee913
--- /dev/null
+++ b/packages/app/src/components/BugReportHistoryDialog.tsx
@@ -0,0 +1,50 @@
+/**
+ * Bug report history dialog — the command-palette (⌘K) entry point to the
+ * persisted report list. A thin transient surface over `BugReportHistoryList`;
+ * the list is rendered only while open so each open re-reads the sidecars. The
+ * empty-state CTA hands off to the compose "Report a bug" dialog via
+ * `onReportABug`. Desktop-only — the mount site gates on the bridge.
+ */
+
+import { Trans } from '@lingui/react/macro';
+import { BugReportHistoryList } from '@/components/BugReportHistory';
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+
+interface BugReportHistoryDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ /** Opens the compose "Report a bug" dialog from the empty-state CTA. */
+ onReportABug: () => void;
+}
+
+function BugReportHistoryDialog({ open, onOpenChange, onReportABug }: BugReportHistoryDialogProps) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>Bug report history</Trans>
+ </DialogTitle>
+ <DialogDescription>
+ <Trans>
+ Reports you've generated on this Mac. Retry a send, reveal a file, or delete one you
+ no longer need.
+ </Trans>
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="max-h-[60vh] overflow-y-auto">
+ {open ? <BugReportHistoryList onReportABug={onReportABug} /> : null}
+ </DialogBody>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+export default BugReportHistoryDialog;
diff --git a/packages/app/src/components/CommandPalette.tsx b/packages/app/src/components/CommandPalette.tsx
index 62441519e..830d0313c 100644
--- a/packages/app/src/components/CommandPalette.tsx
+++ b/packages/app/src/components/CommandPalette.tsx
@@ -13,8 +13,10 @@ import { Plural, Trans, useLingui } from '@lingui/react/macro';
import { Check, FileText, Folder, GitBranch, Hash, Loader2, Sparkles } from 'lucide-react';
import {
type Dispatch,
+ lazy,
type KeyboardEvent as ReactKeyboardEvent,
type SetStateAction,
+ Suspense,
useDeferredValue,
useEffect,
useRef,
@@ -93,6 +95,10 @@ import { useInstalledAgents } from './handoff/useInstalledAgents';
import { basenameOf } from './project-switcher-recents';
import { RecentItemContextMenu, RecentRemoveButton } from './recent-remove-controls';
+// Lazy so the report-history list + its bridge wiring stay out of the main
+// chunk until the user opens the ⌘K "Bug report history" entry (desktop-only).
+const BugReportHistoryDialog = lazy(() => import('@/components/BugReportHistoryDialog'));
+
const COMMAND_PALETTE_SEARCH_TIMEOUT_MS = 3000;
// Re-poll cadence while the server reports the search index is still warming
// (`ready:false`). Short, since a warming response returns immediately (the
@@ -342,6 +348,10 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
const [seedDialogOpen, setSeedDialogOpen] = useState(false);
const [createProjectOpen, setCreateProjectOpen] = useState(false);
const [reportBugOpen, setReportBugOpen] = useState(false);
+ const [reportBugHistoryOpen, setReportBugHistoryOpen] = useState(false);
+ // Defer mounting the (lazy) history dialog until it is first opened, so its
+ // chunk + the `bugReport.list()` fetch don't run on every palette open.
+ const [historyEverOpened, setHistoryEverOpened] = useState(false);
const [feedbackOpen, setFeedbackOpen] = 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-
@@ -887,6 +897,10 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
openSeedDialog: () => setSeedDialogOpen(true),
openCreateProjectDialog: () => setCreateProjectOpen(true),
openReportBugDialog: () => setReportBugOpen(true),
+ openBugReportHistory: () => {
+ setHistoryEverOpened(true);
+ setReportBugHistoryOpen(true);
+ },
openFeedbackDialog: () => setFeedbackOpen(true),
};
const visibleFixedCommands = inExclusiveMode
@@ -1611,6 +1625,21 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
{/* Desktop-only — the registry gates the launching "Report a bug" command
on `bridge !== null`, so the dialog only mounts when the bridge exists. */}
{bridge ? <ReportBugDialog open={reportBugOpen} onOpenChange={setReportBugOpen} /> : null}
+ {/* Desktop-only — the registry gates the launching "Bug report history"
+ command on the same bridge presence. Lazy + deferred until first
+ opened. The empty-state CTA hands off to the compose dialog. */}
+ {bridge && historyEverOpened ? (
+ <Suspense fallback={null}>
+ <BugReportHistoryDialog
+ open={reportBugHistoryOpen}
+ onOpenChange={setReportBugHistoryOpen}
+ onReportABug={() => {
+ setReportBugHistoryOpen(false);
+ setReportBugOpen(true);
+ }}
+ />
+ </Suspense>
+ ) : null}
{/* Host-agnostic — the feedback form POSTs to the hosted intake route, so
the "Send feedback" command (and this dialog) exist on web too. */}
<FeedbackFormDialog
diff --git a/packages/app/src/components/ReportBugDialogBody.tsx b/packages/app/src/components/ReportBugDialogBody.tsx
index 9847bce01..53172e21b 100644
--- a/packages/app/src/components/ReportBugDialogBody.tsx
+++ b/packages/app/src/components/ReportBugDialogBody.tsx
@@ -34,6 +34,7 @@ import {
TriangleAlertIcon,
} from 'lucide-react';
import { useEffect, useId, useRef, useState } from 'react';
+import { BugReportPreviousReports } from '@/components/BugReportHistory';
import { CopyButton } from '@/components/CopyButton';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
@@ -596,6 +597,13 @@ function ReportBugDialog({
</div>
)}
</div>
+ {/* A lightweight disclosure of prior reports so a user can resend
+ one they already made without regenerating. Only in the plain
+ flow — the crash variants stay focused on the report at hand,
+ and it renders nothing until there is history to show. */}
+ {crashInvite === undefined && crashContext === undefined ? (
+ <BugReportPreviousReports />
+ ) : null}
</DialogBody>
<DialogFooter>
<Button
diff --git a/packages/app/src/components/command-palette-commands.ts b/packages/app/src/components/command-palette-commands.ts
index 157b8dc01..2070f24cf 100644
--- a/packages/app/src/components/command-palette-commands.ts
+++ b/packages/app/src/components/command-palette-commands.ts
@@ -21,6 +21,7 @@ import {
FolderPlus,
FoldVertical,
GitBranch,
+ History,
LayoutGrid,
MessageSquare,
Network,
@@ -118,6 +119,8 @@ export interface PaletteCommandContext {
openSeedDialog(): void;
openCreateProjectDialog(): void;
openReportBugDialog(): void;
+ /** Close the palette and open the persisted report history / retry list. */
+ openBugReportHistory(): void;
openFeedbackDialog(): void;
}
@@ -173,6 +176,7 @@ const PALETTE_COMMAND_LABELS = {
settings: msg`Settings`,
installClaudeDesktop: msg`Install for Claude Chat & Cowork (Desktop App)`,
reportBug: msg`Report a bug`,
+ bugReportHistory: msg`Bug report history`,
sendFeedback: msg`Send feedback`,
newFromTemplate: msg`New from template`,
rename: msg`Rename`,
@@ -223,6 +227,7 @@ const COMMAND_ICONS: Record<string, ComponentType<{ className?: string }>> = {
settings: Settings,
'install-claude-desktop': Download,
'report-bug': Bug,
+ 'bug-report-history': History,
'send-feedback': MessageSquare,
'new-from-template': FilePlus2,
rename: Pencil,
@@ -313,6 +318,10 @@ const COMMAND_DISPATCH: Record<string, (ctx: PaletteCommandContext) => void> = {
ctx.closePalette();
ctx.openReportBugDialog();
},
+ 'bug-report-history': (ctx) => {
+ ctx.closePalette();
+ ctx.openBugReportHistory();
+ },
'send-feedback': (ctx) => {
ctx.closePalette();
ctx.openFeedbackDialog();
diff --git a/packages/app/src/lib/command-menu-parity.test.ts b/packages/app/src/lib/command-menu-parity.test.ts
index 6f5177c73..3dd406823 100644
--- a/packages/app/src/lib/command-menu-parity.test.ts
+++ b/packages/app/src/lib/command-menu-parity.test.ts
@@ -456,6 +456,7 @@ describe('command identity registry (Phase 2b)', () => {
'settings',
'install-claude-desktop',
'report-bug',
+ 'bug-report-history',
'send-feedback',
'check-for-updates',
'set-up-integrations',
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index 55e28bae6..78b83690e 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -25,6 +25,8 @@ import type {
OkBugReportCrashAckResult,
OkBugReportCrashDetectedEvent,
OkBugReportCreateResult,
+ OkBugReportDeleteResult,
+ OkBugReportListResult,
OkBugReportScreenshot,
OkBugReportSendMetadata,
OkBugReportSendResult,
@@ -1271,6 +1273,8 @@ export interface OkDesktopBridge {
metadata: OkBugReportSendMetadata;
}): Promise<OkBugReportSendResult>;
crashAck(request: { eventId: string }): Promise<OkBugReportCrashAckResult>;
+ list(): Promise<OkBugReportListResult>;
+ delete(id: string): Promise<OkBugReportDeleteResult>;
onCrashDetected(cb: (event: OkBugReportCrashDetectedEvent) => void): OkUnsubscribe;
};
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 5f85c8598..f604d3c0b 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -140,6 +140,7 @@
"2AIVbm": ["Review your report"],
"2B6eYX": ["What this checkbox changes"],
"2BBAbc": ["List"],
+ "2C-6zf": ["Not sent"],
"2CHoQv": ["Force Reload"],
"2FYpfJ": ["More"],
"2FnYUD": [
@@ -411,6 +412,7 @@
"78G7R3": [
"Validate document frontmatter against JSON Schema files, scoped to doc sets by glob."
],
+ "7Bj3x9": ["Failed"],
"7FamGZ": ["Go to line"],
"7Fkcej": ["+ Add ", ["addChildName"]],
"7H4UHD": ["Documents tagged <0>#", ["tagName"], "</0>"],
@@ -876,6 +878,7 @@
],
"FXk_zY": ["Adds a guided workflow for authoring new Agent Skills."],
"FZtBeR": ["Enable ", ["0"]],
+ "FgQ7XZ": ["Couldn't load your bug reports."],
"FgRAvd": ["Logs & system info"],
"FjkaiT": ["Zoom out"],
"FqGWeR": ["Couldn't reach the agent registry."],
@@ -1409,6 +1412,7 @@
"</0> already has a worktree — it'll open in its own window."
],
"QDZbvN": [["diffDays"], "d ago"],
+ "QHCx0c": ["Bug report history"],
"QLgdT6": ["any doc named ", ["0"]],
"QM3SBZ": ["Plan (", ["done"], "/", ["0"], ")"],
"QOINDn": ["empty"],
@@ -1507,6 +1511,7 @@
"SCzAbA": [["phase"], " — ", ["pct"], "%"],
"SF9qpO": ["Share your email for followups"],
"SFN6dN": ["Heading 3"],
+ "SInSnF": ["Reference <0>", ["0"], "</0>"],
"SItQRc": ["How do you like OpenKnowledge?"],
"SOPwPh": ["Restore to this edit"],
"SQWJ-i": ["Restore sessions"],
@@ -1666,6 +1671,7 @@
"VdXv4D": ["Clone from GitHub"],
"Vftef5": ["Common markdown issues — hard tabs, heading increments, list markers, and more."],
"Vlc75q": ["Keep file deleted"],
+ "VmJT51": ["Loading your reports"],
"VsaI0G": [["folderCount", "plural", { "one": ["folder"], "other": ["folders"] }]],
"VuxVSP": ["Start source completion"],
"VvS_k_": ["Config sharing is now local-only."],
@@ -2011,6 +2017,7 @@
],
"bwil08": ["Building <0>openknowledge.skill</0> and opening the Claude Desktop App"],
"c1LZZH": ["Link copied."],
+ "c2ktXL": ["Previous reports"],
"c3XJ18": ["Help"],
"c3ZGrq": ["the doc ", ["0"]],
"c4fVUV": ["Fix"],
@@ -2036,6 +2043,7 @@
"cOJyVj": ["Disable Themes"],
"cOSAfL": ["No repositories found on your GitHub account."],
"cOrTMo": ["Your share link is ready below."],
+ "cPAWbl": ["Emailed"],
"cRHuuI": ["Couldn't copy path"],
"cRm498": ["No schema files in this project yet — create one to start validating."],
"cSCbv3": ["BETA"],
@@ -2286,6 +2294,7 @@
["shareBranch"],
" already exists. Open its worktree from the switcher instead."
],
+ "h69WC6": ["Sent"],
"h7FzJC": ["Link-graph response did not match expected shape."],
"h9QFb9": ["Skill \"", ["0"], "\" deleted"],
"hBMK4W": ["Project templates"],
@@ -2637,6 +2646,9 @@
". Any local edits will be replaced — your current version is saved to history first, so you can restore it."
],
"nDT8qt": ["Initialized ", ["0"], " but could not open it."],
+ "nGAFeH": [
+ "Reports you've generated on this Mac. Retry a send, reveal a file, or delete one you no longer need."
+ ],
"nJq7et": ["Couldn't uninstall skill: ", ["0"]],
"nMSYz5": [
"This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
@@ -2849,6 +2861,7 @@
"rQAQus": ["Couldn't save template: ", ["error"]],
"rQRrkB": ["yesterday"],
"rSoi6g": [["displayName"], " (", ["bin"], ") isn't installed or on your PATH."],
+ "rUWrSE": ["Delete report"],
"rVJpLz": [
"On — hovering an external link sends its URL to the destination site to fetch a preview."
],
@@ -3077,6 +3090,7 @@
"w7SsvI": ["That folder isn't an OpenKnowledge project yet. Initialize it and open?"],
"w7nm4K": ["Indented blockquote for citations."],
"wDgmsr": ["\"", ["0"], "\" install refreshed (", ["1"], ")"],
+ "wF2wqQ": ["Unknown date"],
"wGSHzy": ["Activate one of the first eight editor tabs."],
"wJijgU": ["Location"],
"wJo9oS": ["Close find"],
@@ -3094,6 +3108,7 @@
"w_Sphq": ["Attachments"],
"waFx9W": ["Managed"],
"wbv9xO": ["Create new project"],
+ "wcfO9r": ["No bug reports yet."],
"wdxz7K": ["Source"],
"weP6me": ["Couldn't load docs — type @ again to retry"],
"wgNoIs": ["Select all"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index dbcc5f187..be18415a2 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -1511,6 +1511,11 @@ msgstr "Browse your repos:"
msgid "Bug report {0}"
msgstr "Bug report {0}"
+#: src/components/BugReportHistoryDialog.tsx
+#: src/components/command-palette-commands.ts
+msgid "Bug report history"
+msgstr "Bug report history"
+
#: src/components/ReportBugDialogBody.tsx
msgid "Bug reporting needs the OpenKnowledge desktop app."
msgstr "Bug reporting needs the OpenKnowledge desktop app."
@@ -2562,6 +2567,10 @@ msgstr "Couldn't load templates"
msgid "Couldn't load this skill's files."
msgstr "Couldn't load this skill's files."
+#: src/components/BugReportHistory.tsx
+msgid "Couldn't load your bug reports."
+msgstr "Couldn't load your bug reports."
+
#. placeholder {0}: result.error
#: src/components/ManagedArtifactProperties.tsx
msgid "Couldn't move skill: {0}"
@@ -3001,6 +3010,10 @@ msgstr "Delete code block"
msgid "Delete Permanently"
msgstr "Delete Permanently"
+#: src/components/BugReportHistory.tsx
+msgid "Delete report"
+msgstr "Delete report"
+
#: src/components/settings/LintingSection.tsx
msgid "Delete schema file {file}"
msgstr "Delete schema file {file}"
@@ -3518,6 +3531,10 @@ msgstr "Email"
msgid "Email address"
msgstr "Email address"
+#: src/components/BugReportHistory.tsx
+msgid "Emailed"
+msgstr "Emailed"
+
#: src/editor/slash-command/component-items.tsx
msgid "Embed a video with native player controls."
msgstr "Embed a video with native player controls."
@@ -3766,6 +3783,10 @@ msgstr "External wiki link"
msgid "failed"
msgstr "failed"
+#: src/components/BugReportHistory.tsx
+msgid "Failed"
+msgstr "Failed"
+
#: src/components/ArrayOfObjectsWidget.tsx
msgid "Failed to add item"
msgstr "Failed to add item"
@@ -5357,6 +5378,10 @@ msgstr "Loading the conversation"
msgid "Loading timeline history"
msgstr "Loading timeline history"
+#: src/components/BugReportHistory.tsx
+msgid "Loading your reports"
+msgstr "Loading your reports"
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Loading..."
msgstr "Loading..."
@@ -5920,6 +5945,10 @@ msgstr "No AI agents installed"
msgid "No API key is set for this endpoint. Add one above."
msgstr "No API key is set for this endpoint. Add one above."
+#: src/components/BugReportHistory.tsx
+msgid "No bug reports yet."
+msgstr "No bug reports yet."
+
#: src/components/ActivityPanelDiffView.tsx
msgid "No changes"
msgstr "No changes"
@@ -6238,6 +6267,10 @@ msgstr "Not now"
msgid "Not required for a localhost endpoint like <0>{endpointHost}</0> — most local servers ignore it. Add one only if yours needs it."
msgstr "Not required for a localhost endpoint like <0>{endpointHost}</0> — most local servers ignore it. Add one only if yours needs it."
+#: src/components/BugReportHistory.tsx
+msgid "Not sent"
+msgstr "Not sent"
+
#. placeholder {0}: summary.pattern
#: src/components/settings/LintingSection.tsx
msgid "nothing ({0} cannot match a doc)"
@@ -7041,6 +7074,10 @@ msgstr "Previous change"
msgid "Previous match"
msgstr "Previous match"
+#: src/components/BugReportHistory.tsx
+msgid "Previous reports"
+msgstr "Previous reports"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Previous tab"
msgstr "Previous tab"
@@ -7321,6 +7358,11 @@ msgstr "Reconnecting…"
msgid "Redo"
msgstr "Redo"
+#. placeholder {0}: row.reference
+#: src/components/BugReportHistory.tsx
+msgid "Reference <0>{0}</0>"
+msgstr "Reference <0>{0}</0>"
+
#: src/components/ProblemsPanel.tsx
msgid "Refresh audit"
msgstr "Refresh audit"
@@ -7583,6 +7625,7 @@ msgstr "Replace key"
msgid "Replace the active match from the replace field."
msgstr "Replace the active match from the replace field."
+#: src/components/BugReportHistory.tsx
#: src/components/command-palette-commands.ts
#: src/components/HelpPopover.tsx
#: src/components/ReportBugDialogBody.tsx
@@ -7602,6 +7645,10 @@ msgstr "Report reference"
msgid "Report this error"
msgstr "Report this error"
+#: src/components/BugReportHistoryDialog.tsx
+msgid "Reports you've generated on this Mac. Retry a send, reveal a file, or delete one you no longer need."
+msgstr "Reports you've generated on this Mac. Retry a send, reveal a file, or delete one you no longer need."
+
#: 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."
@@ -7783,6 +7830,7 @@ msgid "Resuming the conversation"
msgstr "Resuming the conversation"
#: src/components/ActivityModeContent.tsx
+#: src/components/BugReportHistory.tsx
#: src/components/ConnectingBanner.tsx
#: src/components/PublishToGitHubDialog.tsx
#: src/components/settings/ConfigureAgentsSection.tsx
@@ -7810,6 +7858,7 @@ msgstr "Reveal in File Explorer"
msgid "Reveal in File Explorer, {hint}"
msgstr "Reveal in File Explorer, {hint}"
+#: src/components/BugReportHistory.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
@@ -8180,6 +8229,7 @@ msgstr "Send report"
msgid "Send your report by email"
msgstr "Send your report by email"
+#: src/components/BugReportHistory.tsx
#: src/components/FeedbackForm.tsx
msgid "Sending"
msgstr "Sending"
@@ -8188,6 +8238,10 @@ msgstr "Sending"
msgid "Sending report"
msgstr "Sending report"
+#: src/components/BugReportHistory.tsx
+msgid "Sent"
+msgstr "Sent"
+
#: 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."
@@ -9880,6 +9934,7 @@ msgstr "Uninstall OpenKnowledge?"
msgid "Uninstalled \"{0}\" from {1}"
msgstr "Uninstalled \"{0}\" from {1}"
+#: src/components/BugReportHistory.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Unknown"
msgstr "Unknown"
@@ -9892,6 +9947,10 @@ msgstr "Unknown component: {componentName} — source editable below"
msgid "Unknown component: {unregisteredComponentName}"
msgstr "Unknown component: {unregisteredComponentName}"
+#: src/components/BugReportHistory.tsx
+msgid "Unknown date"
+msgstr "Unknown date"
+
#: src/components/DocumentErrorBoundary.tsx
#: src/lib/transports/auth-transport.ts
msgid "Unknown error"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index dc933c14e..e7a754506 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -140,6 +140,7 @@
"2AIVbm": ["Ŕēvĩēŵ ŷōũŕ ŕēƥōŕţ"],
"2B6eYX": ["Ŵĥàţ ţĥĩś ćĥēćķƀōx ćĥàńĝēś"],
"2BBAbc": ["Ĺĩśţ"],
+ "2C-6zf": ["Ńōţ śēńţ"],
"2CHoQv": ["Ƒōŕćē Ŕēĺōàď"],
"2FYpfJ": ["Ḿōŕē"],
"2FnYUD": [
@@ -411,6 +412,7 @@
"78G7R3": [
"Vàĺĩďàţē ďōćũḿēńţ ƒŕōńţḿàţţēŕ àĝàĩńśţ ĵŚŌŃ Śćĥēḿà ƒĩĺēś, śćōƥēď ţō ďōć śēţś ƀŷ ĝĺōƀ."
],
+ "7Bj3x9": ["Ƒàĩĺēď"],
"7FamGZ": ["Ĝō ţō ĺĩńē"],
"7Fkcej": ["+ Àďď ", ["addChildName"]],
"7H4UHD": ["Ďōćũḿēńţś ţàĝĝēď <0>#", ["tagName"], "</0>"],
@@ -876,6 +878,7 @@
],
"FXk_zY": ["Àďďś à ĝũĩďēď ŵōŕķƒĺōŵ ƒōŕ àũţĥōŕĩńĝ ńēŵ Àĝēńţ Śķĩĺĺś."],
"FZtBeR": ["Ēńàƀĺē ", ["0"]],
+ "FgQ7XZ": ["Ćōũĺďń'ţ ĺōàď ŷōũŕ ƀũĝ ŕēƥōŕţś."],
"FgRAvd": ["Ĺōĝś & śŷśţēḿ ĩńƒō"],
"FjkaiT": ["Źōōḿ ōũţ"],
"FqGWeR": ["Ćōũĺďń'ţ ŕēàćĥ ţĥē àĝēńţ ŕēĝĩśţŕŷ."],
@@ -1409,6 +1412,7 @@
"</0> àĺŕēàďŷ ĥàś à ŵōŕķţŕēē — ĩţ'ĺĺ ōƥēń ĩń ĩţś ōŵń ŵĩńďōŵ."
],
"QDZbvN": [["diffDays"], "ď àĝō"],
+ "QHCx0c": ["ßũĝ ŕēƥōŕţ ĥĩśţōŕŷ"],
"QLgdT6": ["àńŷ ďōć ńàḿēď ", ["0"]],
"QM3SBZ": ["Ƥĺàń (", ["done"], "/", ["0"], ")"],
"QOINDn": ["ēḿƥţŷ"],
@@ -1507,6 +1511,7 @@
"SCzAbA": [["phase"], " — ", ["pct"], "%"],
"SF9qpO": ["Śĥàŕē ŷōũŕ ēḿàĩĺ ƒōŕ ƒōĺĺōŵũƥś"],
"SFN6dN": ["Ĥēàďĩńĝ 3"],
+ "SInSnF": ["Ŕēƒēŕēńćē <0>", ["0"], "</0>"],
"SItQRc": ["Ĥōŵ ďō ŷōũ ĺĩķē ŌƥēńĶńōŵĺēďĝē?"],
"SOPwPh": ["Ŕēśţōŕē ţō ţĥĩś ēďĩţ"],
"SQWJ-i": ["Ŕēśţōŕē śēśśĩōńś"],
@@ -1666,6 +1671,7 @@
"VdXv4D": ["Ćĺōńē ƒŕōḿ ĜĩţĤũƀ"],
"Vftef5": ["Ćōḿḿōń ḿàŕķďōŵń ĩśśũēś — ĥàŕď ţàƀś, ĥēàďĩńĝ ĩńćŕēḿēńţś, ĺĩśţ ḿàŕķēŕś, àńď ḿōŕē."],
"Vlc75q": ["Ķēēƥ ƒĩĺē ďēĺēţēď"],
+ "VmJT51": ["Ĺōàďĩńĝ ŷōũŕ ŕēƥōŕţś"],
"VsaI0G": [["folderCount", "plural", { "one": ["ƒōĺďēŕ"], "other": ["ƒōĺďēŕś"] }]],
"VuxVSP": ["Śţàŕţ śōũŕćē ćōḿƥĺēţĩōń"],
"VvS_k_": ["Ćōńƒĩĝ śĥàŕĩńĝ ĩś ńōŵ ĺōćàĺ-ōńĺŷ."],
@@ -2011,6 +2017,7 @@
],
"bwil08": ["ßũĩĺďĩńĝ <0>ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0> àńď ōƥēńĩńĝ ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ"],
"c1LZZH": ["Ĺĩńķ ćōƥĩēď."],
+ "c2ktXL": ["Ƥŕēvĩōũś ŕēƥōŕţś"],
"c3XJ18": ["Ĥēĺƥ"],
"c3ZGrq": ["ţĥē ďōć ", ["0"]],
"c4fVUV": ["Ƒĩx"],
@@ -2036,6 +2043,7 @@
"cOJyVj": ["Ďĩśàƀĺē Ţĥēḿēś"],
"cOSAfL": ["Ńō ŕēƥōśĩţōŕĩēś ƒōũńď ōń ŷōũŕ ĜĩţĤũƀ àććōũńţ."],
"cOrTMo": ["Ŷōũŕ śĥàŕē ĺĩńķ ĩś ŕēàďŷ ƀēĺōŵ."],
+ "cPAWbl": ["Ēḿàĩĺēď"],
"cRHuuI": ["Ćōũĺďń'ţ ćōƥŷ ƥàţĥ"],
"cRm498": ["Ńō śćĥēḿà ƒĩĺēś ĩń ţĥĩś ƥŕōĴēćţ ŷēţ — ćŕēàţē ōńē ţō śţàŕţ vàĺĩďàţĩńĝ."],
"cSCbv3": ["ßĒŢÀ"],
@@ -2286,6 +2294,7 @@
["shareBranch"],
" àĺŕēàďŷ ēxĩśţś. Ōƥēń ĩţś ŵōŕķţŕēē ƒŕōḿ ţĥē śŵĩţćĥēŕ ĩńśţēàď."
],
+ "h69WC6": ["Śēńţ"],
"h7FzJC": ["Ĺĩńķ-ĝŕàƥĥ ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],
"h9QFb9": ["Śķĩĺĺ \"", ["0"], "\" ďēĺēţēď"],
"hBMK4W": ["ƤŕōĴēćţ ţēḿƥĺàţēś"],
@@ -2637,6 +2646,9 @@
". Àńŷ ĺōćàĺ ēďĩţś ŵĩĺĺ ƀē ŕēƥĺàćēď — ŷōũŕ ćũŕŕēńţ vēŕśĩōń ĩś śàvēď ţō ĥĩśţōŕŷ ƒĩŕśţ, śō ŷōũ ćàń ŕēśţōŕē ĩţ."
],
"nDT8qt": ["Ĩńĩţĩàĺĩźēď ", ["0"], " ƀũţ ćōũĺď ńōţ ōƥēń ĩţ."],
+ "nGAFeH": [
+ "Ŕēƥōŕţś ŷōũ'vē ĝēńēŕàţēď ōń ţĥĩś Ḿàć. Ŕēţŕŷ à śēńď, ŕēvēàĺ à ƒĩĺē, ōŕ ďēĺēţē ōńē ŷōũ ńō ĺōńĝēŕ ńēēď."
+ ],
"nJq7et": ["Ćōũĺďń'ţ ũńĩńśţàĺĺ śķĩĺĺ: ", ["0"]],
"nMSYz5": [
"Ţĥĩś ƥàţĥ ĩś ōń àń ēxţēŕńàĺ vōĺũḿē (/Vōĺũḿēś/...). ŌƥēńĶńōŵĺēďĝē ŵĩĺĺ ĺōśē ţŕàćķ ōƒ ƒĩĺēś ŵĥēń ţĥē ďŕĩvē ēĴēćţś."
@@ -2849,6 +2861,7 @@
"rQAQus": ["Ćōũĺďń'ţ śàvē ţēḿƥĺàţē: ", ["error"]],
"rQRrkB": ["ŷēśţēŕďàŷ"],
"rSoi6g": [["displayName"], " (", ["bin"], ") ĩśń'ţ ĩńśţàĺĺēď ōŕ ōń ŷōũŕ ƤÀŢĤ."],
+ "rUWrSE": ["Ďēĺēţē ŕēƥōŕţ"],
"rVJpLz": [
"Ōń — ĥōvēŕĩńĝ àń ēxţēŕńàĺ ĺĩńķ śēńďś ĩţś ŨŔĹ ţō ţĥē ďēśţĩńàţĩōń śĩţē ţō ƒēţćĥ à ƥŕēvĩēŵ."
],
@@ -3077,6 +3090,7 @@
"w7SsvI": ["Ţĥàţ ƒōĺďēŕ ĩśń'ţ àń ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţ ŷēţ. Ĩńĩţĩàĺĩźē ĩţ àńď ōƥēń?"],
"w7nm4K": ["Ĩńďēńţēď ƀĺōćķǫũōţē ƒōŕ ćĩţàţĩōńś."],
"wDgmsr": ["\"", ["0"], "\" ĩńśţàĺĺ ŕēƒŕēśĥēď (", ["1"], ")"],
+ "wF2wqQ": ["Ũńķńōŵń ďàţē"],
"wGSHzy": ["Àćţĩvàţē ōńē ōƒ ţĥē ƒĩŕśţ ēĩĝĥţ ēďĩţōŕ ţàƀś."],
"wJijgU": ["Ĺōćàţĩōń"],
"wJo9oS": ["Ćĺōśē ƒĩńď"],
@@ -3094,6 +3108,7 @@
"w_Sphq": ["Àţţàćĥḿēńţś"],
"waFx9W": ["Ḿàńàĝēď"],
"wbv9xO": ["Ćŕēàţē ńēŵ ƥŕōĴēćţ"],
+ "wcfO9r": ["Ńō ƀũĝ ŕēƥōŕţś ŷēţ."],
"wdxz7K": ["Śōũŕćē"],
"weP6me": ["Ćōũĺďń'ţ ĺōàď ďōćś — ţŷƥē @ àĝàĩń ţō ŕēţŕŷ"],
"wgNoIs": ["Śēĺēćţ àĺĺ"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 53d5cf494..5e95ae050 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -1507,6 +1507,11 @@ msgstr ""
msgid "Bug report {0}"
msgstr ""
+#: src/components/BugReportHistoryDialog.tsx
+#: src/components/command-palette-commands.ts
+msgid "Bug report history"
+msgstr ""
+
#: src/components/ReportBugDialogBody.tsx
msgid "Bug reporting needs the OpenKnowledge desktop app."
msgstr ""
@@ -2558,6 +2563,10 @@ msgstr ""
msgid "Couldn't load this skill's files."
msgstr ""
+#: src/components/BugReportHistory.tsx
+msgid "Couldn't load your bug reports."
+msgstr ""
+
#. placeholder {0}: result.error
#: src/components/ManagedArtifactProperties.tsx
msgid "Couldn't move skill: {0}"
@@ -2997,6 +3006,10 @@ msgstr ""
msgid "Delete Permanently"
msgstr ""
+#: src/components/BugReportHistory.tsx
+msgid "Delete report"
+msgstr ""
+
#: src/components/settings/LintingSection.tsx
msgid "Delete schema file {file}"
msgstr ""
@@ -3514,6 +3527,10 @@ msgstr ""
msgid "Email address"
msgstr ""
+#: src/components/BugReportHistory.tsx
+msgid "Emailed"
+msgstr ""
+
#: src/editor/slash-command/component-items.tsx
msgid "Embed a video with native player controls."
msgstr ""
@@ -3762,6 +3779,10 @@ msgstr ""
msgid "failed"
msgstr ""
+#: src/components/BugReportHistory.tsx
+msgid "Failed"
+msgstr ""
+
#: src/components/ArrayOfObjectsWidget.tsx
msgid "Failed to add item"
msgstr ""
@@ -5353,6 +5374,10 @@ msgstr ""
msgid "Loading timeline history"
msgstr ""
+#: src/components/BugReportHistory.tsx
+msgid "Loading your reports"
+msgstr ""
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Loading..."
msgstr ""
@@ -5916,6 +5941,10 @@ msgstr ""
msgid "No API key is set for this endpoint. Add one above."
msgstr ""
+#: src/components/BugReportHistory.tsx
+msgid "No bug reports yet."
+msgstr ""
+
#: src/components/ActivityPanelDiffView.tsx
msgid "No changes"
msgstr ""
@@ -6234,6 +6263,10 @@ msgstr ""
msgid "Not required for a localhost endpoint like <0>{endpointHost}</0> — most local servers ignore it. Add one only if yours needs it."
msgstr ""
+#: src/components/BugReportHistory.tsx
+msgid "Not sent"
+msgstr ""
+
#. placeholder {0}: summary.pattern
#: src/components/settings/LintingSection.tsx
msgid "nothing ({0} cannot match a doc)"
@@ -7037,6 +7070,10 @@ msgstr ""
msgid "Previous match"
msgstr ""
+#: src/components/BugReportHistory.tsx
+msgid "Previous reports"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Previous tab"
msgstr ""
@@ -7317,6 +7354,11 @@ msgstr ""
msgid "Redo"
msgstr ""
+#. placeholder {0}: row.reference
+#: src/components/BugReportHistory.tsx
+msgid "Reference <0>{0}</0>"
+msgstr ""
+
#: src/components/ProblemsPanel.tsx
msgid "Refresh audit"
msgstr ""
@@ -7579,6 +7621,7 @@ msgstr ""
msgid "Replace the active match from the replace field."
msgstr ""
+#: src/components/BugReportHistory.tsx
#: src/components/command-palette-commands.ts
#: src/components/HelpPopover.tsx
#: src/components/ReportBugDialogBody.tsx
@@ -7598,6 +7641,10 @@ msgstr ""
msgid "Report this error"
msgstr ""
+#: src/components/BugReportHistoryDialog.tsx
+msgid "Reports you've generated on this Mac. Retry a send, reveal a file, or delete one you no longer need."
+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 ""
@@ -7779,6 +7826,7 @@ msgid "Resuming the conversation"
msgstr ""
#: src/components/ActivityModeContent.tsx
+#: src/components/BugReportHistory.tsx
#: src/components/ConnectingBanner.tsx
#: src/components/PublishToGitHubDialog.tsx
#: src/components/settings/ConfigureAgentsSection.tsx
@@ -7806,6 +7854,7 @@ msgstr ""
msgid "Reveal in File Explorer, {hint}"
msgstr ""
+#: src/components/BugReportHistory.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
@@ -8176,6 +8225,7 @@ msgstr ""
msgid "Send your report by email"
msgstr ""
+#: src/components/BugReportHistory.tsx
#: src/components/FeedbackForm.tsx
msgid "Sending"
msgstr ""
@@ -8184,6 +8234,10 @@ msgstr ""
msgid "Sending report"
msgstr ""
+#: src/components/BugReportHistory.tsx
+msgid "Sent"
+msgstr ""
+
#: src/components/ReportBugDialogBody.tsx
msgid "Sent privately to the OpenKnowledge team, along with your note and app version. Never posted publicly."
msgstr ""
@@ -9876,6 +9930,7 @@ msgstr ""
msgid "Uninstalled \"{0}\" from {1}"
msgstr ""
+#: src/components/BugReportHistory.tsx
#: src/components/FolderTimelineCard.tsx
msgid "Unknown"
msgstr ""
@@ -9888,6 +9943,10 @@ msgstr ""
msgid "Unknown component: {unregisteredComponentName}"
msgstr ""
+#: src/components/BugReportHistory.tsx
+msgid "Unknown date"
+msgstr ""
+
#: src/components/DocumentErrorBoundary.tsx
#: src/lib/transports/auth-transport.ts
msgid "Unknown error"
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index 44bfb70eb..18df4245c 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -461,6 +461,8 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
fallback: { mailtoUrl: 'mailto:[email protected]' },
}),
crashAck: async () => ({ ok: true as const }),
+ list: async () => ({ ok: true as const, reports: [] }),
+ delete: async () => ({ ok: true as const }),
onCrashDetected: () => () => {},
},
navigator: {
diff --git a/packages/cli/src/commands/bug-report-bundle.ts b/packages/cli/src/commands/bug-report-bundle.ts
index d8a1de065..59dea80bb 100644
--- a/packages/cli/src/commands/bug-report-bundle.ts
+++ b/packages/cli/src/commands/bug-report-bundle.ts
@@ -39,7 +39,18 @@ export function okBugReportsDir(): string {
export function defaultBugReportZipPath(now: Date = new Date()): string {
const timestamp = now.toISOString().replace(/[:.]/g, '-');
- return join(okBugReportsDir(), `${timestamp}-bugreport.zip`);
+ const dir = okBugReportsDir();
+ const base = `${timestamp}-bugreport`;
+ // The ms-precision ISO basename is the report's stable `id` once the retry
+ // list makes it load-bearing, so it must be unique. Two same-millisecond
+ // generations (a crash-invite capture coinciding with a manual report) would
+ // otherwise collide and overwrite one bundle under one id — append a counter
+ // on collision so both survive with distinct ids.
+ let candidate = join(dir, `${base}.zip`);
+ for (let counter = 2; existsSync(candidate); counter += 1) {
+ candidate = join(dir, `${base}-${counter}.zip`);
+ }
+ return candidate;
}
/** Structural subset of a pino logger, so callers outside the CLI can inject their own. */
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 618c2e82d..eba1820ca 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -26,6 +26,7 @@ export {
type BundleExtraFile,
type BundleLogger,
defaultBugReportZipPath,
+ okBugReportsDir,
} 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
diff --git a/packages/core/src/bug-report-sidecar/schema.ts b/packages/core/src/bug-report-sidecar/schema.ts
new file mode 100644
index 000000000..753c41991
--- /dev/null
+++ b/packages/core/src/bug-report-sidecar/schema.ts
@@ -0,0 +1,150 @@
+/**
+ * Zod schema for a bug-report sidecar — one small YAML file per generated
+ * report, written next to its zip in `~/.ok/bug-reports/` (same basename,
+ * `.yaml`). It records the report's last-known send state so the history list
+ * can show, retry, and clean up prior reports across dialog close and app
+ * restart. The zip is the payload; the sidecar is the durable record.
+ *
+ * Boundary class: a machine-written, machine-read, durable on-disk format that
+ * must evolve gracefully. The pressures (per typescript-api-design):
+ * - additive evolution — a `version` field, an OPEN `state`, all new fields
+ * optional, so a newer app's sidecar never crashes an older app and vice
+ * versa;
+ * - one schema is the single source of truth for both the type and the
+ * validator;
+ * - forgiving reads — a pre-feature zip has no sidecar, and a corrupt or
+ * newer sidecar must degrade to a placeholder row, never break the list.
+ *
+ * The state machine is enforced by the WRITER (desktop main), not by this
+ * schema: `state` is a plain string here so an unknown value read from a newer
+ * app normalizes to `'unknown'` rather than rejecting the file (an anti-pattern
+ * "closed response enum" would). `version` is `.catch`-guarded for the same
+ * reason — a malformed version never rejects the whole file.
+ *
+ * Reuses the same YAML-write + Zod idioms as `skill-state/schema.ts`, but its
+ * reader synthesizes a degraded row on parse failure instead of dropping the
+ * file.
+ */
+
+import { z } from 'zod';
+
+/**
+ * Schema major version. Bump only on a breaking shape change, paired with a
+ * one-shot migrator; additive changes (new optional fields, new `state` values)
+ * stay at v1 and read best-effort on older apps.
+ */
+export const REPORT_SIDECAR_SCHEMA_VERSION = 1;
+
+/**
+ * Known report lifecycle states. Read as an OPEN enum: an unrecognized value
+ * (a newer app wrote a state this build doesn't know) normalizes to `'unknown'`
+ * rather than rejecting the sidecar. Transitions:
+ * generated → uploading → sent (+reference) | upload-failed (+lastError) | email-drafted
+ * A retry moves a non-`sent` report back to `uploading` and on to a terminal
+ * state again.
+ */
+export const REPORT_SIDECAR_STATES = [
+ 'generated',
+ 'uploading',
+ 'sent',
+ 'upload-failed',
+ 'email-drafted',
+] as const;
+
+export type ReportSidecarKnownState = (typeof REPORT_SIDECAR_STATES)[number];
+
+/** The known states plus the `'unknown'` sentinel a read may normalize to. */
+export type ReportSidecarState = ReportSidecarKnownState | 'unknown';
+
+/** Whether `value` is one of the writer's known states. */
+export function isKnownReportSidecarState(value: string): value is ReportSidecarKnownState {
+ return (REPORT_SIDECAR_STATES as readonly string[]).includes(value);
+}
+
+/**
+ * The timestamp-basename shape a report `id` must match — the zip basename
+ * `defaultBugReportZipPath` produces (`<iso-with-dashes>-bugreport[.-N].zip`).
+ * A renderer-supplied `id` is checked against this BEFORE any file operation,
+ * a belt-and-suspenders complement to the bug-reports-dir containment check:
+ * it admits no path separators or parent tokens, so a matching id is always a
+ * single basename inside the reports directory.
+ */
+export const REPORT_ID_PATTERN =
+ /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-bugreport(?:-\d+)?\.zip$/;
+
+/** Whether `id` matches the report timestamp-basename shape. */
+export function isReportIdShape(id: string): boolean {
+ return REPORT_ID_PATTERN.test(id);
+}
+
+/**
+ * Normalize a raw `state` string to a known state or the `'unknown'` sentinel.
+ * A newer app can write a state this build predates; the list renders it as a
+ * degraded "unknown" row instead of crashing.
+ */
+export function normalizeReportSidecarState(value: string): ReportSidecarState {
+ return isKnownReportSidecarState(value) ? value : 'unknown';
+}
+
+/**
+ * One send attempt in the bounded `attempts` history. `transport` / `outcome`
+ * are open strings (forward-compat) even though the writer only emits the
+ * documented values.
+ */
+const AttemptSchema = z.looseObject({
+ /** ISO-8601 timestamp of the attempt. */
+ at: z.string(),
+ /** `'upload'` (network) or `'email'` (the no-intake draft path). */
+ transport: z.string(),
+ /** `'success'` or `'failed'`. */
+ outcome: z.string(),
+ /** Intake reference when the attempt succeeded via upload. */
+ reference: z.string().optional(),
+ /** Short failure reason when the attempt failed. */
+ error: z.string().optional(),
+});
+
+export type ReportSidecarAttempt = z.infer<typeof AttemptSchema>;
+
+const LastErrorSchema = z.looseObject({
+ reason: z.string(),
+ at: z.string(),
+});
+
+/**
+ * The sidecar document. `looseObject` everywhere so a newer app's extra keys
+ * pass through untouched on an older reader. `version` and `zipBytes` are
+ * `.catch`-guarded so a malformed numeric field degrades to a default rather
+ * than rejecting the whole file. `id` and `createdAt` are required — a sidecar
+ * missing them fails validation and the reader synthesizes a degraded row from
+ * the filename instead.
+ */
+export const ReportSidecarSchema = z.looseObject({
+ version: z.number().int().catch(REPORT_SIDECAR_SCHEMA_VERSION),
+ /** Stable key: the report's zip basename (also the sidecar's basename). */
+ id: z.string(),
+ /** ISO-8601 generation time. */
+ createdAt: z.string(),
+ /** `'standard' | 'full'` — open string so a future level still reads. */
+ bundleLevel: z.string(),
+ /** On-disk zip size at generation, for the list and retention budgeting. */
+ zipBytes: z.number().int().nonnegative().catch(0),
+ /** True once retention reclaimed the zip on a confirmed send (a tombstone). */
+ zipDeleted: z.boolean().optional(),
+ /** Last-known state — OPEN (see `normalizeReportSidecarState`). */
+ state: z.string(),
+ /** True when no project was open at capture (bundle was system-wide). Send-metadata reconstruction for retry. */
+ systemWide: z.boolean().optional(),
+ /** Project slug at capture, `null` for system-wide. Send-metadata reconstruction for retry. */
+ projectSlug: z.string().nullable().optional(),
+ /** Intake reference — present when `state === 'sent'`. */
+ reference: z.string().optional(),
+ /** Present when `state === 'upload-failed'`. */
+ lastError: LastErrorSchema.optional(),
+ /** Bounded attempt history (capped by the writer). */
+ attempts: z.array(AttemptSchema).optional(),
+ /** Short redacted note carried for list context. */
+ note: z.string().optional(),
+});
+
+export type ReportSidecar = z.infer<typeof ReportSidecarSchema>;
diff --git a/packages/core/src/commands/command-identity.ts b/packages/core/src/commands/command-identity.ts
index ba3a1ec86..822f8dabc 100644
--- a/packages/core/src/commands/command-identity.ts
+++ b/packages/core/src/commands/command-identity.ts
@@ -362,6 +362,17 @@ export const COMMAND_IDENTITIES: readonly CommandIdentity[] = [
palette: { group: 'project', visibility: 'always' },
menu: [{ section: 'help-links', order: 1, ellipsis: true }],
},
+ {
+ // Palette-only sibling of report-bug (no `menu` placement): the persisted
+ // history/retry list for reports that were generated but never accepted by
+ // the intake. Desktop-only for the same reason report-bug is — the sidecar
+ // store and the retry upload both live behind the Electron bridge.
+ id: 'bug-report-history',
+ labelKey: 'bugReportHistory',
+ keywords: ['bug report history previous reports past retry resend'],
+ availability: { host: 'desktop' },
+ palette: { group: 'project', visibility: 'always' },
+ },
{
// Sibling of report-bug, but host-agnostic: the feedback form POSTs to the
// hosted intake route, so it works in the web host too (unlike the bug
diff --git a/packages/core/src/constants/menu-labels.ts b/packages/core/src/constants/menu-labels.ts
index 87378fbe4..262404ab8 100644
--- a/packages/core/src/constants/menu-labels.ts
+++ b/packages/core/src/constants/menu-labels.ts
@@ -64,6 +64,7 @@ export const MENU_LABELS = {
checkSpelling: 'Check spelling while typing',
openOnGithub: 'OpenKnowledge on GitHub',
reportBug: 'Report a bug',
+ bugReportHistory: 'Bug report history',
sendFeedback: 'Send feedback',
// Additional shared command labels the registry references. Each string is
// rendered identically by the palette, so the parity test stays green. The
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index c32bb2f88..66d906b4a 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -21,6 +21,8 @@ import type {
OkBugReportCrashAckResult,
OkBugReportCrashDetectedEvent,
OkBugReportCreateResult,
+ OkBugReportDeleteResult,
+ OkBugReportListResult,
OkBugReportScreenshot,
OkBugReportSendMetadata,
OkBugReportSendResult,
@@ -1439,6 +1441,8 @@ export interface OkDesktopBridge {
metadata: OkBugReportSendMetadata;
}): Promise<OkBugReportSendResult>;
crashAck(request: { eventId: string }): Promise<OkBugReportCrashAckResult>;
+ list(): Promise<OkBugReportListResult>;
+ delete(id: string): Promise<OkBugReportDeleteResult>;
onCrashDetected(cb: (event: OkBugReportCrashDetectedEvent) => void): OkUnsubscribe;
};
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 99156c1f5..a60aa6818 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1,3 +1,19 @@
+// Bug-report sidecar — the durable per-report YAML record backing the retry
+// list. Schema + open-state normalization; the writer/reader/retention live in
+// desktop main.
+export {
+ isKnownReportSidecarState,
+ isReportIdShape,
+ normalizeReportSidecarState,
+ REPORT_ID_PATTERN,
+ REPORT_SIDECAR_SCHEMA_VERSION,
+ REPORT_SIDECAR_STATES,
+ type ReportSidecar,
+ type ReportSidecarAttempt,
+ type ReportSidecarKnownState,
+ ReportSidecarSchema,
+ type ReportSidecarState,
+} from './bug-report-sidecar/schema.ts';
// Burst-grouping utility
export {
type Burst,
@@ -28,6 +44,9 @@ export type {
OkBugReportCrashAckResult,
OkBugReportCrashDetectedEvent,
OkBugReportCreateResult,
+ OkBugReportDeleteResult,
+ OkBugReportListResult,
+ OkBugReportListRow,
OkBugReportScreenshot,
OkBugReportSendFallbackReason,
OkBugReportSendMetadata,
diff --git a/packages/core/src/logger-types.ts b/packages/core/src/logger-types.ts
index c77560a56..af3776169 100644
--- a/packages/core/src/logger-types.ts
+++ b/packages/core/src/logger-types.ts
@@ -1,3 +1,5 @@
+import type { ReportSidecarState } from './bug-report-sidecar/schema.ts';
+
export type Loggable =
| string
| number
@@ -204,3 +206,69 @@ export type OkBugReportCrashDetectedEvent =
* renderer payload.
*/
export type OkBugReportCrashAckResult = { ok: true } | { ok: false; error: string };
+
+/**
+ * One row in the persisted bug-report history, projected from a report sidecar
+ * plus main-derived facts. `state` is the OPEN sidecar state (`'unknown'` for a
+ * degraded/legacy/corrupt row). `zipPath` is main-derived (never renderer
+ * influenced) and re-validated for containment before any retry/reveal; the
+ * renderer passes it straight back to `send` / reveal without composing a path.
+ *
+ * `systemWide` / `projectSlug` are carried so a retry reconstructs the exact
+ * `OkBugReportSendMetadata` without a second capture. `retryable` is
+ * `true` only when the report is neither `sent` nor mid-`uploading` and its zip
+ * is still on disk. `degraded` is `true` for a synthesized row (no sidecar, a
+ * corrupt sidecar, or an unknown state) so the list can render it plainly
+ * instead of failing.
+ */
+export interface OkBugReportListRow {
+ id: string;
+ createdAt: string;
+ bundleLevel: ReportBundleLevel | 'unknown';
+ /**
+ * Derived from the sidecar's single-source state list, so a state added to
+ * `REPORT_SIDECAR_STATES` propagates here instead of silently drifting.
+ */
+ state: ReportSidecarState;
+ zipBytes: number;
+ zipDeleted: boolean;
+ zipExists: boolean;
+ systemWide: boolean;
+ projectSlug: string | null;
+ /**
+ * State-coupled: present only when `state === 'sent'`. Not modelled as a
+ * discriminated union because `state` is an OPEN enum — enumerating arms
+ * here would reintroduce the drift that deriving `state` removes.
+ */
+ reference?: string;
+ /** State-coupled: present only when `state === 'upload-failed'`. */
+ lastError?: { reason: string; at: string };
+ attemptsCount: number;
+ note?: string;
+ /** Main-derived absolute zip path; re-validated for containment on use. */
+ zipPath: string;
+ retryable: boolean;
+ degraded: boolean;
+}
+
+/**
+ * Result of the desktop `ok:bug-report:dispatch` list operation — the persisted
+ * report history, newest first. Never thrown across the IPC boundary; a scan
+ * failure resolves to `{ ok: false }` so the list renders an error state.
+ */
+export type OkBugReportListResult =
+ | { ok: true; reports: OkBugReportListRow[] }
+ | { ok: false; reason: string };
+
+/**
+ * Result of the desktop `ok:bug-report:dispatch` delete operation. Removes a
+ * report's zip and sidecar by `id` after a containment + id-shape check. Never
+ * thrown across the IPC boundary.
+ * - `id-invalid` — the id failed the timestamp-basename shape / containment gate.
+ * - `in-flight` — the report's own send is currently in progress in this process.
+ * - `not-found` — no zip and no sidecar for the id.
+ * - `io-error` — a filesystem removal failed.
+ */
+export type OkBugReportDeleteResult =
+ | { ok: true }
+ | { ok: false; reason: 'id-invalid' | 'in-flight' | 'not-found' | 'io-error' };
diff --git a/packages/desktop/src/main/bug-report-sidecar.test.ts b/packages/desktop/src/main/bug-report-sidecar.test.ts
new file mode 100644
index 000000000..30f811e10
--- /dev/null
+++ b/packages/desktop/src/main/bug-report-sidecar.test.ts
@@ -0,0 +1,529 @@
+/**
+ * Unit tests for the bug-report sidecar store — write/read/list/delete,
+ * retention, forgiving reads, containment, the in-flight lock, and the
+ * send-path state transitions — all against a temp bug-reports directory.
+ *
+ * The filesystem IS the contract here: every assertion reads the on-disk
+ * sidecar (or the presence/absence of the zip) rather than a recording double,
+ * so the state machine and retention invariants are proven against real files.
+ */
+
+import { existsSync, mkdtempSync, rmSync, truncateSync, utimesSync, writeFileSync } from 'node:fs';
+import { readFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import type { ReportSidecar } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test } from 'vitest';
+import {
+ createBugReportSidecarStore,
+ createInFlightRegistry,
+ deleteReport,
+ listReports,
+ readReportSidecar,
+ reconcileStaleUploading,
+ runRetentionSweep,
+ sidecarPathForId,
+ writeReportSidecar,
+ zipPathForId,
+} from './bug-report-sidecar.ts';
+import {
+ MAX_SENT_TOMBSTONE_COUNT,
+ MAX_UNSENT_REPORT_BYTES,
+ MAX_UNSENT_REPORT_COUNT,
+} from './ipc/bug-report.ts';
+
+const tmpDirs: string[] = [];
+
+function makeTmpDir(): string {
+ const dir = mkdtempSync(resolve(tmpdir(), 'ok-bugreport-sidecar-'));
+ tmpDirs.push(dir);
+ return dir;
+}
+
+afterEach(() => {
+ for (const d of tmpDirs) {
+ if (existsSync(d)) rmSync(d, { recursive: true, force: true });
+ }
+ tmpDirs.length = 0;
+});
+
+/** Indexed access that asserts presence (tests control the arrays). */
+function nth<T>(arr: readonly T[], index: number): T {
+ const value = arr.at(index);
+ if (value === undefined) throw new Error(`no element at index ${index}`);
+ return value;
+}
+
+/** A valid report id (timestamp-basename shape) whose seconds/counter order it. */
+function rid(seconds: number, counter?: number): string {
+ const ss = String(seconds).padStart(2, '0');
+ return `2026-07-15T18-30-${ss}-000Z-bugreport${counter ? `-${counter}` : ''}.zip`;
+}
+
+/** The ISO createdAt that matches an `rid(seconds)` so on-disk order is deterministic. */
+function ridCreatedAt(seconds: number): string {
+ return `2026-07-15T18:30:${String(seconds).padStart(2, '0')}.000Z`;
+}
+
+function seedZip(dir: string, id: string, bytes = 128): void {
+ const path = join(dir, id);
+ writeFileSync(path, Buffer.alloc(bytes));
+}
+
+/**
+ * Seed a report whose zip *reports* `bytes` to `stat` without occupying them:
+ * `truncate` extends the file sparsely, so the byte-budget cap can be driven
+ * past its 1 GiB threshold without writing a gigabyte to a temp dir. Retention
+ * sizes bundles from `stat().size`, which counts the sparse length.
+ */
+async function seedSparseReport(
+ dir: string,
+ seconds: number,
+ bytes: number,
+ overrides: Partial<ReportSidecar> = {},
+): Promise<string> {
+ const id = rid(seconds);
+ const path = join(dir, id);
+ writeFileSync(path, '');
+ truncateSync(path, bytes);
+ await writeReportSidecar(
+ dir,
+ makeSidecar({ id, createdAt: ridCreatedAt(seconds), zipBytes: bytes, ...overrides }),
+ );
+ return id;
+}
+
+function makeSidecar(overrides: Partial<ReportSidecar> & { id: string }): ReportSidecar {
+ return {
+ version: 1,
+ createdAt: ridCreatedAt(0),
+ bundleLevel: 'standard',
+ zipBytes: 128,
+ state: 'generated',
+ systemWide: false,
+ projectSlug: 'demo',
+ ...overrides,
+ };
+}
+
+async function seedReport(
+ dir: string,
+ seconds: number,
+ overrides: Partial<ReportSidecar> = {},
+): Promise<string> {
+ const id = rid(seconds);
+ seedZip(dir, id);
+ await writeReportSidecar(
+ dir,
+ makeSidecar({ id, createdAt: ridCreatedAt(seconds), ...overrides }),
+ );
+ return id;
+}
+
+describe('writeReportSidecar / readReportSidecar', () => {
+ test('round-trips a generated sidecar to disk as YAML next to the zip', async () => {
+ const dir = makeTmpDir();
+ const id = rid(1);
+ await writeReportSidecar(dir, makeSidecar({ id, state: 'generated' }));
+
+ expect(existsSync(sidecarPathForId(dir, id))).toBe(true);
+ const raw = await readFile(sidecarPathForId(dir, id), 'utf-8');
+ // A YAML document, not JSON — the reader parses it back.
+ expect(raw).toContain('state: generated');
+
+ const parsed = await readReportSidecar(sidecarPathForId(dir, id));
+ expect(parsed?.id).toBe(id);
+ expect(parsed?.state).toBe('generated');
+ expect(parsed?.projectSlug).toBe('demo');
+ });
+
+ test('reading an absent sidecar returns null (forgiving)', async () => {
+ const dir = makeTmpDir();
+ expect(await readReportSidecar(sidecarPathForId(dir, rid(1)))).toBeNull();
+ });
+});
+
+describe('listReports — states and ordering', () => {
+ test('returns rows newest-first with the right state, retryability and reference', async () => {
+ const dir = makeTmpDir();
+ await seedReport(dir, 1, { state: 'upload-failed', lastError: { reason: 'offline', at: 'x' } });
+ await seedReport(dir, 3, { state: 'generated' });
+ const sentId = rid(2);
+ // A sent tombstone: sidecar present, zip already reclaimed.
+ await writeReportSidecar(
+ dir,
+ makeSidecar({
+ id: sentId,
+ createdAt: ridCreatedAt(2),
+ state: 'sent',
+ reference: 'OK-42',
+ zipDeleted: true,
+ }),
+ );
+
+ const result = await listReports(dir);
+ if (!result.ok) throw new Error(`expected ok, got ${result.reason}`);
+ expect(result.reports.map((r) => r.id)).toEqual([rid(3), rid(2), rid(1)]);
+
+ const [generated, sent, failed] = result.reports;
+ expect(generated?.state).toBe('generated');
+ expect(generated?.retryable).toBe(true);
+ expect(sent?.state).toBe('sent');
+ expect(sent?.reference).toBe('OK-42');
+ expect(sent?.retryable).toBe(false);
+ expect(sent?.zipExists).toBe(false);
+ expect(failed?.state).toBe('upload-failed');
+ expect(failed?.retryable).toBe(true);
+ expect(failed?.lastError?.reason).toBe('offline');
+ });
+});
+
+describe('listReports — forgiving reads (FR9)', () => {
+ test('a legacy zip with no sidecar renders as a retryable generated row', async () => {
+ const dir = makeTmpDir();
+ const id = rid(5);
+ seedZip(dir, id);
+
+ const result = await listReports(dir);
+ if (!result.ok) throw new Error('expected ok');
+ const row = result.reports.find((r) => r.id === id);
+ expect(row?.state).toBe('generated');
+ expect(row?.retryable).toBe(true);
+ expect(row?.degraded).toBe(false);
+ });
+
+ test('a corrupt sidecar renders as a degraded unknown row without breaking the list', async () => {
+ const dir = makeTmpDir();
+ const goodId = await seedReport(dir, 2, { state: 'generated' });
+ const badId = rid(1);
+ seedZip(dir, badId);
+ // A sidecar file present but neither valid YAML for the schema nor parseable.
+ writeFileSync(sidecarPathForId(dir, badId), 'id: [unterminated\n : : :');
+
+ const result = await listReports(dir);
+ if (!result.ok) throw new Error('expected ok');
+ expect(result.reports.map((r) => r.id).sort()).toEqual([badId, goodId].sort());
+ const bad = result.reports.find((r) => r.id === badId);
+ expect(bad?.state).toBe('unknown');
+ expect(bad?.degraded).toBe(true);
+ });
+
+ test('an unknown state and a newer version both render (open enum, best-effort)', async () => {
+ const dir = makeTmpDir();
+ const unknownId = rid(1);
+ seedZip(dir, unknownId);
+ await writeReportSidecar(
+ dir,
+ makeSidecar({ id: unknownId, state: 'quarantined' as ReportSidecar['state'] }),
+ );
+ const newerId = rid(2);
+ seedZip(dir, newerId);
+ await writeReportSidecar(dir, makeSidecar({ id: newerId, version: 999, state: 'generated' }));
+
+ const result = await listReports(dir);
+ if (!result.ok) throw new Error('expected ok');
+ expect(result.reports.find((r) => r.id === unknownId)?.state).toBe('unknown');
+ expect(result.reports.find((r) => r.id === unknownId)?.degraded).toBe(true);
+ // Newer version still parses and renders its known state.
+ expect(result.reports.find((r) => r.id === newerId)?.state).toBe('generated');
+ });
+});
+
+describe('deleteReport — containment and in-flight', () => {
+ test('deletes a valid report zip + sidecar', async () => {
+ const dir = makeTmpDir();
+ const id = await seedReport(dir, 1);
+ const inFlight = createInFlightRegistry();
+
+ expect(await deleteReport(dir, id, inFlight)).toEqual({ ok: true });
+ expect(existsSync(zipPathForId(dir, id))).toBe(false);
+ expect(existsSync(sidecarPathForId(dir, id))).toBe(false);
+ });
+
+ test('refuses a non-report-shaped id, a traversal, and a relative id', async () => {
+ const dir = makeTmpDir();
+ const inFlight = createInFlightRegistry();
+ for (const badId of ['../escape.zip', 'report.zip', '/etc/passwd', 'not-a-report.txt']) {
+ const result = await deleteReport(dir, badId, inFlight);
+ expect(result).toEqual({ ok: false, reason: 'id-invalid' });
+ }
+ });
+
+ test('returns not-found when neither zip nor sidecar exists', async () => {
+ const dir = makeTmpDir();
+ expect(await deleteReport(dir, rid(9), createInFlightRegistry())).toEqual({
+ ok: false,
+ reason: 'not-found',
+ });
+ });
+
+ test('refuses to delete a report whose send is in flight', async () => {
+ const dir = makeTmpDir();
+ const id = await seedReport(dir, 1);
+ const inFlight = createInFlightRegistry();
+ inFlight.add(id);
+
+ expect(await deleteReport(dir, id, inFlight)).toEqual({ ok: false, reason: 'in-flight' });
+ expect(existsSync(zipPathForId(dir, id))).toBe(true);
+ });
+});
+
+describe('send hooks — state transitions and in-flight lock', () => {
+ test('onSendStart marks uploading and blocks a second concurrent send', async () => {
+ const dir = makeTmpDir();
+ const id = await seedReport(dir, 1, { state: 'generated' });
+ const store = createBugReportSidecarStore({ dir });
+
+ expect(await store.sendHooks.onSendStart(id)).toEqual({ proceed: true });
+ expect((await readReportSidecar(sidecarPathForId(dir, id)))?.state).toBe('uploading');
+ // A second retry while the first is in flight is refused.
+ expect(await store.sendHooks.onSendStart(id)).toEqual({ proceed: false });
+ });
+
+ test('a sent result records the reference, appends an attempt, and reclaims the zip', async () => {
+ const dir = makeTmpDir();
+ const id = await seedReport(dir, 1, { state: 'generated' });
+ const store = createBugReportSidecarStore({ dir });
+
+ await store.sendHooks.onSendStart(id);
+ await store.sendHooks.onSendResult(id, { kind: 'sent', reference: 'OK-777' });
+
+ const sidecar = await readReportSidecar(sidecarPathForId(dir, id));
+ expect(sidecar?.state).toBe('sent');
+ expect(sidecar?.reference).toBe('OK-777');
+ expect(sidecar?.zipDeleted).toBe(true);
+ expect(sidecar?.attempts?.at(-1)).toMatchObject({ transport: 'upload', outcome: 'success' });
+ // The confirmed-sent zip is reclaimed, its tombstone sidecar kept.
+ expect(existsSync(zipPathForId(dir, id))).toBe(false);
+ expect(existsSync(sidecarPathForId(dir, id))).toBe(true);
+ // The lock is released, so a later op on the same id is allowed.
+ expect(await store.sendHooks.onSendStart(id)).toEqual({ proceed: true });
+ });
+
+ test('an upload-failed result records the reason and stays retryable', async () => {
+ const dir = makeTmpDir();
+ const id = await seedReport(dir, 1, { state: 'generated' });
+ const store = createBugReportSidecarStore({ dir });
+
+ await store.sendHooks.onSendStart(id);
+ await store.sendHooks.onSendResult(id, {
+ kind: 'upload-failed',
+ reason: 'complete-rejected: 503',
+ });
+
+ const sidecar = await readReportSidecar(sidecarPathForId(dir, id));
+ expect(sidecar?.state).toBe('upload-failed');
+ expect(sidecar?.lastError?.reason).toBe('complete-rejected: 503');
+ expect(sidecar?.attempts?.at(-1)).toMatchObject({ transport: 'upload', outcome: 'failed' });
+ expect(existsSync(zipPathForId(dir, id))).toBe(true);
+ });
+
+ test('an email-drafted result records the email transport without touching the zip', async () => {
+ const dir = makeTmpDir();
+ const id = await seedReport(dir, 1, { state: 'generated' });
+ const store = createBugReportSidecarStore({ dir });
+
+ await store.sendHooks.onSendResult(id, { kind: 'email-drafted' });
+
+ const sidecar = await readReportSidecar(sidecarPathForId(dir, id));
+ expect(sidecar?.state).toBe('email-drafted');
+ expect(sidecar?.attempts?.at(-1)).toMatchObject({ transport: 'email' });
+ expect(existsSync(zipPathForId(dir, id))).toBe(true);
+ });
+});
+
+describe('runRetentionSweep', () => {
+ test('drops the zip on a confirmed send and keeps the sidecar tombstone', async () => {
+ const dir = makeTmpDir();
+ const id = await seedReport(dir, 1, { state: 'sent', reference: 'OK-1' });
+
+ await runRetentionSweep(dir, createInFlightRegistry());
+
+ expect(existsSync(zipPathForId(dir, id))).toBe(false);
+ expect((await readReportSidecar(sidecarPathForId(dir, id)))?.zipDeleted).toBe(true);
+ });
+
+ test('evicts the oldest unsent over the count cap but never the newest', async () => {
+ const dir = makeTmpDir();
+ const total = MAX_UNSENT_REPORT_COUNT + 2;
+ const ids: string[] = [];
+ for (let i = 1; i <= total; i += 1) ids.push(await seedReport(dir, i, { state: 'generated' }));
+
+ await runRetentionSweep(dir, createInFlightRegistry());
+
+ // The two oldest are evicted; the newest is always kept.
+ expect(existsSync(zipPathForId(dir, nth(ids, 0)))).toBe(false);
+ expect(existsSync(zipPathForId(dir, nth(ids, 1)))).toBe(false);
+ expect(existsSync(zipPathForId(dir, nth(ids, -1)))).toBe(true);
+ const remaining = (await listReports(dir)) as { ok: true; reports: unknown[] };
+ expect(remaining.reports.length).toBe(MAX_UNSENT_REPORT_COUNT);
+ });
+
+ test('never evicts an uploading bundle even when it is the oldest', async () => {
+ const dir = makeTmpDir();
+ const total = MAX_UNSENT_REPORT_COUNT + 2;
+ const ids: string[] = [];
+ for (let i = 1; i <= total; i += 1) {
+ ids.push(await seedReport(dir, i, { state: i === 1 ? 'uploading' : 'generated' }));
+ }
+
+ await runRetentionSweep(dir, createInFlightRegistry());
+
+ // The oldest is `uploading` → skipped; the next two oldest are evicted instead.
+ expect(existsSync(zipPathForId(dir, nth(ids, 0)))).toBe(true);
+ expect(existsSync(zipPathForId(dir, nth(ids, 1)))).toBe(false);
+ expect(existsSync(zipPathForId(dir, nth(ids, 2)))).toBe(false);
+ });
+
+ test('never evicts a bundle whose send is in flight', async () => {
+ const dir = makeTmpDir();
+ const total = MAX_UNSENT_REPORT_COUNT + 1;
+ const ids: string[] = [];
+ for (let i = 1; i <= total; i += 1) ids.push(await seedReport(dir, i, { state: 'generated' }));
+ const inFlight = createInFlightRegistry();
+ inFlight.add(nth(ids, 0)); // the oldest is mid-send
+
+ await runRetentionSweep(dir, inFlight);
+
+ expect(existsSync(zipPathForId(dir, nth(ids, 0)))).toBe(true);
+ // The next oldest is evicted to satisfy the cap instead.
+ expect(existsSync(zipPathForId(dir, nth(ids, 1)))).toBe(false);
+ });
+
+ test('evicts on the byte budget alone, with the count cap never exceeded', async () => {
+ const dir = makeTmpDir();
+ // Three bundles at 40% of the budget each: 120% of the byte cap, but only
+ // 3 of the 10 allowed by the count cap. Eviction here can only be driven by
+ // the byte condition — drop it and nothing is reclaimed.
+ const chunk = Math.floor(MAX_UNSENT_REPORT_BYTES * 0.4);
+ const ids: string[] = [];
+ for (let i = 1; i <= 3; i += 1) ids.push(await seedSparseReport(dir, i, chunk));
+ expect(ids.length).toBeLessThan(MAX_UNSENT_REPORT_COUNT);
+
+ await runRetentionSweep(dir, createInFlightRegistry());
+
+ // Evicting the oldest brings the total to 80% of the budget, so the sweep
+ // stops there — the remaining two (including the newest) stay.
+ expect(existsSync(zipPathForId(dir, nth(ids, 0)))).toBe(false);
+ expect(existsSync(sidecarPathForId(dir, nth(ids, 0)))).toBe(false);
+ expect(existsSync(zipPathForId(dir, nth(ids, 1)))).toBe(true);
+ expect(existsSync(zipPathForId(dir, nth(ids, -1)))).toBe(true);
+ });
+
+ test('keeps the newest unsent bundle even when it alone busts the byte budget', async () => {
+ const dir = makeTmpDir();
+ const older = await seedSparseReport(dir, 1, 1024);
+ const huge = await seedSparseReport(dir, 2, MAX_UNSENT_REPORT_BYTES * 2);
+
+ await runRetentionSweep(dir, createInFlightRegistry());
+
+ // The residual over-budget state is the intended invariant: never strand a
+ // user with no bundle to retry, even when the only one left is oversized.
+ expect(existsSync(zipPathForId(dir, older))).toBe(false);
+ expect(existsSync(zipPathForId(dir, huge))).toBe(true);
+ });
+
+ test('reclaims an unreadable sidecar whose bundle is already gone', async () => {
+ const dir = makeTmpDir();
+ const orphanId = rid(1);
+ // Sidecar file present but unparseable, with no zip beside it: it is
+ // neither a sent tombstone nor an unsent bundle, so without an explicit
+ // sweep it belongs to no cap and accumulates forever.
+ writeFileSync(sidecarPathForId(dir, orphanId), 'id: [unterminated\n : : :');
+ const liveId = await seedReport(dir, 2, { state: 'generated' });
+
+ await runRetentionSweep(dir, createInFlightRegistry());
+
+ expect(existsSync(sidecarPathForId(dir, orphanId))).toBe(false);
+ expect(existsSync(zipPathForId(dir, liveId))).toBe(true);
+ });
+
+ test('keeps a forward-compatible sidecar with an unrecognized state and no zip', async () => {
+ const dir = makeTmpDir();
+ const futureId = rid(1);
+ // A newer app wrote a state this build normalizes to `unknown`. It PARSES,
+ // so it is not the corrupt case — reclaiming it would defeat the open-enum
+ // forward compatibility the schema exists for.
+ await writeReportSidecar(
+ dir,
+ makeSidecar({
+ id: futureId,
+ createdAt: ridCreatedAt(1),
+ state: 'paused' as ReportSidecar['state'],
+ zipDeleted: true,
+ }),
+ );
+
+ await runRetentionSweep(dir, createInFlightRegistry());
+
+ expect(existsSync(sidecarPathForId(dir, futureId))).toBe(true);
+ });
+
+ test('bounds sent tombstones by their own count cap, oldest first', async () => {
+ const dir = makeTmpDir();
+ const total = MAX_SENT_TOMBSTONE_COUNT + 3;
+ const ids: string[] = [];
+ for (let i = 1; i <= total; i += 1) {
+ const id = rid(i);
+ ids.push(id);
+ await writeReportSidecar(
+ dir,
+ makeSidecar({
+ id,
+ createdAt: ridCreatedAt(i),
+ state: 'sent',
+ reference: `OK-${i}`,
+ zipDeleted: true,
+ }),
+ );
+ }
+
+ await runRetentionSweep(dir, createInFlightRegistry());
+
+ // The three oldest tombstone sidecars are removed.
+ expect(existsSync(sidecarPathForId(dir, nth(ids, 0)))).toBe(false);
+ expect(existsSync(sidecarPathForId(dir, nth(ids, 2)))).toBe(false);
+ expect(existsSync(sidecarPathForId(dir, nth(ids, -1)))).toBe(true);
+ });
+});
+
+describe('reconcileStaleUploading', () => {
+ test('demotes a stale uploading sidecar to upload-failed at boot', async () => {
+ const dir = makeTmpDir();
+ const staleId = await seedReport(dir, 1, { state: 'uploading' });
+ const okId = await seedReport(dir, 2, { state: 'generated' });
+
+ const reconciled = await reconcileStaleUploading(dir);
+ expect(reconciled).toBe(1);
+
+ const stale = await readReportSidecar(sidecarPathForId(dir, staleId));
+ expect(stale?.state).toBe('upload-failed');
+ expect(stale?.lastError?.reason).toBe('interrupted-by-restart');
+ // A non-uploading sidecar is untouched.
+ expect((await readReportSidecar(sidecarPathForId(dir, okId)))?.state).toBe('generated');
+ });
+});
+
+describe('legacy zip mtime ordering', () => {
+ test('a sidecar-less zip sorts by its file mtime', async () => {
+ const dir = makeTmpDir();
+ const older = rid(1);
+ const newer = rid(2);
+ seedZip(dir, older);
+ seedZip(dir, newer);
+ utimesSync(
+ join(dir, older),
+ new Date('2026-07-15T18:30:01.000Z'),
+ new Date('2026-07-15T18:30:01.000Z'),
+ );
+ utimesSync(
+ join(dir, newer),
+ new Date('2026-07-15T18:30:09.000Z'),
+ new Date('2026-07-15T18:30:09.000Z'),
+ );
+
+ const result = await listReports(dir);
+ if (!result.ok) throw new Error('expected ok');
+ expect(result.reports.map((r) => r.id)).toEqual([newer, older]);
+ });
+});
diff --git a/packages/desktop/src/main/bug-report-sidecar.ts b/packages/desktop/src/main/bug-report-sidecar.ts
new file mode 100644
index 000000000..357a3c99b
--- /dev/null
+++ b/packages/desktop/src/main/bug-report-sidecar.ts
@@ -0,0 +1,584 @@
+/**
+ * Bug-report sidecar store — the durable, filesystem-as-truth record backing
+ * the report retry list.
+ *
+ * One small YAML file per generated report lives next to its zip in
+ * `~/.ok/bug-reports/`, same basename with a `.yaml` extension. It records the
+ * report's last-known send state so the history list can show, retry, and clean
+ * up prior reports across dialog close and app restart — the zip is the
+ * payload, the sidecar is the record. There is no central index: the list is
+ * derived by scanning the directory (mirrors the crash-ack / no-central-index
+ * grain).
+ *
+ * This module owns the write/read/list/delete/retention/reconcile logic and the
+ * process-local in-flight lock. It plugs into `handleBugReportCreate` (writes the
+ * `generated` sidecar) and `handleBugReportSend` (records the `uploading` →
+ * terminal transitions) through the hook seams those handlers expose, so the
+ * state machine is exercised by the same unit tests that drive create/send.
+ *
+ * Reuses `atomic-yaml-write` (tmp + rename) and the `yaml` document API exactly
+ * as `server/src/skill-state.ts` does — but a corrupt or absent sidecar
+ * synthesizes a degraded row rather than dropping the file: one bad file must
+ * never break the list, and a pre-feature zip with no sidecar must still appear.
+ * Writes are atomic; a write failure never loses the newest unsent bundle. The
+ * state machine is enforced by these writers, not by the schema.
+ */
+
+import { readdir, readFile, realpath, stat, unlink } from 'node:fs/promises';
+import { basename, dirname, join } from 'node:path';
+import {
+ isReportIdShape,
+ normalizeReportSidecarState,
+ type OkBugReportDeleteResult,
+ type OkBugReportListResult,
+ type OkBugReportListRow,
+ REPORT_SIDECAR_SCHEMA_VERSION,
+ type ReportBundleLevel,
+ type ReportSidecar,
+ ReportSidecarSchema,
+ type ReportSidecarState,
+} from '@inkeep/open-knowledge-core';
+import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';
+import { type ParsedNode, parseDocument } from 'yaml';
+import {
+ type BugReportSendSidecarHooks,
+ type GeneratedReportMeta,
+ MAX_REPORT_ATTEMPTS,
+ MAX_SENT_TOMBSTONE_COUNT,
+ MAX_UNSENT_REPORT_BYTES,
+ MAX_UNSENT_REPORT_COUNT,
+ type SidecarSendOutcome,
+} from './ipc/bug-report.ts';
+import { isPathWithinProject } from './path-containment.ts';
+
+/** Minimal logger duck-type (matches pino `getLogger(name)` and ad-hoc shims). */
+export interface SidecarLogger {
+ warn: (data: unknown, message: string) => void;
+}
+
+/**
+ * Process-local set of report ids whose send is currently in flight. A send
+ * cannot outlive the process, so this in-memory structure is authoritative for
+ * "is this report mid-send right now?": it blocks a second concurrent retry, a
+ * delete, and a retention eviction of a report being uploaded. A
+ * fresh registry per store instance keeps tests isolated.
+ */
+export interface InFlightRegistry {
+ has(id: string): boolean;
+ add(id: string): void;
+ delete(id: string): void;
+}
+
+export function createInFlightRegistry(): InFlightRegistry {
+ const ids = new Set<string>();
+ return {
+ has: (id) => ids.has(id),
+ add: (id) => {
+ ids.add(id);
+ },
+ delete: (id) => {
+ ids.delete(id);
+ },
+ };
+}
+
+/** The sidecar path for a report id (`<base>-bugreport.zip` → `<base>-bugreport.yaml`). */
+export function sidecarPathForId(dir: string, id: string): string {
+ return join(dir, id.replace(/\.zip$/, '.yaml'));
+}
+
+/** The zip path for a report id. */
+export function zipPathForId(dir: string, id: string): string {
+ return join(dir, id);
+}
+
+/**
+ * Serialize a validated sidecar to YAML and write it atomically. Mirrors
+ * `skill-state`'s `parseDocument('')` + `createNode` + `toString()` (the raw
+ * `atomicWriteFile` writes strings, not YAML — CORRECTION per the impl guide).
+ * Validates before write so a malformed object never lands on disk. Throws on a
+ * genuine write failure; callers decide whether to swallow (create is fail-soft)
+ * or surface it.
+ */
+export async function writeReportSidecar(dir: string, sidecar: ReportSidecar): Promise<void> {
+ const parsed = ReportSidecarSchema.safeParse(sidecar);
+ if (!parsed.success) {
+ throw new Error(
+ `refusing to write invalid report sidecar: ${parsed.error.issues
+ .map((i) => `${i.path.join('.')}: ${i.message}`)
+ .join('; ')}`,
+ );
+ }
+ const doc = parseDocument('');
+ doc.contents = doc.createNode(parsed.data) as ParsedNode;
+ await atomicWriteFile(sidecarPathForId(dir, parsed.data.id), doc.toString());
+}
+
+/**
+ * Read + validate a sidecar. Returns `null` on ENOENT, YAML parse error, or
+ * schema violation — the forgiving-read contract (the caller synthesizes a
+ * degraded row). Only a genuine non-ENOENT IO error propagates.
+ */
+export async function readReportSidecar(sidecarPath: string): Promise<ReportSidecar | null> {
+ let content: string;
+ try {
+ content = await readFile(sidecarPath, 'utf-8');
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw err;
+ }
+ const doc = parseDocument(content);
+ if (doc.errors.length > 0) return null;
+ const parsed = ReportSidecarSchema.safeParse(doc.toJSON());
+ return parsed.success ? parsed.data : null;
+}
+
+interface ScannedReport {
+ id: string;
+ sidecar: ReportSidecar | null;
+ /** A sidecar FILE was present (even if unreadable/corrupt). */
+ sidecarPresent: boolean;
+ zipExists: boolean;
+ zipBytes: number;
+ zipMtime: string | null;
+}
+
+/**
+ * Scan the reports directory into a union of every report keyed by id: a zip
+ * with or without a sidecar, and a tombstone sidecar whose zip is gone. Scoped
+ * to the report basename shape so an unrelated file in the directory is ignored.
+ */
+async function scanReports(dir: string): Promise<ScannedReport[]> {
+ const entries = await readdir(dir).catch(() => [] as string[]);
+ const ids = new Set<string>();
+ const sidecarIds = new Set<string>();
+ for (const entry of entries) {
+ if (entry.endsWith('.zip') && isReportIdShape(entry)) {
+ ids.add(entry);
+ } else if (entry.endsWith('.yaml')) {
+ const id = entry.replace(/\.yaml$/, '.zip');
+ if (isReportIdShape(id)) {
+ ids.add(id);
+ sidecarIds.add(id);
+ }
+ }
+ }
+ return Promise.all(
+ [...ids].map(async (id): Promise<ScannedReport> => {
+ const zipStat = await stat(zipPathForId(dir, id)).catch(() => null);
+ const sidecarPresent = sidecarIds.has(id);
+ const sidecar = sidecarPresent
+ ? await readReportSidecar(sidecarPathForId(dir, id)).catch(() => null)
+ : null;
+ return {
+ id,
+ sidecar,
+ sidecarPresent,
+ zipExists: zipStat !== null,
+ zipBytes: zipStat?.size ?? sidecar?.zipBytes ?? 0,
+ zipMtime: zipStat?.mtime.toISOString() ?? null,
+ };
+ }),
+ );
+}
+
+/** Normalize a raw `bundleLevel` to a known level or the `'unknown'` sentinel. */
+function projectBundleLevel(raw: string | undefined): ReportBundleLevel | 'unknown' {
+ return raw === 'standard' || raw === 'full' ? raw : 'unknown';
+}
+
+/** Project a scanned report to the renderer-facing list row. */
+function toListRow(dir: string, scanned: ScannedReport): OkBugReportListRow {
+ const s = scanned.sidecar;
+ // A sidecar file that was present but unreadable can't be trusted as
+ // `generated` — it renders as a degraded `unknown` row. A plain
+ // sidecar-less legacy zip is a normal, retryable `generated` report.
+ const state: ReportSidecarState = s
+ ? normalizeReportSidecarState(s.state)
+ : scanned.sidecarPresent
+ ? 'unknown'
+ : scanned.zipExists
+ ? 'generated'
+ : 'unknown';
+ const degraded = (scanned.sidecarPresent && s === null) || state === 'unknown';
+ const projectSlug = s?.projectSlug ?? null;
+ return {
+ id: scanned.id,
+ createdAt: s?.createdAt ?? scanned.zipMtime ?? '',
+ bundleLevel: projectBundleLevel(s?.bundleLevel),
+ state,
+ zipBytes: scanned.zipBytes,
+ zipDeleted: s?.zipDeleted ?? !scanned.zipExists,
+ zipExists: scanned.zipExists,
+ systemWide: s?.systemWide ?? projectSlug === null,
+ projectSlug,
+ ...(s?.reference !== undefined ? { reference: s.reference } : {}),
+ ...(s?.lastError !== undefined ? { lastError: s.lastError } : {}),
+ attemptsCount: s?.attempts?.length ?? 0,
+ zipPath: zipPathForId(dir, scanned.id),
+ retryable: scanned.zipExists && state !== 'sent' && state !== 'uploading',
+ degraded,
+ };
+}
+
+/** List persisted reports, newest first. Never throws — a scan failure resolves to `{ ok: false }`. */
+export async function listReports(dir: string): Promise<OkBugReportListResult> {
+ try {
+ const scanned = await scanReports(dir);
+ const reports = scanned
+ .map((r) => toListRow(dir, r))
+ // Newest first by createdAt; empty timestamps (unreadable, no zip mtime)
+ // sort last, tie-broken by id so the order is deterministic.
+ .sort((a, b) => {
+ if (a.createdAt === b.createdAt) return a.id < b.id ? 1 : -1;
+ if (a.createdAt === '') return 1;
+ if (b.createdAt === '') return -1;
+ return a.createdAt < b.createdAt ? 1 : -1;
+ });
+ return { ok: true, reports };
+ } catch (err) {
+ return { ok: false, reason: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+/**
+ * Verify a renderer-supplied `id` is a report basename and resolves inside the
+ * reports directory before any file op — a belt-and-suspenders gate. The
+ * lexical containment check is the cheap pre-filter; the realpath check holds
+ * against a symlinked report path, matching the send handler's order.
+ */
+async function resolveContainedId(dir: string, id: string): Promise<string | null> {
+ if (!isReportIdShape(id)) return null;
+ const zipPath = zipPathForId(dir, id);
+ if (!isPathWithinProject(zipPath, dir, process.platform)) return null;
+ try {
+ const canonicalRoot = await realpath(dir);
+ // The zip may be gone (a sent tombstone) — resolve the directory instead so
+ // deleting a tombstone's sidecar still passes containment.
+ const canonicalDir = await realpath(dirname(zipPath));
+ if (!isPathWithinProject(join(canonicalDir, id), canonicalRoot, process.platform)) return null;
+ } catch {
+ return null;
+ }
+ return zipPath;
+}
+
+/** Best-effort unlink that ignores ENOENT; returns false only on a real removal failure. */
+async function unlinkIfPresent(path: string): Promise<boolean> {
+ try {
+ await unlink(path);
+ return true;
+ } catch (err) {
+ return (err as NodeJS.ErrnoException).code === 'ENOENT';
+ }
+}
+
+/**
+ * Delete a report's zip and sidecar by id. Containment + id-shape checked;
+ * refused while the report's own send is in flight. `not-found` when neither file
+ * exists; `io-error` when a removal fails.
+ */
+export async function deleteReport(
+ dir: string,
+ id: string,
+ inFlight: InFlightRegistry,
+): Promise<OkBugReportDeleteResult> {
+ const zipPath = await resolveContainedId(dir, id);
+ if (zipPath === null) return { ok: false, reason: 'id-invalid' };
+ if (inFlight.has(id)) return { ok: false, reason: 'in-flight' };
+ const sidecarPath = sidecarPathForId(dir, id);
+ const zipExisted = await stat(zipPath).then(
+ () => true,
+ () => false,
+ );
+ const sidecarExisted = await stat(sidecarPath).then(
+ () => true,
+ () => false,
+ );
+ if (!zipExisted && !sidecarExisted) return { ok: false, reason: 'not-found' };
+ const zipOk = await unlinkIfPresent(zipPath);
+ const sidecarOk = await unlinkIfPresent(sidecarPath);
+ return zipOk && sidecarOk ? { ok: true } : { ok: false, reason: 'io-error' };
+}
+
+/** Build a minimal `generated` sidecar for a report with no readable record (a retried legacy zip). */
+async function synthesizeSidecar(dir: string, id: string): Promise<ReportSidecar> {
+ const zipStat = await stat(zipPathForId(dir, id)).catch(() => null);
+ return {
+ version: REPORT_SIDECAR_SCHEMA_VERSION,
+ id,
+ createdAt: zipStat?.mtime.toISOString() ?? new Date().toISOString(),
+ bundleLevel: 'standard',
+ zipBytes: zipStat?.size ?? 0,
+ state: 'generated',
+ systemWide: true,
+ projectSlug: null,
+ };
+}
+
+/**
+ * Mark a report `uploading` and acquire the in-flight lock (the `onSendStart`
+ * hook). Returns `{ proceed: false }` when the report's send is already in
+ * flight — the caller refuses the second concurrent retry. Fail-open: an
+ * internal write error keeps the lock and still proceeds, so a transient
+ * sidecar issue never blocks an actual send.
+ */
+async function markUploading(
+ dir: string,
+ id: string,
+ inFlight: InFlightRegistry,
+ logger?: SidecarLogger,
+): Promise<{ proceed: boolean }> {
+ if (inFlight.has(id)) return { proceed: false };
+ inFlight.add(id);
+ try {
+ const base =
+ (await readReportSidecar(sidecarPathForId(dir, id)).catch(() => null)) ??
+ (await synthesizeSidecar(dir, id));
+ await writeReportSidecar(dir, { ...base, state: 'uploading' });
+ } catch (err) {
+ logger?.warn({ id, err }, 'bug-report: failed to mark report uploading');
+ }
+ return { proceed: true };
+}
+
+/**
+ * Record a send's terminal outcome (the `onSendResult` hook): write the
+ * `sent`/`upload-failed`/`email-drafted` state, append a bounded attempt,
+ * release the in-flight lock, and run retention (which reclaims the zip on a
+ * confirmed send). Never throws.
+ */
+async function recordSendResult(
+ dir: string,
+ id: string,
+ outcome: SidecarSendOutcome,
+ inFlight: InFlightRegistry,
+ logger?: SidecarLogger,
+): Promise<void> {
+ const at = new Date().toISOString();
+ try {
+ const base =
+ (await readReportSidecar(sidecarPathForId(dir, id)).catch(() => null)) ??
+ (await synthesizeSidecar(dir, id));
+ const attempt =
+ outcome.kind === 'sent'
+ ? { at, transport: 'upload', outcome: 'success', reference: outcome.reference }
+ : outcome.kind === 'upload-failed'
+ ? { at, transport: 'upload', outcome: 'failed', error: outcome.reason }
+ : { at, transport: 'email', outcome: 'success' };
+ const attempts = [...(base.attempts ?? []), attempt].slice(-MAX_REPORT_ATTEMPTS);
+ // Rebuild without a stale lastError, then set the new terminal fields.
+ const { lastError: _priorError, reference: _priorRef, ...rest } = base;
+ let next: ReportSidecar = { ...rest, attempts };
+ if (outcome.kind === 'sent') {
+ next = { ...next, state: 'sent', reference: outcome.reference };
+ } else if (outcome.kind === 'upload-failed') {
+ next = { ...next, state: 'upload-failed', lastError: { reason: outcome.reason, at } };
+ } else {
+ next = { ...next, state: 'email-drafted' };
+ }
+ await writeReportSidecar(dir, next);
+ } catch (err) {
+ logger?.warn({ id, err }, 'bug-report: failed to record send result');
+ } finally {
+ inFlight.delete(id);
+ }
+ // Retention runs after the terminal write so a just-`sent` report's zip is
+ // reclaimed and the caps re-enforced. The report is no longer in flight here.
+ // The sweep logs its own per-file failures and is documented never to throw,
+ // so anything caught here is a contract violation — log it rather than
+ // discarding it, or a sweep that stops running becomes undiagnosable.
+ await runRetentionSweep(dir, inFlight, logger).catch((err: unknown) => {
+ logger?.warn({ err }, 'bug-report: retention sweep failed unexpectedly');
+ });
+}
+
+/**
+ * Startup reconciliation: a send cannot survive a restart, so any
+ * sidecar still in `uploading` at boot is a poison row left by a crash or quit
+ * mid-send — demote it to `upload-failed` so it becomes retryable and evictable
+ * again. Runs before any send, so the in-flight set is empty. Never throws.
+ */
+export async function reconcileStaleUploading(
+ dir: string,
+ logger?: SidecarLogger,
+): Promise<number> {
+ let reconciled = 0;
+ try {
+ const scanned = await scanReports(dir);
+ const at = new Date().toISOString();
+ for (const report of scanned) {
+ if (report.sidecar === null) continue;
+ if (normalizeReportSidecarState(report.sidecar.state) !== 'uploading') continue;
+ const next: ReportSidecar = {
+ ...report.sidecar,
+ state: 'upload-failed',
+ lastError: { reason: 'interrupted-by-restart', at },
+ };
+ await writeReportSidecar(dir, next).then(
+ () => {
+ reconciled += 1;
+ },
+ (err: unknown) => {
+ logger?.warn(
+ { id: report.id, err },
+ 'bug-report: failed to reconcile stale uploading sidecar',
+ );
+ },
+ );
+ }
+ } catch (err) {
+ logger?.warn({ err }, 'bug-report: stale-uploading reconciliation scan failed');
+ }
+ return reconciled;
+}
+
+/**
+ * Hybrid retention sweep. Reclaims the zip on every confirmed send
+ * (keeping the sidecar tombstone), then bounds the sent tombstones by count and
+ * the UNSENT bundles by count + total size. Eviction never removes the newest
+ * unsent bundle, an `uploading` bundle, or a bundle whose send is in flight, and
+ * an unlink failure is skipped rather than aborting the sweep. Never throws.
+ */
+export async function runRetentionSweep(
+ dir: string,
+ inFlight: InFlightRegistry,
+ logger?: SidecarLogger,
+): Promise<void> {
+ let scanned: ScannedReport[];
+ try {
+ scanned = await scanReports(dir);
+ } catch (err) {
+ logger?.warn({ err }, 'bug-report: retention scan failed');
+ return;
+ }
+
+ const stateOf = (r: ScannedReport): ReportSidecarState =>
+ r.sidecar
+ ? normalizeReportSidecarState(r.sidecar.state)
+ : r.zipExists
+ ? 'generated'
+ : 'unknown';
+
+ // Drop the zip on a confirmed send; keep the sidecar as a tombstone.
+ for (const r of scanned) {
+ if (stateOf(r) === 'sent' && r.zipExists && r.sidecar && !inFlight.has(r.id)) {
+ const removed = await unlinkIfPresent(zipPathForId(dir, r.id));
+ if (removed) {
+ r.zipExists = false;
+ await writeReportSidecar(dir, { ...r.sidecar, zipDeleted: true }).catch((err: unknown) => {
+ logger?.warn({ id: r.id, err }, 'bug-report: failed to tombstone a sent report');
+ });
+ }
+ }
+ }
+
+ const sortByCreatedAtAsc = (a: ScannedReport, b: ScannedReport): number => {
+ const at = a.sidecar?.createdAt ?? a.zipMtime ?? '';
+ const bt = b.sidecar?.createdAt ?? b.zipMtime ?? '';
+ return at < bt ? -1 : at > bt ? 1 : a.id < b.id ? -1 : 1;
+ };
+
+ // Sent-tombstone cap: oldest first, delete the sidecar (the zip is already gone).
+ const tombstones = scanned
+ .filter((r) => stateOf(r) === 'sent' && !r.zipExists)
+ .sort(sortByCreatedAtAsc);
+ const tombstoneOverflow = Math.max(0, tombstones.length - MAX_SENT_TOMBSTONE_COUNT);
+ for (const tombstone of tombstones.slice(0, tombstoneOverflow)) {
+ await unlinkIfPresent(sidecarPathForId(dir, tombstone.id));
+ }
+
+ // Orphan sweep: an unparseable sidecar whose zip is already gone belongs to
+ // neither cap above (not `sent`, so not a tombstone; no zip, so not unsent)
+ // and would otherwise accumulate forever. Keyed on a sidecar that is present
+ // but FAILED TO PARSE — never on a normalized `'unknown'` state, since a
+ // sidecar written by a newer app with a state this build doesn't recognize
+ // still parses, and reclaiming it would make the open-enum forward
+ // compatibility the schema exists for a lie.
+ for (const r of scanned) {
+ if (r.sidecarPresent && r.sidecar === null && !r.zipExists && !inFlight.has(r.id)) {
+ await unlinkIfPresent(sidecarPathForId(dir, r.id));
+ logger?.warn({ id: r.id }, 'bug-report: reclaimed an unreadable sidecar with no bundle');
+ }
+ }
+
+ // Unsent-bundle caps (count + total size). A bundle is unsent when its zip is
+ // present and it is not `sent`. Never evict the newest unsent, an `uploading`
+ // bundle, or an in-flight one.
+ const unsent = scanned
+ .filter((r) => r.zipExists && stateOf(r) !== 'sent')
+ .sort(sortByCreatedAtAsc);
+ let unsentCount = unsent.length;
+ let unsentBytes = unsent.reduce((sum, r) => sum + r.zipBytes, 0);
+ const newestUnsentId = unsent.at(-1)?.id ?? null;
+ for (const r of unsent) {
+ if (unsentCount <= MAX_UNSENT_REPORT_COUNT && unsentBytes <= MAX_UNSENT_REPORT_BYTES) break;
+ if (r.id === newestUnsentId) continue;
+ if (stateOf(r) === 'uploading' || inFlight.has(r.id)) continue;
+ const zipRemoved = await unlinkIfPresent(zipPathForId(dir, r.id));
+ if (!zipRemoved) continue;
+ await unlinkIfPresent(sidecarPathForId(dir, r.id));
+ unsentCount -= 1;
+ unsentBytes -= r.zipBytes;
+ logger?.warn(
+ { id: r.id, zipBytes: r.zipBytes },
+ 'bug-report: evicted an over-budget unsent report',
+ );
+ }
+}
+
+/** The report-sidecar surface desktop main wires into the bug-report dispatch handlers. */
+export interface BugReportSidecarStore {
+ /** `onReportGenerated` hook: persist the `generated` sidecar + run retention. */
+ recordGenerated(meta: GeneratedReportMeta): Promise<void>;
+ /** Send-path state hooks passed to `handleBugReportSend`. */
+ sendHooks: BugReportSendSidecarHooks;
+ /** List persisted reports (dispatch `list` arm). */
+ list(): Promise<OkBugReportListResult>;
+ /** Delete a report by id (dispatch `delete` arm). */
+ remove(id: string): Promise<OkBugReportDeleteResult>;
+ /** Demote any stale `uploading` sidecar to `upload-failed` (boot). */
+ reconcileStaleUploading(): Promise<number>;
+}
+
+/**
+ * Construct the report-sidecar store for a reports directory, with its own
+ * process-local in-flight registry. One instance is wired into desktop main's
+ * bug-report dispatch handlers.
+ */
+export function createBugReportSidecarStore(opts: {
+ dir: string;
+ logger?: SidecarLogger;
+}): BugReportSidecarStore {
+ const { dir, logger } = opts;
+ const inFlight = createInFlightRegistry();
+ return {
+ async recordGenerated(meta) {
+ const sidecar: ReportSidecar = {
+ version: REPORT_SIDECAR_SCHEMA_VERSION,
+ id: basename(meta.zipPath),
+ createdAt: new Date().toISOString(),
+ bundleLevel: meta.level,
+ zipBytes: meta.zipBytes,
+ state: 'generated',
+ systemWide: meta.systemWide,
+ projectSlug: meta.projectSlug,
+ };
+ try {
+ await writeReportSidecar(dir, sidecar);
+ } catch (err) {
+ logger?.warn({ id: sidecar.id, err }, 'bug-report: failed to write generated sidecar');
+ }
+ await runRetentionSweep(dir, inFlight, logger).catch((err: unknown) => {
+ logger?.warn({ err }, 'bug-report: retention sweep failed unexpectedly');
+ });
+ },
+ sendHooks: {
+ onSendStart: (id) => markUploading(dir, id, inFlight, logger),
+ onSendResult: (id, outcome) => recordSendResult(dir, id, outcome, inFlight, logger),
+ },
+ list: () => listReports(dir),
+ remove: (id) => deleteReport(dir, id, inFlight),
+ reconcileStaleUploading: () => reconcileStaleUploading(dir, logger),
+ };
+}
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 00f631f24..a967e890c 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -54,6 +54,7 @@ import {
isEntryUpToDate,
isOwnManagedEntry,
type McpInstallOptions,
+ okBugReportsDir,
type ProjectAiIntegrationsResult,
previewContent,
readExistingMcpEntry,
@@ -165,6 +166,7 @@ import {
proxyRunCheckout,
proxyShareTargetStatus,
} from './branch-info-proxy.ts';
+import { createBugReportSidecarStore } from './bug-report-sidecar.ts';
import { wrapperPathInBundle } from './bundle-paths.ts';
import {
type BundleReplaceWatcherHandle,
@@ -1075,6 +1077,19 @@ const bugReportScreenshots = new Map<number, BugReportScreenshotEntry>();
/** Max width (logical px) of the screenshot preview data-URL handed to the renderer. */
const BUG_REPORT_SCREENSHOT_PREVIEW_WIDTH = 720;
+/**
+ * Durable per-report sidecar record backing the history/retry list — owns the
+ * write-on-generate, the send-state transitions, the retention sweep, and the
+ * process-local in-flight lock, all scoped to `~/.ok/bug-reports/`. The logger
+ * is a thin adapter so `getLogger` resolves at call time, not module load.
+ */
+const bugReportSidecar = createBugReportSidecarStore({
+ dir: okBugReportsDir(),
+ logger: {
+ warn: (data, message) => getLogger('bug-report').warn(data as Record<string, unknown>, message),
+ },
+});
+
/**
* Active-editor target snapshot pushed by the renderer via
* `ok:editor:active-target-changed`. Drives the macOS File menu's state-aware
@@ -4747,6 +4762,12 @@ function registerIpcHandlers() {
request,
);
}
+ if (request.kind === 'list') {
+ return bugReportSidecar.list();
+ }
+ if (request.kind === 'delete') {
+ return bugReportSidecar.remove(request.id);
+ }
if (request.kind === 'send') {
return handleBugReportSend(
{
@@ -4761,6 +4782,9 @@ function registerIpcHandlers() {
// Same containment root the Reveal handler whitelists above — only
// zips `create` produced may be read and uploaded.
bugReportsRoot: dirname(defaultBugReportZipPath()),
+ // Records uploading → sent/upload-failed/email-drafted on the sidecar
+ // and holds the in-flight lock, for the first send and a list retry.
+ sidecar: bugReportSidecar.sendHooks,
},
request,
);
@@ -4799,6 +4823,9 @@ function registerIpcHandlers() {
// Main-owned bytes captured for this exact window; `create` stages them
// only when the renderer opted in via `includeScreenshot`.
screenshotPngBytes: () => bugReportScreenshots.get(event.sender.id)?.png ?? null,
+ // Persist the report's `generated` sidecar and run the retention sweep
+ // once the bundle is written, so it survives dialog close + restart.
+ onReportGenerated: (meta) => bugReportSidecar.recordGenerated(meta),
logger: getLogger('bug-report'),
},
request,
@@ -6025,6 +6052,11 @@ function bootPrimaryInstance(): void {
quit: () => app.quit(),
logger: getLogger('signal-clean-quit'),
});
+ // A sidecar left `uploading` is a send interrupted by a crash/quit last
+ // session — a send never survives a restart, so demote it to `upload-failed`
+ // making it retryable and evictable again. Fire-and-forget +
+ // fail-soft: a reconcile failure must not block boot.
+ void bugReportSidecar.reconcileStaleUploading();
app.on('child-process-gone', (_event, details) => {
// Feed the server-exit recorder every Utility death (not just the crash
// reasons the invitation pipeline acts on) so the bundle can distinguish a
diff --git a/packages/desktop/src/main/ipc/bug-report.test.ts b/packages/desktop/src/main/ipc/bug-report.test.ts
index be188c0b5..9a282cdd0 100644
--- a/packages/desktop/src/main/ipc/bug-report.test.ts
+++ b/packages/desktop/src/main/ipc/bug-report.test.ts
@@ -29,6 +29,11 @@ import { createServer, type Server } from 'node:http';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import {
+ createBugReportSidecarStore,
+ readReportSidecar,
+ sidecarPathForId,
+} from '../bug-report-sidecar.ts';
import { createCrashDetection } from '../crash-detection.ts';
import { handleShellOpenExternal } from '../shell-allowlist.ts';
import {
@@ -423,11 +428,15 @@ const SEND_METADATA = {
note: 'the editor froze',
};
-/** Non-UTF-8 byte pattern so the PUT byte-identity assertion is meaningful. */
+/**
+ * Non-UTF-8 byte pattern so the PUT byte-identity assertion is meaningful. The
+ * basename carries the report-id shape `defaultBugReportZipPath` produces,
+ * since `send` gates on it the same way `delete` does.
+ */
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');
+ const zipPath = join(bugReportsRoot, '2026-07-15T18-30-00-000Z-bugreport.zip');
writeFileSync(zipPath, bytes);
return zipPath;
}
@@ -497,7 +506,7 @@ describe('handleBugReportSend — upload happy path', () => {
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',
+ filename: '2026-07-15T18-30-00-000Z-bugreport.zip',
sizeBytes: 2048,
contentType: 'application/zip',
metadata: { ...SEND_METADATA, ...SEND_HOST },
@@ -1338,3 +1347,143 @@ describe('handleBugReportCrashAck', () => {
expect(acked).toEqual([]);
});
});
+
+describe('bug-report sidecar wiring — create writes the record, send tracks state', () => {
+ const REPORT_ID = '2026-07-15T18-30-00-000Z-bugreport.zip';
+
+ /**
+ * A create rig whose output lands in a shared bug-reports dir with a real
+ * report basename, wired to a live sidecar store — so the generated sidecar
+ * and the send transitions are asserted against the on-disk file.
+ */
+ function makeSidecarRig() {
+ const dir = makeTmpDir('ok-bugreport-sidecar-wiring-');
+ const store = createBugReportSidecarStore({ dir });
+ const zipPath = join(dir, REPORT_ID);
+ const createDeps: BugReportCreateDeps = {
+ projectDir: makeProjectDir(),
+ desktopMeta: DESKTOP_META,
+ outputPath: zipPath,
+ userLogsDir: makeTmpDir(),
+ onReportGenerated: store.recordGenerated,
+ };
+ return { dir, store, zipPath, createDeps };
+ }
+
+ test('create persists a generated sidecar next to the zip', async () => {
+ const { dir, createDeps, zipPath } = makeSidecarRig();
+
+ const result = await handleBugReportCreate(createDeps, { kind: 'create', level: 'standard' });
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ expect(result.zipPath).toBe(zipPath);
+
+ const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));
+ expect(sidecar?.id).toBe(REPORT_ID);
+ expect(sidecar?.state).toBe('generated');
+ expect(sidecar?.bundleLevel).toBe('standard');
+ expect(sidecar?.zipBytes).toBe(result.zipSizeBytes);
+ });
+
+ test('a successful send flips the sidecar to sent + reference and reclaims the zip', async () => {
+ const { dir, store, createDeps, zipPath } = makeSidecarRig();
+ await handleBugReportCreate(createDeps, { kind: 'create', level: 'standard' });
+ const stub = await startIntakeStub();
+
+ const result = await handleBugReportSend(
+ { ...makeSendDeps(stub.url, dir), sidecar: store.sendHooks },
+ { kind: 'send', zipPath, metadata: SEND_METADATA },
+ );
+
+ expect(result).toEqual({ ok: true, reference: 'OK-1042' });
+ const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));
+ expect(sidecar?.state).toBe('sent');
+ expect(sidecar?.reference).toBe('OK-1042');
+ expect(sidecar?.zipDeleted).toBe(true);
+ expect(sidecar?.attempts?.at(-1)).toMatchObject({ transport: 'upload', outcome: 'success' });
+ // Retention reclaimed the confirmed-sent zip.
+ expect(existsSync(zipPath)).toBe(false);
+ });
+
+ test('a failed send records upload-failed and keeps the zip for a later retry', async () => {
+ const { dir, store, createDeps, zipPath } = makeSidecarRig();
+ await handleBugReportCreate(createDeps, { kind: 'create', level: 'standard' });
+ const stub = await startIntakeStub({ mintStatus: 500 });
+
+ const result = await handleBugReportSend(
+ { ...makeSendDeps(stub.url, dir), sidecar: store.sendHooks },
+ { kind: 'send', zipPath, metadata: SEND_METADATA },
+ );
+
+ expect(result.ok).toBe(false);
+ const sidecar = await readReportSidecar(sidecarPathForId(dir, REPORT_ID));
+ expect(sidecar?.state).toBe('upload-failed');
+ expect(sidecar?.lastError?.reason).toContain('mint-rejected');
+ expect(existsSync(zipPath)).toBe(true);
+
+ // The list now surfaces the failed report as retryable.
+ const listed = await store.list();
+ if (!listed.ok) throw new Error('expected ok');
+ const row = listed.reports.find((r) => r.id === REPORT_ID);
+ expect(row?.state).toBe('upload-failed');
+ expect(row?.retryable).toBe(true);
+ });
+
+ test('a send refused by the in-flight lock never reaches the intake', async () => {
+ const { dir, store, createDeps, zipPath } = makeSidecarRig();
+ await handleBugReportCreate(createDeps, { kind: 'create', level: 'standard' });
+ const stub = await startIntakeStub();
+ // Take the lock as the owning send would, then drive a second send for the
+ // same report through the handler — the double-upload this gate prevents.
+ const owner = await store.sendHooks.onSendStart(REPORT_ID);
+ expect(owner.proceed).toBe(true);
+
+ const result = await handleBugReportSend(
+ { ...makeSendDeps(stub.url, dir), sidecar: store.sendHooks },
+ { kind: 'send', zipPath, metadata: SEND_METADATA },
+ );
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected refusal');
+ expect(result.reason).toBe('send-failed');
+ // The refusal must happen BEFORE any network work: the bundle is uploaded
+ // exactly once no matter how many retries race.
+ expect(stub.requests).toHaveLength(0);
+ // The owning send still holds the report; the refusal left it untouched.
+ expect((await readReportSidecar(sidecarPathForId(dir, REPORT_ID)))?.state).toBe('uploading');
+ });
+
+ test('a zip inside the reports dir with a non-report basename is refused', async () => {
+ const { dir, store, createDeps } = makeSidecarRig();
+ await handleBugReportCreate(createDeps, { kind: 'create', level: 'standard' });
+ const stub = await startIntakeStub();
+ // Contained, readable, but not a report basename — the same shape gate
+ // `delete` applies, so no renderer-supplied path skips it on the send side.
+ const strayPath = join(dir, 'not-a-report.zip');
+ writeFileSync(strayPath, Buffer.alloc(64));
+
+ const result = await handleBugReportSend(
+ { ...makeSendDeps(stub.url, dir), sidecar: store.sendHooks },
+ { kind: 'send', zipPath: strayPath, metadata: SEND_METADATA },
+ );
+
+ expect(result.ok).toBe(false);
+ expect(stub.requests).toHaveLength(0);
+ });
+
+ test('the unconfigured (no-intake) send path records email-drafted', async () => {
+ const { dir, store, createDeps, zipPath } = makeSidecarRig();
+ await handleBugReportCreate(createDeps, { kind: 'create', level: 'standard' });
+
+ const result = await handleBugReportSend(
+ { ...makeSendDeps(undefined, dir), sidecar: store.sendHooks },
+ { kind: 'send', zipPath, metadata: SEND_METADATA },
+ );
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected fallback');
+ expect(result.reason).toBe('email-draft');
+ expect((await readReportSidecar(sidecarPathForId(dir, REPORT_ID)))?.state).toBe(
+ 'email-drafted',
+ );
+ });
+});
diff --git a/packages/desktop/src/main/ipc/bug-report.ts b/packages/desktop/src/main/ipc/bug-report.ts
index b49d4c51d..dc26280ca 100644
--- a/packages/desktop/src/main/ipc/bug-report.ts
+++ b/packages/desktop/src/main/ipc/bug-report.ts
@@ -28,6 +28,7 @@ import {
} from '@inkeep/open-knowledge';
import {
BUG_REPORT_SCREENSHOT_ZIP_NAME,
+ isReportIdShape,
type OkBugReportCrashAckResult,
type OkBugReportCreateResult,
type OkBugReportScreenshot,
@@ -65,6 +66,18 @@ interface OkBugReportCaptureScreenshotRequest {
kind: 'capture-screenshot';
}
+/** Read the persisted report history (newest first). */
+interface OkBugReportListRequest {
+ kind: 'list';
+}
+
+/** Remove a persisted report (zip + sidecar) by `id`, containment-checked. */
+interface OkBugReportDeleteRequest {
+ kind: 'delete';
+ /** The report's timestamp-basename `id` (== zip basename). */
+ id: string;
+}
+
export interface OkBugReportSendRequest {
kind: 'send';
/** Zip produced by a prior `create` — the exact file the user reviewed is what uploads. */
@@ -83,7 +96,9 @@ export type OkBugReportRequest =
| OkBugReportCreateRequest
| OkBugReportSendRequest
| OkBugReportCrashAckRequest
- | OkBugReportCaptureScreenshotRequest;
+ | OkBugReportCaptureScreenshotRequest
+ | OkBugReportListRequest
+ | OkBugReportDeleteRequest;
/**
* Host metadata handed to the bundle collector through its typed
@@ -129,6 +144,14 @@ export interface BugReportCreateDeps {
* silent omission from the bundle.
*/
logger?: BundleLogger;
+ /**
+ * Persist the report's `generated` sidecar (and run the retention sweep)
+ * after a bundle is written. Injected so the durable-record write is exercised
+ * by the create tests against a temp bug-reports dir; a create context that
+ * doesn't persist (or a sidecar write that throws) never changes the create
+ * outcome — the zip is already on disk.
+ */
+ onReportGenerated?: (meta: GeneratedReportMeta) => Promise<void>;
}
/**
@@ -216,6 +239,26 @@ export async function handleBugReportCreate(
}),
});
const { size: zipSizeBytes } = await stat(zipPath);
+ // Persist the durable `generated` record next to the zip. A failure here
+ // must never lose the report (the zip is written) — the writer is fail-soft
+ // and the call is guarded, so create still succeeds if the sidecar can't be
+ // written.
+ if (deps.onReportGenerated) {
+ await deps
+ .onReportGenerated({
+ zipPath,
+ zipBytes: zipSizeBytes,
+ level: request.level,
+ systemWide: summary.systemWide,
+ projectSlug: summary.projectSlug,
+ })
+ .catch((err: unknown) => {
+ deps.logger?.warn(
+ { zipPath, err },
+ 'bug-report: failed to persist report sidecar on generate',
+ );
+ });
+ }
return { ok: true, zipPath, zipSizeBytes, summary };
} catch (err) {
// Environmental failure at the fs boundary (unwritable destination, disk
@@ -383,6 +426,14 @@ export interface BugReportSendDeps {
bugReportsRoot: string;
/** Transport-timeout overrides (test seam; defaults 30s mint/complete, 120s PUT). */
timeouts?: Partial<BugReportUploadTimeouts>;
+ /**
+ * Sidecar-state hooks that record the `uploading` → `sent`/`upload-failed`/
+ * `email-drafted` transition, append an attempt, and honor the in-flight lock.
+ * Fires for BOTH the first dialog send and a later list retry (same handler).
+ * Absent leaves the send behavior unchanged (unit tests that only exercise the
+ * transport omit it).
+ */
+ sidecar?: BugReportSendSidecarHooks;
}
/**
@@ -409,6 +460,62 @@ const COMPLETE_TIMEOUT_MS = 30_000;
*/
export const MAX_UPLOAD_ZIP_BYTES = 256 * 1024 * 1024;
+/**
+ * Hybrid retention caps for `~/.ok/bug-reports/`, co-located with the upload
+ * ceiling because they bound the same on-disk report set. On a confirmed send
+ * the zip is dropped (the sidecar tombstone stays); the remaining UNSENT
+ * bundles are then bounded by a count cap and a total-size budget, and the
+ * sent tombstones by their own count cap. Eviction never removes the newest
+ * unsent bundle or a bundle whose send is in flight. Fixed constants
+ * for v1 — `config.yml` exposure is Future Work.
+ */
+export const MAX_UNSENT_REPORT_COUNT = 10;
+export const MAX_UNSENT_REPORT_BYTES = 1024 * 1024 * 1024;
+export const MAX_SENT_TOMBSTONE_COUNT = 25;
+
+/** Cap on the sidecar's per-report `attempts` history (newest kept). */
+export const MAX_REPORT_ATTEMPTS = 10;
+
+/**
+ * Facts a successful `create` hands to the sidecar writer so it can persist the
+ * report's initial `generated` record (and reconstruct a later retry's send
+ * metadata without a second capture). Keyed to the returned `zipPath`, whose
+ * basename becomes the report `id`.
+ */
+export interface GeneratedReportMeta {
+ zipPath: string;
+ zipBytes: number;
+ level: ReportBundleLevel;
+ systemWide: boolean;
+ projectSlug: string | null;
+}
+
+/**
+ * Terminal outcome of a send attempt, handed to the sidecar writer so it can
+ * record the state transition and append an attempt. `email-drafted` is the
+ * designed no-intake path (nothing uploaded), distinct from `upload-failed`.
+ */
+export type SidecarSendOutcome =
+ | { kind: 'sent'; reference: string }
+ | { kind: 'upload-failed'; reason: string }
+ | { kind: 'email-drafted' };
+
+/**
+ * Sidecar-state hooks injected into `send` so the durable record tracks each
+ * transition and the in-flight lock is honored — implemented by desktop main's
+ * bug-report sidecar store, or a recording double in tests. `onSendStart` marks
+ * the report `uploading` and acquires the in-flight lock, returning
+ * `{ proceed: false }` when this report's send is already in flight (a second
+ * concurrent retry). `onSendResult` records the terminal state, appends an
+ * attempt, releases the lock, and runs retention. Only the actual-upload branch
+ * calls `onSendStart`; every terminal branch (including email-draft) calls
+ * `onSendResult`.
+ */
+export interface BugReportSendSidecarHooks {
+ onSendStart(id: string): Promise<{ proceed: boolean }>;
+ onSendResult(id: string, outcome: SidecarSendOutcome): Promise<void>;
+}
+
/**
* Admit a report-transport URL — the intake base or a minted upload URL —
* only when transport-safe: `https:` anywhere, or plain `http:` strictly on
@@ -631,6 +738,32 @@ async function uploadBugReport(
}
}
+/**
+ * Run a sidecar bookkeeping hook without letting it decide the send's outcome.
+ *
+ * Each hook catches internally and is documented never to throw, so a rejection
+ * crossing back here is a contract violation rather than an expected path — but
+ * swallowing it silently would be worse than the failure it hides. The
+ * post-upload call is the sharp case: an escaped rejection there would skip the
+ * `{ ok: true }` return, leave the in-flight lock held, and refuse every later
+ * retry for the process lifetime. Bookkeeping must never cost the user a send
+ * that already succeeded.
+ */
+async function runSidecarHook(hook: Promise<unknown> | undefined): Promise<void> {
+ if (hook === undefined) return;
+ try {
+ await hook;
+ } catch (err) {
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:bug-report:dispatch',
+ reason: 'sidecar-hook-error',
+ handler: 'handleBugReportSend',
+ cause: err,
+ });
+ }
+}
+
/**
* Upload the reviewed zip for the `send` operation. Never throws — every
* non-success maps to the discriminated `{ok: false}` result whose fallback
@@ -655,6 +788,25 @@ export async function handleBugReportSend(
fallback: { mailtoUrl: buildBugReportMailto(hostFacts) },
};
}
+ // Basename shape is the same belt-and-suspenders gate `delete` applies via
+ // `resolveContainedId`. Containment below is what actually holds, but
+ // requiring the report-id shape on every renderer-id-driven file operation
+ // keeps the invariant uniform across `send` and `delete` rather than leaving
+ // `send` the one path where an arbitrary basename inside the directory is
+ // admitted.
+ if (!isReportIdShape(basename(request.zipPath))) {
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:bug-report:dispatch',
+ reason: 'zip-path-shape',
+ 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
@@ -731,6 +883,9 @@ export async function handleBugReportSend(
zipPath: request.zipPath,
}),
};
+ // The report id is the zip's basename — the sidecar key the state transitions
+ // are recorded under, for both the first dialog send and a later list retry.
+ const reportId = basename(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
@@ -742,8 +897,40 @@ export async function handleBugReportSend(
reason: 'intake-unconfigured',
handler: 'handleBugReportSend',
});
+ await runSidecarHook(deps.sidecar?.onSendResult(reportId, { kind: 'email-drafted' }));
return { ok: false, reason: 'email-draft', fallback };
}
+ if (deps.sidecar) {
+ // Mark the report `uploading` and take the in-flight lock. A second retry
+ // arriving while this send is in flight is refused here rather than
+ // uploading the same bundle twice; the owning send records the terminal
+ // state when it finishes.
+ // A hook that rejects here leaves the lock state unknown. Proceed rather
+ // than refuse: the user asked to send, and silently blocking every send on
+ // a bookkeeping fault is a worse failure than the double-upload this gate
+ // exists to prevent (which needs a genuinely concurrent retry to occur).
+ let gate: { proceed: boolean } = { proceed: true };
+ try {
+ gate = await deps.sidecar.onSendStart(reportId);
+ } catch (err) {
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:bug-report:dispatch',
+ reason: 'sidecar-hook-error',
+ handler: 'handleBugReportSend',
+ cause: err,
+ });
+ }
+ if (!gate.proceed) {
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:bug-report:dispatch',
+ reason: 'send-in-flight',
+ handler: 'handleBugReportSend',
+ });
+ return { ok: false, reason: 'send-failed', fallback };
+ }
+ }
const wireMetadata: BugReportWireMetadata = { ...metadata, ...hostFacts };
const outcome = await uploadBugReport(
deps.intakeBaseUrl,
@@ -751,7 +938,12 @@ export async function handleBugReportSend(
wireMetadata,
deps.timeouts,
);
- if (outcome.ok) return { ok: true, reference: outcome.reference };
+ if (outcome.ok) {
+ await runSidecarHook(
+ deps.sidecar?.onSendResult(reportId, { kind: 'sent', reference: outcome.reference }),
+ );
+ return { ok: true, reference: outcome.reference };
+ }
logIpcError({
event: 'ipc.error',
channel: 'ok:bug-report:dispatch',
@@ -759,6 +951,9 @@ export async function handleBugReportSend(
handler: 'handleBugReportSend',
cause: outcome.cause,
});
+ await runSidecarHook(
+ deps.sidecar?.onSendResult(reportId, { kind: 'upload-failed', reason: outcome.reason }),
+ );
return { ok: false, reason: 'send-failed', fallback };
}
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index 064182a53..13ee39756 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -23,6 +23,8 @@ import type {
OkBugReportCrashAckResult,
OkBugReportCrashDetectedEvent,
OkBugReportCreateResult,
+ OkBugReportDeleteResult,
+ OkBugReportListResult,
OkBugReportScreenshot,
OkBugReportSendMetadata,
OkBugReportSendResult,
@@ -534,6 +536,10 @@ const bridge: OkDesktopBridge = {
kind: 'crash-ack',
eventId: request.eventId,
}) as Promise<OkBugReportCrashAckResult>,
+ list: () =>
+ invoke('ok:bug-report:dispatch', { kind: 'list' }) as Promise<OkBugReportListResult>,
+ delete: (id: string) =>
+ invoke('ok:bug-report:dispatch', { kind: 'delete', id }) as Promise<OkBugReportDeleteResult>,
onCrashDetected(cb: (event: OkBugReportCrashDetectedEvent) => void) {
const listener = (_event: IpcRendererEvent, event: OkBugReportCrashDetectedEvent) =>
cb(event);
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index ea57bca6e..227a9b7b6 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -27,6 +27,8 @@ import type {
OkBugReportCrashAckResult,
OkBugReportCrashDetectedEvent,
OkBugReportCreateResult,
+ OkBugReportDeleteResult,
+ OkBugReportListResult,
OkBugReportScreenshot,
OkBugReportSendMetadata,
OkBugReportSendResult,
@@ -1658,6 +1660,10 @@ export interface OkDesktopBridge {
metadata: OkBugReportSendMetadata;
}): Promise<OkBugReportSendResult>;
crashAck(request: { eventId: string }): Promise<OkBugReportCrashAckResult>;
+ /** The persisted report history (newest first) read from the sidecars. */
+ list(): Promise<OkBugReportListResult>;
+ /** Remove a persisted report's zip + sidecar by `id` (containment-checked). */
+ delete(id: string): Promise<OkBugReportDeleteResult>;
onCrashDetected(cb: (event: OkBugReportCrashDetectedEvent) => void): OkUnsubscribe;
};
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index 702865420..79f969e7e 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -75,6 +75,8 @@ import type {
LocalOpOkInitResponse,
OkBugReportCrashAckResult,
OkBugReportCreateResult,
+ OkBugReportDeleteResult,
+ OkBugReportListResult,
OkBugReportScreenshot,
OkBugReportSendResult,
OkFolderState,
@@ -916,6 +918,11 @@ export interface RequestChannels {
* - `{kind: 'capture-screenshot'}` → capture the sender window before the
* dialog paints; returns a downscaled preview (or `null`) and holds the
* full-res bytes in main for a later `create` to stage.
+ * - `{kind: 'list'}` → the persisted report history (newest first), read
+ * from the per-report sidecars in `~/.ok/bug-reports/`.
+ * - `{kind: 'delete', id}` → remove a persisted report's zip + sidecar by
+ * `id`, containment-checked.
+ * Later report operations widen this payload rather than adding channels.
* Never throws — every failure mode is discriminated so the dialog can
* render it; each preload method casts the union result to its own arm.
*/
@@ -926,6 +933,8 @@ export interface RequestChannels {
| OkBugReportSendResult
| OkBugReportCrashAckResult
| OkBugReportScreenshot
+ | OkBugReportListResult
+ | OkBugReportDeleteResult
| null;
};
/** Read the LRU-capped recent-projects list from app state. */