Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): add diagnostic report flow

Gusbeaf2b24661c
diff --git a/src/web/src/components/community/bots/bot-list-card.test.ts b/src/web/src/components/community/bots/bot-list-card.test.ts
index 550db8153..9de072dcc 100644
--- a/src/web/src/components/community/bots/bot-list-card.test.ts
+++ b/src/web/src/components/community/bots/bot-list-card.test.ts
@@ -8,6 +8,7 @@ import type { BotSummary } from "@/hooks/community/use-bots"
// assert is the presence/absence of `data-testid="bot-card-model"` and its text.
const useBotsMock = vi.fn()
+const bugReportDialogMock = vi.fn()
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn() }),
@@ -37,6 +38,12 @@ function passthrough(name: string) {
vi.mock("./create-bot-sheet", () => ({ CreateBotSheet: passthrough("create-sheet") }))
vi.mock("./edit-bot-sheet", () => ({ EditBotSheet: passthrough("edit-sheet") }))
vi.mock("./bot-activity-modal", () => ({ BotActivityModal: passthrough("activity-modal") }))
+vi.mock("./bug-report-dialog", () => ({
+ BugReportDialog: (props: { bot: Pick<BotSummary, "id" | "name"> }) => {
+ bugReportDialogMock(props)
+ return React.createElement("div", { "data-mock": "bug-report-dialog" })
+ },
+}))
vi.mock("@/components/avatar", () => ({ AgentAvatar: () => React.createElement("span", {}) }))
vi.mock("@/components/provider-logo", () => ({ ProviderLogo: () => React.createElement("span", {}) }))
vi.mock("@/components/ui/dropdown-menu", () => ({
@@ -130,3 +137,51 @@ describe("BotList — card model segment", () => {
expect(modelSegments(renderer)).toEqual(["local default"])
})
})
+
+describe("BotList — bug-report feature entry", () => {
+ beforeEach(() => {
+ useBotsMock.mockReset()
+ bugReportDialogMock.mockReset()
+ })
+
+ it.each([
+ ["absent", undefined],
+ ["disabled", { bugReports: false }],
+ ["malformed", { bugReports: "true" }],
+ ])("hides Report a problem when the top-level feature is %s", (_label, features) => {
+ const bots = [bot({})]
+ useBotsMock.mockReturnValue({
+ bots,
+ isLoading: false,
+ data: features === undefined ? { bots } : { bots, features },
+ })
+
+ const renderer = render()
+ expect(
+ renderer.root.findAll((node) => node.props?.["data-testid"] === "bot-report-problem-item"),
+ ).toHaveLength(0)
+ expect(bugReportDialogMock).not.toHaveBeenCalled()
+ })
+
+ it("renders exactly one Report a problem action per bot when enabled", () => {
+ const bots = [bot({ id: "b1" }), bot({ id: "b2", name: "Maya" })]
+ useBotsMock.mockReturnValue({
+ bots,
+ isLoading: false,
+ data: { bots, features: { bugReports: true } },
+ })
+
+ const renderer = render()
+ const reportItems = renderer.root.findAll(
+ (node) => node.props?.["data-testid"] === "bot-report-problem-item",
+ )
+ expect(reportItems).toHaveLength(2)
+ expect(reportItems.map((item) => item.props.children).join(" ")).toContain("Report a problem")
+ expect(bugReportDialogMock).not.toHaveBeenCalled()
+
+ act(() => reportItems[1]!.props.onClick())
+ expect(bugReportDialogMock).toHaveBeenCalledWith(
+ expect.objectContaining({ bot: { id: "b2", name: "Maya" } }),
+ )
+ })
+})
diff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsx
index a324d3e13..d4cd3baa1 100644
--- a/src/web/src/components/community/bots/bot-list.tsx
+++ b/src/web/src/components/community/bots/bot-list.tsx
@@ -37,6 +37,7 @@ import { useOnlineUserIds } from "@/stores/community/ws"
import { CreateBotSheet } from "./create-bot-sheet"
import { EditBotSheet } from "./edit-bot-sheet"
import { BotActivityModal } from "./bot-activity-modal"
+import { BugReportDialog } from "./bug-report-dialog"
import { CreateTile } from "@/components/community/onboarding-tiles/create-tile"
import { AgentHelpGallery } from "@/components/community/onboarding-tiles/agent-help-gallery"
import {
@@ -46,6 +47,8 @@ import {
updateCommunityOnboardingResources,
useCommunityOnboarding,
} from "@/lib/community-onboarding"
+import { bugReportsFeatureEnabled } from "@/hooks/community/use-bot-bug-report"
+import { tid } from "@/lib/community/testids"
/**
* BotList — the /c/me/bots surface.
@@ -76,7 +79,9 @@ function BotCardSkeleton() {
export function BotList({ onBack }: { onBack?: () => void } = {}) {
const router = useRouter()
const searchParams = useSearchParams()
- const { bots, isLoading } = useBots()
+ const botsQuery = useBots()
+ const { bots, isLoading } = botsQuery
+ const bugReportsEnabled = bugReportsFeatureEnabled(botsQuery.data)
const { machines, isLoading: machinesLoading } = useMachines()
// Presence read: single API for humans + bots, server-pushed identically
// (see plans/community-account-debt-fixes.md Fix 3 — the owner is always
@@ -94,6 +99,8 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
const [editOpen, setEditOpen] = useState(false)
const [activityBot, setActivityBot] = useState<BotSummary | null>(null)
const [activityOpen, setActivityOpen] = useState(false)
+ const [bugReportBot, setBugReportBot] = useState<Pick<BotSummary, "id" | "name"> | null>(null)
+ const [bugReportOpen, setBugReportOpen] = useState(false)
const [confirmDelete, setConfirmDelete] = useState<BotSummary | null>(null)
const [confirmReset, setConfirmReset] = useState<BotSummary | null>(null)
// Batch "reset all agents on this machine" confirm — keyed by machineId so the
@@ -516,6 +523,17 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
>
<span className="size-4" aria-hidden /> Edit
</DropdownMenuItem>
+ {bugReportsEnabled && (
+ <DropdownMenuItem
+ data-testid={tid.botReportProblemItem}
+ onClick={() => {
+ setBugReportBot({ id: bot.id, name: bot.name })
+ setBugReportOpen(true)
+ }}
+ >
+ <span className="size-4" aria-hidden /> Report a problem
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
data-testid={`bot-reset-session-item`}
onClick={() => setConfirmReset(bot)}
@@ -555,6 +573,14 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
open={activityOpen}
onOpenChange={setActivityOpen}
/>
+ {bugReportsEnabled && bugReportBot && (
+ <BugReportDialog
+ key={bugReportBot.id}
+ bot={bugReportBot}
+ open={bugReportOpen}
+ onOpenChange={setBugReportOpen}
+ />
+ )}
<AlertDialog
open={!!confirmDelete}
onOpenChange={(open) => !open && setConfirmDelete(null)}
diff --git a/src/web/src/components/community/bots/bug-report-dialog.test.ts b/src/web/src/components/community/bots/bug-report-dialog.test.ts
new file mode 100644
index 000000000..b7b732091
--- /dev/null
+++ b/src/web/src/components/community/bots/bug-report-dialog.test.ts
@@ -0,0 +1,187 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+
+function passthrough(name: string) {
+ return function Passthrough({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) {
+ return React.createElement("div", { ...props, "data-mock": name }, children)
+ }
+}
+
+vi.mock("@/components/ui/alert-dialog", () => ({
+ AlertDialog: passthrough("dialog"),
+ AlertDialogAction: passthrough("action"),
+ AlertDialogCancel: passthrough("cancel"),
+ AlertDialogContent: passthrough("content"),
+ AlertDialogDescription: passthrough("description"),
+ AlertDialogFooter: passthrough("footer"),
+ AlertDialogHeader: passthrough("header"),
+ AlertDialogTitle: passthrough("title"),
+}))
+
+import { BugReportDialog } from "./bug-report-dialog"
+
+const onConfirm = vi.fn()
+const onOpenChange = vi.fn()
+
+function render(overrides: Record<string, unknown> = {}) {
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(BugReportDialog, {
+ bot: { id: "b2", name: "Maya" },
+ open: true,
+ phase: "confirm",
+ isSubmitting: false,
+ reportId: null,
+ failureCode: null,
+ onConfirm,
+ onOpenChange,
+ ...overrides,
+ }),
+ )
+ })
+ return renderer
+}
+
+function text(renderer: TestRenderer.ReactTestRenderer): string {
+ return renderer.root
+ .findAll((node) => typeof node.children?.[0] === "string")
+ .flatMap((node) => node.children.filter((child): child is string => typeof child === "string"))
+ .join(" ")
+}
+
+describe("BugReportDialog", () => {
+ beforeEach(() => {
+ onConfirm.mockReset()
+ onOpenChange.mockReset()
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ it("discloses allowlisted sources, exclusions, retention, and runtime-stderr residual risk before submit", () => {
+ const renderer = render()
+ const copy = text(renderer)
+
+ for (const allowed of ["daemon", "FSM", "status"]) expect(copy).toContain(allowed)
+ expect(copy).toContain("7 days")
+ expect(copy).toContain("doesn’t actively read")
+ for (const excluded of [
+ "messages",
+ "prompts",
+ "responses",
+ "thinking",
+ "tool payloads",
+ "working directory",
+ "context timeline",
+ "memory",
+ "todo",
+ "AGENTS",
+ "raw runtime",
+ "environment variables",
+ ]) expect(copy).toContain(excluded)
+ for (const residual of [
+ "runtime stderr",
+ "user content",
+ "provider responses",
+ "paths",
+ "sensitive content",
+ ]) expect(copy).toContain(residual)
+ expect(copy).toContain("best-effort")
+ expect(copy).toContain("not a general PII guarantee")
+ expect(renderer.root.findAllByType("input")).toHaveLength(0)
+ expect(renderer.root.findAllByType("textarea")).toHaveLength(0)
+ expect(onConfirm).not.toHaveBeenCalled()
+ })
+
+ it("submits only from explicit confirmation and disables repeat confirmation", () => {
+ const renderer = render()
+ const submit = renderer.root.findByProps({ "data-testid": "bot-report-problem-submit" })
+ act(() => submit.props.onClick())
+ expect(onConfirm).toHaveBeenCalledTimes(1)
+
+ const pending = render({ isSubmitting: true })
+ expect(pending.root.findByProps({ "data-testid": "bot-report-problem-submit" }).props.disabled).toBe(true)
+ })
+
+ it.each([
+ ["collecting", "Collecting diagnostics"],
+ ["uploaded", "Report uploaded"],
+ ["failed", "Report failed"],
+ ["timeout", "Collection timed out"],
+ ])("renders the %s state", (phase, expected) => {
+ const renderer = render({
+ phase,
+ reportId: "dbr_test123",
+ failureCode: phase === "failed" ? "offline" : null,
+ })
+ expect(renderer.root.findByProps({ "data-testid": "bot-report-problem-status" })).toBeTruthy()
+ expect(text(renderer)).toContain(expected)
+ })
+
+ it("uses fixed safe failure copy and never renders arbitrary backend detail", () => {
+ const renderer = render({
+ phase: "failed",
+ reportId: "dbr_offline",
+ failureCode: "offline",
+ errorDetail: "Bearer secret at /Users/private should leak",
+ })
+ expect(text(renderer)).toContain("Bring the daemon online")
+ expect(text(renderer)).not.toContain("Bearer secret")
+ expect(text(renderer)).not.toContain("/Users/private")
+ expect(text(renderer)).not.toContain("Collecting diagnostics")
+ })
+
+ it("never renders storage metadata, checksum, download location, or machine id", () => {
+ const renderer = render({
+ phase: "uploaded",
+ reportId: "dbr_test123",
+ machineId: "cm_private_machine",
+ objectKey: "reports/dbr_test123.ndjson.gz",
+ objectExpiresAt: 9_999,
+ url: "https://example.invalid/report",
+ downloadUrl: "https://example.invalid/download",
+ sha256: "a".repeat(64),
+ checksum: "private-checksum",
+ })
+ const copy = text(renderer)
+ expect(copy).toContain("dbr_test123")
+ for (const forbidden of [
+ "cm_private_machine",
+ "reports/dbr_test123.ndjson.gz",
+ "example.invalid",
+ "private-checksum",
+ "a".repeat(64),
+ ]) expect(copy).not.toContain(forbidden)
+ })
+
+ it("labels and copies only the owner-safe report id after an explicit click", async () => {
+ const writeText = vi.fn().mockResolvedValue(undefined)
+ vi.stubGlobal("navigator", { clipboard: { writeText } })
+ const renderer = render({ phase: "uploaded", reportId: "dbr_test123" })
+
+ expect(text(renderer)).toContain("Report ID")
+ expect(writeText).not.toHaveBeenCalled()
+ await act(async () => {
+ await renderer.root.findByProps({ "aria-label": "Copy report ID" }).props.onClick()
+ })
+ expect(writeText).toHaveBeenCalledTimes(1)
+ expect(writeText).toHaveBeenCalledWith("dbr_test123")
+ expect(text(renderer)).toContain("Copied")
+ })
+
+ it("shows fixed recoverable feedback when clipboard access fails", async () => {
+ const writeText = vi.fn().mockRejectedValue(new Error("Bearer secret /Users/private"))
+ vi.stubGlobal("navigator", { clipboard: { writeText } })
+ const renderer = render({ phase: "uploaded", reportId: "dbr_test123" })
+
+ await act(async () => {
+ await renderer.root.findByProps({ "aria-label": "Copy report ID" }).props.onClick()
+ })
+ expect(text(renderer)).toContain("Couldn’t copy. Select the ID instead.")
+ expect(text(renderer)).not.toContain("Bearer secret")
+ expect(text(renderer)).not.toContain("/Users/private")
+ })
+})
diff --git a/src/web/src/components/community/bots/bug-report-dialog.tsx b/src/web/src/components/community/bots/bug-report-dialog.tsx
new file mode 100644
index 000000000..3e6bbcb16
--- /dev/null
+++ b/src/web/src/components/community/bots/bug-report-dialog.tsx
@@ -0,0 +1,168 @@
+"use client"
+
+import { useState } from "react"
+import { Button } from "@/components/ui/button"
+import {
+ AlertDialog,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog"
+import {
+ bugReportFailureMessage,
+ type BugReportFailureCode,
+ type BugReportPhase,
+ useBotBugReport,
+} from "@/hooks/community/use-bot-bug-report"
+import { tid } from "@/lib/community/testids"
+
+type BugIdentity = { id: string; name: string }
+
+type DialogViewProps = {
+ bot: BugIdentity
+ open: boolean
+ phase: BugReportPhase
+ isSubmitting: boolean
+ reportId: string | null
+ failureCode: BugReportFailureCode | null
+ onConfirm: () => void | Promise<void>
+ onOpenChange: (open: boolean) => void
+}
+
+type BugReportDialogProps =
+ | (Pick<DialogViewProps, "bot" | "open" | "onOpenChange"> & { phase?: never })
+ | DialogViewProps
+
+function statusTitle(phase: BugReportPhase): string {
+ if (phase === "collecting") return "Collecting diagnostics"
+ if (phase === "uploaded") return "Report uploaded"
+ if (phase === "timeout") return "Collection timed out"
+ return "Report failed"
+}
+
+function ReportIdCopy({ reportId }: { reportId: string }) {
+ const [copyStatus, setCopyStatus] = useState<"idle" | "copied" | "failed">("idle")
+
+ const copy = async () => {
+ try {
+ await navigator.clipboard.writeText(reportId)
+ setCopyStatus("copied")
+ } catch {
+ setCopyStatus("failed")
+ }
+ }
+
+ return (
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <span className="text-xs font-medium text-foreground">Report ID</span>
+ <code className="font-mono text-xs text-muted-foreground">{reportId}</code>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-7 px-2 text-xs"
+ aria-label="Copy report ID"
+ onClick={() => void copy()}
+ >
+ Copy
+ </Button>
+ {copyStatus === "copied" && <span className="text-xs text-muted-foreground">Copied</span>}
+ {copyStatus === "failed" && (
+ <span className="text-xs text-muted-foreground">Couldn’t copy. Select the ID instead.</span>
+ )}
+ </div>
+ )
+}
+
+function BugReportDialogView(props: DialogViewProps) {
+ const terminal = props.phase === "uploaded" || props.phase === "timeout"
+ const status = props.phase !== "confirm" && props.phase !== "submitting"
+ const submitLabel = props.phase === "failed"
+ ? "Try again"
+ : terminal
+ ? "Report another problem"
+ : props.isSubmitting
+ ? "Submitting…"
+ : "Confirm and collect"
+
+ return (
+ <AlertDialog open={props.open} onOpenChange={props.onOpenChange}>
+ <AlertDialogContent data-testid={tid.botReportProblemDialog}>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Report a problem with {props.bot.name}?</AlertDialogTitle>
+ <AlertDialogDescription className="space-y-3 text-left">
+ <span className="block">
+ The report includes allowlisted daemon, FSM, and status diagnostics and is retained for 7 days.
+ </span>
+ <span className="block">
+ It doesn’t actively read messages, prompts, responses, thinking, tool payloads, your working directory,
+ context timeline, memory, todo, AGENTS, raw runtime data, or environment variables.
+ </span>
+ <span className="block">
+ Target runtime stderr may still contain user content, provider responses, paths, or other sensitive content
+ despite best-effort scrubbing. This is not a general PII guarantee.
+ </span>
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+
+ {status && (
+ <div
+ data-testid={tid.botReportProblemStatus}
+ className="rounded-md bg-muted/60 px-3 py-2 text-sm"
+ >
+ <p className="font-medium text-foreground">{statusTitle(props.phase)}</p>
+ {props.phase === "failed" && (
+ <p className="mt-1 text-muted-foreground">
+ {bugReportFailureMessage(props.failureCode)}
+ </p>
+ )}
+ {props.reportId && (
+ <ReportIdCopy key={props.reportId} reportId={props.reportId} />
+ )}
+ </div>
+ )}
+
+ <AlertDialogFooter>
+ <AlertDialogCancel>Close</AlertDialogCancel>
+ {props.phase !== "collecting" && (
+ <Button
+ data-testid={tid.botReportProblemSubmit}
+ disabled={props.isSubmitting}
+ onClick={() => void props.onConfirm()}
+ >
+ {submitLabel}
+ </Button>
+ )}
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+}
+
+function ConnectedBugReportDialog({
+ bot,
+ open,
+ onOpenChange,
+}: Pick<DialogViewProps, "bot" | "open" | "onOpenChange">) {
+ const { state, confirm } = useBotBugReport({ agentId: bot.id, open })
+ return (
+ <BugReportDialogView
+ bot={bot}
+ open={open}
+ phase={state.phase}
+ isSubmitting={state.phase === "submitting"}
+ reportId={state.reportId}
+ failureCode={state.failureCode}
+ onConfirm={confirm}
+ onOpenChange={onOpenChange}
+ />
+ )
+}
+
+export function BugReportDialog(props: BugReportDialogProps) {
+ if (props.phase !== undefined) return <BugReportDialogView {...props} />
+ return <ConnectedBugReportDialog {...props} />
+}
diff --git a/src/web/src/hooks/community/use-bot-bug-report.test.ts b/src/web/src/hooks/community/use-bot-bug-report.test.ts
new file mode 100644
index 000000000..4227b0d90
--- /dev/null
+++ b/src/web/src/hooks/community/use-bot-bug-report.test.ts
@@ -0,0 +1,523 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ BUG_REPORT_POLL_INTERVAL_MS,
+ bugReportFailureMessage,
+ bugReportsFeatureEnabled,
+ buildBugReportCreateRequest,
+ buildBugReportStatusRequest,
+ bugReportReducer,
+ initialBugReportState,
+ projectOwnerBugReport,
+ shouldPollBugReport,
+ startBugReportAttempt,
+ useBotBugReport,
+} from "./use-bot-bug-report"
+
+const apiFetchMock = vi.fn()
+
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}))
+
+type BugReportHookResult = ReturnType<typeof useBotBugReport>
+
+function renderBugReportHook(initialOpen = true) {
+ const result: { current: BugReportHookResult } = { current: null as never }
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0 } },
+ })
+
+ function Probe({ open }: { open: boolean }) {
+ result.current = useBotBugReport({ agentId: "bot_1", open })
+ return null
+ }
+
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Probe, { open: initialOpen }),
+ ),
+ )
+ })
+
+ return {
+ queryClient,
+ renderer,
+ result,
+ setOpen(open: boolean) {
+ act(() => {
+ renderer.update(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Probe, { open }),
+ ),
+ )
+ })
+ },
+ }
+}
+
+async function flushMicrotasks() {
+ await act(async () => {
+ await Promise.resolve()
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+}
+
+function pendingReport(nowMs = Date.now()) {
+ return {
+ reportId: "dbr_pending",
+ status: "pending",
+ deadlineAt: nowMs + 600_000,
+ completedAt: null,
+ failureCode: null,
+ objectExpired: false,
+ }
+}
+
+beforeEach(() => {
+ apiFetchMock.mockReset()
+ vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(
+ "00000000-0000-4000-8000-000000000001",
+ )
+})
+
+afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+describe("bug-report frontend adapter", () => {
+ it("enables the entry only for an exact top-level true capability", () => {
+ expect(bugReportsFeatureEnabled(undefined)).toBe(false)
+ expect(bugReportsFeatureEnabled({ bots: [], features: {} })).toBe(false)
+ expect(bugReportsFeatureEnabled({ bots: [], features: { bugReports: false } })).toBe(false)
+ expect(bugReportsFeatureEnabled({ bots: [], features: { bugReports: "true" } })).toBe(false)
+ expect(bugReportsFeatureEnabled({ bots: [], features: { bugReports: true } })).toBe(true)
+ })
+
+ it("locks the POST and GET owner-route shapes without a real route", () => {
+ expect(buildBugReportCreateRequest("bot_1", "00000000-0000-4000-8000-000000000001")).toEqual({
+ path: "/api/community/bots/bot_1/diagnostics",
+ init: {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ clientNonce: "00000000-0000-4000-8000-000000000001" }),
+ },
+ })
+ expect(buildBugReportStatusRequest("dbr_test123")).toEqual({
+ path: "/api/community/diagnostics/dbr_test123",
+ init: { method: "GET" },
+ })
+ })
+
+ it("projects only owner-visible status fields and drops storage and machine metadata", () => {
+ const projected = projectOwnerBugReport({
+ reportId: "dbr_test123",
+ status: "uploaded",
+ deadlineAt: 2_000,
+ completedAt: 1_500,
+ failureCode: null,
+ objectExpired: false,
+ machineId: "cm_private",
+ objectKey: "reports/dbr_test123.ndjson.gz",
+ objectExpiresAt: 3_000,
+ expiresAt: 3_000,
+ url: "https://example.invalid/report",
+ downloadUrl: "https://example.invalid/download",
+ sha256: "a".repeat(64),
+ checksum: "secret-metadata",
+ })
+
+ expect(projected).toEqual({
+ reportId: "dbr_test123",
+ status: "uploaded",
+ deadlineAt: 2_000,
+ completedAt: 1_500,
+ failureCode: null,
+ objectExpired: false,
+ })
+ expect(JSON.stringify(projected)).not.toMatch(/machine|objectKey|url|sha|checksum/i)
+ })
+
+ it.each([
+ ["offline", "Bring the daemon online, then try again."],
+ ["timeout", "Collection timed out. Try again."],
+ ["upload_conflict", "The report could not be uploaded safely. Try again."],
+ ["invalid_upload", "The report upload was rejected. Try again."],
+ ["diagnostics_unavailable", "Diagnostics are unavailable right now. Try again."],
+ ["collector_busy", "Another report is being collected. Try again shortly."],
+ ["bot_not_bound", "This bot is no longer available on that machine."],
+ ["collection_failed", "Diagnostics could not be collected. Try again."],
+ ["local_artifact_invalid", "The local diagnostic bundle could not be verified."],
+ ["bundle_too_large", "The diagnostic bundle was too large to upload."],
+ ["upload_failed", "The report upload failed. Try again."],
+ ["internal_error", "The report could not be completed. Try again."],
+ ])("maps %s to fixed safe copy", (code, expected) => {
+ expect(bugReportFailureMessage(code)).toBe(expected)
+ })
+
+ it("uses one fixed generic message for unknown codes instead of reflecting arbitrary detail", () => {
+ expect(bugReportFailureMessage("Bearer secret /Users/private")).toBe(
+ "The report could not be completed. Try again.",
+ )
+ })
+})
+
+describe("bug-report client state", () => {
+ it("generates one UUID per logical attempt and ignores double confirmation", () => {
+ const randomUUID = vi
+ .fn()
+ .mockReturnValueOnce("00000000-0000-4000-8000-000000000001")
+ .mockReturnValueOnce("00000000-0000-4000-8000-000000000002")
+
+ const first = startBugReportAttempt(initialBugReportState, randomUUID)
+ const doubleConfirm = startBugReportAttempt(first, randomUUID)
+ expect(randomUUID).toHaveBeenCalledTimes(1)
+ expect(doubleConfirm).toEqual(first)
+ })
+
+ it("reuses the nonce after an ambiguous POST failure and adopts an existing pending id", () => {
+ const started = {
+ ...initialBugReportState,
+ phase: "submitting" as const,
+ clientNonce: "nonce-stable",
+ }
+ const ambiguous = bugReportReducer(started, { type: "create_error" })
+ expect(ambiguous).toMatchObject({
+ phase: "failed",
+ terminal: false,
+ clientNonce: "nonce-stable",
+ reportId: null,
+ })
+
+ const randomUUID = vi.fn(() => "nonce-new")
+ const retry = startBugReportAttempt(ambiguous, randomUUID)
+ expect(randomUUID).not.toHaveBeenCalled()
+ expect(retry.clientNonce).toBe("nonce-stable")
+
+ const collecting = bugReportReducer(retry, {
+ type: "created",
+ delivery: "unknown",
+ report: {
+ reportId: "dbr_existing_pending",
+ status: "pending",
+ deadlineAt: 5_000,
+ completedAt: null,
+ failureCode: null,
+ objectExpired: false,
+ },
+ })
+ expect(collecting).toMatchObject({
+ phase: "collecting",
+ terminal: false,
+ clientNonce: "nonce-stable",
+ reportId: "dbr_existing_pending",
+ })
+ })
+
+ it("keeps the report id and collecting phase across polling failure", () => {
+ const collecting = {
+ ...initialBugReportState,
+ phase: "collecting" as const,
+ clientNonce: "nonce-1",
+ reportId: "dbr_1",
+ deadlineAt: 5_000,
+ }
+ expect(bugReportReducer(collecting, { type: "poll_error" })).toMatchObject({
+ phase: "collecting",
+ reportId: "dbr_1",
+ clientNonce: "nonce-1",
+ })
+ })
+
+ it("maps uploaded/failed/timeout and stops polling at terminal, close, or deadline", () => {
+ const collecting = {
+ ...initialBugReportState,
+ phase: "collecting" as const,
+ clientNonce: "nonce-1",
+ reportId: "dbr_1",
+ deadlineAt: 5_000,
+ }
+ const uploaded = bugReportReducer(collecting, {
+ type: "status",
+ report: { reportId: "dbr_1", status: "uploaded", deadlineAt: 5_000, completedAt: 2_000, failureCode: null, objectExpired: false },
+ })
+ const failed = bugReportReducer(collecting, {
+ type: "status",
+ report: { reportId: "dbr_1", status: "failed", deadlineAt: 5_000, completedAt: 2_000, failureCode: "offline", objectExpired: false },
+ })
+ const timeout = bugReportReducer(collecting, {
+ type: "status",
+ report: { reportId: "dbr_1", status: "failed", deadlineAt: 5_000, completedAt: 5_000, failureCode: "timeout", objectExpired: false },
+ })
+
+ expect(uploaded).toMatchObject({ phase: "uploaded", terminal: true })
+ expect(failed).toMatchObject({ phase: "failed", terminal: true })
+ expect(timeout).toMatchObject({ phase: "timeout", terminal: true })
+ expect(shouldPollBugReport(collecting, { open: true, nowMs: 4_999 })).toBe(true)
+ expect(shouldPollBugReport(collecting, { open: false, nowMs: 4_999 })).toBe(false)
+ expect(shouldPollBugReport(collecting, { open: true, nowMs: 5_000 })).toBe(false)
+ expect(shouldPollBugReport(uploaded, { open: true, nowMs: 2_001 })).toBe(false)
+ expect(shouldPollBugReport(failed, { open: true, nowMs: 2_001 })).toBe(false)
+ expect(shouldPollBugReport(timeout, { open: true, nowMs: 5_001 })).toBe(false)
+ })
+
+ it("creates a fresh UUID only for an explicit new attempt after confirmed terminal", () => {
+ const failed = {
+ ...initialBugReportState,
+ phase: "failed" as const,
+ terminal: true,
+ clientNonce: "nonce-old",
+ reportId: "dbr_old",
+ failureCode: "offline",
+ }
+ const randomUUID = vi.fn(() => "nonce-new")
+ const next = startBugReportAttempt(failed, randomUUID)
+ expect(randomUUID).toHaveBeenCalledTimes(1)
+ expect(next).toMatchObject({
+ phase: "submitting",
+ terminal: false,
+ clientNonce: "nonce-new",
+ reportId: null,
+ })
+ })
+})
+
+describe("useBotBugReport", () => {
+ it("turns two synchronous confirms into one POST with one nonce", async () => {
+ let resolveCreate!: (value: unknown) => void
+ apiFetchMock.mockImplementationOnce(
+ () => new Promise((resolve) => {
+ resolveCreate = resolve
+ }),
+ )
+
+ const { renderer, result } = renderBugReportHook()
+ act(() => {
+ void result.current.confirm()
+ void result.current.confirm()
+ })
+
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ expect(globalThis.crypto.randomUUID).toHaveBeenCalledTimes(1)
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/bots/bot_1/diagnostics",
+ expect.objectContaining({
+ method: "POST",
+ body: JSON.stringify({
+ clientNonce: "00000000-0000-4000-8000-000000000001",
+ }),
+ }),
+ )
+
+ resolveCreate({ report: { ...pendingReport(), status: "uploaded", completedAt: 2_000 } })
+ await flushMicrotasks()
+ renderer.unmount()
+ })
+
+ it("retries an ambiguous POST with the same nonce, then polls the adopted pending id", async () => {
+ apiFetchMock
+ .mockRejectedValueOnce(new TypeError("connection dropped"))
+ .mockResolvedValueOnce({ report: pendingReport(), delivery: "unknown" })
+ .mockResolvedValueOnce({ report: pendingReport() })
+
+ const { renderer, result } = renderBugReportHook()
+ await act(async () => {
+ await result.current.confirm()
+ })
+ expect(result.current.state).toMatchObject({ phase: "failed", terminal: false })
+
+ await act(async () => {
+ await result.current.confirm()
+ })
+ await flushMicrotasks()
+
+ const postCalls = apiFetchMock.mock.calls.filter(([, init]) =>
+ (init as RequestInit | undefined)?.method === "POST",
+ )
+ expect(postCalls).toHaveLength(2)
+ expect(postCalls[0]?.[1]).toMatchObject(postCalls[1]?.[1] as RequestInit)
+ expect(globalThis.crypto.randomUUID).toHaveBeenCalledTimes(1)
+ expect(result.current.state).toMatchObject({
+ phase: "collecting",
+ reportId: "dbr_pending",
+ clientNonce: "00000000-0000-4000-8000-000000000001",
+ })
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/diagnostics/dbr_pending",
+ expect.objectContaining({ method: "GET", signal: expect.any(AbortSignal) }),
+ )
+
+ act(() => {
+ void result.current.confirm()
+ })
+ expect(apiFetchMock.mock.calls.filter(([, init]) =>
+ (init as RequestInit | undefined)?.method === "POST",
+ )).toHaveLength(2)
+ renderer.unmount()
+ })
+
+ it("aborts the exact in-flight status query and stops polling when the dialog closes", async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(0)
+ let statusSignal: AbortSignal | undefined
+ apiFetchMock
+ .mockResolvedValueOnce({ report: pendingReport(), delivery: "accepted" })
+ .mockImplementationOnce((_path: string, init: RequestInit) => new Promise((_resolve, reject) => {
+ statusSignal = init.signal as AbortSignal
+ statusSignal.addEventListener("abort", () => reject(new Error("aborted")))
+ }))
+
+ const hook = renderBugReportHook()
+ const cancelQueries = vi.spyOn(hook.queryClient, "cancelQueries")
+ await act(async () => {
+ await hook.result.current.confirm()
+ })
+ await vi.waitFor(() => expect(statusSignal).toBeDefined())
+
+ hook.setOpen(false)
+ expect(cancelQueries).toHaveBeenCalledWith({
+ queryKey: communityKeys.bugReport("dbr_pending"),
+ exact: true,
+ })
+ expect(statusSignal?.aborted).toBe(true)
+ const getCount = apiFetchMock.mock.calls.filter(([, init]) =>
+ (init as RequestInit | undefined)?.method === "GET",
+ ).length
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000)
+ })
+ expect(apiFetchMock.mock.calls.filter(([, init]) =>
+ (init as RequestInit | undefined)?.method === "GET",
+ )).toHaveLength(getCount)
+ hook.renderer.unmount()
+ })
+
+ it("aborts the exact in-flight status query on unmount", async () => {
+ let statusSignal: AbortSignal | undefined
+ apiFetchMock
+ .mockResolvedValueOnce({ report: pendingReport(), delivery: "accepted" })
+ .mockImplementationOnce((_path: string, init: RequestInit) => new Promise((_resolve, reject) => {
+ statusSignal = init.signal as AbortSignal
+ statusSignal.addEventListener("abort", () => reject(new Error("aborted")))
+ }))
+
+ const hook = renderBugReportHook()
+ const cancelQueries = vi.spyOn(hook.queryClient, "cancelQueries")
+ await act(async () => {
+ await hook.result.current.confirm()
+ })
+ await vi.waitFor(() => expect(statusSignal).toBeDefined())
+
+ act(() => hook.renderer.unmount())
+ expect(cancelQueries).toHaveBeenCalledWith({
+ queryKey: communityKeys.bugReport("dbr_pending"),
+ exact: true,
+ })
+ expect(statusSignal?.aborted).toBe(true)
+ })
+
+ it("refetches only while the adopted report remains collecting", async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(0)
+ apiFetchMock
+ .mockResolvedValueOnce({ report: pendingReport(), delivery: "accepted" })
+ .mockResolvedValue({ report: pendingReport() })
+
+ const hook = renderBugReportHook()
+ await act(async () => {
+ await hook.result.current.confirm()
+ })
+ await flushMicrotasks()
+ expect(apiFetchMock.mock.calls.filter(([, init]) =>
+ (init as RequestInit | undefined)?.method === "GET",
+ )).toHaveLength(1)
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(BUG_REPORT_POLL_INTERVAL_MS)
+ })
+ expect(apiFetchMock.mock.calls.filter(([, init]) =>
+ (init as RequestInit | undefined)?.method === "GET",
+ )).toHaveLength(2)
+ hook.renderer.unmount()
+ })
+
+ it.each([
+ ["uploaded", null, "uploaded"],
+ ["failed", "timeout", "timeout"],
+ ] as const)("does not poll again after %s becomes terminal", async (status, failureCode, phase) => {
+ vi.useFakeTimers()
+ vi.setSystemTime(0)
+ apiFetchMock
+ .mockResolvedValueOnce({ report: pendingReport(), delivery: "accepted" })
+ .mockResolvedValueOnce({
+ report: {
+ ...pendingReport(),
+ status,
+ failureCode,
+ completedAt: 2_000,
+ },
+ })
+
+ const hook = renderBugReportHook()
+ await act(async () => {
+ await hook.result.current.confirm()
+ })
+ await flushMicrotasks()
+ expect(hook.result.current.state.phase).toBe(phase)
+
+ const getCount = apiFetchMock.mock.calls.filter(([, init]) =>
+ (init as RequestInit | undefined)?.method === "GET",
+ ).length
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000)
+ })
+ expect(apiFetchMock.mock.calls.filter(([, init]) =>
+ (init as RequestInit | undefined)?.method === "GET",
+ )).toHaveLength(getCount)
+ hook.renderer.unmount()
+ })
+
+ it("fails closed on malformed owner payload without reflecting unknown fields", async () => {
+ apiFetchMock.mockResolvedValueOnce({
+ report: {
+ reportId: "dbr_hostile",
+ status: "provider-secret-status",
+ deadlineAt: 60_000,
+ completedAt: null,
+ failureCode: "Bearer secret /Users/private",
+ detail: "raw provider detail must not render",
+ objectExpired: false,
+ },
+ })
+
+ const hook = renderBugReportHook()
+ await act(async () => {
+ await hook.result.current.confirm()
+ })
+ await flushMicrotasks()
+
+ expect(hook.result.current.state).toMatchObject({
+ phase: "failed",
+ terminal: true,
+ failureCode: "internal_error",
+ })
+ expect(bugReportFailureMessage(hook.result.current.state.failureCode)).toBe(
+ "The report could not be completed. Try again.",
+ )
+ expect(JSON.stringify(hook.result.current.state)).not.toMatch(
+ /provider-secret-status|Bearer secret|Users\/private|raw provider detail/,
+ )
+ hook.renderer.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/use-bot-bug-report.ts b/src/web/src/hooks/community/use-bot-bug-report.ts
new file mode 100644
index 000000000..266874b15
--- /dev/null
+++ b/src/web/src/hooks/community/use-bot-bug-report.ts
@@ -0,0 +1,344 @@
+"use client"
+
+import { useCallback, useEffect, useRef, useState } from "react"
+import { useQuery, useQueryClient } from "@tanstack/react-query"
+import { apiFetch } from "@/lib/api/client"
+import { communityKeys } from "@/lib/query-keys"
+
+export const BUG_REPORT_POLL_INTERVAL_MS = 1_000
+
+const FAILURE_CODES = [
+ "offline",
+ "timeout",
+ "upload_conflict",
+ "invalid_upload",
+ "diagnostics_unavailable",
+ "collector_busy",
+ "bot_not_bound",
+ "collection_failed",
+ "local_artifact_invalid",
+ "bundle_too_large",
+ "upload_failed",
+ "internal_error",
+] as const
+
+export type BugReportFailureCode = (typeof FAILURE_CODES)[number]
+export type BugReportPhase =
+ | "confirm"
+ | "submitting"
+ | "collecting"
+ | "uploaded"
+ | "failed"
+ | "timeout"
+
+export type OwnerBugReport = {
+ reportId: string
+ status: "pending" | "uploaded" | "failed"
+ deadlineAt: number
+ completedAt: number | null
+ failureCode: BugReportFailureCode | null
+ objectExpired: boolean
+}
+
+export type BugReportState = {
+ phase: BugReportPhase
+ terminal: boolean
+ clientNonce: string | null
+ reportId: string | null
+ deadlineAt: number | null
+ completedAt: number | null
+ failureCode: BugReportFailureCode | null
+ objectExpired: boolean
+}
+
+export const initialBugReportState: BugReportState = {
+ phase: "confirm",
+ terminal: false,
+ clientNonce: null,
+ reportId: null,
+ deadlineAt: null,
+ completedAt: null,
+ failureCode: null,
+ objectExpired: false,
+}
+
+type BugReportAction =
+ | { type: "create_error" }
+ | { type: "poll_error" }
+ | { type: "invalid_payload" }
+ | { type: "deadline" }
+ | { type: "created"; delivery: "accepted" | "unknown"; report: OwnerBugReport }
+ | { type: "status"; report: OwnerBugReport }
+
+const failureMessages: Record<BugReportFailureCode, string> = {
+ offline: "Bring the daemon online, then try again.",
+ timeout: "Collection timed out. Try again.",
+ upload_conflict: "The report could not be uploaded safely. Try again.",
+ invalid_upload: "The report upload was rejected. Try again.",
+ diagnostics_unavailable: "Diagnostics are unavailable right now. Try again.",
+ collector_busy: "Another report is being collected. Try again shortly.",
+ bot_not_bound: "This bot is no longer available on that machine.",
+ collection_failed: "Diagnostics could not be collected. Try again.",
+ local_artifact_invalid: "The local diagnostic bundle could not be verified.",
+ bundle_too_large: "The diagnostic bundle was too large to upload.",
+ upload_failed: "The report upload failed. Try again.",
+ internal_error: "The report could not be completed. Try again.",
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value)
+}
+
+function isFailureCode(value: unknown): value is BugReportFailureCode {
+ return typeof value === "string" && (FAILURE_CODES as readonly string[]).includes(value)
+}
+
+function isTimestamp(value: unknown): value is number {
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
+}
+
+export function bugReportsFeatureEnabled(value: unknown): boolean {
+ if (!isRecord(value) || !isRecord(value.features)) return false
+ return value.features.bugReports === true
+}
+
+export function buildBugReportCreateRequest(agentId: string, clientNonce: string) {
+ return {
+ path: `/api/community/bots/${agentId}/diagnostics`,
+ init: {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ clientNonce }),
+ },
+ }
+}
+
+export function buildBugReportStatusRequest(reportId: string) {
+ return {
+ path: `/api/community/diagnostics/${reportId}`,
+ init: { method: "GET" },
+ }
+}
+
+export function projectOwnerBugReport(value: unknown): OwnerBugReport | null {
+ if (!isRecord(value)) return null
+ if (typeof value.reportId !== "string" || !value.reportId.startsWith("dbr_")) return null
+ if (value.status !== "pending" && value.status !== "uploaded" && value.status !== "failed") {
+ return null
+ }
+ if (!isTimestamp(value.deadlineAt) || typeof value.objectExpired !== "boolean") return null
+ if (value.completedAt !== null && value.completedAt !== undefined && !isTimestamp(value.completedAt)) {
+ return null
+ }
+ if (value.failureCode !== null && value.failureCode !== undefined && !isFailureCode(value.failureCode)) {
+ return null
+ }
+ if (value.status === "failed" && !isFailureCode(value.failureCode)) return null
+ if (value.status !== "failed" && value.failureCode !== null && value.failureCode !== undefined) {
+ return null
+ }
+
+ return {
+ reportId: value.reportId,
+ status: value.status,
+ deadlineAt: value.deadlineAt,
+ completedAt: value.completedAt ?? null,
+ failureCode: value.failureCode ?? null,
+ objectExpired: value.objectExpired,
+ }
+}
+
+export function bugReportFailureMessage(code: unknown): string {
+ return isFailureCode(code) ? failureMessages[code] : failureMessages.internal_error
+}
+
+export function startBugReportAttempt(
+ state: BugReportState,
+ randomUUID: () => string = () => globalThis.crypto.randomUUID(),
+): BugReportState {
+ if (state.phase === "submitting" || state.phase === "collecting") return state
+ if (!state.terminal && state.clientNonce) {
+ return { ...state, phase: "submitting", failureCode: null }
+ }
+ return {
+ ...initialBugReportState,
+ phase: "submitting",
+ clientNonce: randomUUID(),
+ }
+}
+
+function stateForReport(state: BugReportState, report: OwnerBugReport): BugReportState {
+ const shared = {
+ ...state,
+ reportId: report.reportId,
+ deadlineAt: report.deadlineAt,
+ completedAt: report.completedAt,
+ failureCode: report.failureCode,
+ objectExpired: report.objectExpired,
+ }
+ if (report.status === "pending") {
+ return { ...shared, phase: "collecting", terminal: false }
+ }
+ if (report.status === "uploaded") {
+ return { ...shared, phase: "uploaded", terminal: true }
+ }
+ return {
+ ...shared,
+ phase: report.failureCode === "timeout" ? "timeout" : "failed",
+ terminal: true,
+ }
+}
+
+export function bugReportReducer(state: BugReportState, action: BugReportAction): BugReportState {
+ if (action.type === "created" || action.type === "status") {
+ return stateForReport(state, action.report)
+ }
+ if (action.type === "create_error") {
+ return { ...state, phase: "failed", terminal: false, failureCode: "internal_error" }
+ }
+ if (action.type === "invalid_payload") {
+ return { ...state, phase: "failed", terminal: true, failureCode: "internal_error" }
+ }
+ if (action.type === "deadline") {
+ return { ...state, phase: "timeout", terminal: true, failureCode: "timeout" }
+ }
+ return state
+}
+
+export function shouldPollBugReport(
+ state: BugReportState,
+ options: { open: boolean; nowMs: number },
+): boolean {
+ return Boolean(
+ options.open &&
+ state.phase === "collecting" &&
+ state.reportId &&
+ state.deadlineAt !== null &&
+ options.nowMs < state.deadlineAt,
+ )
+}
+
+function reportFromEnvelope(value: unknown): OwnerBugReport | null {
+ if (!isRecord(value)) return null
+ return projectOwnerBugReport(value.report)
+}
+
+export function useBotBugReport({ agentId, open }: { agentId: string; open: boolean }) {
+ const queryClient = useQueryClient()
+ const [state, setState] = useState<BugReportState>(initialBugReportState)
+ const stateRef = useRef(state)
+ const mountedRef = useRef(true)
+
+ const replaceState = useCallback((next: BugReportState) => {
+ stateRef.current = next
+ if (mountedRef.current) setState(next)
+ }, [])
+
+ const apply = useCallback((action: BugReportAction) => {
+ let next = bugReportReducer(stateRef.current, action)
+ if (
+ (action.type === "created" || action.type === "status") &&
+ next.phase === "collecting" &&
+ next.deadlineAt !== null &&
+ Date.now() >= next.deadlineAt
+ ) {
+ next = bugReportReducer(next, { type: "deadline" })
+ }
+ replaceState(next)
+ }, [replaceState])
+
+ const confirm = useCallback(async () => {
+ const current = stateRef.current
+ const started = startBugReportAttempt(current)
+ if (started === current) return
+ replaceState(started)
+
+ const request = buildBugReportCreateRequest(agentId, started.clientNonce!)
+ try {
+ const response = await apiFetch<unknown>(request.path, request.init)
+ const report = reportFromEnvelope(response)
+ if (!report) {
+ apply({ type: "invalid_payload" })
+ return
+ }
+ const delivery = isRecord(response) && response.delivery === "accepted"
+ ? "accepted"
+ : "unknown"
+ apply({ type: "created", delivery, report })
+ } catch {
+ apply({ type: "create_error" })
+ }
+ }, [agentId, apply, replaceState])
+
+ const reportId = state.reportId
+ const polling = Boolean(open && state.phase === "collecting" && reportId)
+ const statusQuery = useQuery({
+ queryKey: communityKeys.bugReport(reportId ?? "inactive"),
+ enabled: polling,
+ retry: false,
+ queryFn: async ({ signal }) => {
+ const request = buildBugReportStatusRequest(reportId!)
+ const response = await apiFetch<unknown>(request.path, { ...request.init, signal })
+ const report = reportFromEnvelope(response)
+ if (report) apply({ type: "status", report })
+ else apply({ type: "invalid_payload" })
+ return report
+ },
+ })
+ const refetchStatus = statusQuery.refetch
+ const statusErrorUpdatedAt = statusQuery.errorUpdatedAt
+
+ useEffect(() => {
+ if (!polling) return
+ const interval = globalThis.setInterval(() => {
+ if (shouldPollBugReport(stateRef.current, { open, nowMs: Date.now() })) {
+ void refetchStatus()
+ } else {
+ apply({ type: "deadline" })
+ }
+ }, BUG_REPORT_POLL_INTERVAL_MS)
+ return () => globalThis.clearInterval(interval)
+ }, [apply, open, polling, refetchStatus])
+
+ useEffect(() => {
+ if (statusErrorUpdatedAt) apply({ type: "poll_error" })
+ }, [apply, statusErrorUpdatedAt])
+
+ useEffect(() => {
+ if (state.phase !== "collecting" || state.deadlineAt === null) return
+ const remaining = state.deadlineAt - Date.now()
+ if (remaining <= 0) {
+ apply({ type: "deadline" })
+ return
+ }
+ const timeout = globalThis.setTimeout(() => apply({ type: "deadline" }), remaining)
+ return () => globalThis.clearTimeout(timeout)
+ }, [apply, state.deadlineAt, state.phase])
+
+ useEffect(() => {
+ if (open || !reportId) return
+ void queryClient.cancelQueries({
+ queryKey: communityKeys.bugReport(reportId),
+ exact: true,
+ })
+ }, [open, queryClient, reportId])
+
+ useEffect(() => {
+ if (!reportId) return
+ return () => {
+ void queryClient.cancelQueries({
+ queryKey: communityKeys.bugReport(reportId),
+ exact: true,
+ })
+ }
+ }, [queryClient, reportId])
+
+ useEffect(() => {
+ mountedRef.current = true
+ return () => {
+ mountedRef.current = false
+ }
+ }, [])
+
+ return { state, confirm }
+}
diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.ts
index 8f2409e4d..e309b4f8f 100644
--- a/src/web/src/lib/community/testids.test.ts
+++ b/src/web/src/lib/community/testids.test.ts
@@ -6,4 +6,11 @@ describe("community QA selectors", () => {
expect(tid.inboxUnreadChild("post_1")).toBe("community-inbox-unread-child-post_1")
expect(tid.channelRefPill("post_1")).toBe("community-channel-ref-pill-post_1")
})
+
+ it("exposes only the four stable My Bots bug-report flow selectors", () => {
+ expect(tid.botReportProblemItem).toBe("bot-report-problem-item")
+ expect(tid.botReportProblemDialog).toBe("bot-report-problem-dialog")
+ expect(tid.botReportProblemSubmit).toBe("bot-report-problem-submit")
+ expect(tid.botReportProblemStatus).toBe("bot-report-problem-status")
+ })
})
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 5acfe27c3..7a4e787bb 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -20,6 +20,10 @@ export const tid = {
machinePairCopy: "community-machine-pair-copy",
homeButton: "community-home-button",
alookLogo: "community-alook-logo",
+ botReportProblemItem: "bot-report-problem-item",
+ botReportProblemDialog: "bot-report-problem-dialog",
+ botReportProblemSubmit: "bot-report-problem-submit",
+ botReportProblemStatus: "bot-report-problem-status",
forumTagDialog: "community-forum-tag-dialog",
diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.ts
index 24721e3db..7d2398304 100644
--- a/src/web/src/lib/query-keys.test.ts
+++ b/src/web/src/lib/query-keys.test.ts
@@ -122,6 +122,17 @@ describe("communityKeys", () => {
])
})
+ it("keeps report polling specific to one report and outside the bots-list cache", () => {
+ expect(communityKeys.bugReport("dbr_1")).toEqual([
+ "community",
+ "bug-report",
+ "dbr_1",
+ ])
+ expect(communityKeys.bugReport("dbr_1")).not.toEqual(communityKeys.bots())
+ expect(communityKeys.bugReport("dbr_1").slice(0, 2)).not.toEqual(communityKeys.bots())
+ expect(communityKeys.bugReport("dbr_1")).not.toEqual(communityKeys.bugReport("dbr_2"))
+ })
+
it("returns a distinct new tuple each call (no shared mutable arrays)", () => {
const a = communityKeys.channelMessages("c1")
const b = communityKeys.channelMessages("c1")
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 70ee7f6a2..abc1ffbba 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -125,6 +125,8 @@ export const communityKeys = {
// ── Bots ────────────────────────────────────────────────────────────────
bots: () => [...communityKeys.all, "bots"] as const,
+ bugReport: (reportId: string) =>
+ [...communityKeys.all, "bug-report", reportId] as const,
botAuditLog: (botId: string) =>
[...communityKeys.all, "bot", botId, "audit-log"] as const,