Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Attach an app screenshot to bug reports (#2657)

Andrew Mikofalvy64412434743a
diff --git a/.changeset/bug-report-screenshot.md b/.changeset/bug-report-screenshot.md
new file mode 100644
index 000000000..7d1803884
--- /dev/null
+++ b/.changeset/bug-report-screenshot.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Report a bug can now include a screenshot of the app. When you open the Report a bug dialog, OpenKnowledge captures the app exactly as it looked underneath the dialog and shows you a preview inside the compose step. The screenshot is included by default; uncheck it to leave it out. Because the preview shows precisely what will be attached, you can confirm the picture before sending it: a screenshot is an image of your screen and is not redacted the way logs are, so review it and uncheck it if anything on screen shouldn't be shared. When kept, the screenshot rides inside the report bundle at `extra/screenshot.png`, and like the rest of the bundle it never leaves your machine until you send the report.
diff --git a/packages/app/src/components/ReportBugDialog.dom.test.tsx b/packages/app/src/components/ReportBugDialog.dom.test.tsx
index d9b26e391..b7c4c2c7d 100644
--- a/packages/app/src/components/ReportBugDialog.dom.test.tsx
+++ b/packages/app/src/components/ReportBugDialog.dom.test.tsx
@@ -11,6 +11,7 @@ import { afterEach, describe, expect, mock, test } from 'bun:test';
import type {
OkBugReportCrashDetectedEvent,
OkBugReportCreateResult,
+ OkBugReportScreenshot,
OkBugReportSendMetadata,
OkBugReportSendResult,
ReportBundleSummary,
@@ -66,8 +67,20 @@ const CREATE_OK: OkBugReportCreateResult = {
zipSizeBytes: 7130316, // renders as "6.8 MB"
summary: SUMMARY,
};
+const SCREENSHOT: OkBugReportScreenshot = {
+ // A 1x1 transparent PNG stands in for the captured preview.
+ dataUrl:
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
+ width: 1200,
+ height: 800,
+};
-type CreateRequest = { level: 'standard' | 'full'; note?: string; includeCrashDump?: boolean };
+type CreateRequest = {
+ level: 'standard' | 'full';
+ note?: string;
+ includeCrashDump?: boolean;
+ includeScreenshot?: boolean;
+};
type SendRequest = { zipPath: string; metadata: OkBugReportSendMetadata };
interface BridgeLog {
@@ -76,12 +89,15 @@ interface BridgeLog {
revealed: string[];
opened: string[];
clipboard: string[];
+ screenshotCalls: number;
}
function installBridge(
handlers: {
create?: (request: CreateRequest) => Promise<OkBugReportCreateResult>;
send?: (request: SendRequest) => Promise<OkBugReportSendResult>;
+ /** Omit to model a build without capture (the gate reveals with no screenshot). */
+ captureScreenshot?: () => Promise<OkBugReportScreenshot | null>;
} = {},
): BridgeLog {
const log: BridgeLog = {
@@ -90,6 +106,7 @@ function installBridge(
revealed: [],
opened: [],
clipboard: [],
+ screenshotCalls: 0,
};
const bridge = {
bugReport: {
@@ -103,6 +120,16 @@ function installBridge(
? handlers.send(request)
: Promise.resolve({ ok: true as const, reference: 'OK-8H3KQD' });
},
+ // Only present when a handler is supplied, so the default suite exercises
+ // the no-capture reveal path (matching a non-desktop / older bridge).
+ ...(handlers.captureScreenshot
+ ? {
+ captureScreenshot: () => {
+ log.screenshotCalls += 1;
+ return handlers.captureScreenshot?.() ?? Promise.resolve(null);
+ },
+ }
+ : {}),
},
shell: {
showItemInFolder: (path: string) => {
@@ -179,6 +206,11 @@ describe('ReportBugDialog', () => {
afterEach(() => {
cleanup();
clearBridge();
+ // Drop any launcher stand-in a test appended so it can't stall the next
+ // test's capture (the gate waits for these to clear before shooting).
+ for (const el of document.querySelectorAll('[cmdk-root],[data-radix-popper-content-wrapper]')) {
+ el.remove();
+ }
});
test('compose state offers a labeled optional note, an always-on logs row, an off-by-default diagnostics checkbox, and the redaction note', async () => {
@@ -600,4 +632,115 @@ describe('ReportBugDialog', () => {
expect(screen.getByText(/6\.8 MB · secrets redacted · 2 files/)).not.toBeNull();
expect(screen.queryByText(/crash dump not redacted/)).toBeNull();
});
+
+ test('a captured screenshot shows a default-on preview + checkbox that ride into create', async () => {
+ const log = installBridge({ captureScreenshot: () => Promise.resolve(SCREENSHOT) });
+ await renderDialog();
+
+ // Captured exactly once — before the dialog was revealed.
+ expect(log.screenshotCalls).toBe(1);
+
+ const shot = screen.getByRole('checkbox', { name: 'Screenshot' });
+ expect(shot.getAttribute('aria-checked')).toBe('true');
+ const preview = screen.getByAltText('Preview of the screenshot');
+ expect(preview.getAttribute('src')).toBe(SCREENSHOT.dataUrl);
+
+ await createReport();
+ expect(log.createCalls).toEqual([{ level: 'standard', includeScreenshot: true }]);
+ });
+
+ test('unchecking the screenshot keeps it out of create', async () => {
+ const log = installBridge({ captureScreenshot: () => Promise.resolve(SCREENSHOT) });
+ await renderDialog();
+
+ await userEvent.click(screen.getByRole('checkbox', { name: 'Screenshot' }));
+ await createReport();
+
+ expect(log.createCalls).toEqual([{ level: 'standard', includeScreenshot: false }]);
+ });
+
+ test('without capture support neither the screenshot checkbox nor the flag appears', async () => {
+ const log = installBridge();
+ await renderDialog();
+
+ expect(screen.queryByRole('checkbox', { name: 'Screenshot' })).toBeNull();
+ await createReport();
+
+ expect(log.createCalls).toEqual([{ level: 'standard' }]);
+ expect(log.createCalls[0]).not.toHaveProperty('includeScreenshot');
+ });
+
+ test('the review card leaves the redaction claim unqualified for a screenshot-only bundle', async () => {
+ installBridge({
+ captureScreenshot: () => Promise.resolve(SCREENSHOT),
+ create: () =>
+ Promise.resolve({
+ ...CREATE_OK,
+ summary: { ...SUMMARY, files: [...SUMMARY.files, 'extra/screenshot.png'] },
+ }),
+ });
+ await renderDialog();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Create report' }));
+ await screen.findByRole('heading', { name: 'Review your report' });
+
+ // The screenshot rides under extra/, but the user already previewed it, so
+ // it must NOT trip the crash-dump "not redacted" wording.
+ expect(screen.getByText(/6\.8 MB · secrets redacted · 3 files/)).not.toBeNull();
+ expect(screen.queryByText(/crash dump not redacted/)).toBeNull();
+ });
+
+ test('the capture waits for the launcher (⌘K palette) to clear before revealing', async () => {
+ // Stand in for the command palette still animating out as the dialog opens
+ // (the reported leak: the palette was opened only to reach Report a bug).
+ const launcher = document.createElement('div');
+ launcher.setAttribute('cmdk-root', '');
+ document.body.appendChild(launcher);
+
+ const log = installBridge({ captureScreenshot: () => Promise.resolve(SCREENSHOT) });
+ const { ReportBugDialog } = await import('./ReportBugDialog');
+ render(
+ <TooltipProvider>
+ <ReportBugDialog open onOpenChange={() => {}} />
+ </TooltipProvider>,
+ );
+
+ // While the launcher is on screen the shot is held back: nothing captured
+ // and the dialog stays hidden.
+ await Promise.resolve();
+ expect(log.screenshotCalls).toBe(0);
+ expect(screen.queryByRole('dialog')).toBeNull();
+
+ // Launcher unmounts → capture fires and the dialog reveals with the preview.
+ launcher.remove();
+ await screen.findByRole('dialog');
+ expect(log.screenshotCalls).toBe(1);
+ expect(screen.getByRole('checkbox', { name: 'Screenshot' })).not.toBeNull();
+ });
+
+ test('a capture that rejects still reveals the dialog, with no screenshot option', async () => {
+ const log = installBridge({
+ captureScreenshot: () => Promise.reject(new Error('capture failed')),
+ });
+ await renderDialog();
+
+ // The gate's capture `.catch(() => settle(null))` must degrade gracefully:
+ // the dialog opens (no stranded user), just without a screenshot to offer.
+ expect(screen.getByRole('dialog')).not.toBeNull();
+ expect(screen.queryByRole('checkbox', { name: 'Screenshot' })).toBeNull();
+ expect(log.screenshotCalls).toBe(1);
+ });
+
+ test('the crash-invite variant skips capture entirely — opens instantly, no screenshot', async () => {
+ const log = installBridge({ captureScreenshot: () => Promise.resolve(SCREENSHOT) });
+ await renderDialog({ crashInvite: BOOT_INVITE });
+
+ // The crash invite opens itself the moment main reports a crash, so the
+ // gate must not hold it closed for a capture (that would delay an already
+ // unprompted dialog) nor offer a screenshot — the crash dump is its artifact.
+ expect(log.screenshotCalls).toBe(0);
+ expect(screen.queryByRole('checkbox', { name: 'Screenshot' })).toBeNull();
+ // Still the crash-invite compose (its banner renders).
+ expect(screen.getByText('OpenKnowledge quit unexpectedly last time.')).not.toBeNull();
+ });
});
diff --git a/packages/app/src/components/ReportBugDialog.tsx b/packages/app/src/components/ReportBugDialog.tsx
index 12de4edff..4f1954d8c 100644
--- a/packages/app/src/components/ReportBugDialog.tsx
+++ b/packages/app/src/components/ReportBugDialog.tsx
@@ -1,31 +1,135 @@
/**
- * Report-a-bug dialog — thin lazy-loading gate. The ~800-line dialog body
- * (phase machine, zip preview, upload-transport UI) is behind `React.lazy()`,
- * so it only enters the bundle graph the first time the dialog is opened —
- * keeping it out of the main app chunk (size-limit budget). Mirrors the
- * `ConsentDialog` / `ConsentDialogBody` split.
+ * Report-a-bug dialog — thin lazy-loading gate + screenshot capture-before-show.
+ *
+ * The ~800-line dialog body (phase machine, zip preview, upload-transport UI)
+ * is behind `React.lazy()`, so it only enters the bundle graph the first time
+ * the dialog is opened — keeping it out of the main app chunk (size-limit
+ * budget). Mirrors the `ConsentDialog` / `ConsentDialogBody` split.
+ *
+ * The gate is also the single chokepoint where the app screenshot is captured.
+ * Every trigger (command palette, help popover, navigator, error boundary,
+ * crash invite) flows through here, so capturing on open means one place owns
+ * it. The capture must exclude the dialog itself, so the gate holds the Radix
+ * overlay closed (`open={props.open && ready}`) until main has captured the
+ * page underneath — then reveals the dialog with the preview already in hand.
+ * Non-desktop (or an older bridge without `captureScreenshot`) reveals
+ * immediately with no screenshot; a hung capture reveals on a timeout.
*/
-import { lazy, Suspense, useState } from 'react';
+import type { OkBugReportScreenshot } from '@inkeep/open-knowledge-core';
+import { lazy, Suspense, useEffect, useRef, useState } from 'react';
import type { ReportBugDialogProps } from './ReportBugDialogBody';
const ReportBugDialogBody = lazy(() => import('./ReportBugDialogBody'));
+/**
+ * Ceiling on how long the dialog waits for the screenshot capture before
+ * opening anyway. `capturePage()` is normally tens of ms; this only guards a
+ * pathologically slow or stuck main so the user is never stranded staring at
+ * an un-opened dialog after clicking "Report a bug".
+ */
+const CAPTURE_REVEAL_TIMEOUT_MS = 1200;
+
+/**
+ * A launcher surface opened only to REACH this dialog — the ⌘K command palette
+ * (a cmdk root) or a help popover/menu (a Radix popper) — is still animating out
+ * when the dialog opens, and would leak into the screenshot if captured too
+ * soon. The capture waits for these to unmount; persistent context the user was
+ * genuinely in (a Settings dialog, an error-boundary card) is neither a cmdk
+ * root nor a popper, so it is captured, not waited on.
+ */
+const LAUNCHER_SELECTOR = '[cmdk-root],[data-radix-popper-content-wrapper]';
+
+/**
+ * Ceiling on how long the capture waits for a launcher to clear before shooting
+ * anyway. Comfortably outlasts a Radix exit animation (~150-200ms), so a launcher
+ * that never unmounts (or a missing animation event) still can't stall the shot.
+ */
+const CAPTURE_SETTLE_DEADLINE_MS = 500;
+
export function ReportBugDialog(props: ReportBugDialogProps) {
// Pull the heavy chunk only once first opened — a ~1-frame delay on first
// open is worth keeping it out of first paint for a rarely-used surface.
// Once opened, the body stays mounted so Radix's close animation and
// focus-return to the trigger behave exactly as before the split.
const [everOpened, setEverOpened] = useState(props.open);
+ // `ready` gates the Radix overlay so the screenshot is captured BEFORE the
+ // dialog paints over the app; `screenshot` is the captured preview (or null).
+ const [ready, setReady] = useState(false);
+ const [screenshot, setScreenshot] = useState<OkBugReportScreenshot | null>(null);
+ // Bumped on every open transition (and on close/unmount cleanup) so a capture
+ // that resolves after its open cycle ended drops its result.
+ const openCycleRef = useRef(0);
+
if (props.open && !everOpened) {
setEverOpened(true);
}
+
+ useEffect(() => {
+ if (!props.open) {
+ setReady(false);
+ return;
+ }
+ const cycle = ++openCycleRef.current;
+ const capture = window.okDesktop?.bugReport?.captureScreenshot;
+ // Skip the capture-before-show for the crash invite: it opens itself,
+ // unprompted, the moment main pushes a crash-detected event, so holding it
+ // closed for a capture would delay an already-surprising dialog and race
+ // with whatever the user is mid-interaction on (and a post-crash screenshot
+ // adds little over the crash dump the invite already offers). Reveal at once
+ // with no screenshot, exactly as a build without capture would.
+ if (typeof capture !== 'function' || props.crashInvite !== undefined) {
+ // Web, or a desktop build predating this method: nothing to capture, so
+ // reveal at once and offer no screenshot option.
+ setScreenshot(null);
+ setReady(true);
+ return;
+ }
+ setScreenshot(null);
+ // First of the timeout / capture-resolve to fire reveals the dialog; the
+ // other is ignored. Guarded on the cycle so a stale close can't reveal.
+ let settled = false;
+ const settle = (shot: OkBugReportScreenshot | null) => {
+ if (settled || openCycleRef.current !== cycle) return;
+ settled = true;
+ setScreenshot(shot);
+ setReady(true);
+ };
+ const revealTimer = setTimeout(() => settle(null), CAPTURE_REVEAL_TIMEOUT_MS);
+ // Hold the capture until the launcher that was opened to reach this dialog
+ // has finished animating out and unmounted, then take the shot one frame
+ // later (so the removal has painted). Bounded by a deadline so a launcher
+ // that never clears can't block the shot.
+ const startedAt = performance.now();
+ let rafId = 0;
+ const settleThenCapture = () => {
+ if (openCycleRef.current !== cycle) return;
+ const pastDeadline = performance.now() - startedAt >= CAPTURE_SETTLE_DEADLINE_MS;
+ if (document.querySelector(LAUNCHER_SELECTOR) !== null && !pastDeadline) {
+ rafId = requestAnimationFrame(settleThenCapture);
+ return;
+ }
+ rafId = requestAnimationFrame(() => {
+ if (openCycleRef.current !== cycle) return;
+ capture()
+ .then(settle)
+ .catch(() => settle(null));
+ });
+ };
+ rafId = requestAnimationFrame(settleThenCapture);
+ return () => {
+ openCycleRef.current += 1;
+ clearTimeout(revealTimer);
+ cancelAnimationFrame(rafId);
+ };
+ }, [props.open, props.crashInvite]);
+
if (!everOpened) {
return null;
}
return (
<Suspense fallback={null}>
- <ReportBugDialogBody {...props} />
+ <ReportBugDialogBody {...props} open={props.open && ready} screenshot={screenshot} />
</Suspense>
);
}
diff --git a/packages/app/src/components/ReportBugDialogBody.tsx b/packages/app/src/components/ReportBugDialogBody.tsx
index f0fddffa3..914f57cc3 100644
--- a/packages/app/src/components/ReportBugDialogBody.tsx
+++ b/packages/app/src/components/ReportBugDialogBody.tsx
@@ -20,8 +20,10 @@
import type {
OkBugReportCrashDetectedEvent,
+ OkBugReportScreenshot,
ReportBundleSummary,
} from '@inkeep/open-knowledge-core';
+import { BUG_REPORT_SCREENSHOT_ZIP_ENTRY } from '@inkeep/open-knowledge-core';
import { Plural, Trans, useLingui } from '@lingui/react/macro';
import {
AlertCircleIcon,
@@ -145,14 +147,19 @@ function zipBasename(zipPath: string): string {
}
/**
- * The one artifact bundled raw is the opted-in crash minidump under `extra/`
- * — process memory that text redaction cannot scrub. The review/email/failure
- * cards must qualify their "secrets redacted" claim whenever one is present.
- * The summary's file inventory, not the dialog's checkbox state, is the
- * truth: opting in with no dump on disk adds nothing to the bundle.
+ * The one artifact whose rawness the cards must call out is the opted-in crash
+ * minidump under `extra/` — process memory that text redaction cannot scrub.
+ * The review/email/failure cards must qualify their "secrets redacted" claim
+ * whenever one is present. The opted-in screenshot also lands under `extra/`
+ * but is excluded here: the user previewed it before including it, so it needs
+ * no after-the-fact "not redacted" caveat. The summary's file inventory, not
+ * the dialog's checkbox state, is the truth: opting in with no dump on disk
+ * adds nothing to the bundle.
*/
function reportIncludesRawDump(report: CreatedReport): boolean {
- return report.summary.files.some((file) => file.startsWith('extra/'));
+ return report.summary.files.some(
+ (file) => file.startsWith('extra/') && file !== BUG_REPORT_SCREENSHOT_ZIP_ENTRY,
+ );
}
export interface ReportBugDialogProps {
@@ -177,6 +184,15 @@ export interface ReportBugDialogProps {
* dismiss. The event's kind and id fold into the report's note.
*/
crashInvite?: OkBugReportCrashDetectedEvent;
+ /**
+ * Screenshot of the app captured (by the gate) before this dialog painted,
+ * or `null` when none is available (web, capture failed, or capture timed
+ * out). When present, compose shows a preview + a default-on "Screenshot"
+ * checkbox; keeping it checked stages the full-resolution image into the
+ * bundle. The gate owns capture so every trigger gets the screenshot without
+ * threading it through each mount site.
+ */
+ screenshot?: OkBugReportScreenshot | null;
}
function ReportBugDialog({
@@ -185,12 +201,16 @@ function ReportBugDialog({
systemWide = false,
crashContext,
crashInvite,
+ screenshot = null,
}: ReportBugDialogProps) {
const { t } = useLingui();
const [phase, setPhase] = useState<Phase>(COMPOSE_IDLE);
const [note, setNote] = useState('');
const [detailed, setDetailed] = useState(crashContext !== undefined || crashInvite !== undefined);
const [includeDump, setIncludeDump] = useState(false);
+ // Default-on per the spec: when a screenshot was captured it rides along
+ // unless the user unchecks it. Only ever sent to `create` when one exists.
+ const [includeScreenshot, setIncludeScreenshot] = useState(true);
const [sentFraction, setSentFraction] = useState(0);
// Bumped whenever the current async create/send no longer owns the dialog
// (cancel, close): the awaiting handler compares and drops its result.
@@ -202,6 +222,8 @@ function ReportBugDialog({
const detailedHintId = useId();
const dumpId = useId();
const dumpHintId = useId();
+ const screenshotId = useId();
+ const screenshotHintId = useId();
const referenceId = useId();
const whatToIncludeId = useId();
@@ -241,6 +263,9 @@ function ReportBugDialog({
setNote('');
setDetailed(crashContext !== undefined || crashInvite !== undefined);
setIncludeDump(false);
+ // Re-default the screenshot to on so the next open (which captures a
+ // fresh screenshot) starts checked, matching the compose default.
+ setIncludeScreenshot(true);
}
setPhase(COMPOSE_IDLE);
}
@@ -265,6 +290,9 @@ function ReportBugDialog({
// Only the crash invite ever asks for the dump — the plain compose has
// no opt-in surface, so it must not even send the flag.
...(crashInvite !== undefined ? { includeCrashDump: includeDump } : {}),
+ // Only send the flag when a screenshot was actually captured — absent
+ // means main has nothing staged, so it must not claim an inclusion.
+ ...(screenshot !== null ? { includeScreenshot } : {}),
});
if (opSeqRef.current !== seq) return;
if (result.ok) {
@@ -510,6 +538,40 @@ function ReportBugDialog({
</p>
</div>
</div>
+ {screenshot !== null && (
+ <div className="flex items-start gap-2.5">
+ <Checkbox
+ id={screenshotId}
+ checked={includeScreenshot}
+ onCheckedChange={(value) => setIncludeScreenshot(value === true)}
+ aria-describedby={screenshotHintId}
+ disabled={phase.creating}
+ className="mt-0.5"
+ />
+ <div className="flex min-w-0 flex-col gap-1.5">
+ <label htmlFor={screenshotId} className="text-sm font-medium">
+ <Trans>Screenshot</Trans>
+ </label>
+ <p id={screenshotHintId} className="text-1sm text-muted-foreground">
+ <Trans>
+ A picture of the app from just before you opened this. It isn't redacted,
+ so check the preview and uncheck it if anything shouldn't be shared.
+ </Trans>
+ </p>
+ {/* Preview dims when excluded so the checkbox state reads
+ at a glance; the label above already names it. */}
+ <div className="mt-0.5 overflow-hidden rounded-md border bg-muted/40">
+ <img
+ src={screenshot.dataUrl}
+ alt={t`Preview of the screenshot`}
+ className={`block max-h-44 w-full object-contain transition-opacity motion-reduce:transition-none ${
+ includeScreenshot ? 'opacity-100' : 'opacity-40'
+ }`}
+ />
+ </div>
+ </div>
+ </div>
+ )}
{crashInvite !== undefined && (
<div className="flex items-start gap-2.5">
<Checkbox
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index 3c9b08632..93622162d 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -25,6 +25,7 @@ import type {
OkBugReportCrashAckResult,
OkBugReportCrashDetectedEvent,
OkBugReportCreateResult,
+ OkBugReportScreenshot,
OkBugReportSendMetadata,
OkBugReportSendResult,
OkFolderState,
@@ -1160,9 +1161,10 @@ export interface OkDesktopBridge {
/**
* In-app "Report a bug" — `create` builds the redacted diagnostic zip
- * (optional crash-dump opt-in via `includeCrashDump`); `send` uploads it
- * with an email fallback; `onCrashDetected` / `crashAck` carry the
- * crash-invite round-trip.
+ * (optional crash-dump opt-in via `includeCrashDump`, optional app
+ * screenshot via `includeScreenshot`); `captureScreenshot` grabs the app
+ * before the dialog paints; `send` uploads it with an email fallback;
+ * `onCrashDetected` / `crashAck` carry the crash-invite round-trip.
* Canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.
* Mirrored here per the OkDesktopBridge 3-way-mirror invariant.
*/
@@ -1171,7 +1173,9 @@ export interface OkDesktopBridge {
level: ReportBundleLevel;
note?: string;
includeCrashDump?: boolean;
+ includeScreenshot?: boolean;
}): Promise<OkBugReportCreateResult>;
+ captureScreenshot(): Promise<OkBugReportScreenshot | null>;
send(request: {
zipPath: string;
metadata: OkBugReportSendMetadata;
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 480e11de0..6eefa9923 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -864,6 +864,7 @@
"IreQBq": ["Repository"],
"It9ARY": ["Toggle the right document panel."],
"Ix0K8o": ["Hide external URL nodes"],
+ "IxyZXD": ["Screenshot"],
"J2MgzQ": ["Undo all edits on ", ["docName"]],
"J2Mv98": ["Name (e.g. ", ["login"], ")"],
"J2eKUI": ["File"],
@@ -1450,6 +1451,7 @@
"WqLq6M": ["Open with AI ", ["displayName"]],
"Wt5W56": ["Sync is off — your edits will not sync to the remote repository."],
"Wtw22s": ["Installing"],
+ "WuntOK": ["Preview of the screenshot"],
"WyQxwa": ["Connect this project to GitHub to share."],
"WyXG7w": ["Close all"],
"Wyxs0x": ["Path cannot contain \"..\""],
@@ -2705,6 +2707,9 @@
"yz7wBu": ["Close"],
"yzF66j": ["Link"],
"yzGPkm": ["Expand graph"],
+ "yzYE4B": [
+ "A picture of the app from just before you opened this. It isn't redacted, so check the preview and uncheck it if anything shouldn't be shared."
+ ],
"z-lawV": ["worktree"],
"z0a2EA": ["Diagram from Mermaid source — flowchart, sequence, class, state, ER, gantt, pie."],
"z1uNN0": ["No emoji found."],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index c614b78cf..3b12ad6ee 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -647,6 +647,10 @@ msgstr "A non-empty folder already exists at this path. Pick a different folder.
msgid "A personal color-theme picker — not shared with your project. When on, it appears under Plugins in the sidebar."
msgstr "A personal color-theme picker — not shared with your project. When on, it appears under Plugins in the sidebar."
+#: src/components/ReportBugDialogBody.tsx
+msgid "A picture of the app from just before you opened this. It isn't redacted, so check the preview and uncheck it if anything shouldn't be shared."
+msgstr "A picture of the app from just before you opened this. It isn't redacted, so check the preview and uncheck it if anything shouldn't be shared."
+
#: src/components/CreateProjectDialog.tsx
msgid "A project already exists at this location. Pick a different parent folder."
msgstr "A project already exists at this location. Pick a different parent folder."
@@ -5858,6 +5862,10 @@ msgstr "Preparing share URL..."
msgid "Preview browsers can't auto-copy. Use Cmd/Ctrl+C on the URL above, or open OK in the desktop app."
msgstr "Preview browsers can't auto-copy. Use Cmd/Ctrl+C on the URL above, or open OK in the desktop app."
+#: src/components/ReportBugDialogBody.tsx
+msgid "Preview of the screenshot"
+msgstr "Preview of the screenshot"
+
#: src/components/ConsentDialogBody.tsx
msgid "Preview unavailable: {errorDetail}"
msgstr "Preview unavailable: {errorDetail}"
@@ -6610,6 +6618,10 @@ msgstr "Scope"
msgid "Scope: "
msgstr "Scope: "
+#: src/components/ReportBugDialogBody.tsx
+msgid "Screenshot"
+msgstr "Screenshot"
+
#: src/components/CommandPalette.tsx
#: src/components/settings/SettingsDialogShell.tsx
#: src/components/SidebarSearchBar.tsx
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 915923f24..54cabc030 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -864,6 +864,7 @@
"IreQBq": ["Ŕēƥōśĩţōŕŷ"],
"It9ARY": ["Ţōĝĝĺē ţĥē ŕĩĝĥţ ďōćũḿēńţ ƥàńēĺ."],
"Ix0K8o": ["Ĥĩďē ēxţēŕńàĺ ŨŔĹ ńōďēś"],
+ "IxyZXD": ["Śćŕēēńśĥōţ"],
"J2MgzQ": ["Ũńďō àĺĺ ēďĩţś ōń ", ["docName"]],
"J2Mv98": ["Ńàḿē (ē.ĝ. ", ["login"], ")"],
"J2eKUI": ["Ƒĩĺē"],
@@ -1450,6 +1451,7 @@
"WqLq6M": ["Ōƥēń ŵĩţĥ ÀĨ ", ["displayName"]],
"Wt5W56": ["Śŷńć ĩś ōƒƒ — ŷōũŕ ēďĩţś ŵĩĺĺ ńōţ śŷńć ţō ţĥē ŕēḿōţē ŕēƥōśĩţōŕŷ."],
"Wtw22s": ["Ĩńśţàĺĺĩńĝ"],
+ "WuntOK": ["Ƥŕēvĩēŵ ōƒ ţĥē śćŕēēńśĥōţ"],
"WyQxwa": ["Ćōńńēćţ ţĥĩś ƥŕōĴēćţ ţō ĜĩţĤũƀ ţō śĥàŕē."],
"WyXG7w": ["Ćĺōśē àĺĺ"],
"Wyxs0x": ["Ƥàţĥ ćàńńōţ ćōńţàĩń \"..\""],
@@ -2705,6 +2707,9 @@
"yz7wBu": ["Ćĺōśē"],
"yzF66j": ["Ĺĩńķ"],
"yzGPkm": ["Ēxƥàńď ĝŕàƥĥ"],
+ "yzYE4B": [
+ "À ƥĩćţũŕē ōƒ ţĥē àƥƥ ƒŕōḿ Ĵũśţ ƀēƒōŕē ŷōũ ōƥēńēď ţĥĩś. Ĩţ ĩśń'ţ ŕēďàćţēď, śō ćĥēćķ ţĥē ƥŕēvĩēŵ àńď ũńćĥēćķ ĩţ ĩƒ àńŷţĥĩńĝ śĥōũĺďń'ţ ƀē śĥàŕēď."
+ ],
"z-lawV": ["ŵōŕķţŕēē"],
"z0a2EA": ["Ďĩàĝŕàḿ ƒŕōḿ Ḿēŕḿàĩď śōũŕćē — ƒĺōŵćĥàŕţ, śēǫũēńćē, ćĺàśś, śţàţē, ĒŔ, ĝàńţţ, ƥĩē."],
"z1uNN0": ["Ńō ēḿōĴĩ ƒōũńď."],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index f92ee32fa..09f58f11a 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -642,6 +642,10 @@ msgstr ""
msgid "A personal color-theme picker — not shared with your project. When on, it appears under Plugins in the sidebar."
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "A picture of the app from just before you opened this. It isn't redacted, so check the preview and uncheck it if anything shouldn't be shared."
+msgstr ""
+
#: src/components/CreateProjectDialog.tsx
msgid "A project already exists at this location. Pick a different parent folder."
msgstr ""
@@ -5853,6 +5857,10 @@ msgstr ""
msgid "Preview browsers can't auto-copy. Use Cmd/Ctrl+C on the URL above, or open OK in the desktop app."
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Preview of the screenshot"
+msgstr ""
+
#: src/components/ConsentDialogBody.tsx
msgid "Preview unavailable: {errorDetail}"
msgstr ""
@@ -6605,6 +6613,10 @@ msgstr ""
msgid "Scope: "
msgstr ""
+#: src/components/ReportBugDialogBody.tsx
+msgid "Screenshot"
+msgstr ""
+
#: src/components/CommandPalette.tsx
#: src/components/settings/SettingsDialogShell.tsx
#: src/components/SidebarSearchBar.tsx
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index d3bed056f..b7d5a2449 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -447,6 +447,7 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
},
bugReport: {
create: async () => ({ ok: false as const, error: 'test mock' }),
+ captureScreenshot: async () => null,
send: async () => ({
ok: false as const,
reason: 'send-failed' as const,
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 04ce5775d..7fc44c0c1 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -21,6 +21,7 @@ import type {
OkBugReportCrashAckResult,
OkBugReportCrashDetectedEvent,
OkBugReportCreateResult,
+ OkBugReportScreenshot,
OkBugReportSendMetadata,
OkBugReportSendResult,
ReportBundleLevel,
@@ -1346,9 +1347,10 @@ export interface OkDesktopBridge {
/**
* In-app "Report a bug" — `create` builds the redacted diagnostic zip
- * (optional crash-dump opt-in via `includeCrashDump`); `send` uploads it
- * with an email fallback; `onCrashDetected` / `crashAck` carry the
- * crash-invite round-trip.
+ * (optional crash-dump opt-in via `includeCrashDump`, optional app
+ * screenshot via `includeScreenshot`); `captureScreenshot` grabs the app
+ * before the dialog paints; `send` uploads it with an email fallback;
+ * `onCrashDetected` / `crashAck` carry the crash-invite round-trip.
* Canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.
* Mirrored here per the OkDesktopBridge 3-way-mirror invariant.
*/
@@ -1357,7 +1359,9 @@ export interface OkDesktopBridge {
level: ReportBundleLevel;
note?: string;
includeCrashDump?: boolean;
+ includeScreenshot?: boolean;
}): Promise<OkBugReportCreateResult>;
+ captureScreenshot(): Promise<OkBugReportScreenshot | null>;
send(request: {
zipPath: string;
metadata: OkBugReportSendMetadata;
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 8e4df1a93..942c519df 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -28,6 +28,7 @@ export type {
OkBugReportCrashAckResult,
OkBugReportCrashDetectedEvent,
OkBugReportCreateResult,
+ OkBugReportScreenshot,
OkBugReportSendFallbackReason,
OkBugReportSendMetadata,
OkBugReportSendResult,
@@ -36,7 +37,11 @@ export type {
SerializedError,
SerializedErrorTruncation,
} from './logger-types.ts';
-export { LOG_LEVELS } from './logger-types.ts';
+export {
+ BUG_REPORT_SCREENSHOT_ZIP_ENTRY,
+ BUG_REPORT_SCREENSHOT_ZIP_NAME,
+ LOG_LEVELS,
+} from './logger-types.ts';
// Renderer/browser console-capture helpers (level mapping, structured-message
// unwrap, batch bounds) shared by the desktop main listener, the server
// `/api/client-logs` ingest, and the web renderer forwarder.
diff --git a/packages/core/src/logger-types.ts b/packages/core/src/logger-types.ts
index b0a94a05d..06d5d1c3d 100644
--- a/packages/core/src/logger-types.ts
+++ b/packages/core/src/logger-types.ts
@@ -78,6 +78,30 @@ export interface ReportBundleSummary {
generatedAt: string;
}
+/**
+ * Zip name of the opted-in app screenshot inside a bug-report bundle, and its
+ * full entry path once the bundle collector prefixes every `extraFiles` entry
+ * with `extra/`. Named here so main (which stages the screenshot) and the
+ * renderer (which must tell a screenshot apart from the raw crash dump in the
+ * review card's `summary.files` inventory) agree on the exact string.
+ */
+export const BUG_REPORT_SCREENSHOT_ZIP_NAME = 'screenshot.png';
+export const BUG_REPORT_SCREENSHOT_ZIP_ENTRY = `extra/${BUG_REPORT_SCREENSHOT_ZIP_NAME}`;
+
+/**
+ * A captured picture of the app window handed to the renderer for the report
+ * dialog's include-a-screenshot preview. `dataUrl` is a downscaled PNG for the
+ * `<img>` preview only; the full-resolution bytes stay in main and are staged
+ * into the bundle only when the user keeps the screenshot checked. `width` /
+ * `height` are the capture's logical (DIP) dimensions, so the preview can hold
+ * the real aspect ratio without a layout shift.
+ */
+export interface OkBugReportScreenshot {
+ dataUrl: string;
+ width: number;
+ height: number;
+}
+
/**
* Result of the desktop `ok:bug-report:dispatch` create operation. Never
* thrown across the IPC boundary — every failure mode is discriminated so the
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 8c647a758..67f822ca3 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -216,6 +216,8 @@ import { formatInstanceAppName, resolveInstanceLabel } from './instance-identity
import { deriveInstanceUserDataDir } from './instance-isolation.ts';
import { registerIntegrationsSettings } from './integrations-settings.ts';
import {
+ type BugReportScreenshotEntry,
+ handleBugReportCaptureScreenshot,
handleBugReportCrashAck,
handleBugReportCreate,
handleBugReportSend,
@@ -925,6 +927,24 @@ let mcpWiringHandle: RunMcpWiringHandle | null = null;
*/
let crashDetection: CrashDetection | null = null;
+/**
+ * Full-resolution PNG bytes of the app screenshot captured when a window's
+ * report-a-bug dialog opened, keyed by the sender `webContents.id`. Held in
+ * main (never handed to the renderer as a path) until the matching `create`
+ * stages it into the bundle — mirrors the trust model of the crash minidump.
+ * The renderer only ever receives a downscaled data-URL preview. Each entry
+ * carries the PNG plus its `destroyed`-listener reaper (so re-capture can drop
+ * the stale listener). A capture is kept (not dropped on consume) so a
+ * re-create after "Back" reuses the same open-time screenshot the user
+ * previewed; it is overwritten by the next open's capture and deleted when the
+ * window's contents are destroyed, so at most one screenshot per live window
+ * sits in memory.
+ */
+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;
+
/**
* Active-editor target snapshot pushed by the renderer via
* `ok:editor:active-target-changed`. Drives the macOS File menu's state-aware
@@ -3819,6 +3839,25 @@ function registerIpcHandlers() {
request,
);
}
+ if (request.kind === 'capture-screenshot') {
+ // Captured before the report dialog paints (the gate awaits this reply
+ // before revealing the Radix overlay), so the picture is the app state
+ // underneath the dialog, not the dialog itself. The store/listener
+ // lifecycle lives in the unit-tested `handleBugReportCaptureScreenshot`;
+ // this arm only supplies the Electron seams.
+ const captureWin = BrowserWindow.fromWebContents(event.sender);
+ if (!captureWin) return null;
+ const sender = event.sender;
+ return handleBugReportCaptureScreenshot({
+ store: bugReportScreenshots,
+ senderId: sender.id,
+ capturePage: () => captureWin.webContents.capturePage(),
+ previewWidth: BUG_REPORT_SCREENSHOT_PREVIEW_WIDTH,
+ registerCleanup: (cleanup) => sender.once('destroyed', cleanup),
+ unregisterCleanup: (cleanup) => sender.removeListener('destroyed', cleanup),
+ logger: getLogger('bug-report'),
+ });
+ }
const win = BrowserWindow.fromWebContents(event.sender);
const ctx =
win && wm ? wm.getContextForBrowserWindow(win as unknown as BrowserWindowLike) : null;
@@ -3831,6 +3870,9 @@ function registerIpcHandlers() {
channel: channelFromVersion(app.getVersion()),
},
newestMinidumpPath: () => crashDetection?.newestMinidumpPath() ?? null,
+ // 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,
logger: getLogger('bug-report'),
},
request,
diff --git a/packages/desktop/src/main/ipc/bug-report.test.ts b/packages/desktop/src/main/ipc/bug-report.test.ts
index fc9ec6c72..3d82abc45 100644
--- a/packages/desktop/src/main/ipc/bug-report.test.ts
+++ b/packages/desktop/src/main/ipc/bug-report.test.ts
@@ -33,8 +33,12 @@ import { createCrashDetection } from '../crash-detection.ts';
import { handleShellOpenExternal } from '../shell-allowlist.ts';
import {
type BugReportCreateDeps,
+ type BugReportScreenshotEntry,
type BugReportSendDeps,
+ type CapturableImage,
+ type CaptureScreenshotDeps,
DEFAULT_BUG_REPORT_INTAKE_URL,
+ handleBugReportCaptureScreenshot,
handleBugReportCrashAck,
handleBugReportCreate,
handleBugReportSend,
@@ -1020,6 +1024,208 @@ describe('handleBugReportCreate — crash-dump opt-in', () => {
});
});
+describe('handleBugReportCreate — screenshot opt-in', () => {
+ // A PNG signature wrapping a would-be-redacted token: the screenshot must
+ // arrive byte-identical — images ride the `extra/` seam raw, never scrubbed.
+ const pngBytes = Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ Buffer.from('sk-ant-api03-abcdefghijklmnopqrstuvwx'),
+ Buffer.from([0x00, 0x1f, 0x8b]),
+ ]);
+
+ test('includeScreenshot stages the capture byte-for-byte at extra/screenshot.png', async () => {
+ const deps = makeDeps({ screenshotPngBytes: () => pngBytes });
+
+ const result = await handleBugReportCreate(deps, {
+ kind: 'create',
+ level: 'standard',
+ includeScreenshot: true,
+ });
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ expect(listZipEntries(result.zipPath)).toContain('extra/screenshot.png');
+ expect(readZipEntryBytes(result.zipPath, 'extra/screenshot.png').equals(pngBytes)).toBe(true);
+ });
+
+ test('without the opt-in no screenshot is included even when one was captured', async () => {
+ const deps = makeDeps({ screenshotPngBytes: () => pngBytes });
+
+ const result = await handleBugReportCreate(deps, { kind: 'create', level: 'standard' });
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ expect(listZipEntries(result.zipPath).some((e) => e.startsWith('extra/'))).toBe(false);
+ });
+
+ test('opting in with no captured screenshot still builds the bundle', async () => {
+ const deps = makeDeps({ screenshotPngBytes: () => null });
+
+ const result = await handleBugReportCreate(deps, {
+ kind: 'create',
+ level: 'standard',
+ includeScreenshot: true,
+ });
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ expect(listZipEntries(result.zipPath).some((e) => e.startsWith('extra/'))).toBe(false);
+ });
+
+ test('an opted-in screenshot and crash dump both land under extra/', async () => {
+ const dumpPath = join(makeTmpDir(), 'renderer-crash.dmp');
+ const dumpBytes = Buffer.from([0x4d, 0x44, 0x4d, 0x50, 0x00, 0xff]);
+ writeFileSync(dumpPath, dumpBytes);
+ const deps = makeDeps({
+ newestMinidumpPath: () => dumpPath,
+ screenshotPngBytes: () => pngBytes,
+ });
+
+ const result = await handleBugReportCreate(deps, {
+ kind: 'create',
+ level: 'standard',
+ includeCrashDump: true,
+ includeScreenshot: true,
+ });
+
+ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);
+ const entries = listZipEntries(result.zipPath);
+ expect(entries).toContain('extra/screenshot.png');
+ expect(entries).toContain('extra/renderer-crash.dmp');
+ expect(readZipEntryBytes(result.zipPath, 'extra/screenshot.png').equals(pngBytes)).toBe(true);
+ expect(readZipEntryBytes(result.zipPath, 'extra/renderer-crash.dmp').equals(dumpBytes)).toBe(
+ true,
+ );
+ });
+
+ test('a non-boolean includeScreenshot is refused as invalid-request', async () => {
+ const deps = makeDeps({ screenshotPngBytes: () => pngBytes });
+
+ const result = await handleBugReportCreate(deps, {
+ kind: 'create',
+ level: 'standard',
+ includeScreenshot: 'yes',
+ } as unknown as Parameters<typeof handleBugReportCreate>[1]);
+
+ expect(result).toEqual({ ok: false, error: 'invalid-request' });
+ });
+});
+
+describe('handleBugReportCaptureScreenshot', () => {
+ function fakeImage(spec: {
+ png: Buffer;
+ width: number;
+ height: number;
+ dataUrl?: string;
+ }): CapturableImage {
+ return {
+ toPNG: () => spec.png,
+ getSize: () => ({ width: spec.width, height: spec.height }),
+ resize: ({ width }) => fakeImage({ ...spec, width, dataUrl: `resized:${width}` }),
+ toDataURL: () => spec.dataUrl ?? `full:${spec.width}x${spec.height}`,
+ };
+ }
+
+ function makeCaptureDeps(overrides: Partial<CaptureScreenshotDeps> = {}): {
+ deps: CaptureScreenshotDeps;
+ store: Map<number, BugReportScreenshotEntry>;
+ registered: Array<() => void>;
+ unregistered: Array<() => void>;
+ } {
+ const store = new Map<number, BugReportScreenshotEntry>();
+ const registered: Array<() => void> = [];
+ const unregistered: Array<() => void> = [];
+ return {
+ store,
+ registered,
+ unregistered,
+ deps: {
+ store,
+ senderId: 7,
+ previewWidth: 720,
+ capturePage: async () =>
+ fakeImage({ png: Buffer.from([1, 2, 3]), width: 1000, height: 800 }),
+ registerCleanup: (cb) => registered.push(cb),
+ unregisterCleanup: (cb) => unregistered.push(cb),
+ ...overrides,
+ },
+ };
+ }
+
+ test('a successful capture stores full-res bytes, registers a reaper, and returns a downscaled preview', async () => {
+ const { deps, store, registered } = makeCaptureDeps();
+
+ const result = await handleBugReportCaptureScreenshot(deps);
+
+ // Wide capture (1000 > 720) downscales for the preview data-URL...
+ expect(result).toEqual({ dataUrl: 'resized:720', width: 1000, height: 800 });
+ // ...while the FULL-resolution bytes are what get stored for the bundle.
+ expect(store.get(7)?.png.equals(Buffer.from([1, 2, 3]))).toBe(true);
+ expect(registered).toHaveLength(1);
+ });
+
+ test('a capture no wider than the preview cap is not resized', async () => {
+ const { deps } = makeCaptureDeps({
+ capturePage: async () => fakeImage({ png: Buffer.from([9]), width: 640, height: 480 }),
+ });
+
+ expect(await handleBugReportCaptureScreenshot(deps)).toEqual({
+ dataUrl: 'full:640x480',
+ width: 640,
+ height: 480,
+ });
+ });
+
+ test('a zero-byte capture returns null and stores nothing', async () => {
+ const { deps, store } = makeCaptureDeps({
+ capturePage: async () => fakeImage({ png: Buffer.alloc(0), width: 800, height: 600 }),
+ });
+
+ expect(await handleBugReportCaptureScreenshot(deps)).toBeNull();
+ expect(store.has(7)).toBe(false);
+ });
+
+ test('re-capture on the same window unregisters the prior reaper before registering the next', async () => {
+ const { deps, store, registered, unregistered } = makeCaptureDeps();
+
+ await handleBugReportCaptureScreenshot(deps);
+ const firstReaper = registered[0];
+ await handleBugReportCaptureScreenshot(deps);
+
+ // The first capture's listener is removed, so repeated opens don't
+ // accumulate MaxListeners-worth of reapers on one WebContents.
+ expect(unregistered).toContain(firstReaper);
+ expect(registered).toHaveLength(2);
+ expect(store.size).toBe(1);
+ });
+
+ test('the registered reaper deletes the window entry on window close', async () => {
+ const { deps, store, registered } = makeCaptureDeps();
+
+ await handleBugReportCaptureScreenshot(deps);
+ expect(store.has(7)).toBe(true);
+ registered[0]?.(); // simulate the 'destroyed' event firing
+ expect(store.has(7)).toBe(false);
+ });
+
+ test('a capturePage rejection resolves to null, is logged, and never throws', async () => {
+ const warnings: Array<{ payload: Record<string, unknown>; message: string }> = [];
+ const { deps, store } = makeCaptureDeps({
+ capturePage: async () => {
+ throw new Error('offscreen surface');
+ },
+ logger: {
+ info: () => {},
+ warn: (payload, message) => {
+ warnings.push({ payload, message });
+ },
+ },
+ });
+
+ expect(await handleBugReportCaptureScreenshot(deps)).toBeNull();
+ expect(store.has(7)).toBe(false);
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]?.payload.err).toContain('offscreen surface');
+ });
+});
+
describe('handleBugReportCreate — failure modes', () => {
test('an unwritable destination maps to a discriminated error instead of throwing', async () => {
const blockerFile = join(makeTmpDir(), 'not-a-dir');
diff --git a/packages/desktop/src/main/ipc/bug-report.ts b/packages/desktop/src/main/ipc/bug-report.ts
index 38548a6a3..9a2f751ba 100644
--- a/packages/desktop/src/main/ipc/bug-report.ts
+++ b/packages/desktop/src/main/ipc/bug-report.ts
@@ -16,20 +16,24 @@
* window-manager context; the renderer never passes a project path.
*/
-import { readFile, realpath, stat } from 'node:fs/promises';
-import { basename } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { readFile, realpath, stat, unlink, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { basename, join } from 'node:path';
import {
type BundleLogger,
collectReportBundle,
defaultBugReportZipPath,
redactContent,
} from '@inkeep/open-knowledge';
-import type {
- OkBugReportCrashAckResult,
- OkBugReportCreateResult,
- OkBugReportSendMetadata,
- OkBugReportSendResult,
- ReportBundleLevel,
+import {
+ BUG_REPORT_SCREENSHOT_ZIP_NAME,
+ type OkBugReportCrashAckResult,
+ type OkBugReportCreateResult,
+ type OkBugReportScreenshot,
+ type OkBugReportSendMetadata,
+ type OkBugReportSendResult,
+ type ReportBundleLevel,
} from '@inkeep/open-knowledge-core';
import { logIpcError } from '../ipc-log.ts';
import { isPathWithinProject } from '../path-containment.ts';
@@ -47,6 +51,18 @@ export interface OkBugReportCreateRequest {
* dump — only the dialog's explicit checkbox sets this.
*/
includeCrashDump?: boolean;
+ /**
+ * Screenshot opt-in (default on in the dialog): stage the app screenshot
+ * captured when the dialog opened into the bundle at `extra/screenshot.png`,
+ * raw. The picture is unredactable, but the dialog previews it before send so
+ * the user has already seen exactly what is included — absence still means no
+ * screenshot, and the bytes are main-owned (never a renderer-supplied path).
+ */
+ includeScreenshot?: boolean;
+}
+
+interface OkBugReportCaptureScreenshotRequest {
+ kind: 'capture-screenshot';
}
export interface OkBugReportSendRequest {
@@ -66,7 +82,8 @@ export interface OkBugReportCrashAckRequest {
export type OkBugReportRequest =
| OkBugReportCreateRequest
| OkBugReportSendRequest
- | OkBugReportCrashAckRequest;
+ | OkBugReportCrashAckRequest
+ | OkBugReportCaptureScreenshotRequest;
/**
* Host metadata handed to the bundle collector through its typed
@@ -98,6 +115,14 @@ export interface BugReportCreateDeps {
* the dump.
*/
newestMinidumpPath?: () => string | null;
+ /**
+ * Main-owned PNG bytes of the screenshot captured when the report dialog
+ * opened, consulted only when the renderer opted in via `includeScreenshot`.
+ * Returns `null` when no screenshot was captured for the sender window (capture
+ * failed, or a non-desktop caller). The bytes are staged to a temp file the
+ * handler owns and deletes — the renderer never supplies a path.
+ */
+ screenshotPngBytes?: () => Buffer | null;
/**
* Sink for the collector's warnings — most importantly an opted-in crash
* dump that could not be staged, which must be traceable rather than a
@@ -130,7 +155,8 @@ function isCreateRequest(request: unknown): request is OkBugReportCreateRequest
r.kind === 'create' &&
(r.level === 'standard' || r.level === 'full') &&
isValidNote(r.note) &&
- (r.includeCrashDump === undefined || typeof r.includeCrashDump === 'boolean')
+ (r.includeCrashDump === undefined || typeof r.includeCrashDump === 'boolean') &&
+ (r.includeScreenshot === undefined || typeof r.includeScreenshot === 'boolean')
);
}
@@ -154,7 +180,25 @@ export async function handleBugReportCreate(
}
const minidumpPath =
request.includeCrashDump === true ? (deps.newestMinidumpPath?.() ?? null) : null;
+ const screenshotBytes =
+ request.includeScreenshot === true ? (deps.screenshotPngBytes?.() ?? null) : null;
+
+ // Both raw artifacts ride the same byte-for-byte `extra/` seam the collector
+ // never scrubs. The minidump comes in by path; the screenshot bytes are
+ // main-owned in-memory, so stage them to a temp file the `finally` deletes —
+ // a picture of the user's screen must not linger in tmp once it is zipped.
+ const extraFiles: { sourcePath: string; zipName?: string }[] = [];
+ if (minidumpPath !== null) extraFiles.push({ sourcePath: minidumpPath });
+ let screenshotTmpPath: string | null = null;
try {
+ if (screenshotBytes !== null) {
+ screenshotTmpPath = join(tmpdir(), `ok-bugreport-screenshot-${randomUUID()}.png`);
+ // Owner-only: the file is a picture of the user's screen sitting in a
+ // world-readable tmp dir until the collector zips it, so keep it off
+ // other local accounts (matches the subsystem's sensitive-sidecar mode).
+ await writeFile(screenshotTmpPath, screenshotBytes, { mode: 0o600 });
+ extraFiles.push({ sourcePath: screenshotTmpPath, zipName: BUG_REPORT_SCREENSHOT_ZIP_NAME });
+ }
const { zipPath, summary } = await collectReportBundle({
level: request.level,
projectDir: deps.projectDir ?? undefined,
@@ -163,7 +207,7 @@ export async function handleBugReportCreate(
redact: true,
outputPath: deps.outputPath ?? defaultBugReportZipPath(),
userLogsDir: deps.userLogsDir,
- extraFiles: minidumpPath === null ? undefined : [{ sourcePath: minidumpPath }],
+ extraFiles: extraFiles.length === 0 ? undefined : extraFiles,
logger: deps.logger,
readDesktopEnv: () => ({
electronVersion: deps.desktopMeta.version,
@@ -185,6 +229,104 @@ export async function handleBugReportCreate(
cause: err,
});
return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ } finally {
+ if (screenshotTmpPath !== null) {
+ // A failed unlink leaves a screenshot of the user's screen in tmp, so
+ // make it traceable rather than silent — but never let cleanup failure
+ // change the create outcome.
+ await unlink(screenshotTmpPath).catch((err: unknown) => {
+ deps.logger?.warn(
+ { screenshotTmpPath, err: err instanceof Error ? err.message : String(err) },
+ 'bug-report: failed to remove temp screenshot file',
+ );
+ });
+ }
+ }
+}
+
+/**
+ * Minimal shape of an Electron `NativeImage` the capture handler needs, so its
+ * store/listener lifecycle and zero-byte handling are unit-testable without an
+ * Electron stub. `main/index.ts` passes the real `NativeImage` (structurally
+ * compatible); tests pass a fake.
+ */
+export interface CapturableImage {
+ toPNG(): Buffer;
+ getSize(): { width: number; height: number };
+ resize(options: { width: number }): CapturableImage;
+ toDataURL(): string;
+}
+
+/** Store entry: the full-resolution PNG plus the `destroyed`-listener that reaps it. */
+export interface BugReportScreenshotEntry {
+ png: Buffer;
+ cleanup: () => void;
+}
+
+export interface CaptureScreenshotDeps {
+ /** Main-owned per-window store, keyed by `webContents.id`. */
+ store: Map<number, BugReportScreenshotEntry>;
+ /** Sender `webContents.id` — this window's store key. */
+ senderId: number;
+ /** Wraps `win.webContents.capturePage()`. May reject; the handler degrades to null. */
+ capturePage: () => Promise<CapturableImage>;
+ /** Max preview width (logical px); wider captures downscale for the data-URL. */
+ previewWidth: number;
+ /** Registers the one-shot `destroyed` reaper (wraps `sender.once('destroyed', cb)`). */
+ registerCleanup: (cleanup: () => void) => void;
+ /** Removes a previously-registered reaper (wraps `sender.removeListener('destroyed', cb)`). */
+ unregisterCleanup: (cleanup: () => void) => void;
+ logger?: BundleLogger;
+}
+
+/**
+ * Capture the sender window for the `capture-screenshot` operation: hold the
+ * full-resolution PNG in main (keyed by window) and return the renderer a
+ * downscaled data-URL preview. Never throws — a failed or empty capture
+ * resolves to `null` so the dialog simply omits the screenshot option.
+ *
+ * Re-capture on the same window replaces the prior entry AND unregisters its
+ * `destroyed` reaper first, so repeated dialog opens can't accumulate
+ * MaxListeners-worth of listeners on one `WebContents`.
+ */
+export async function handleBugReportCaptureScreenshot(
+ deps: CaptureScreenshotDeps,
+): Promise<OkBugReportScreenshot | null> {
+ const dropExisting = () => {
+ const existing = deps.store.get(deps.senderId);
+ if (existing !== undefined) {
+ deps.unregisterCleanup(existing.cleanup);
+ deps.store.delete(deps.senderId);
+ }
+ };
+ try {
+ const image = await deps.capturePage();
+ const png = image.toPNG();
+ // A zero-byte capture (offscreen, or not yet painted) is not a usable
+ // screenshot — omit the option rather than offer an empty picture.
+ if (png.length === 0) {
+ dropExisting();
+ return null;
+ }
+ // Replace any prior capture for this window, dropping its stale reaper.
+ dropExisting();
+ const cleanup = () => {
+ deps.store.delete(deps.senderId);
+ };
+ deps.store.set(deps.senderId, { png, cleanup });
+ deps.registerCleanup(cleanup);
+ const { width, height } = image.getSize();
+ // The renderer only needs a legible thumbnail; downscale wide captures to
+ // keep the data-URL small (the full-resolution bytes go in the bundle).
+ const preview = width > deps.previewWidth ? image.resize({ width: deps.previewWidth }) : image;
+ return { dataUrl: preview.toDataURL(), width, height };
+ } catch (err) {
+ dropExisting();
+ deps.logger?.warn(
+ { err: err instanceof Error ? err.message : String(err) },
+ 'bug-report: screenshot capture failed; dialog will omit the screenshot option',
+ );
+ return null;
}
}
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index 0192c49b2..8fd02c486 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -23,6 +23,7 @@ import type {
OkBugReportCrashAckResult,
OkBugReportCrashDetectedEvent,
OkBugReportCreateResult,
+ OkBugReportScreenshot,
OkBugReportSendMetadata,
OkBugReportSendResult,
ReportBundleLevel,
@@ -486,13 +487,23 @@ const bridge: OkDesktopBridge = {
// (`ok:bug-report:dispatch`), respecting the hand-rolled-channel cap.
// Each method knows its operation, so it casts the union result to its
// own arm (the worktree-dispatch precedent).
- create: (request: { level: ReportBundleLevel; note?: string; includeCrashDump?: boolean }) =>
+ create: (request: {
+ level: ReportBundleLevel;
+ note?: string;
+ includeCrashDump?: boolean;
+ includeScreenshot?: boolean;
+ }) =>
invoke('ok:bug-report:dispatch', {
kind: 'create',
level: request.level,
note: request.note,
includeCrashDump: request.includeCrashDump,
+ includeScreenshot: request.includeScreenshot,
}) as Promise<OkBugReportCreateResult>,
+ captureScreenshot: () =>
+ invoke('ok:bug-report:dispatch', {
+ kind: 'capture-screenshot',
+ }) as Promise<OkBugReportScreenshot | null>,
send: (request: { zipPath: string; metadata: OkBugReportSendMetadata }) =>
invoke('ok:bug-report:dispatch', {
kind: 'send',
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index c485ca2b1..a8bd81bf6 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -27,6 +27,7 @@ import type {
OkBugReportCrashAckResult,
OkBugReportCrashDetectedEvent,
OkBugReportCreateResult,
+ OkBugReportScreenshot,
OkBugReportSendMetadata,
OkBugReportSendResult,
OkFolderState,
@@ -1552,7 +1553,14 @@ export interface OkDesktopBridge {
* labeled via `summary.systemWide`) under `~/.ok/bug-reports/`, folding in
* the newest un-acked crash minidump only when `includeCrashDump` is set
* (the crash invite's explicit opt-in — minidumps carry raw memory no text
- * redaction can scrub); `send` uploads the reviewed zip to the private
+ * redaction can scrub) and the app screenshot (staged raw at
+ * `extra/screenshot.png`) only when `includeScreenshot` is set.
+ * `captureScreenshot` grabs the sender window's page as a downscaled preview
+ * and holds the full-resolution bytes in main for that later `create`; the
+ * report dialog calls it before it paints, so the picture is the app state
+ * underneath the dialog rather than the dialog itself, and returns `null`
+ * when capture is unavailable (non-desktop / capture failure). `send` uploads
+ * the reviewed zip to the private
* intake endpoint when one is configured, otherwise resolving to the
* prefilled email fallback (`fallback.mailtoUrl`) — `reason` discriminates
* the designed no-intake email path (`'email-draft'`, no network attempted)
@@ -1571,7 +1579,9 @@ export interface OkDesktopBridge {
level: ReportBundleLevel;
note?: string;
includeCrashDump?: boolean;
+ includeScreenshot?: boolean;
}): Promise<OkBugReportCreateResult>;
+ captureScreenshot(): Promise<OkBugReportScreenshot | null>;
send(request: {
zipPath: string;
metadata: OkBugReportSendMetadata;
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index d689b6756..13f355560 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -61,6 +61,7 @@ import type {
LocalOpOkInitResponse,
OkBugReportCrashAckResult,
OkBugReportCreateResult,
+ OkBugReportScreenshot,
OkBugReportSendResult,
OkFolderState,
ShareTargetStatusResponse,
@@ -818,12 +819,20 @@ export interface RequestChannels {
* - `{kind: 'crash-ack', eventId}` → persist that the user answered a
* `ok:bug-report:crash-detected` invitation so that crash event never
* re-prompts, across restarts included.
+ * - `{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.
* Never throws — every failure mode is discriminated so the dialog can
* render it; each preload method casts the union result to its own arm.
*/
'ok:bug-report:dispatch': {
args: [request: OkBugReportRequest];
- result: OkBugReportCreateResult | OkBugReportSendResult | OkBugReportCrashAckResult;
+ result:
+ | OkBugReportCreateResult
+ | OkBugReportSendResult
+ | OkBugReportCrashAckResult
+ | OkBugReportScreenshot
+ | null;
};
/** Read the LRU-capped recent-projects list from app state. */
'ok:project:list-recent': { args: []; result: RecentProject[] };
diff --git a/packages/desktop/tests/smoke/report-bug.e2e.ts b/packages/desktop/tests/smoke/report-bug.e2e.ts
index 7f9d06105..0cab83f4d 100644
--- a/packages/desktop/tests/smoke/report-bug.e2e.ts
+++ b/packages/desktop/tests/smoke/report-bug.e2e.ts
@@ -144,6 +144,15 @@ test.describe('Report-a-bug entry points', () => {
await paletteRow.click();
await expect(composeDialog).toBeVisible({ timeout: 10_000 });
+ // The include-a-screenshot option is deliberately NOT asserted here:
+ // `webContents.capturePage()` returns an empty image on the headless CI
+ // runner (the window is never composited to a readable surface), so the
+ // gate offers no screenshot and the checkbox/preview never appear. That
+ // path is covered where it can run deterministically — the bun unit tier
+ // (byte-identical staging at `extra/screenshot.png`) and the app DOM tier
+ // (preview, default-on checkbox, opt-out, launcher-wait) — with mocked
+ // capture. This smoke test stays scoped to the entry points + bundle flow.
+
// Compose → create. The note rides into the bundle; typing it here
// exercises the same field the crash variants relabel.
await composeDialog
@@ -165,7 +174,8 @@ test.describe('Report-a-bug entry points', () => {
expect(zips).toHaveLength(1);
const zipName = zips[0];
expect(zipName).toMatch(/-bugreport\.zip$/);
- expect(statSync(join(reportsDir, zipName)).size).toBeGreaterThan(0);
+ const zipPath = join(reportsDir, zipName);
+ expect(statSync(zipPath).size).toBeGreaterThan(0);
await expect(reviewDialog.getByTitle(zipName)).toBeVisible();
});
});