Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): capture bug-report shot before dismissing (PRD-9538) (#6632)
Andrew Mikofalvyfd119e333c8c
diff --git a/.changeset/prd-9538-bug-report-capture-before-dismiss.md b/.changeset/prd-9538-bug-report-capture-before-dismiss.mdnew file mode 100644index 000000000..70ce7991f--- /dev/null+++ b/.changeset/prd-9538-bug-report-capture-before-dismiss.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++A bug report started from the toolbar's **?** menu no longer captures that button's "Resources" tooltip in its screenshot. The report shortcut still captures the command palette or any menu that is open.diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 0443e0da1..138494fee 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -409,7 +409,7 @@ None of your content, by default. Everything above is written to your own disk.| What | When | Where it goes || --- | --- | --- || Diagnostic bundle | Only when you run `ok diagnose bundle` (you can inspect it first). On macOS it also carries the crash reports the OS recorded for this app and its helper processes (listed above), which are machine-wide rather than project-scoped; only this app's are collected, never another application's, though a report of ours still names the processes it was running alongside, and the summary printed before the zip is written says what that search found even when the answer is nothing. On every platform it also carries the past week of the operating system's records of this app being ended from outside (listed above), and the same summary says what that read found | Wherever you send it |-| In-app bug report | Only when you click **Send** in the desktop app's **Help → Report a bug…** dialog, or the `Cmd+Shift+D` / `Ctrl+Shift+D` shortcut that opens the same dialog — it builds a secret-redacted zip you can reveal and inspect first, and nothing is sent without that explicit click. The zip carries a picture of the app window unless you uncheck **Screenshot** in that dialog, and the preview there is the picture that would be sent. You can also attach up to three images by dropping them on the **What happened?** box, pasting them anywhere in the dialog (`Cmd+V` / `Ctrl+V`), or browsing with the paperclip in that box. Neither these images nor the screenshot are scanned or redacted, so review them before sending. A report started from an agent chat's **Report a problem with this chat…** also carries, unless you uncheck **This conversation**, the newest 4 MB of that chat's messages, tool calls, and their output, and the chat's metadata file, which names the chat's title, the project folder's path, the document the chat started from, and the agent and its settings. Known secrets are scrubbed from both. Images and other binary content in the chat, including images pasted into a message, are replaced by a note of their type and size, while text files attached to a message are included and scrubbed the same way. If the chat's messages can't be added, the review step says so and the report goes without the conversation. If only the metadata file can't be read, the report carries the messages without it, and the review step doesn't say so. A report reached through a surface you opened only to get to the reporter — the command palette, the Help popover, the Windows and Linux menu bar, or an agent chat's **Settings** menu — waits for that surface to close first, and carries no marker, because the row it would point at has already gone. Every other report you start yourself photographs the screen as it is, so an open menu or another person's document visible at the time is in the picture, and carries a marker drawn where your pointer was, since a screenshot never includes the cursor. No marker is drawn either if the pointer has not moved since the window loaded, or has since left the window. The invitation that appears on its own after a crash is the exception to all of this: it carries no picture at all. When the app holds a crash dump, the same dialog adds a **Crash dump** checkbox. It starts checked on the invitation that follows a crash with a dump available, and unchecked on a report you open yourself. A crash dump is a memory snapshot that can contain document content and can't be redacted, so it is attached only if that box is checked when you create the report, and you review the result before anything is sent. The invitation attaches the dump of the crash it was raised for, never a newer one; if that dump can't be added, the review step says so and the report goes without it. On macOS the zip also carries the update helper's install log (listed above), which is machine-wide rather than project-scoped; the zip's own README names it and says where it came from. At the **Detailed diagnostics** level — pre-checked on the invitation that follows a crash — it additionally carries the crash reports macOS itself recorded for this app and its helpers (also listed above), which are machine-wide for the same reason and named in the same README; only this app's are collected, never another application's, though a report of ours still names the processes it was running alongside, and the zip always says what that search found even when the answer is nothing. On every platform the same level also adds the past week of the operating system's records of this app being ended from outside (also listed above), listed in `manifest.json` for a project's zip and named in the same README for a system-wide zip whenever records were kept. The zip also carries a short send history of the bug reports previously generated on this machine — when each was generated and whether sending it succeeded — which is what makes a report that failed to send diagnosable at all. That history is machine-wide too, so it names the other projects you have filed reports from; it carries no document content, and the README names it the same way | Send uploads the zip to the bug-report intake: `openknowledge.ai` unless [`OK_BUG_REPORT_INTAKE_URL`](./configuration.mdx#environment-variables) points elsewhere. If the upload fails, Send falls back to a prefilled email draft to [email protected] that you send yourself, naming the zip to attach |+| In-app bug report | Only when you click **Send** in the desktop app's **Help → Report a bug…** dialog, or the `Cmd+Shift+D` / `Ctrl+Shift+D` shortcut that opens the same dialog — it builds a secret-redacted zip you can reveal and inspect first, and nothing is sent without that explicit click. The zip carries a picture of the app window unless you uncheck **Screenshot** in that dialog, and the preview there is the picture that would be sent. You can also attach up to three images by dropping them on the **What happened?** box, pasting them anywhere in the dialog (`Cmd+V` / `Ctrl+V`), or browsing with the paperclip in that box. Neither these images nor the screenshot are scanned or redacted, so review them before sending. A report started from an agent chat's **Report a problem with this chat…** also carries, unless you uncheck **This conversation**, the newest 4 MB of that chat's messages, tool calls, and their output, and the chat's metadata file, which names the chat's title, the project folder's path, the document the chat started from, and the agent and its settings. Known secrets are scrubbed from both. Images and other binary content in the chat, including images pasted into a message, are replaced by a note of their type and size, while text files attached to a message are included and scrubbed the same way. If the chat's messages can't be added, the review step says so and the report goes without the conversation. If only the metadata file can't be read, the report carries the messages without it, and the review step doesn't say so. A report started from the command palette, the Help popover, the Windows and Linux menu bar, or an agent chat's **Settings** menu photographs the screen with that palette or menu left out, and carries no marker, because the pointer was only choosing the command. To photograph the command palette itself, press the shortcut while it is open. Every other report you start yourself photographs the screen as it is, so an open menu or another person's document visible at the time is in the picture, and carries a marker drawn where your pointer was, since a screenshot never includes the cursor. No marker is drawn either if the pointer has not moved since the window loaded, or has since left the window. The invitation that appears on its own after a crash is the exception to all of this: it carries no picture at all. When the app holds a crash dump, the same dialog adds a **Crash dump** checkbox. It starts checked on the invitation that follows a crash with a dump available, and unchecked on a report you open yourself. A crash dump is a memory snapshot that can contain document content and can't be redacted, so it is attached only if that box is checked when you create the report, and you review the result before anything is sent. The invitation attaches the dump of the crash it was raised for, never a newer one; if that dump can't be added, the review step says so and the report goes without it. On macOS the zip also carries the update helper's install log (listed above), which is machine-wide rather than project-scoped; the zip's own README names it and says where it came from. At the **Detailed diagnostics** level — pre-checked on the invitation that follows a crash — it additionally carries the crash reports macOS itself recorded for this app and its helpers (also listed above), which are machine-wide for the same reason and named in the same README; only this app's are collected, never another application's, though a report of ours still names the processes it was running alongside, and the zip always says what that search found even when the answer is nothing. On every platform the same level also adds the past week of the operating system's records of this app being ended from outside (also listed above), listed in `manifest.json` for a project's zip and named in the same README for a system-wide zip whenever records were kept. The zip also carries a short send history of the bug reports previously generated on this machine — when each was generated and whether sending it succeeded — which is what makes a report that failed to send diagnosable at all. That history is machine-wide too, so it names the other projects you have filed reports from; it carries no document content, and the README names it the same way | Send uploads the zip to the bug-report intake: `openknowledge.ai` unless [`OK_BUG_REPORT_INTAKE_URL`](./configuration.mdx#environment-variables) points elsewhere. If the upload fails, Send falls back to a prefilled email draft to [email protected] that you send yourself, naming the zip to attach || Uninstall feedback | Only if you answer the optional "Before you go" screen or prompt. The macOS desktop asks after you confirm removal, before the app quits and cleanup starts; feedback can be sent even if cleanup later fails. Interactive `ok uninstall` asks only after successful cleanup. Skipping sends nothing; CLI runs with `--yes`, `--json`, or non-interactive input never ask | `openknowledge.ai/api/feedback` — the reason you picked, your note, your email address if you gave one, plus the app version and platform. It files one ticket for the team; nothing from your notes is included || Feedback form | Only when you click **Send** in the feedback form, opened from **Help → Send feedback**, the command palette's **Send feedback** command, or the feedback card in the window's bottom-left corner. Images you drop on, paste into, or attach to the message box go with it; like bug report images, they are not scanned or redacted | `openknowledge.ai/api/feedback` — your rating, the reasons you picked, your note, your email address if you gave one, up to three attached images, plus the app version and platform. In the desktop app the images upload first to the bug-report intake (`openknowledge.ai` unless [`OK_BUG_REPORT_INTAKE_URL`](./configuration.mdx#environment-variables) points elsewhere) and the feedback carries links to them. If an image upload fails, the images go inline with the feedback to `openknowledge.ai/api/feedback` instead || Semantic search embeddings | Only when you enable [semantic search](./configuration.mdx#semantic-search) **and** set a key — off by default | Your configured embeddings provider (OpenAI by default) |diff --git a/packages/app/src/components/AppErrorBoundary.tsx b/packages/app/src/components/AppErrorBoundary.tsxindex 74c41706c..267e20d12 100644--- a/packages/app/src/components/AppErrorBoundary.tsx+++ b/packages/app/src/components/AppErrorBoundary.tsx@@ -1,15 +1,16 @@import { Trans, useLingui } from '@lingui/react/macro';-import { useEffect, useRef, useState } from 'react';+import { useEffect, useRef } from 'react';import { ErrorBoundary, type FallbackProps } from 'react-error-boundary';import { OkBlobRunnerEasterEgg } from '@/components/OkBlobRunnerEasterEgg';import { ReportBugDialog } from '@/components/ReportBugDialog';import { Button } from '@/components/ui/button';+import { useBugReport } from '@/lib/bug-report-capture';import { recallComponentStack, rememberComponentStack } from '@/lib/component-stack-registry';import { recordAppShellCrashTrip } from '@/lib/tab-session-restore-suppression';function AppErrorFallback({ error, resetErrorBoundary }: FallbackProps) {const { t } = useLingui();- const [reportOpen, setReportOpen] = useState(false);+ const bugReport = useBugReport();const retryRef = useRef<HTMLButtonElement>(null);const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;const message =@@ -42,7 +43,7 @@ function AppErrorFallback({ error, resetErrorBoundary }: FallbackProps) {<Buttonvariant="ghost"className="font-mono uppercase"- onClick={() => setReportOpen(true)}+ onClick={() => bugReport.start({ launcherBorne: false })}><Trans>Report this error</Trans></Button>@@ -51,8 +52,8 @@ function AppErrorFallback({ error, resetErrorBoundary }: FallbackProps) {{bridge ? (<CrashReportingBoundary><ReportBugDialog- open={reportOpen}- onOpenChange={setReportOpen}+ capture={bugReport.capture}+ onClose={bugReport.close}systemWide={bridge.config.mode === 'navigator'}crashContext={{source: 'app shell',diff --git a/packages/app/src/components/AppMenubar.dom.test.tsx b/packages/app/src/components/AppMenubar.dom.test.tsxindex 0aa7d679e..5b6abd168 100644--- a/packages/app/src/components/AppMenubar.dom.test.tsx+++ b/packages/app/src/components/AppMenubar.dom.test.tsx@@ -93,6 +93,13 @@ describe('AppMenubar Help menu', () => {expect(dispatch).toHaveBeenCalledWith({ kind: 'menu-action', action: 'report-bug' });});+ test('the open Help menu is marked as a bug-report launcher', async () => {+ installBridge('win32');+ await openHelpMenu();++ expect(screen.getByRole('menu').hasAttribute('data-bug-report-launcher')).toBe(true);+ });+test('Help entries read identically to the native menu, ellipsis included', async () => {installBridge('linux');await openHelpMenu();diff --git a/packages/app/src/components/AppMenubar.tsx b/packages/app/src/components/AppMenubar.tsxindex 1ff962a65..3b481c602 100644--- a/packages/app/src/components/AppMenubar.tsx+++ b/packages/app/src/components/AppMenubar.tsx@@ -64,7 +64,7 @@ export function AppMenubar({ className }: AppMenubarProps) {><MenubarMenu><MenubarTrigger className="px-2 py-1 text-xs font-normal">{t`File`}</MenubarTrigger>- <MenubarContent>+ <MenubarContent data-bug-report-launcher=""><MenubarItem onSelect={() => dispatch({ kind: 'menu-action', action: 'new-doc' })}>{t`New file`}<MenubarShortcut>Ctrl+N</MenubarShortcut>@@ -198,7 +198,7 @@ export function AppMenubar({ className }: AppMenubarProps) {<MenubarMenu><MenubarTrigger className="px-2 py-1 text-xs font-normal">{t`Edit`}</MenubarTrigger>- <MenubarContent>+ <MenubarContent data-bug-report-launcher=""><MenubarItem onSelect={() => dispatch({ kind: 'role', role: 'undo' })}>{t`Undo`}<MenubarShortcut>Ctrl+Z</MenubarShortcut>@@ -236,7 +236,7 @@ export function AppMenubar({ className }: AppMenubarProps) {<MenubarMenu><MenubarTrigger className="px-2 py-1 text-xs font-normal">{t`View`}</MenubarTrigger>- <MenubarContent>+ <MenubarContent data-bug-report-launcher=""><MenubarItem onSelect={() => dispatch({ kind: 'menu-action', action: 'navigate-back' })}>{t`Back`}<MenubarShortcut>Alt+Left</MenubarShortcut>@@ -348,7 +348,7 @@ export function AppMenubar({ className }: AppMenubarProps) {<MenubarMenu><MenubarTrigger className="px-2 py-1 text-xs font-normal">{t`Window`}</MenubarTrigger>- <MenubarContent>+ <MenubarContent data-bug-report-launcher=""><MenubarItem onSelect={() => dispatch({ kind: 'role', role: 'minimize' })}>{t`Minimize`}</MenubarItem>@@ -360,7 +360,7 @@ export function AppMenubar({ className }: AppMenubarProps) {<MenubarMenu><MenubarTrigger className="px-2 py-1 text-xs font-normal">{t`Help`}</MenubarTrigger>- <MenubarContent>+ <MenubarContent data-bug-report-launcher=""><MenubarItem onSelect={() => dispatch({ kind: 'command', command: 'open-github' })}>{t`OpenKnowledge on GitHub`}</MenubarItem>diff --git a/packages/app/src/components/CommandPalette.dom.test.tsx b/packages/app/src/components/CommandPalette.dom.test.tsxindex ca30aff94..d87929c33 100644--- a/packages/app/src/components/CommandPalette.dom.test.tsx+++ b/packages/app/src/components/CommandPalette.dom.test.tsx@@ -1,7 +1,9 @@import type { HandoffHostPlatform } from '@inkeep/open-knowledge-core/agent-registry';+import type { OkBugReportScreenshot } from '@inkeep/open-knowledge-core/logger-types';import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import type { ReactNode } from 'react';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import type { BugReportCapture } from '@/lib/bug-report-capture';import {__resetLocalMenuActionBusForTests,subscribeLocalMenuAction,@@ -10,6 +12,7 @@ import {__resetPaneVisibilityStoreForTests,paneVisibilityStore,} from '@/lib/pane-visibility-store';+import { installPointerPositionTracker } from '@/lib/pointer-position';import { __resetViewMenuStateForTests, setViewMenuState } from '@/lib/view-menu-state-store';import {restrictHandoffTargetPlatforms,@@ -30,6 +33,7 @@ type CommandDialogProps = {description?: string;className?: string;commandProps?: Record<string, unknown>;+ contentAttributes?: Record<string, string>;transition?: unknown;placement?: unknown;};@@ -50,7 +54,7 @@ let requestDocPanelTabCalls: string[] = [];let seedDialogProps: Array<{ open: boolean; onSeedApplied?: () => void }> = [];let newItemDialogProps: Array<{ open: boolean; kind: string; initialDir: string }> = [];let createProjectDialogProps: Array<{ open: boolean; bridge: unknown }> = [];-let reportBugDialogProps: Array<{ open: boolean; launcherBorne?: boolean }> = [];+let reportBugDialogProps: Array<{ capture: BugReportCapture | null }> = [];let feedbackDialogProps: Array<{ open: boolean; source?: string }> = [];let commandDialogProps: CommandDialogProps[] = [];let refreshInstallStatesCalls = 0;@@ -166,9 +170,9 @@ vi.doMock('@/components/CreateProjectDialog', () => ({}));vi.doMock('@/components/ReportBugDialog', () => ({- ReportBugDialog: (props: { open: boolean; launcherBorne?: boolean }) => {+ ReportBugDialog: (props: { capture: BugReportCapture | null }) => {reportBugDialogProps.push(props);- return <div data-open={String(props.open)} data-testid="report-bug-dialog" />;+ return <div data-open={String(props.capture !== null)} data-testid="report-bug-dialog" />;},}));@@ -346,6 +350,35 @@ async function setQuery(value: string) {});}+const SCREENSHOT: OkBugReportScreenshot = {+ dataUrl: 'data:image/png;base64,iVBORw0KGgo=',+ width: 1200,+ height: 800,+};++function installCaptureBridge(onCapture: () => void): void {+ Object.defineProperty(window, 'okDesktop', {+ configurable: true,+ writable: true,+ value: {+ bugReport: {+ captureScreenshot: () => {+ onCapture();+ return Promise.resolve(SCREENSHOT);+ },+ },+ },+ });+}++function clearCaptureBridge(): void {+ Object.defineProperty(window, 'okDesktop', {+ configurable: true,+ writable: true,+ value: undefined,+ });+}+describe('CommandPalette DOM behavior', () => {beforeEach(() => {cleanup();@@ -358,6 +391,7 @@ describe('CommandPalette DOM behavior', () => {newItemDialogProps = [];createProjectDialogProps = [];reportBugDialogProps = [];+ clearCaptureBridge();feedbackDialogProps = [];commandDialogProps = [];refreshInstallStatesCalls = 0;@@ -555,7 +589,7 @@ describe('CommandPalette DOM behavior', () => {expect(createProjectDialogProps.at(-1)?.bridge).toBe(bridge);});- test('report-a-bug command is desktop-only, searchable by issue tokens, and opens ReportBugDialog', async () => {+ test('report-a-bug command is desktop-only, searchable by issue tokens, leaves the palette out of the shot, then closes it', async () => {await renderPalette({ bridge: null });await setQuery('bug');@@ -570,17 +604,45 @@ describe('CommandPalette DOM behavior', () => {const reportBug = screen.getByTestId('command-palette-report-bug');expect(reportBug.textContent).toContain('Report a bug');- fireEvent.click(reportBug);+ const stopPointerTracking = installPointerPositionTracker();+ window.dispatchEvent(new PointerEvent('pointermove', { clientX: 40, clientY: 50 }));+ let paletteAtCapture: {+ inDocument: boolean;+ hiddenAsLauncher: boolean;+ closeRequested: boolean;+ } | null = null;+ installCaptureBridge(() => {+ const palette = screen.queryByRole('dialog', { name: 'Workspace Command Palette' });+ paletteAtCapture = {+ inDocument: palette !== null,+ hiddenAsLauncher:+ document.documentElement.hasAttribute('data-bug-report-capturing') &&+ commandDialogProps.at(-1)?.contentAttributes?.['data-bug-report-launcher'] === '',+ closeRequested: onOpenChange.mock.calls.length > 0,+ };+ });+ try {+ fireEvent.click(reportBug);+ await waitFor(() => {+ expect(screen.getByTestId('report-bug-dialog').getAttribute('data-open')).toBe('true');+ });+ } finally {+ stopPointerTracking();+ }+ expect(paletteAtCapture).toEqual({+ inDocument: true,+ hiddenAsLauncher: true,+ closeRequested: false,+ });expect(onOpenChange).toHaveBeenCalledWith(false);- await waitFor(() => {- expect(screen.getByTestId('report-bug-dialog').getAttribute('data-open')).toBe('true');+ expect(reportBugDialogProps.at(-1)?.capture).toEqual({+ screenshot: SCREENSHOT,+ pointerMarked: false,});- expect(reportBugDialogProps.at(-1)?.open).toBe(true);- expect(reportBugDialogProps.at(-1)?.launcherBorne).toBe(true);});- test('the bug-report-history CTA opens the compose dialog launcher-free', async () => {+ test('the bug-report-history CTA captures with the history still up, pointer marked, then opens', async () => {const bridge = createBridge();await renderPalette({ bridge });@@ -588,13 +650,27 @@ describe('CommandPalette DOM behavior', () => {fireEvent.click(screen.getByTestId('command-palette-bug-report-history'));const cta = await screen.findByTestId('history-report-cta');- fireEvent.click(cta);+ const stopPointerTracking = installPointerPositionTracker();+ window.dispatchEvent(new PointerEvent('pointermove', { clientX: 40, clientY: 50 }));+ let historyAtCapture: boolean | null = null;+ installCaptureBridge(() => {+ historyAtCapture = screen.queryByTestId('history-report-cta') !== null;+ });+ try {+ fireEvent.click(cta);- await waitFor(() => {- expect(screen.getByTestId('report-bug-dialog').getAttribute('data-open')).toBe('true');+ await waitFor(() => {+ expect(screen.getByTestId('report-bug-dialog').getAttribute('data-open')).toBe('true');+ });+ } finally {+ stopPointerTracking();+ }+ expect(historyAtCapture).toBe(true);+ expect(screen.queryByTestId('history-report-cta')).toBeNull();+ expect(reportBugDialogProps.at(-1)?.capture).toEqual({+ screenshot: SCREENSHOT,+ pointerMarked: true,});- expect(reportBugDialogProps.at(-1)?.open).toBe(true);- expect(reportBugDialogProps.at(-1)?.launcherBorne).toBe(false);});test('send-feedback command renders on both hosts and opens FeedbackFormDialog', async () => {diff --git a/packages/app/src/components/CommandPalette.tsx b/packages/app/src/components/CommandPalette.tsxindex 220c5a808..dcafda8b0 100644--- a/packages/app/src/components/CommandPalette.tsx+++ b/packages/app/src/components/CommandPalette.tsx@@ -87,12 +87,8 @@ import { useCreateBlankSkill } from '@/hooks/use-create-blank-skill';import { useIsEmbedded } from '@/hooks/use-is-embedded';import { useSemanticSearchStatus } from '@/hooks/use-semantic-search-status';import { useWorktrees } from '@/hooks/use-worktrees';-import type {- OkDesktopBridge,- OkMenuAction,- OkMenuActionOrigin,- RecentProjectEntry,-} from '@/lib/desktop-bridge-types';+import { useBugReport } from '@/lib/bug-report-capture';+import type { OkDesktopBridge, OkMenuAction, RecentProjectEntry } from '@/lib/desktop-bridge-types';import { hashFromDocName } from '@/lib/doc-hash';import { runWithToast as runWithToastBase } from '@/lib/error-state';import { openExternalUrl as openExternalUrlViaHost } from '@/lib/external-link';@@ -285,7 +281,7 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPalconst [createDialogKind, setCreateDialogKind] = useState<'file' | 'folder' | null>(null);const [seedDialogOpen, setSeedDialogOpen] = useState(false);const [createProjectOpen, setCreateProjectOpen] = useState(false);- const [reportBugOrigin, setReportBugOrigin] = useState<OkMenuActionOrigin | null>(null);+ const bugReport = useBugReport();const [reportBugHistoryOpen, setReportBugHistoryOpen] = useState(false);const [historyEverOpened, setHistoryEverOpened] = useState(false);@@ -719,7 +715,7 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPalopenNewItemDialog: (kind) => setCreateDialogKind(kind),openSeedDialog: () => setSeedDialogOpen(true),openCreateProjectDialog: () => setCreateProjectOpen(true),- openReportBugDialog: () => setReportBugOrigin({ launcherBorne: true }),+ reportBug: () => bugReport.start({ launcherBorne: true }, () => onOpenChange(false)),openBugReportHistory: () => {setHistoryEverOpened(true);setReportBugHistoryOpen(true);@@ -944,6 +940,7 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal'[&_[cmdk-input-wrapper]_svg]:h-4 [&_[cmdk-input-wrapper]_svg]:w-4 [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4',}}onEscapeKeyDown={onPaletteEscapeKeyDown}+ contentAttributes={{ 'data-bug-report-launcher': '' }}><CommandInputref={inputRef}@@ -1484,25 +1481,16 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal/>) : null}{}- {bridge ? (- <ReportBugDialog- open={reportBugOrigin !== null}- onOpenChange={(next) => {- if (!next) setReportBugOrigin(null);- }}- launcherBorne={reportBugOrigin?.launcherBorne === true}- />- ) : null}+ {bridge ? <ReportBugDialog capture={bugReport.capture} onClose={bugReport.close} /> : null}{}{bridge && historyEverOpened ? (<Suspense fallback={null}><BugReportHistoryDialogopen={reportBugHistoryOpen}onOpenChange={setReportBugHistoryOpen}- onReportABug={() => {- setReportBugHistoryOpen(false);- setReportBugOrigin({ launcherBorne: false });- }}+ onReportABug={() =>+ bugReport.start({ launcherBorne: false }, () => setReportBugHistoryOpen(false))+ }/></Suspense>) : null}diff --git a/packages/app/src/components/DocumentErrorBoundary.tsx b/packages/app/src/components/DocumentErrorBoundary.tsxindex d5b4f8779..e2b36b72d 100644--- a/packages/app/src/components/DocumentErrorBoundary.tsx+++ b/packages/app/src/components/DocumentErrorBoundary.tsx@@ -15,6 +15,7 @@ import {ServerCapabilityMismatchError,SyncTimeoutError,} from '@/editor/sync-promise';+import { useBugReport } from '@/lib/bug-report-capture';import { recallComponentStack, rememberComponentStack } from '@/lib/component-stack-registry';import { restartCollabServer } from '@/lib/restart-collab-server';@@ -109,7 +110,7 @@ function DocumentErrorFallback({const { title, summary } = errorCopy(error);const canGoBack = !!previousDocName && !!onNavigateBack;const retryRef = useRef<HTMLButtonElement>(null);- const [reportOpen, setReportOpen] = useState(false);+ const bugReport = useBugReport();const [restarting, setRestarting] = useState(false);const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;const restartBridge = bridge && isServerReachError(error) ? bridge : null;@@ -163,7 +164,7 @@ function DocumentErrorFallback({<Buttonvariant="ghost"className="font-mono uppercase"- onClick={() => setReportOpen(true)}+ onClick={() => bugReport.start({ launcherBorne: false })}><Trans>Report this error</Trans></Button>@@ -186,8 +187,8 @@ function DocumentErrorFallback({</div>{bridge ? (<ReportBugDialog- open={reportOpen}- onOpenChange={setReportOpen}+ capture={bugReport.capture}+ onClose={bugReport.close}crashContext={{source: 'document view',docName: errorDocName(error) ?? activeDocName,diff --git a/packages/app/src/components/HelpPopover.browser.test.tsx b/packages/app/src/components/HelpPopover.browser.test.tsxindex 265f0d50a..1ff22c0fe 100644--- a/packages/app/src/components/HelpPopover.browser.test.tsx+++ b/packages/app/src/components/HelpPopover.browser.test.tsx@@ -4,6 +4,7 @@ import { act, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { afterEach, describe, expect, test, vi } from 'vitest';import { TooltipProvider } from '@/components/ui/tooltip';+import { captureBugReport } from '@/lib/bug-report-capture';import { i18n } from '@/lib/i18n';import spanishCatalog from '@/locales/es/messages.json';import { renderWithI18n } from '../../tests/foundation/render-with-i18n.test-helper';@@ -92,3 +93,52 @@ describe('HelpPopover version footer layout', () => {});});});++describe('HelpPopover in a launcher-borne bug-report shot', () => {+ test('the open popover is already hidden when the bridge takes the screenshot', async () => {+ installDesktopBridge(CLOUD_VERSION);+ const content = popoverContent(await openHelpPopover());+ let visibilityAtCapture: string | null = null;+ const bridge = (window as unknown as { okDesktop: Record<string, unknown> }).okDesktop;+ bridge.bugReport = {+ captureScreenshot: async () => {+ visibilityAtCapture = getComputedStyle(content).visibility;+ return null;+ },+ };++ await captureBugReport({ launcherBorne: true });++ expect(visibilityAtCapture).toBe('hidden');+ await vi.waitFor(() => expect(getComputedStyle(content).visibility).toBe('visible'));+ });++ test('reporting from the popover never shows it again between the shot and its close', async () => {+ installDesktopBridge(CLOUD_VERSION);+ const content = popoverContent(await openHelpPopover());+ const seen: string[] = [];+ let sampling = false;+ const sample = () => {+ if (!content.isConnected) return;+ if (sampling) seen.push(getComputedStyle(content).visibility);+ requestAnimationFrame(sample);+ };+ requestAnimationFrame(sample);+ const bridge = (window as unknown as { okDesktop: Record<string, unknown> }).okDesktop;+ bridge.bugReport = {+ captureScreenshot: async () => {+ sampling = true;+ return null;+ },+ };++ await userEvent.click(screen.getByRole('button', { name: 'Report a bug' }));++ await vi.waitFor(() => expect(content.isConnected).toBe(false));+ expect(seen.length).toBeGreaterThan(0);+ expect(seen.filter((visibility) => visibility !== 'hidden')).toEqual([]);+ await vi.waitFor(() =>+ expect(document.documentElement.hasAttribute('data-bug-report-capturing')).toBe(false),+ );+ });+});diff --git a/packages/app/src/components/HelpPopover.dom.test.tsx b/packages/app/src/components/HelpPopover.dom.test.tsxindex bac2f5f9b..51f8f9987 100644--- a/packages/app/src/components/HelpPopover.dom.test.tsx+++ b/packages/app/src/components/HelpPopover.dom.test.tsx@@ -1,9 +1,11 @@+import type { OkBugReportScreenshot } from '@inkeep/open-knowledge-core/logger-types';import * as actualLinguiMacro from '@lingui/react/macro';import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import type { ReactNode } from 'react';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { TooltipProvider } from '@/components/ui/tooltip';+import type { BugReportCapture } from '@/lib/bug-report-capture';import { renderLinguiTemplate } from '@/test-utils/lingui-mock';import { createServedBindingLog } from '@/test-utils/served-binding.test-helper';@@ -28,14 +30,20 @@ vi.doMock('@/lib/external-link', () => ({dispatchExternalLinkClick: () => {},}));-const reportBugDialogProps: Array<{ open: boolean; launcherBorne?: boolean }> = [];+const reportBugDialogProps: Array<{ capture: BugReportCapture | null }> = [];vi.doMock('@/components/ReportBugDialog', () => ({- ReportBugDialog: (props: { open: boolean; launcherBorne?: boolean }) => {+ ReportBugDialog: (props: { capture: BugReportCapture | null }) => {reportBugDialogProps.push(props);- return <div data-open={String(props.open)} data-testid="report-bug-dialog" />;+ return <div data-open={String(props.capture !== null)} data-testid="report-bug-dialog" />;},}));+const SCREENSHOT: OkBugReportScreenshot = {+ dataUrl: 'data:image/png;base64,iVBORw0KGgo=',+ width: 1200,+ height: 800,+};+async function renderOpenHelpPopover() {const { HelpPopover } = await import('./HelpPopover');render(@@ -198,8 +206,21 @@ describe('HelpPopover with the desktop bridge present', () => {expect(docs.compareDocumentPosition(sendFeedback)).toBe(Node.DOCUMENT_POSITION_FOLLOWING);});- test('the report it opens waits for the popover to clear before shooting', async () => {+ test('Report a bug shoots with the popover still up and no tooltip showing, then closes it and opens the report', async () => {reportBugDialogProps.length = 0;+ let sceneAtCapture: { popoverOpen: boolean; tooltipOpen: boolean } | null = null;+ (window as unknown as { okDesktop: unknown }).okDesktop = {+ state: { query: async () => ({ channel: 'latest', schemaIncompatibility: null }) },+ bugReport: {+ captureScreenshot: () => {+ sceneAtCapture = {+ popoverOpen: screen.queryByRole('navigation', { name: 'Resources' }) !== null,+ tooltipOpen: screen.queryByRole('tooltip') !== null,+ };+ return Promise.resolve(SCREENSHOT);+ },+ },+ };await renderOpenHelpPopover();const nav = screen.getByRole('navigation', { name: 'Resources' });@@ -208,7 +229,19 @@ describe('HelpPopover with the desktop bridge present', () => {await waitFor(() => {expect(screen.getByTestId('report-bug-dialog').getAttribute('data-open')).toBe('true');});- expect(reportBugDialogProps.at(-1)?.launcherBorne).toBe(true);+ expect(sceneAtCapture).toEqual({ popoverOpen: true, tooltipOpen: false });+ expect(screen.queryByRole('navigation', { name: 'Resources' })).toBeNull();+ expect(reportBugDialogProps.at(-1)?.capture).toEqual({+ screenshot: SCREENSHOT,+ pointerMarked: false,+ });+ });++ test('the popover content is marked as the launcher the capture hides', async () => {+ await renderOpenHelpPopover();++ const nav = screen.getByRole('navigation', { name: 'Resources' });+ expect(nav.closest('[data-bug-report-launcher]')).not.toBeNull();});test('keeps the download route available for reinstalling or sharing from desktop', async () => {diff --git a/packages/app/src/components/HelpPopover.tsx b/packages/app/src/components/HelpPopover.tsxindex 6eeafeec5..06d43e8c9 100644--- a/packages/app/src/components/HelpPopover.tsx+++ b/packages/app/src/components/HelpPopover.tsx@@ -22,6 +22,7 @@ import { SubscribeForm } from '@/components/SubscribeForm';import { Button } from '@/components/ui/button';import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';+import { useBugReport } from '@/lib/bug-report-capture';import type { OkAboutInfo } from '@/lib/desktop-bridge-types';import { dispatchExternalLinkClick } from '@/lib/external-link';import { feedbackNudgeStore } from '@/lib/feedback-nudge-store';@@ -138,7 +139,7 @@ export const HelpPopover: FC = () => {const { t } = useLingui();const [popoverOpen, setPopoverOpen] = useState(false);const [subscribeOpen, setSubscribeOpen] = useState(false);- const [reportBugOpen, setReportBugOpen] = useState(false);+ const bugReport = useBugReport();const [feedbackOpen, setFeedbackOpen] = useState(false);const [starCount, setStarCount] = useState<number | null>(null);const [about, setAbout] = useState<OkAboutInfo | null>(null);@@ -204,6 +205,7 @@ export const HelpPopover: FC = () => {<PopoverContentalign="end"aria-label={t`Resources`}+ data-bug-report-launcher=""className="w-56 p-3 subtle-scrollbar max-h-(--radix-popover-content-available-height) overflow-y-auto data-[state=closed]:overflow-hidden">{sections.map((section, index) => (@@ -229,10 +231,9 @@ export const HelpPopover: FC = () => {{hasDesktopBridge && (<ActionRowicon={Bug}- onSelect={() => {- setPopoverOpen(false);- setReportBugOpen(true);- }}+ onSelect={() =>+ bugReport.start({ launcherBorne: true }, () => setPopoverOpen(false))+ }><Trans>Report a bug</Trans></ActionRow>@@ -326,7 +327,7 @@ export const HelpPopover: FC = () => {</Popover>{}{hasDesktopBridge && (- <ReportBugDialog open={reportBugOpen} onOpenChange={setReportBugOpen} launcherBorne />+ <ReportBugDialog capture={bugReport.capture} onClose={bugReport.close} />)}<FeedbackFormDialogopen={feedbackOpen}diff --git a/packages/app/src/components/NavigatorApp.tsx b/packages/app/src/components/NavigatorApp.tsxindex 7ae6443b0..9ac9007bb 100644--- a/packages/app/src/components/NavigatorApp.tsx+++ b/packages/app/src/components/NavigatorApp.tsx@@ -8,11 +8,11 @@ import { Spinner } from '@/components/ui/spinner';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { useLanguageBridge } from '@/hooks/use-language-bridge';import { useThemeBridge } from '@/hooks/use-theme-bridge';+import { useBugReport } from '@/lib/bug-report-capture';import { ConfigContext } from '@/lib/config-context';import type {OkDesktopBridge,OkLocalOpAuthStatusResponse,- OkMenuActionOrigin,OkPackId,OkProjectEntryPoint,OkSeedPackInfo,@@ -102,7 +102,7 @@ export function NavigatorApp({ bridge }: { bridge: OkDesktopBridge }) {const [openingLabel, setOpeningLabel] = useState<string | null>(null);const [cloneDialogOpen, setCloneDialogOpen] = useState(false);const [createDialogOpen, setCreateDialogOpen] = useState(false);- const [reportBugOrigin, setReportBugOrigin] = useState<OkMenuActionOrigin | null>(null);+ const bugReport = useBugReport();const [feedbackOpen, setFeedbackOpen] = useState(false);const [createPackId, setCreatePackId] = useState<OkPackId | undefined>(undefined);const [createPacks, setCreatePacks] = useState<OkSeedPackInfo[] | undefined>(undefined);@@ -179,11 +179,11 @@ export function NavigatorApp({ bridge }: { bridge: OkDesktopBridge }) {useEffect(() => {return subscribeLocalMenuAction((action, origin) => {if (action === 'new-project') setCreateDialogOpen(true);- if (action === 'report-bug') setReportBugOrigin((current) => current ?? origin);+ if (action === 'report-bug') bugReport.start(origin);if (action === 'send-feedback') setFeedbackOpen(true);if (action === 'close-active-tab-or-window') window.close();});- }, []);+ }, [bugReport.start]);useEffect(() => {return bridge.onRecentRemovedMissing(({ path }) => {@@ -398,14 +398,7 @@ export function NavigatorApp({ bridge }: { bridge: OkDesktopBridge }) {packs={createPacks}/>- <ReportBugDialog- open={reportBugOrigin !== null}- onOpenChange={(next) => {- if (!next) setReportBugOrigin(null);- }}- launcherBorne={reportBugOrigin?.launcherBorne === true}- systemWide- />+ <ReportBugDialog capture={bugReport.capture} onClose={bugReport.close} systemWide /><FeedbackFormDialog open={feedbackOpen} onOpenChange={setFeedbackOpen} source="help_menu" />diff --git a/packages/app/src/components/ReportBugCrashInviteTrigger.tsx b/packages/app/src/components/ReportBugCrashInviteTrigger.tsxindex eae9a31df..45789dd48 100644--- a/packages/app/src/components/ReportBugCrashInviteTrigger.tsx+++ b/packages/app/src/components/ReportBugCrashInviteTrigger.tsx@@ -1,5 +1,6 @@import { useSyncExternalStore } from 'react';import { ReportBugDialog } from '@/components/ReportBugDialog';+import { BUG_REPORT_NO_CAPTURE } from '@/lib/bug-report-capture';import { crashInviteStore } from '@/lib/crash-invite-store';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';@@ -11,9 +12,8 @@ export function ReportBugCrashInviteTrigger({ bridge }: { bridge: OkDesktopBridgreturn (<ReportBugDialogkey={invite.eventId}- open- onOpenChange={(open) => {- if (open) return;+ capture={BUG_REPORT_NO_CAPTURE}+ onClose={() => {void bridge.bugReport.crashAck({ eventId: invite.eventId });crashInviteStore.dismiss();}}diff --git a/packages/app/src/components/ReportBugDialog.dom.test.tsx b/packages/app/src/components/ReportBugDialog.dom.test.tsxindex 534d46e75..bfe11c480 100644--- a/packages/app/src/components/ReportBugDialog.dom.test.tsx+++ b/packages/app/src/components/ReportBugDialog.dom.test.tsx@@ -13,9 +13,9 @@ import { useEffect, useState } from 'react';import { afterEach, describe, expect, test, vi } from 'vitest';import { TooltipProvider } from '@/components/ui/tooltip';import { makeFilesDataTransfer } from '@/editor/composer-drop.test-helper';+import { BUG_REPORT_NO_CAPTURE, type BugReportCapture } from '@/lib/bug-report-capture';import { bugReportSendManager } from '@/lib/bug-report-send-manager';import { contactEmailStore } from '@/lib/contact-email-store';-import { installPointerPositionTracker } from '@/lib/pointer-position';import { renderLinguiTemplate } from '@/test-utils/lingui-mock';vi.doMock('@lingui/react/macro', () => ({@@ -68,6 +68,7 @@ const SCREENSHOT: OkBugReportScreenshot = {width: 1200,height: 800,};+const WITH_SCREENSHOT: BugReportCapture = { screenshot: SCREENSHOT, pointerMarked: false };type CreateRequest = {level: 'standard' | 'full';@@ -86,7 +87,6 @@ interface BridgeLog {revealed: string[];opened: string[];clipboard: string[];- screenshotCalls: number;crashDumpAvailabilityCalls: number;}@@ -94,7 +94,6 @@ function installBridge(handlers: {create?: (request: CreateRequest) => Promise<OkBugReportCreateResult>;send?: (request: SendRequest) => Promise<OkBugReportSendResult>;- captureScreenshot?: () => Promise<OkBugReportScreenshot | null>;crashDumpAvailability?: () => Promise<{ available: boolean }>;platform?: string;cliCommandName?: string;@@ -106,7 +105,6 @@ function installBridge(revealed: [],opened: [],clipboard: [],- screenshotCalls: 0,crashDumpAvailabilityCalls: 0,};const bridge = {@@ -123,14 +121,6 @@ function installBridge(? handlers.send(request): Promise.resolve({ ok: true as const, reference: 'OK-8H3KQD' });},- ...(handlers.captureScreenshot- ? {- captureScreenshot: () => {- log.screenshotCalls += 1;- return handlers.captureScreenshot?.() ?? Promise.resolve(null);- },- }- : {}),...(handlers.crashDumpAvailability? {crashDumpAvailability: () => {@@ -173,20 +163,6 @@ function clearBridge() {}}-async function waitFrames(count: number): Promise<void> {- for (let i = 0; i < count; i += 1) {- await act(async () => {- await new Promise<void>((resolve) => {- requestAnimationFrame(() => resolve());- });- });- }-}--function movePointerTo(x: number, y: number): void {- window.dispatchEvent(new PointerEvent('pointermove', { clientX: x, clientY: y, bubbles: true }));-}-function deferred<T>() {let resolve!: (value: T) => void;const promise = new Promise<T>((r) => {@@ -201,11 +177,13 @@ async function renderDialog(crashContext?: import('./ReportBugDialogBody').ReportBugCrashContext;crashInvite?: OkBugReportCrashDetectedEvent;agentChat?: { threadId: string };+ capture?: BugReportCapture;} = {},options: { statefulOpen?: boolean } = {},) {const { ReportBugDialog } = await import('./ReportBugDialog');- const openChangeCalls: boolean[] = [];+ const { capture = BUG_REPORT_NO_CAPTURE, ...dialogProps } = props;+ const closeCalls = { count: 0 };let setHostOpen: ((open: boolean) => void) | null = null;function Host() {const [open, setOpen] = useState(true);@@ -215,12 +193,12 @@ async function renderDialog(return (<TooltipProvider><ReportBugDialog- open={options.statefulOpen === true ? open : true}- onOpenChange={(next) => {- openChangeCalls.push(next);- setOpen(next);+ capture={options.statefulOpen === true && !open ? null : capture}+ onClose={() => {+ closeCalls.count += 1;+ setOpen(false);}}- {...props}+ {...dialogProps}/></TooltipProvider>);@@ -228,7 +206,7 @@ async function renderDialog(render(<Host />);await screen.findByRole('dialog', {}, { timeout: 15_000 });return {- openChangeCalls,+ closeCalls,reopen: () =>act(() => {setHostOpen?.(true);@@ -245,20 +223,13 @@ async function createReport(note?: string) {}describe('ReportBugDialog', () => {- let stopPointerTracking: (() => void) | undefined;-afterEach(async () => {cleanup();vi.restoreAllMocks();- stopPointerTracking?.();- stopPointerTracking = undefined;await vi.waitFor(() => {expect(bugReportSendManager.getSnapshot().some((op) => op.status === 'sending')).toBe(false);});clearBridge();- 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 () => {@@ -405,12 +376,12 @@ describe('ReportBugDialog', () => {test('Send hands the reviewed zip to the background send manager and closes the dialog', async () => {const send = deferred<OkBugReportSendResult>();const log = installBridge({ send: () => send.promise });- const { openChangeCalls } = await renderDialog({}, { statefulOpen: true });+ const { closeCalls } = await renderDialog({}, { statefulOpen: true });await createReport('upload me');await userEvent.click(screen.getByRole('button', { name: 'Send report' }));- expect(openChangeCalls).toEqual([false]);+ expect(closeCalls.count).toBe(1);await vi.waitFor(() => {expect(screen.queryByRole('dialog')).toBeNull();});@@ -463,7 +434,7 @@ describe('ReportBugDialog', () => {'%s resolves outside the dialog — no terminal phase, no reopen, no draft',async (_, result) => {const log = installBridge({ send: () => Promise.resolve(result) });- const { openChangeCalls } = await renderDialog({}, { statefulOpen: true });+ const { closeCalls } = await renderDialog({}, { statefulOpen: true });await createReport('still my note');await userEvent.click(screen.getByRole('button', { name: 'Send report' }));@@ -471,7 +442,7 @@ describe('ReportBugDialog', () => {expect(log.sendCalls).toHaveLength(1);});- expect(openChangeCalls).toEqual([false]);+ expect(closeCalls.count).toBe(1);expect(screen.queryByRole('dialog')).toBeNull();expect(screen.queryByRole('heading', { name: "Couldn't send the report" })).toBeNull();expect(screen.queryByRole('heading', { name: 'Send your report by email' })).toBeNull();@@ -482,14 +453,14 @@ describe('ReportBugDialog', () => {test('Escape closes the dialog from review, and review keeps its close button', async () => {installBridge();- const { openChangeCalls } = await renderDialog({}, { statefulOpen: true });+ const { closeCalls } = await renderDialog({}, { statefulOpen: true });await createReport();expect(screen.getByRole('button', { name: 'Close' })).not.toBeNull();await userEvent.keyboard('{Escape}');- expect(openChangeCalls).toEqual([false]);+ expect(closeCalls.count).toBe(1);await vi.waitFor(() => {expect(screen.queryByRole('dialog')).toBeNull();});@@ -1035,10 +1006,8 @@ describe('ReportBugDialog', () => {});test('a captured screenshot shows a default-on preview + checkbox that ride into create', async () => {- const log = installBridge({ captureScreenshot: () => Promise.resolve(SCREENSHOT) });- await renderDialog();-- expect(log.screenshotCalls).toBe(1);+ const log = installBridge();+ await renderDialog({ capture: WITH_SCREENSHOT });const shot = screen.getByRole('checkbox', { name: 'Screenshot' });expect(shot.getAttribute('aria-checked')).toBe('true');@@ -1063,8 +1032,8 @@ describe('ReportBugDialog', () => {});test('an image pasted while the screenshot preview is open does not attach behind it', async () => {- installBridge({ captureScreenshot: () => Promise.resolve(SCREENSHOT) });- await renderDialog();+ installBridge();+ await renderDialog({ capture: WITH_SCREENSHOT });await userEvent.click(screen.getByRole('button', { name: 'Enlarge screenshot' }));const preview = await screen.findByRole('dialog', { name: 'Screenshot preview' });const event = createEvent.paste(preview, {@@ -1091,8 +1060,8 @@ describe('ReportBugDialog', () => {});test('unchecking the screenshot keeps it out of create', async () => {- const log = installBridge({ captureScreenshot: () => Promise.resolve(SCREENSHOT) });- await renderDialog();+ const log = installBridge();+ await renderDialog({ capture: WITH_SCREENSHOT });await userEvent.click(screen.getByRole('checkbox', { name: 'Screenshot' }));await createReport();@@ -1113,14 +1082,13 @@ describe('ReportBugDialog', () => {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 renderDialog({ capture: WITH_SCREENSHOT });await userEvent.click(screen.getByRole('button', { name: 'Create report' }));await screen.findByRole('heading', { name: 'Review your report' });@@ -1131,14 +1099,13 @@ describe('ReportBugDialog', () => {test('a screenshot-bearing bundle tells main to upload the screenshot', async () => {const log = installBridge({- captureScreenshot: () => Promise.resolve(SCREENSHOT),create: () =>Promise.resolve({...CREATE_OK,summary: { ...SUMMARY, files: [...SUMMARY.files, 'extra/screenshot.png'] },}),});- await renderDialog();+ await renderDialog({ capture: WITH_SCREENSHOT });await userEvent.click(screen.getByRole('button', { name: 'Create report' }));await screen.findByRole('heading', { name: 'Review your report' });@@ -1150,288 +1117,34 @@ describe('ReportBugDialog', () => {expect(log.sendCalls[0]?.includeScreenshot).toBe(true);});- test('a trigger with no launcher captures at once, overlay still on screen', async () => {- const popper = document.createElement('div');- popper.setAttribute('data-radix-popper-content-wrapper', '');- document.body.appendChild(popper);-- let popperAtCapture: boolean | null = null;- let capturedAfterMs = Number.POSITIVE_INFINITY;- let openedAt = Number.NaN;- const log = installBridge({- captureScreenshot: () => {- popperAtCapture = document.querySelector('[data-radix-popper-content-wrapper]') !== null;- capturedAfterMs = performance.now() - openedAt;- return Promise.resolve(SCREENSHOT);- },- });- const { ReportBugDialog } = await import('./ReportBugDialog');- openedAt = performance.now();- render(- <TooltipProvider>- <ReportBugDialog open onOpenChange={() => {}} />- </TooltipProvider>,- );-- await screen.findByRole('dialog');- expect(log.screenshotCalls).toBe(1);- expect(popperAtCapture).toBe(true);- expect(capturedAfterMs).toBeLessThan(400);- expect(screen.getByRole('checkbox', { name: 'Screenshot' })).not.toBeNull();- });-- test('a known pointer position is in the frame that gets captured, and gone once it settles', async () => {- stopPointerTracking = installPointerPositionTracker();- movePointerTo(420, 260);-- let markerAtCapture: { left: string; top: string } | null = null;- const log = installBridge({- captureScreenshot: () => {- const marker = document.querySelector<HTMLElement>('.ok-pointer-marker');- markerAtCapture = marker && { left: marker.style.left, top: marker.style.top };- return Promise.resolve(SCREENSHOT);- },- });- const { ReportBugDialog } = await import('./ReportBugDialog');- render(- <TooltipProvider>- <ReportBugDialog open onOpenChange={() => {}} />- </TooltipProvider>,- );-- await screen.findByRole('dialog');- expect(log.screenshotCalls).toBe(1);- expect(markerAtCapture).toEqual({ left: '420px', top: '260px' });- expect(document.querySelector('.ok-pointer-marker')).toBeNull();- });-- test('with the pointer never moved, the capture runs with no marker and nothing else changes', async () => {- stopPointerTracking = installPointerPositionTracker();-- let markersAtCapture = -1;- const log = installBridge({- captureScreenshot: () => {- markersAtCapture = document.querySelectorAll('.ok-pointer-marker').length;- return Promise.resolve(SCREENSHOT);- },- });- await renderDialog();-- expect(markersAtCapture).toBe(0);- expect(log.screenshotCalls).toBe(1);- expect(screen.getByRole('checkbox', { name: 'Screenshot' })).not.toBeNull();- });-test('the screenshot hint promises a pointer marker only when one was drawn', async () => {- stopPointerTracking = installPointerPositionTracker();- movePointerTo(120, 140);- installBridge({ captureScreenshot: () => Promise.resolve(SCREENSHOT) });- await renderDialog();+ installBridge();+ await renderDialog({ capture: { screenshot: SCREENSHOT, pointerMarked: true } });expect(screen.getByText(/with the pointer marked/)).not.toBeNull();});test('with no marker drawn, the hint does not mention one', async () => {- stopPointerTracking = installPointerPositionTracker();- installBridge({ captureScreenshot: () => Promise.resolve(SCREENSHOT) });- await renderDialog();+ installBridge();+ await renderDialog({ capture: WITH_SCREENSHOT });expect(screen.getByRole('checkbox', { name: 'Screenshot' })).not.toBeNull();expect(screen.queryByText(/with the pointer marked/)).toBeNull();expect(screen.getByText(/Captured before this dialog\./)).not.toBeNull();});- test('a rejected capture still takes the marker off the screen', async () => {- stopPointerTracking = installPointerPositionTracker();- movePointerTo(80, 90);-- let markersAtCapture = -1;- installBridge({- captureScreenshot: () => {- markersAtCapture = document.querySelectorAll('.ok-pointer-marker').length;- return Promise.reject(new Error('capture failed'));- },- });- await renderDialog();-- expect(markersAtCapture).toBe(1);- expect(document.querySelector('.ok-pointer-marker')).toBeNull();- });-- test('closing before the capture resolves takes the marker with it', async () => {- stopPointerTracking = installPointerPositionTracker();- movePointerTo(80, 90);-- const pending = deferred<OkBugReportScreenshot>();- installBridge({ captureScreenshot: () => pending.promise });- const { ReportBugDialog } = await import('./ReportBugDialog');- const { rerender } = render(- <TooltipProvider>- <ReportBugDialog open onOpenChange={() => {}} />- </TooltipProvider>,- );-- await waitFrames(3);- expect(document.querySelectorAll('.ok-pointer-marker')).toHaveLength(1);-- rerender(- <TooltipProvider>- <ReportBugDialog open={false} onOpenChange={() => {}} />- </TooltipProvider>,- );- expect(document.querySelector('.ok-pointer-marker')).toBeNull();-- pending.resolve(SCREENSHOT);- await waitFrames(1);- });-- test('a capture that lands after the reveal timeout is discarded, not offered', async () => {- stopPointerTracking = installPointerPositionTracker();- movePointerTo(140, 200);-- const pending = deferred<OkBugReportScreenshot>();- const log = installBridge({ captureScreenshot: () => pending.promise });- const { ReportBugDialog } = await import('./ReportBugDialog');- render(- <TooltipProvider>- <ReportBugDialog open onOpenChange={() => {}} />- </TooltipProvider>,- );-- await screen.findByRole('dialog', {}, { timeout: 3000 });- expect(screen.queryByRole('checkbox', { name: 'Screenshot' })).toBeNull();- expect(document.querySelector('.ok-pointer-marker')).toBeNull();-- pending.resolve(SCREENSHOT);- await waitFrames(3);- expect(screen.queryByRole('checkbox', { name: 'Screenshot' })).toBeNull();- expect(log.screenshotCalls).toBe(1);- });-- test('a frame that lands after the reveal timeout draws no marker to strand on screen', async () => {- stopPointerTracking = installPointerPositionTracker();- movePointerTo(310, 190);-- const queued: FrameRequestCallback[] = [];- const rafSpy = vi- .spyOn(window, 'requestAnimationFrame')- .mockImplementation((cb: FrameRequestCallback) => queued.push(cb));-- const log = installBridge({ captureScreenshot: () => Promise.resolve(SCREENSHOT) });- const { ReportBugDialog } = await import('./ReportBugDialog');- render(- <TooltipProvider>- <ReportBugDialog open onOpenChange={() => {}} />- </TooltipProvider>,- );-- try {- await vi.waitFor(() => expect(queued.length).toBeGreaterThan(0), { timeout: 5000 });- await screen.findByRole('dialog', {}, { timeout: 5000 });- expect(log.screenshotCalls).toBe(0);- } finally {- rafSpy.mockRestore();- }-- await act(async () => {- for (let i = 0; i < 4 && queued.length > 0; i += 1) {- for (const cb of queued.splice(0)) cb(performance.now());- await Promise.resolve();- }- });-- expect(document.querySelector('.ok-pointer-marker')).toBeNull();- expect(log.screenshotCalls).toBe(0);- });-- test('a crash invite draws no marker — it takes no screenshot to draw one into', async () => {- stopPointerTracking = installPointerPositionTracker();- movePointerTo(80, 90);-- const log = installBridge({ captureScreenshot: () => Promise.resolve(SCREENSHOT) });- await renderDialog({ crashInvite: BOOT_INVITE });-- expect(log.screenshotCalls).toBe(0);- expect(document.querySelector('.ok-pointer-marker')).toBeNull();- });-- test('a launcher-borne capture draws no marker — the row it would mark is gone', async () => {- stopPointerTracking = installPointerPositionTracker();- movePointerTo(500, 300);-- const launcher = document.createElement('div');- launcher.setAttribute('cmdk-root', '');- document.body.appendChild(launcher);-- let markersAtCapture = -1;- const log = installBridge({- captureScreenshot: () => {- markersAtCapture = document.querySelectorAll('.ok-pointer-marker').length;- return Promise.resolve(SCREENSHOT);- },- });- const { ReportBugDialog } = await import('./ReportBugDialog');- render(- <TooltipProvider>- <ReportBugDialog open onOpenChange={() => {}} launcherBorne />- </TooltipProvider>,- );-- await waitFrames(3);- launcher.remove();- await screen.findByRole('dialog');-- expect(log.screenshotCalls).toBe(1);- expect(markersAtCapture).toBe(0);- expect(document.querySelector('.ok-pointer-marker')).toBeNull();- });-- test('the capture waits for the launcher (⌘K palette) to clear before revealing', async () => {- const launcher = document.createElement('div');- launcher.setAttribute('cmdk-root', '');- document.body.appendChild(launcher);-- let launcherAtCapture: boolean | null = null;- const log = installBridge({- captureScreenshot: () => {- launcherAtCapture = document.querySelector('[cmdk-root]') !== null;- return Promise.resolve(SCREENSHOT);- },- });- const { ReportBugDialog } = await import('./ReportBugDialog');- render(- <TooltipProvider>- <ReportBugDialog open onOpenChange={() => {}} launcherBorne />- </TooltipProvider>,- );-- await waitFrames(6);- expect(log.screenshotCalls).toBe(0);- expect(screen.queryByRole('dialog')).toBeNull();-- launcher.remove();- await screen.findByRole('dialog');- expect(log.screenshotCalls).toBe(1);- expect(launcherAtCapture).toBe(false);- 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();+ test('a capture that came back empty reveals the dialog with no screenshot option', async () => {+ installBridge();+ await renderDialog({ capture: BUG_REPORT_NO_CAPTURE });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) });+ test('the crash-invite variant opens with no screenshot option', async () => {+ installBridge();await renderDialog({ crashInvite: BOOT_INVITE });- expect(log.screenshotCalls).toBe(0);expect(screen.queryByRole('checkbox', { name: 'Screenshot' })).toBeNull();expect(screen.getByText('OpenKnowledge quit unexpectedly last time.')).not.toBeNull();});@@ -1672,8 +1385,8 @@ describe('ReportBugDialog — reporter attachments', () => {describe('compact report interactions', () => {test('enlarging a screenshot preserves the note and screenshot opt-out and restores focus', async () => {- installBridge({ captureScreenshot: async () => SCREENSHOT });- await renderDialog({}, { statefulOpen: true });+ installBridge();+ await renderDialog({ capture: WITH_SCREENSHOT }, { statefulOpen: true });await userEvent.type(screen.getByRole('textbox', { name: /what happened/i }),'Keep this draft',diff --git a/packages/app/src/components/ReportBugDialog.tsx b/packages/app/src/components/ReportBugDialog.tsxindex 31764859e..c926ddc37 100644--- a/packages/app/src/components/ReportBugDialog.tsx+++ b/packages/app/src/components/ReportBugDialog.tsx@@ -1,49 +1,35 @@-import type { OkBugReportScreenshot } from '@inkeep/open-knowledge-core/logger-types';import { lazy, Suspense, useEffect, useRef, useState } from 'react';-import { getLastPointerPosition } from '@/lib/pointer-position';-import type { ReportBugDialogProps } from './ReportBugDialogBody';+import type { BugReportCapture } from '@/lib/bug-report-capture';+import type { ReportBugDialogProps as ReportBugDialogBodyProps } from './ReportBugDialogBody';const ReportBugDialogBody = lazy(() => import('./ReportBugDialogBody'));-const CAPTURE_REVEAL_TIMEOUT_MS = 1200;--const LAUNCHER_SELECTOR = '[cmdk-root],[data-radix-popper-content-wrapper]';--const CAPTURE_SETTLE_DEADLINE_MS = 500;--function markPointerPosition(): (() => void) | null {- const position = getLastPointerPosition();- if (position === null) return null;- const marker = document.createElement('div');- marker.className = 'ok-pointer-marker';- marker.setAttribute('aria-hidden', 'true');- marker.style.left = `${position.x}px`;- marker.style.top = `${position.y}px`;- document.body.append(marker);- return () => marker.remove();-}--interface ReportBugDialogGateProps extends ReportBugDialogProps {- launcherBorne?: boolean;+export interface ReportBugDialogGateProps+ extends Omit<+ ReportBugDialogBodyProps,+ 'open' | 'onOpenChange' | 'screenshot' | 'pointerMarked' | 'crashDumpAvailable'+ > {+ capture: BugReportCapture | null;+ onClose: () => void;}-export function ReportBugDialog({ launcherBorne = false, ...props }: ReportBugDialogGateProps) {- const [everOpened, setEverOpened] = useState(props.open);- const [ready, setReady] = useState(false);- const [screenshot, setScreenshot] = useState<OkBugReportScreenshot | null>(null);- const [pointerMarked, setPointerMarked] = useState(false);+export function ReportBugDialog({ capture, onClose, ...props }: ReportBugDialogGateProps) {+ const open = capture !== null;+ const [everOpened, setEverOpened] = useState(open);+ const [lastCapture, setLastCapture] = useState(capture);const [crashDumpAvailable, setCrashDumpAvailable] = useState(false);const openCycleRef = useRef(0);- if (props.open && !everOpened) {+ if (open && !everOpened) {setEverOpened(true);}+ if (capture !== null && capture !== lastCapture) {+ setLastCapture(capture);+ }+ const shown = capture ?? lastCapture;useEffect(() => {- if (!props.open) {- setReady(false);- return;- }+ if (!open) return;const cycle = ++openCycleRef.current;setCrashDumpAvailable(false);const availability = window.okDesktop?.bugReport?.crashDumpAvailability;@@ -57,64 +43,10 @@ export function ReportBugDialog({ launcherBorne = false, ...props }: ReportBugDiconsole.warn('[bug-report] crash-dump availability probe failed:', err);});}- const capture = window.okDesktop?.bugReport?.captureScreenshot;- if (typeof capture !== 'function' || props.crashInvite !== undefined) {- setScreenshot(null);- setReady(true);- return;- }- setScreenshot(null);- let settled = false;- let removePointerMarker = () => {};- let marked = false;- const settle = (shot: OkBugReportScreenshot | null) => {- if (settled || openCycleRef.current !== cycle) return;- settled = true;- removePointerMarker();- setScreenshot(shot);- setPointerMarked(shot !== null && marked);- setReady(true);- };- const revealTimer = setTimeout(() => {- console.warn(- `[bug-report] screenshot capture did not settle within ${CAPTURE_REVEAL_TIMEOUT_MS}ms; revealing without one`,- );- settle(null);- }, CAPTURE_REVEAL_TIMEOUT_MS);- const startedAt = performance.now();- let rafId = 0;- const settleThenCapture = () => {- if (settled || openCycleRef.current !== cycle) return;- const pastDeadline = performance.now() - startedAt >= CAPTURE_SETTLE_DEADLINE_MS;- if (launcherBorne && document.querySelector(LAUNCHER_SELECTOR) !== null && !pastDeadline) {- rafId = requestAnimationFrame(settleThenCapture);- return;- }- if (!launcherBorne) {- const remove = markPointerPosition();- if (remove !== null) {- removePointerMarker = remove;- marked = true;- }- }- rafId = requestAnimationFrame(() => {- if (settled || openCycleRef.current !== cycle) return;- capture()- .then(settle)- .catch((err: unknown) => {- console.warn('[bug-report] screenshot capture failed:', err);- settle(null);- });- });- };- rafId = requestAnimationFrame(settleThenCapture);return () => {openCycleRef.current += 1;- clearTimeout(revealTimer);- cancelAnimationFrame(rafId);- removePointerMarker();};- }, [props.open, props.crashInvite, launcherBorne]);+ }, [open, props.crashInvite]);if (!everOpened) {return null;@@ -123,9 +55,12 @@ export function ReportBugDialog({ launcherBorne = false, ...props }: ReportBugDi<Suspense fallback={null}><ReportBugDialogBody{...props}- open={props.open && ready}- screenshot={screenshot}- pointerMarked={pointerMarked}+ open={open}+ onOpenChange={(next) => {+ if (!next) onClose();+ }}+ screenshot={shown?.screenshot ?? null}+ pointerMarked={shown?.pointerMarked ?? false}crashDumpAvailable={crashDumpAvailable}/></Suspense>diff --git a/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsx b/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsxindex b9630849f..71ebea4a0 100644--- a/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsx+++ b/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsx@@ -1,18 +1,20 @@import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { afterEach, describe, expect, test, vi } from 'vitest';+import type { BugReportCapture } from '@/lib/bug-report-capture';import { KEYBOARD_SHORTCUTS } from '@/lib/keyboard-shortcuts';import {__resetLocalMenuActionBusForTests,emitLocalMenuAction,} from '@/lib/local-menu-action-bus';+import { installPointerPositionTracker } from '@/lib/pointer-position';import { ReportBugMenuTrigger } from './ReportBugMenuTrigger';vi.mock('./ReportBugDialog', () => ({- ReportBugDialog: ({ open, launcherBorne }: { open: boolean; launcherBorne?: boolean }) =>- open ? (+ ReportBugDialog: ({ capture }: { capture: BugReportCapture | null }) =>+ capture !== null ? (<divaria-label="Report a bug"- data-launcher-borne={String(launcherBorne === true)}+ data-pointer-marked={String(capture.pointerMarked)}role="dialog"/>) : null,@@ -46,12 +48,47 @@ function fireMenuAction(act(() => emitLocalMenuAction(action, origin));}+function installCaptureBridge(): { calls: number } {+ const log = { calls: 0 };+ Object.defineProperty(window, 'okDesktop', {+ configurable: true,+ writable: true,+ value: {+ bugReport: {+ captureScreenshot: () => {+ log.calls += 1;+ return Promise.resolve({+ dataUrl: 'data:image/png;base64,iVBORw0KGgo=',+ width: 1,+ height: 1,+ });+ },+ },+ },+ });+ return log;+}+describe('ReportBugMenuTrigger', () => {+ let stopPointerTracking: (() => void) | undefined;+afterEach(() => {cleanup();__resetLocalMenuActionBusForTests();+ stopPointerTracking?.();+ stopPointerTracking = undefined;+ Object.defineProperty(window, 'okDesktop', {+ configurable: true,+ writable: true,+ value: undefined,+ });});+ function trackPointerAt(x: number, y: number): void {+ stopPointerTracking = installPointerPositionTracker();+ window.dispatchEvent(new PointerEvent('pointermove', { clientX: x, clientY: y }));+ }+test('dialog is closed until the report-bug menu action fires', () => {render(<ReportBugMenuTrigger />);expect(screen.queryByRole('dialog')).toBeNull();@@ -96,37 +133,41 @@ describe('ReportBugMenuTrigger', () => {expect(screen.queryByRole('dialog')).toBeNull();});- test('a native-menu dispatch opens a report that captures without waiting', async () => {+ test('a native-menu dispatch opens a report whose shot marks the pointer', async () => {+ trackPointerAt(120, 80);+ installCaptureBridge();render(<ReportBugMenuTrigger />);fireMenuAction('report-bug');const dialog = await screen.findByRole('dialog');- expect(dialog.dataset.launcherBorne).toBe('false');+ expect(dialog.dataset.pointerMarked).toBe('true');});- test('an in-app menubar dispatch opens a report that waits out the menu', async () => {+ test('an in-app menubar dispatch opens a report whose shot leaves the pointer unmarked', async () => {+ trackPointerAt(120, 80);+ installCaptureBridge();render(<ReportBugMenuTrigger />);fireMenuAction('report-bug', { launcherBorne: true });const dialog = await screen.findByRole('dialog');- expect(dialog.dataset.launcherBorne).toBe('true');+ expect(dialog.dataset.pointerMarked).toBe('false');});- test('a second dispatch while open keeps the origin the capture was taken for', async () => {+ test('a second dispatch while open keeps the capture the first one took', async () => {+ trackPointerAt(120, 80);+ const log = installCaptureBridge();render(<ReportBugMenuTrigger />);fireMenuAction('report-bug');await screen.findByRole('dialog');fireMenuAction('report-bug', { launcherBorne: true });- await waitFor(- () => {- expect(screen.getByRole('dialog').dataset.launcherBorne).toBe('false');- },- { timeout: ASYNC_TIMEOUT_MS },- );+ for (let frame = 0; frame < 3; frame++)+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ expect(screen.getByRole('dialog').dataset.pointerMarked).toBe('true');+ expect(log.calls).toBe(1);});test('unsubscribes from the bus on unmount', async () => {diff --git a/packages/app/src/components/ReportBugMenuTrigger.tsx b/packages/app/src/components/ReportBugMenuTrigger.tsxindex c3cf217ff..b084e0bb5 100644--- a/packages/app/src/components/ReportBugMenuTrigger.tsx+++ b/packages/app/src/components/ReportBugMenuTrigger.tsx@@ -1,6 +1,6 @@-import { useEffect, useState } from 'react';+import { useEffect } from 'react';import { ReportBugDialog } from '@/components/ReportBugDialog';-import type { OkMenuActionOrigin } from '@/lib/desktop-bridge-types';+import { useBugReport } from '@/lib/bug-report-capture';import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';interface ReportBugMenuTriggerProps {@@ -8,22 +8,18 @@ interface ReportBugMenuTriggerProps {}export function ReportBugMenuTrigger({ systemWide }: ReportBugMenuTriggerProps) {- const [origin, setOrigin] = useState<OkMenuActionOrigin | null>(null);+ const bugReport = useBugReport();useEffect(() => {- return subscribeLocalMenuAction((action, dispatchOrigin) => {- if (action !== 'report-bug') return;- setOrigin((current) => current ?? dispatchOrigin);+ return subscribeLocalMenuAction((action, origin) => {+ if (action === 'report-bug') bugReport.start(origin);});- }, []);+ }, [bugReport.start]);return (<ReportBugDialog- open={origin !== null}- onOpenChange={(next) => {- if (!next) setOrigin(null);- }}- launcherBorne={origin?.launcherBorne === true}+ capture={bugReport.capture}+ onClose={bugReport.close}systemWide={systemWide}/>);diff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsxindex eedeb24ea..ae68197de 100644--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx@@ -6458,14 +6458,14 @@ describe('ThreadView reporting a problem with the chat', () => {}}, 30_000);- test('the screenshot waits for the settings menu to close and marks no row', async () => {+ test('the screenshot is shot before the report opens, with the settings menu marked as its launcher and no row marked', async () => {const stopPointerTracking = installPointerPositionTracker();window.dispatchEvent(new PointerEvent('pointermove', { clientX: 240, clientY: 160, bubbles: true }),);let captures = 0;let markersAtCapture = -1;- let menuAtCapture: boolean | null = null;+ let reportOpenAtCapture: boolean | null = null;Object.assign(window, {okDesktop: {bugReport: {@@ -6473,7 +6473,8 @@ describe('ThreadView reporting a problem with the chat', () => {captureScreenshot: () => {captures += 1;markersAtCapture = document.querySelectorAll('.ok-pointer-marker').length;- menuAtCapture = screen.queryByTestId('agent-thread-settings-popover') !== null;+ reportOpenAtCapture =+ screen.queryByRole('checkbox', { name: 'This conversation' }) !== null;return Promise.resolve(null);},},@@ -6483,12 +6484,14 @@ describe('ThreadView reporting a problem with the chat', () => {model = makeModel({ items: [], turnActive: false });render(<ThreadView info={makeInfo({ status: 'ready' })} />);await userEvent.click(screen.getByRole('button', { name: /^Agent settings/ }));+ const menu = await screen.findByTestId('agent-thread-settings-popover');+ expect(menu.hasAttribute('data-bug-report-launcher')).toBe(true);await userEvent.click(await screen.findByTestId('agent-thread-report-problem'));await screen.findByRole('checkbox', { name: 'This conversation' }, { timeout: 15_000 });expect(captures).toBe(1);expect(markersAtCapture).toBe(0);- expect(menuAtCapture).toBe(false);+ expect(reportOpenAtCapture).toBe(false);} finally {stopPointerTracking();Reflect.deleteProperty(window, 'okDesktop');diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsxindex baa68304f..1fea56ef1 100644--- a/packages/app/src/components/acp/ThreadView.tsx+++ b/packages/app/src/components/acp/ThreadView.tsx@@ -196,6 +196,7 @@ import {type ToolOutputMode,toolOutputMode,} from '@/lib/acp/tool-output-format';+import { useBugReport } from '@/lib/bug-report-capture';import { docNameFromHash, filePathToDocName, hashFromDocName } from '@/lib/doc-hash';import { dispatchExternalLinkClick } from '@/lib/external-link';import { isOverlayLayerOpen } from '@/lib/overlay-layers';@@ -1787,6 +1788,7 @@ function AgentSettingsPopover({<DropdownMenuContentalign="end"className="w-60"+ data-bug-report-launcher=""data-testid="agent-thread-settings-popover"><DropdownMenuLabel className="font-normal text-muted-foreground">@@ -1881,7 +1883,12 @@ function AgentSettingsPopover({</AgentSettingsTrigger></DropdownMenuTrigger>{}- <DropdownMenuContent align="end" className="w-60" data-testid="agent-thread-settings-popover">+ <DropdownMenuContent+ align="end"+ className="w-60"+ data-bug-report-launcher=""+ data-testid="agent-thread-settings-popover"+ >{}{info.archived === true ? (<DropdownMenuLabel@@ -4385,7 +4392,7 @@ function ThreadComposer({onIngestAllFiles: (files: readonly File[]) => Promise<void>;onRemovePendingAttachment: (index: number) => void;}): ReactNode {- const [reportOpen, setReportOpen] = useState(false);+ const bugReport = useBugReport();const canReportProblem = typeof window !== 'undefined' && window.okDesktop != null;const { t, i18n } = useLingui();const agentName = agentDisplayName(info.agent.name);@@ -4554,15 +4561,16 @@ function ThreadComposer({info={info}hasStartedWork={hasStartedWork}onNewChat={onNewChat}- {...(canReportProblem ? { onReportProblem: () => setReportOpen(true) } : {})}+ {...(canReportProblem+ ? { onReportProblem: () => bugReport.start({ launcherBorne: true }) }+ : {})}triggerRef={settingsTriggerRef}/>{canReportProblem ? (<ReportBugDialog- open={reportOpen}- onOpenChange={setReportOpen}+ capture={bugReport.capture}+ onClose={bugReport.close}agentChat={{ threadId: info.threadId }}- launcherBorne/>) : null}<div className="ml-auto flex items-center gap-1.5">diff --git a/packages/app/src/components/command-palette-commands.ts b/packages/app/src/components/command-palette-commands.tsindex da7897bc5..7f146eb5c 100644--- a/packages/app/src/components/command-palette-commands.ts+++ b/packages/app/src/components/command-palette-commands.ts@@ -98,7 +98,7 @@ export interface PaletteCommandContext {openNewItemDialog(kind: 'file' | 'folder'): void;openSeedDialog(): void;openCreateProjectDialog(): void;- openReportBugDialog(): void;+ reportBug(): void;openBugReportHistory(): void;openFeedbackDialog(): void;createBlankSkill(): void;@@ -325,8 +325,7 @@ const COMMAND_DISPATCH: Record<string, (ctx: PaletteCommandContext) => void> = {window.location.hash = '#install-claude-desktop';},'report-bug': (ctx) => {- ctx.closePalette();- ctx.openReportBugDialog();+ ctx.reportBug();},'bug-report-history': (ctx) => {ctx.closePalette();diff --git a/packages/app/src/components/ui/command.browser.test.tsx b/packages/app/src/components/ui/command.browser.test.tsxnew file mode 100644index 000000000..15b02545e--- /dev/null+++ b/packages/app/src/components/ui/command.browser.test.tsx@@ -0,0 +1,66 @@+import { cleanup, screen } from '@testing-library/react';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { captureBugReport } from '@/lib/bug-report-capture';+import { renderWithI18n } from '../../../tests/foundation/render-with-i18n.test-helper';+import { CommandDialog } from './command';++type Visibility = { content: string; overlay: string };++function overlayOf(content: HTMLElement): HTMLElement {+ const overlay = content.parentElement?.querySelector<HTMLElement>('[data-slot="dialog-overlay"]');+ if (overlay == null) throw new Error('the dialog content has no sibling overlay');+ return overlay;+}++function recordVisibilityAtCapture(content: HTMLElement): { seen: Visibility | null } {+ const record: { seen: Visibility | null } = { seen: null };+ (window as unknown as { okDesktop?: unknown }).okDesktop = {+ bugReport: {+ captureScreenshot: async () => {+ record.seen = {+ content: getComputedStyle(content).visibility,+ overlay: getComputedStyle(overlayOf(content)).visibility,+ };+ return null;+ },+ },+ };+ return record;+}++function renderLauncherDialog(): HTMLElement {+ renderWithI18n(+ <CommandDialog open title="Palette" contentAttributes={{ 'data-bug-report-launcher': '' }}>+ <p>palette body</p>+ </CommandDialog>,+ );+ return screen.getByRole('dialog', { name: 'Palette' });+}++afterEach(async () => {+ cleanup();+ (window as unknown as { okDesktop?: unknown }).okDesktop = undefined;+ await vi.waitFor(() =>+ expect(document.documentElement.hasAttribute('data-bug-report-capturing')).toBe(false),+ );+});++describe('CommandDialog marked as a bug-report launcher', () => {+ test('a report started from inside it leaves the dialog and its backdrop out of the shot', async () => {+ const content = renderLauncherDialog();+ const record = recordVisibilityAtCapture(content);++ await captureBugReport({ launcherBorne: true });++ expect(record.seen).toEqual({ content: 'hidden', overlay: 'hidden' });+ });++ test('the report shortcut photographs the open dialog and its backdrop', async () => {+ const content = renderLauncherDialog();+ const record = recordVisibilityAtCapture(content);++ await captureBugReport({ launcherBorne: false });++ expect(record.seen).toEqual({ content: 'visible', overlay: 'visible' });+ });+});diff --git a/packages/app/src/components/ui/command.tsx b/packages/app/src/components/ui/command.tsxindex d83ff3de5..80962d3a0 100644--- a/packages/app/src/components/ui/command.tsx+++ b/packages/app/src/components/ui/command.tsx@@ -24,6 +24,7 @@ interface CommandDialogProps extends ComponentProps<typeof Dialog> {showCloseButton?: boolean;commandProps?: ComponentProps<typeof CommandPrimitive>;onEscapeKeyDown?: ComponentProps<typeof DialogContent>['onEscapeKeyDown'];+ contentAttributes?: Record<`data-${string}`, string>;}function CommandDialog({@@ -34,6 +35,7 @@ function CommandDialog({showCloseButton = true,commandProps,onEscapeKeyDown,+ contentAttributes,...props}: CommandDialogProps) {const { className: commandClassName, ...restCommandProps } = commandProps ?? {};@@ -43,6 +45,7 @@ function CommandDialog({className={cn('top-[12vh] translate-y-0 overflow-hidden p-0', className)}showCloseButton={showCloseButton}onEscapeKeyDown={onEscapeKeyDown}+ {...contentAttributes}>{}<DialogTitle className="sr-only">{title}</DialogTitle>diff --git a/packages/app/src/globals.css b/packages/app/src/globals.cssindex 7d1fca82b..baea1d87e 100644--- a/packages/app/src/globals.css+++ b/packages/app/src/globals.css@@ -6854,6 +6854,16 @@ html [data-editor-file-list-slot] [data-slot="sidebar-inner"] {forced-color-adjust: none;}+html[data-bug-report-capturing] [data-bug-report-launcher] {+ visibility: hidden;+ transition: none;+}++html[data-bug-report-capturing] [data-slot="dialog-overlay"]:has(~ [data-bug-report-launcher]) {+ visibility: hidden;+ transition: none;+}+html:not([data-color-theme]):not(.dark).raw-mdx-fallback-wrapper[data-severity="error"]> divdiff --git a/packages/app/src/lib/bug-report-capture.dom.test.ts b/packages/app/src/lib/bug-report-capture.dom.test.tsnew file mode 100644index 000000000..584dc935d--- /dev/null+++ b/packages/app/src/lib/bug-report-capture.dom.test.ts@@ -0,0 +1,361 @@+import type { OkBugReportScreenshot } from '@inkeep/open-knowledge-core/logger-types';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { collectBlocks, readGlobalsCssRaw } from '@/globals-css.test-helper';+import { installPointerPositionTracker } from '@/lib/pointer-position';+import {+ type BugReportCapture,+ captureBugReport,+ createBugReportController,+} from './bug-report-capture';++const SCREENSHOT: OkBugReportScreenshot = {+ dataUrl: 'data:image/png;base64,iVBORw0KGgo=',+ width: 1200,+ height: 800,+};++const LAUNCHER_FREE = { launcherBorne: false } as const;+const LAUNCHER_BORNE = { launcherBorne: true } as const;++function installCapture(capture: () => Promise<OkBugReportScreenshot | null>): { calls: number } {+ const log = { calls: 0 };+ Object.defineProperty(window, 'okDesktop', {+ configurable: true,+ writable: true,+ value: {+ bugReport: {+ captureScreenshot: () => {+ log.calls += 1;+ return capture();+ },+ },+ },+ });+ return log;+}++function installLauncherStylesheet(): HTMLStyleElement {+ const rule = collectBlocks(readGlobalsCssRaw()).find((block) =>+ block.prelude.includes('[data-bug-report-launcher]'),+ );+ expect(rule, 'globals.css declares the launcher-hiding rule').toBeDefined();+ const style = document.createElement('style');+ style.textContent = `${rule?.prelude}{${rule?.declarations}}`;+ document.head.append(style);+ return style;+}++function movePointerTo(x: number, y: number): void {+ window.dispatchEvent(new PointerEvent('pointermove', { clientX: x, clientY: y, bubbles: true }));+}++async function releaseHeldFrames(queued: FrameRequestCallback[]): Promise<void> {+ vi.mocked(window.requestAnimationFrame).mockRestore();+ for (const cb of queued.splice(0)) cb(performance.now());+ await vi.waitFor(() =>+ expect(document.documentElement.hasAttribute('data-bug-report-capturing')).toBe(false),+ );+}++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((r) => {+ resolve = r;+ });+ return { promise, resolve };+}++describe('captureBugReport', () => {+ let stopPointerTracking: (() => void) | undefined;++ afterEach(() => {+ stopPointerTracking?.();+ stopPointerTracking = undefined;+ vi.restoreAllMocks();+ Object.defineProperty(window, 'okDesktop', {+ configurable: true,+ writable: true,+ value: undefined,+ });+ document.body.replaceChildren();+ document.head.replaceChildren();+ document.documentElement.removeAttribute('data-bug-report-capturing');+ });++ test('hides launcher-marked elements and nothing else while the bridge shoots, then restores them', async () => {+ installLauncherStylesheet();+ const launcher = document.createElement('div');+ launcher.setAttribute('data-bug-report-launcher', '');+ const overlay = document.createElement('div');+ overlay.setAttribute('data-radix-popper-content-wrapper', '');+ document.body.append(launcher, overlay);++ let visibilityAtCapture: { launcher: string; overlay: string } | null = null;+ installCapture(() => {+ visibilityAtCapture = {+ launcher: getComputedStyle(launcher).visibility,+ overlay: getComputedStyle(overlay).visibility,+ };+ return Promise.resolve(SCREENSHOT);+ });++ const result = await captureBugReport(LAUNCHER_BORNE);++ expect(visibilityAtCapture).toEqual({ launcher: 'hidden', overlay: 'visible' });+ expect(result).toEqual({ screenshot: SCREENSHOT, pointerMarked: false });+ await vi.waitFor(() => expect(getComputedStyle(launcher).visibility).toBe('visible'));+ expect(document.documentElement.hasAttribute('data-bug-report-capturing')).toBe(false);+ });++ test('a launcher-free origin keeps launcher-marked menus in the shot', async () => {+ installLauncherStylesheet();+ const launcher = document.createElement('div');+ launcher.setAttribute('data-bug-report-launcher', '');+ document.body.append(launcher);++ let visibilityAtCapture: string | null = null;+ installCapture(() => {+ visibilityAtCapture = getComputedStyle(launcher).visibility;+ return Promise.resolve(SCREENSHOT);+ });++ await captureBugReport(LAUNCHER_FREE);++ expect(visibilityAtCapture).toBe('visible');+ });++ test('overlapping launcher-borne captures keep launchers hidden until the last one settles', async () => {+ const first = deferred<OkBugReportScreenshot>();+ const second = deferred<OkBugReportScreenshot>();+ const queue = [first.promise, second.promise];+ const log = installCapture(() => queue.shift() ?? Promise.resolve(null));+ const capturing = () => document.documentElement.hasAttribute('data-bug-report-capturing');++ const a = captureBugReport(LAUNCHER_BORNE);+ const b = captureBugReport(LAUNCHER_BORNE);+ await vi.waitFor(() => expect(log.calls).toBe(2));+ first.resolve(SCREENSHOT);+ await a;+ for (let frame = 0; frame < 4; frame += 1) {+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ }+ expect(capturing()).toBe(true);+ second.resolve(SCREENSHOT);+ await b;+ await vi.waitFor(() => expect(capturing()).toBe(false));+ });++ test('a launcher-free origin puts the pointer marker in the frame and takes it out afterwards', async () => {+ stopPointerTracking = installPointerPositionTracker();+ movePointerTo(420, 260);++ let markerAtCapture: { left: string; top: string } | null = null;+ installCapture(() => {+ const marker = document.querySelector<HTMLElement>('.ok-pointer-marker');+ markerAtCapture = marker && { left: marker.style.left, top: marker.style.top };+ return Promise.resolve(SCREENSHOT);+ });++ const result = await captureBugReport(LAUNCHER_FREE);++ expect(markerAtCapture).toEqual({ left: '420px', top: '260px' });+ expect(document.querySelector('.ok-pointer-marker')).toBeNull();+ expect(result).toEqual({ screenshot: SCREENSHOT, pointerMarked: true });+ });++ test('a launcher-borne origin draws no marker even with the pointer known', async () => {+ stopPointerTracking = installPointerPositionTracker();+ movePointerTo(500, 300);++ let markersAtCapture = -1;+ installCapture(() => {+ markersAtCapture = document.querySelectorAll('.ok-pointer-marker').length;+ return Promise.resolve(SCREENSHOT);+ });++ const result = await captureBugReport(LAUNCHER_BORNE);++ expect(markersAtCapture).toBe(0);+ expect(result.pointerMarked).toBe(false);+ });++ test('with the pointer never seen, a launcher-free capture draws no marker and says so', async () => {+ stopPointerTracking = installPointerPositionTracker();++ let markersAtCapture = -1;+ installCapture(() => {+ markersAtCapture = document.querySelectorAll('.ok-pointer-marker').length;+ return Promise.resolve(SCREENSHOT);+ });++ const result = await captureBugReport(LAUNCHER_FREE);++ expect(markersAtCapture).toBe(0);+ expect(result).toEqual({ screenshot: SCREENSHOT, pointerMarked: false });+ });++ test('a bridge with no capture resolves empty without touching the document', async () => {+ stopPointerTracking = installPointerPositionTracker();+ movePointerTo(10, 10);+ const observed: string[] = [];+ const observer = new MutationObserver((records) => {+ for (const record of records) observed.push(record.type);+ });+ observer.observe(document.documentElement, {+ attributes: true,+ childList: true,+ subtree: true,+ });++ const result = await captureBugReport(LAUNCHER_FREE);+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ observer.disconnect();++ expect(result).toEqual({ screenshot: null, pointerMarked: false });+ expect(observed).toEqual([]);+ });++ test('a rejected capture resolves empty and still cleans up', async () => {+ stopPointerTracking = installPointerPositionTracker();+ movePointerTo(80, 90);+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ let markersAtCapture = -1;+ installCapture(() => {+ markersAtCapture = document.querySelectorAll('.ok-pointer-marker').length;+ return Promise.reject(new Error('capture failed'));+ });++ const result = await captureBugReport(LAUNCHER_FREE);++ expect(markersAtCapture).toBe(1);+ expect(result).toEqual({ screenshot: null, pointerMarked: false });+ expect(document.querySelector('.ok-pointer-marker')).toBeNull();+ expect(document.documentElement.hasAttribute('data-bug-report-capturing')).toBe(false);+ expect(warn).toHaveBeenCalledWith('[bug-report] screenshot capture failed:', expect.any(Error));+ });++ test('a capture that outlives the reveal timeout resolves empty, cleans up, and its late frame is discarded', async () => {+ stopPointerTracking = installPointerPositionTracker();+ movePointerTo(140, 200);+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const pending = deferred<OkBugReportScreenshot>();+ const log = installCapture(() => pending.promise);++ const result = await captureBugReport(LAUNCHER_FREE);++ expect(result).toEqual({ screenshot: null, pointerMarked: false });+ expect(document.querySelector('.ok-pointer-marker')).toBeNull();+ expect(document.documentElement.hasAttribute('data-bug-report-capturing')).toBe(false);+ expect(warn).toHaveBeenCalledWith(+ '[bug-report] screenshot capture did not settle within 1200ms; revealing without one',+ );+ expect(log.calls).toBe(1);+ pending.resolve(SCREENSHOT);+ await pending.promise;+ expect(document.querySelector('.ok-pointer-marker')).toBeNull();+ });++ test('the bridge is called only after a frame showing the capturing state has painted', async () => {+ const queued: FrameRequestCallback[] = [];+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb: FrameRequestCallback) =>+ queued.push(cb),+ );+ const log = installCapture(() => Promise.resolve(SCREENSHOT));++ const result = captureBugReport(LAUNCHER_BORNE);+ expect(document.documentElement.hasAttribute('data-bug-report-capturing')).toBe(true);+ for (const cb of queued.splice(0)) cb(performance.now());+ expect(log.calls).toBe(0);+ for (const cb of queued.splice(0)) cb(performance.now());+ expect(log.calls).toBe(1);++ expect(await result).toEqual({ screenshot: SCREENSHOT, pointerMarked: false });+ await releaseHeldFrames(queued);+ });++ test('a frame that never arrives before the timeout never reaches the bridge', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const queued: FrameRequestCallback[] = [];+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb: FrameRequestCallback) =>+ queued.push(cb),+ );+ const log = installCapture(() => Promise.resolve(SCREENSHOT));++ const result = await captureBugReport(LAUNCHER_BORNE);+ expect(result.screenshot).toBeNull();+ expect(log.calls).toBe(0);++ for (const cb of queued.splice(0)) cb(performance.now());+ await Promise.resolve();+ expect(log.calls).toBe(0);+ await releaseHeldFrames(queued);+ });+});++describe('createBugReportController', () => {+ afterEach(() => {+ Object.defineProperty(window, 'okDesktop', {+ configurable: true,+ writable: true,+ value: undefined,+ });+ });++ function controllerWithLog() {+ const captures: Array<BugReportCapture | null> = [];+ const controller = createBugReportController((capture) => captures.push(capture));+ return { controller, captures };+ }++ test('start captures, runs the dismissal, then opens with the result', async () => {+ const pending = deferred<OkBugReportScreenshot>();+ installCapture(() => pending.promise);+ const { controller, captures } = controllerWithLog();+ const order: string[] = [];++ controller.start(LAUNCHER_BORNE, () => order.push('dismiss'));+ expect(captures).toEqual([]);+ pending.resolve(SCREENSHOT);+ await vi.waitFor(() => expect(captures).toHaveLength(1));++ expect(order).toEqual(['dismiss']);+ expect(captures[0]).toEqual({ screenshot: SCREENSHOT, pointerMarked: false });+ });++ test('a start while capturing or open is ignored, so the first origin wins', async () => {+ const log = installCapture(() => Promise.resolve(SCREENSHOT));+ const { controller, captures } = controllerWithLog();++ controller.start(LAUNCHER_BORNE);+ controller.start(LAUNCHER_FREE);+ await vi.waitFor(() => expect(captures).toHaveLength(1));+ controller.start(LAUNCHER_FREE);+ for (let frame = 0; frame < 2; frame++)+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));++ expect(log.calls).toBe(1);+ expect(captures).toEqual([{ screenshot: SCREENSHOT, pointerMarked: false }]);+ });++ test('close drops a result that lands afterwards and leaves the next start free to run', async () => {+ const first = deferred<OkBugReportScreenshot>();+ const second = deferred<OkBugReportScreenshot>();+ const queue = [first.promise, second.promise];+ installCapture(() => queue.shift() ?? Promise.resolve(null));+ const { controller, captures } = controllerWithLog();+ const dismissals: string[] = [];++ controller.start(LAUNCHER_BORNE, () => dismissals.push('first'));+ controller.close();+ controller.start(LAUNCHER_BORNE, () => dismissals.push('second'));+ first.resolve(SCREENSHOT);+ second.resolve({ ...SCREENSHOT, width: 1 });+ await vi.waitFor(() => expect(captures.filter((c) => c !== null)).toHaveLength(1));++ expect(dismissals).toEqual(['second']);+ expect(captures.at(-1)).toEqual({+ screenshot: { ...SCREENSHOT, width: 1 },+ pointerMarked: false,+ });+ });+});diff --git a/packages/app/src/lib/bug-report-capture.ts b/packages/app/src/lib/bug-report-capture.tsnew file mode 100644index 000000000..b588202ab--- /dev/null+++ b/packages/app/src/lib/bug-report-capture.ts@@ -0,0 +1,163 @@+import type { OkBugReportScreenshot } from '@inkeep/open-knowledge-core/logger-types';+import { useEffect, useState } from 'react';+import type { OkMenuActionOrigin } from '@/lib/desktop-bridge-types';+import { getLastPointerPosition } from '@/lib/pointer-position';++export interface BugReportCapture {+ readonly screenshot: OkBugReportScreenshot | null;+ readonly pointerMarked: boolean;+}++export const BUG_REPORT_NO_CAPTURE: BugReportCapture = Object.freeze({+ screenshot: null,+ pointerMarked: false,+});++const CAPTURING_ATTRIBUTE = 'data-bug-report-capturing';++let launcherHides = 0;++function hideLaunchers(): () => void {+ launcherHides += 1;+ document.documentElement.setAttribute(CAPTURING_ATTRIBUTE, '');+ return () => {+ launcherHides -= 1;+ if (launcherHides === 0) document.documentElement.removeAttribute(CAPTURING_ATTRIBUTE);+ };+}++const LAUNCHER_SELECTOR = '[data-bug-report-launcher]';+const LAUNCHER_LEAVE_TIMEOUT_MS = 1000;++function nextFrame(): Promise<void> {+ return new Promise((resolve) => requestAnimationFrame(() => resolve()));+}++async function showLaunchersOnceTheyLeave(show: () => void): Promise<void> {+ try {+ await nextFrame();+ await nextFrame();+ const leaving = Array.from(document.querySelectorAll<HTMLElement>(LAUNCHER_SELECTOR)).flatMap(+ (launcher) => launcher.getAnimations?.({ subtree: true }) ?? [],+ );+ await Promise.race([+ Promise.allSettled(leaving.map((animation) => animation.finished)),+ new Promise((resolve) => setTimeout(resolve, LAUNCHER_LEAVE_TIMEOUT_MS)),+ ]);+ } finally {+ show();+ }+}++const CAPTURE_REVEAL_TIMEOUT_MS = 1200;++function markPointerPosition(): (() => void) | null {+ const position = getLastPointerPosition();+ if (position === null) return null;+ const marker = document.createElement('div');+ marker.className = 'ok-pointer-marker';+ marker.setAttribute('aria-hidden', 'true');+ marker.style.left = `${position.x}px`;+ marker.style.top = `${position.y}px`;+ document.body.append(marker);+ return () => marker.remove();+}++function shootAfterPaintedFrame(+ capture: () => Promise<OkBugReportScreenshot | null>,+): Promise<OkBugReportScreenshot | null> {+ return new Promise((resolve) => {+ let settled = false;+ const settle = (shot: OkBugReportScreenshot | null) => {+ if (settled) return;+ settled = true;+ clearTimeout(revealTimer);+ resolve(shot);+ };+ const revealTimer = setTimeout(() => {+ console.warn(+ `[bug-report] screenshot capture did not settle within ${CAPTURE_REVEAL_TIMEOUT_MS}ms; revealing without one`,+ );+ settle(null);+ }, CAPTURE_REVEAL_TIMEOUT_MS);+ requestAnimationFrame(() => {+ requestAnimationFrame(() => {+ if (settled) return;+ capture().then(settle, (err: unknown) => {+ console.warn('[bug-report] screenshot capture failed:', err);+ settle(null);+ });+ });+ });+ });+}++export async function captureBugReport(origin: OkMenuActionOrigin): Promise<BugReportCapture> {+ const capture = window.okDesktop?.bugReport?.captureScreenshot;+ if (typeof capture !== 'function') return BUG_REPORT_NO_CAPTURE;+ let showLaunchers: (() => void) | null = null;+ let removePointerMarker: (() => void) | null = null;+ try {+ if (origin.launcherBorne) showLaunchers = hideLaunchers();+ else removePointerMarker = markPointerPosition();+ const screenshot = await shootAfterPaintedFrame(capture);+ return { screenshot, pointerMarked: screenshot !== null && removePointerMarker !== null };+ } finally {+ removePointerMarker?.();+ if (showLaunchers !== null) void showLaunchersOnceTheyLeave(showLaunchers);+ }+}++type Phase =+ | { readonly kind: 'idle' }+ | { readonly kind: 'capturing'; readonly pending: Promise<BugReportCapture> }+ | { readonly kind: 'open' };++const IDLE: Phase = { kind: 'idle' };++export interface BugReportController {+ start(origin: OkMenuActionOrigin, beforeOpen?: () => void): void;+ close(): void;+}++export function createBugReportController(+ onChange: (capture: BugReportCapture | null) => void,+): BugReportController {+ let phase: Phase = IDLE;+ return {+ start(origin, beforeOpen) {+ if (phase.kind !== 'idle') return;+ const pending = captureBugReport(origin);+ phase = { kind: 'capturing', pending };+ const current = () => phase.kind === 'capturing' && phase.pending === pending;+ void pending.then(+ (capture) => {+ if (!current()) return;+ phase = IDLE;+ beforeOpen?.();+ onChange(capture);+ phase = { kind: 'open' };+ },+ (err: unknown) => {+ if (current()) phase = IDLE;+ throw err;+ },+ );+ },+ close() {+ phase = IDLE;+ onChange(null);+ },+ };+}++export interface BugReportState extends BugReportController {+ readonly capture: BugReportCapture | null;+}++export function useBugReport(): BugReportState {+ const [capture, setCapture] = useState<BugReportCapture | null>(null);+ const [controller] = useState(() => createBugReportController(setCapture));+ useEffect(() => () => controller.close(), [controller]);+ return { capture, start: controller.start, close: controller.close };+}