Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(dev): finalize local diagnostic report flow

Gus69621ee2c4f9
diff --git a/scripts/ci/dev-registry-isolation.test.ts b/scripts/ci/dev-registry-isolation.test.ts
new file mode 100644
index 000000000..0c7c99cba
--- /dev/null
+++ b/scripts/ci/dev-registry-isolation.test.ts
@@ -0,0 +1,52 @@
+import { readFileSync } from "node:fs"
+import { dirname, resolve } from "node:path"
+import { describe, expect, it } from "vitest"
+
+const repositoryRoot = resolve(import.meta.dirname, "../..")
+const launcherPath = resolve(repositoryRoot, "scripts/dev-with-wrangler-registry.mjs")
+const packagePaths = [
+ "src/web/package.json",
+ "src/ws-do/package.json",
+ "src/wake-worker/package.json",
+ "src/email-worker/package.json",
+]
+const registryLauncher = /(?:^|\s)node\s+\.\.\/\.\.\/scripts\/dev-with-wrangler-registry\.mjs\s+([^\s]+)/g
+
+function devScript(packagePath: string): string {
+ const packageJson = JSON.parse(readFileSync(resolve(repositoryRoot, packagePath), "utf8")) as {
+ scripts?: { dev?: unknown }
+ }
+ expect(typeof packageJson.scripts?.dev).toBe("string")
+ return packageJson.scripts?.dev as string
+}
+
+function resolvedRegistryPath(root: string, packagePath: string): string {
+ const matches = [...devScript(packagePath).matchAll(registryLauncher)]
+ expect(matches).toHaveLength(1)
+ return resolve(root, dirname(packagePath), matches[0][1])
+}
+
+describe("local Wrangler registry isolation", () => {
+ it("sets Wrangler's registry to the absolute worktree-local path before spawning", () => {
+ const launcher = readFileSync(launcherPath, "utf8")
+
+ expect(launcher).toContain("WRANGLER_REGISTRY_PATH: resolve(process.cwd(), registryPath)")
+ })
+
+ it("uses one shared registry inside the current worktree for every dev entrypoint", () => {
+ const paths = packagePaths.map((packagePath) => resolvedRegistryPath(repositoryRoot, packagePath))
+
+ expect(new Set(paths)).toEqual(new Set([resolve(repositoryRoot, ".wrangler/registry")]))
+ })
+
+ it("resolves identical Worker names to different registries in separate worktrees", () => {
+ const firstRoot = "/tmp/alook-primary"
+ const secondRoot = "/tmp/alook-disposable"
+ const firstPaths = packagePaths.map((packagePath) => resolvedRegistryPath(firstRoot, packagePath))
+ const secondPaths = packagePaths.map((packagePath) => resolvedRegistryPath(secondRoot, packagePath))
+
+ expect(new Set(firstPaths)).toEqual(new Set([resolve(firstRoot, ".wrangler/registry")]))
+ expect(new Set(secondPaths)).toEqual(new Set([resolve(secondRoot, ".wrangler/registry")]))
+ expect(firstPaths[0]).not.toBe(secondPaths[0])
+ })
+})
diff --git a/scripts/dev-with-wrangler-registry.mjs b/scripts/dev-with-wrangler-registry.mjs
new file mode 100644
index 000000000..15f529afa
--- /dev/null
+++ b/scripts/dev-with-wrangler-registry.mjs
@@ -0,0 +1,34 @@
+import { spawn } from "node:child_process"
+import { resolve } from "node:path"
+
+const [registryPath, command, ...args] = process.argv.slice(2)
+const packageManagerCli = process.env.npm_execpath
+
+if (!registryPath || !command || !packageManagerCli) {
+ throw new Error("usage: dev-with-wrangler-registry <registry-path> <command> [...args]")
+}
+
+const child = spawn(
+ process.execPath,
+ [packageManagerCli, "exec", command, ...args],
+ {
+ stdio: "inherit",
+ env: {
+ ...process.env,
+ WRANGLER_REGISTRY_PATH: resolve(process.cwd(), registryPath),
+ },
+ },
+)
+
+for (const signal of ["SIGINT", "SIGTERM"]) {
+ process.once(signal, () => child.kill(signal))
+}
+
+child.once("error", (error) => {
+ console.error(error)
+ process.exitCode = 1
+})
+
+child.once("exit", (code) => {
+ process.exitCode = code ?? 1
+})
diff --git a/src/daemon/src/cli/daemonRunner.test.ts b/src/daemon/src/cli/daemonRunner.test.ts
index 7b66551f7..ee657ecb0 100644
--- a/src/daemon/src/cli/daemonRunner.test.ts
+++ b/src/daemon/src/cli/daemonRunner.test.ts
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
+import { gunzipSync } from "node:zlib";
import type { PreparedDaemon } from "./daemonRunner";
import {
createDaemonProcessLogger,
@@ -10,6 +11,7 @@ import {
logDaemonUp,
runPreparedDaemon,
} from "./daemonRunner";
+import { createRotatingFileSink } from "../util/rotatingFileSink";
const runnerDaemonHarness = vi.hoisted(() => {
const create = vi.fn();
@@ -287,6 +289,128 @@ describe("daemon runner logger", () => {
}
});
+ it("preserves projected FSM timestamps through the runner bundle seam", async () => {
+ resetDiagnosticHarness();
+ vi.useFakeTimers();
+ const listenersBefore = processListenerSnapshot();
+ const daemonHarness = installDaemonHarness(dir);
+ const traceSink = createRotatingFileSink(path.join(dir, "fsm-trace.jsonl"), 1024 * 1024, {
+ mode: 0o600,
+ hardMaxBytes: true,
+ });
+ daemonHarness.fsmTraceSource.openSnapshot.mockImplementation(() => traceSink.openSnapshot());
+ const eventTime = 1_700_000_001_000;
+ traceSink.write(JSON.stringify({
+ recordKind: "turn_span",
+ agentId: "bot_1",
+ event: "turn_begin",
+ effects: [],
+ nowMs: eventTime + 1,
+ timeIso: new Date(eventTime + 1).toISOString(),
+ traceTurnId: "turn-1",
+ daemonTurnOrdinal: 1,
+ spawnOrdinal: 1,
+ turnOrdinal: 1,
+ launchIdSnapshot: null,
+ }));
+ traceSink.write(JSON.stringify({
+ recordKind: "fsm",
+ agentId: "bot_1",
+ event: "register",
+ status: "idle",
+ turnActive: false,
+ inbox: 0,
+ lastDeliverAt: null,
+ lastProgressAt: eventTime,
+ idleSince: eventTime,
+ resetting: false,
+ resettingSince: null,
+ stoppingSince: null,
+ apmPhase: "idle",
+ effects: [],
+ nowMs: eventTime,
+ timeIso: new Date(eventTime).toISOString(),
+ sinceProgressMs: 0,
+ sinceDeliverMs: null,
+ sinceStoppingMs: null,
+ }));
+ fs.writeFileSync(path.join(dir, "status.json"), JSON.stringify({
+ writtenAt: eventTime,
+ agents: [{
+ agentId: "bot_1",
+ status: "idle",
+ derivedActivity: "idle",
+ turnActive: false,
+ inbox: 0,
+ sinceProgressMs: 0,
+ stoppingSince: null,
+ }],
+ }));
+ const readyError = new Error("stop after ready receipt");
+
+ try {
+ await expect(runPreparedDaemon(preparedDaemon(dir), {
+ foreground: false,
+ releaseOwnership: vi.fn(),
+ onReady: () => { throw readyError; },
+ })).rejects.toBe(readyError);
+
+ const coordinatorArgs = runnerDiagnosticHarness.createCoordinator.mock.calls[0]?.[0] as {
+ buildBundle: (args: {
+ command: {
+ type: "diagnostics:collect";
+ reportId: string;
+ agentId: string;
+ fromMs: number;
+ deadlineAt: number;
+ };
+ outputPath: string;
+ }) => Promise<unknown>;
+ };
+ const outputPath = path.join(dir, "runner-report.ndjson.gz");
+ await coordinatorArgs.buildBundle({
+ command: {
+ type: "diagnostics:collect",
+ reportId: "dbr_0123456789abcdef",
+ agentId: "bot_1",
+ fromMs: eventTime - 1,
+ deadlineAt: eventTime + 87_000_000,
+ },
+ outputPath,
+ });
+ const rows = gunzipSync(fs.readFileSync(outputPath)).toString("utf8")
+ .trimEnd()
+ .split("\n")
+ .map((line) => JSON.parse(line));
+
+ const fsmRows = rows.filter((row) => row.recordType === "fsm");
+ expect(fsmRows).toEqual([
+ expect.objectContaining({
+ recordKind: "fsm",
+ agentId: "bot_1",
+ event: "register",
+ nowMs: eventTime,
+ timeMs: eventTime,
+ }),
+ expect.objectContaining({
+ recordKind: "turn_span",
+ agentId: "bot_1",
+ event: "turn_begin",
+ nowMs: eventTime + 1,
+ timeMs: eventTime + 1,
+ }),
+ ]);
+ expect(rows.at(-1)).toMatchObject({
+ recordType: "bundle_footer",
+ counts: { status: 1, fsm: 2 },
+ });
+ } finally {
+ removeNewProcessListeners(listenersBefore);
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ }
+ });
+
it("observes a rejected fire-and-observe recovery through the safe logger", async () => {
resetDiagnosticHarness();
vi.useFakeTimers();
diff --git a/src/daemon/src/cli/daemonRunner.ts b/src/daemon/src/cli/daemonRunner.ts
index acda5f073..3aca41655 100644
--- a/src/daemon/src/cli/daemonRunner.ts
+++ b/src/daemon/src/cli/daemonRunner.ts
@@ -159,7 +159,11 @@ async function buildRunnerDiagnosticBundle(args: {
droppedRows[row.source === "daemon_log" ? "daemon_log" : "fsm"] += 1;
continue;
}
- events.push(projected as DiagnosticEventRow);
+ events.push({
+ ...projected,
+ recordType: projected.recordType,
+ timeMs: row.timeMs,
+ });
}
return buildDiagnosticBundle({
diff --git a/src/daemon/src/diagnostics/bundle.test.ts b/src/daemon/src/diagnostics/bundle.test.ts
index 2bd000e74..a499dac43 100644
--- a/src/daemon/src/diagnostics/bundle.test.ts
+++ b/src/daemon/src/diagnostics/bundle.test.ts
@@ -147,6 +147,34 @@ describe("B2c bounded gzip NDJSON bundle", () => {
expect(encoded).not.toMatch(/\/Users\/|\/home\/|daemon\.log|fsm-trace\.jsonl|Error:|stack/);
});
+ it("makes invalid internal event timestamps visible in the footer", async () => {
+ const api = await loadSubject();
+ const outputPath = join(tempDir(), "invalid-event-time.ndjson.gz");
+ const missingTime = event("fsm", "missing", 1500);
+ Reflect.deleteProperty(missingTime, "timeMs");
+ await api.buildDiagnosticBundle({
+ outputPath,
+ header: header(),
+ status: null,
+ events: [
+ event("fsm", "nan", Number.NaN),
+ event("fsm", "fractional", 1500.5),
+ event("fsm", "negative", -1),
+ missingTime,
+ ],
+ sourceDroppedRows: { fsm: 3 },
+ });
+
+ const rows = decode(outputPath).rows;
+ expect(rows.map((row) => row.recordType)).toEqual(["bundle_header", "bundle_footer"]);
+ expect(rows.at(-1)).toMatchObject({
+ counts: { status: 0, daemon_log: 0, fsm: 0 },
+ droppedRows: { fsm: 7 },
+ warnings: ["invalid_timestamp"],
+ missingSources: [],
+ });
+ });
+
it("evicts globally oldest complete rows so newer FSM beats older daemon rows", async () => {
const api = await loadSubject();
const outputPath = join(tempDir(), "fsm-wins.ndjson.gz");
diff --git a/src/daemon/src/diagnostics/bundle.ts b/src/daemon/src/diagnostics/bundle.ts
index fda6a05f8..4bc8e7e6c 100644
--- a/src/daemon/src/diagnostics/bundle.ts
+++ b/src/daemon/src/diagnostics/bundle.ts
@@ -139,7 +139,12 @@ export async function buildDiagnosticBundle(args: {
};
for await (const row of asAsync(args.events)) {
- if ((row.recordType !== "daemon_log" && row.recordType !== "fsm") || !Number.isSafeInteger(row.timeMs)) continue;
+ if (row.recordType !== "daemon_log" && row.recordType !== "fsm") continue;
+ if (!Number.isSafeInteger(row.timeMs) || row.timeMs < 0) {
+ droppedRows[row.recordType] = (droppedRows[row.recordType] ?? 0) + 1;
+ if (!warnings.includes("invalid_timestamp")) warnings.push("invalid_timestamp");
+ continue;
+ }
const serialized = line(row);
retained.push({ row, bytes: serialized });
retainedBytes += serialized.byteLength;
diff --git a/src/email-worker/package.json b/src/email-worker/package.json
index 134d20b72..4138eda41 100644
--- a/src/email-worker/package.json
+++ b/src/email-worker/package.json
@@ -3,7 +3,7 @@
"version": "0.1.2",
"private": true,
"scripts": {
- "dev": "wrangler dev --persist-to ../web/.wrangler/state",
+ "dev": "node ../../scripts/dev-with-wrangler-registry.mjs ../../.wrangler/registry wrangler dev --persist-to ../web/.wrangler/state",
"deploy": "wrangler deploy",
"knip": "knip",
"test": "vitest run",
diff --git a/src/wake-worker/package.json b/src/wake-worker/package.json
index e0d946ea5..50337fa97 100644
--- a/src/wake-worker/package.json
+++ b/src/wake-worker/package.json
@@ -3,7 +3,7 @@
"version": "0.1.2",
"private": true,
"scripts": {
- "dev": "wrangler dev --persist-to ../web/.wrangler/state",
+ "dev": "node ../../scripts/dev-with-wrangler-registry.mjs ../../.wrangler/registry wrangler dev --persist-to ../web/.wrangler/state",
"deploy": "wrangler deploy",
"knip": "knip",
"test": "vitest run",
diff --git a/src/web/cloudflare-env.d.ts b/src/web/cloudflare-env.d.ts
index da16b0652..5a107ffae 100644
--- a/src/web/cloudflare-env.d.ts
+++ b/src/web/cloudflare-env.d.ts
@@ -1,5 +1,5 @@
/* eslint-disable */
-// Generated by Wrangler by running `wrangler types --env-interface=CloudflareEnv ./cloudflare-env.d.ts` (hash: d75aadbc99481d079ae2cbfa7547585d)
+// Generated by Wrangler by running `wrangler types --env-interface=CloudflareEnv ./cloudflare-env.d.ts` (hash: 50fe13e080f1b562dfa5be61100ab886)
// Runtime types generated with [email protected] 2026-04-09 nodejs_compat
interface __BaseEnv_CloudflareEnv {
CACHE_KV: KVNamespace;
@@ -11,7 +11,6 @@ interface __BaseEnv_CloudflareEnv {
DB: D1Database;
WAKE_QUEUE: Queue;
ASSETS: Fetcher;
- BUG_REPORTS_ENABLED: "false";
RUNTIME_MODEL_OPTIONS: "{\"claude\":[\"claude-opus-4-6\",\"claude-sonnet-4-6\",\"claude-haiku-4-5\"],\"codex\":[\"gpt-5.4\",\"gpt-5.3-codex\"]}";
MIN_CLI_VERSION: "0.0.159";
BETTER_AUTH_SECRET: string;
@@ -38,7 +37,7 @@ type StringifyValues<EnvType extends Record<string, unknown>> = {
[Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;
};
declare namespace NodeJS {
- interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "BUG_REPORTS_ENABLED" | "RUNTIME_MODEL_OPTIONS" | "MIN_CLI_VERSION" | "BETTER_AUTH_SECRET" | "BETTER_AUTH_URL" | "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET" | "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET">> {}
+ interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "RUNTIME_MODEL_OPTIONS" | "MIN_CLI_VERSION" | "BETTER_AUTH_SECRET" | "BETTER_AUTH_URL" | "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET" | "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET">> {}
}
// Begin runtime types
diff --git a/src/web/package.json b/src/web/package.json
index 8e2463c28..ebac3b5a2 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -3,7 +3,7 @@
"version": "0.1.2",
"private": true,
"scripts": {
- "dev": "next dev",
+ "dev": "node ../../scripts/dev-with-wrangler-registry.mjs ../../.wrangler/registry next dev",
"build": "tsx scripts/validate-blog-assets.ts && next build",
"validate:blog": "tsx scripts/validate-blog-assets.ts",
"preflight:bug-reports": "tsx scripts/preflight-bug-reports.ts",
diff --git a/src/web/src/app/api/community/bots/[id]/diagnostics/route.test.ts b/src/web/src/app/api/community/bots/[id]/diagnostics/route.test.ts
index 3dfd1ce57..8dacc9384 100644
--- a/src/web/src/app/api/community/bots/[id]/diagnostics/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/diagnostics/route.test.ts
@@ -5,12 +5,8 @@ const createOrGet = vi.fn();
const failPending = vi.fn();
const getForOwner = vi.fn();
const pushDiagnostic = vi.fn();
-const featureEnabled = vi.fn();
vi.mock("@/lib/db", () => ({ getDb: () => ({}) }));
-vi.mock("@/lib/community/diagnostic-feature", () => ({
- isBugReportsEnabled: (...args: unknown[]) => featureEnabled(...args),
-}));
vi.mock("@/lib/community/diagnostic-report-push", () => ({
pushDiagnosticReportToMachine: (...args: unknown[]) => pushDiagnostic(...args),
}));
@@ -18,7 +14,7 @@ vi.mock("@/lib/middleware/auth", () => ({
withAuth: (handler: any) => async (req: NextRequest, context?: any) => {
const params = context?.params instanceof Promise ? await context.params : context?.params;
return handler(req, {
- env: { DB: {}, BUG_REPORTS_ENABLED: "true" },
+ env: { DB: {} },
userId: "owner_1",
params,
@@ -92,23 +88,10 @@ describe("POST /api/community/bots/:id/diagnostics", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.spyOn(Date, "now").mockReturnValue(NOW);
- featureEnabled.mockReturnValue(true);
createOrGet.mockResolvedValue({ kind: "created", report: row() });
pushDiagnostic.mockResolvedValue({ kind: "delivered", sent: 1 });
});
- it("does zero DB and zero WS work while creation is disabled", async () => {
- featureEnabled.mockReturnValue(false);
-
- const response = await POST(request(), context);
-
- expect(response.status).toBe(404);
- expect(createOrGet).not.toHaveBeenCalled();
- expect(pushDiagnostic).not.toHaveBeenCalled();
- expect(failPending).not.toHaveBeenCalled();
- expect(getForOwner).not.toHaveBeenCalled();
- });
-
it.each([
["missing nonce", {}],
["invalid nonce", { clientNonce: "not-a-uuid" }],
diff --git a/src/web/src/app/api/community/bots/[id]/diagnostics/route.ts b/src/web/src/app/api/community/bots/[id]/diagnostics/route.ts
index 46e452b53..e09c82b3d 100644
--- a/src/web/src/app/api/community/bots/[id]/diagnostics/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/diagnostics/route.ts
@@ -4,7 +4,6 @@ import {
queries,
} from "@alook/shared";
import { getDb } from "@/lib/db";
-import { isBugReportsEnabled } from "@/lib/community/diagnostic-feature";
import { pushDiagnosticReportToMachine } from "@/lib/community/diagnostic-report-push";
import {
projectOwnerDiagnosticReport,
@@ -26,10 +25,6 @@ function reportEnvelope(
}
export const POST = withAuth(async (req: NextRequest, ctx) => {
- if (!isBugReportsEnabled(ctx.env)) {
- return writeError("diagnostic reports are unavailable", 404);
- }
-
const [body, bodyError] = await parseBody(req, DiagnosticReportCreateRequestSchema);
if (bodyError) return bodyError;
const agentId = ctx.params?.id as string;
diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.ts
index 30adfc1b0..37ca75c21 100644
--- a/src/web/src/app/api/community/bots/route.test.ts
+++ b/src/web/src/app/api/community/bots/route.test.ts
@@ -9,7 +9,6 @@ const mockPushBotEventToMachine = vi.fn()
const mockListBotsForOwner = vi.fn()
const mockGetBotDailyActivityForOwner = vi.fn()
const mockEnsureSiblingBotFriendship = vi.fn()
-const mockProjectBugReportsFeature = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -42,9 +41,6 @@ vi.mock("@alook/shared", async () => {
vi.mock("@/lib/community/bot-push", () => ({
pushBotEventToMachine: (...a: unknown[]) => mockPushBotEventToMachine(...a),
}))
-vi.mock("@/lib/community/diagnostic-feature", () => ({
- projectBugReportsFeature: (...a: unknown[]) => mockProjectBugReportsFeature(...a),
-}))
vi.mock("@/lib/middleware/auth", () => ({
withAuth: (handler: any) => async (req: any, ctx?: any) => {
@@ -155,7 +151,6 @@ describe("POST /api/community/bots — model", () => {
describe("GET /api/community/bots — heatmap activity", () => {
beforeEach(() => {
vi.clearAllMocks()
- mockProjectBugReportsFeature.mockReturnValue({ bugReports: false })
})
it("attaches each bot's 30-day dailyActivity from the batched owner read", async () => {
@@ -190,22 +185,6 @@ describe("GET /api/community/bots — heatmap activity", () => {
mockGetBotDailyActivityForOwner.mockResolvedValue(new Map())
const res = await GET(getReq(), ctx)
expect(res.status).toBe(200)
- expect((await res.json()) as { bots: unknown[] }).toEqual({
- bots: [],
- features: { bugReports: false },
- })
- })
-
- it("projects only the diagnostic capability boolean beside the bots", async () => {
- mockListBotsForOwner.mockResolvedValue([])
- mockGetBotDailyActivityForOwner.mockResolvedValue(new Map())
- mockProjectBugReportsFeature.mockReturnValue({ bugReports: true })
-
- const res = await GET(getReq(), ctx)
- const body = await res.json()
-
- expect(body).toEqual({ bots: [], features: { bugReports: true } })
- expect(Object.keys(body.features)).toEqual(["bugReports"])
- expect(mockProjectBugReportsFeature).toHaveBeenCalledWith(expect.objectContaining({ DB: {} }))
+ expect((await res.json()) as { bots: unknown[] }).toEqual({ bots: [] })
})
})
diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.ts
index fcab9beb5..a6e04d61f 100644
--- a/src/web/src/app/api/community/bots/route.ts
+++ b/src/web/src/app/api/community/bots/route.ts
@@ -10,7 +10,6 @@ import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"
import { pushBotEventToMachine } from "@/lib/community/bot-push"
-import { projectBugReportsFeature } from "@/lib/community/diagnostic-feature"
export const GET = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
@@ -29,10 +28,7 @@ export const GET = withAuth(async (_req, ctx) => {
...bot,
dailyActivity: activityByBot.get(bot.id) ?? [],
}))
- return writeJSON({
- bots: withActivity,
- features: projectBugReportsFeature(ctx.env),
- })
+ return writeJSON({ bots: withActivity })
})
export const POST = withAuth(async (req: NextRequest, ctx) => {
diff --git a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.test.ts b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.test.ts
index 413ea65db..6b71b1e99 100644
--- a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.test.ts
+++ b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.test.ts
@@ -20,7 +20,7 @@ vi.mock("@/lib/middleware/community-daemon-auth", () => ({
return NextResponse.json({ error: "unauthorized" }, { status: 401 });
}
return handler(request, {
- env: { DB: {}, BUG_REPORTS: { privateBucket: true }, BUG_REPORTS_ENABLED: "false" },
+ env: { DB: {}, BUG_REPORTS: { privateBucket: true } },
machineId: "cm_original",
userId: "owner_1",
credentialId: "cred_1",
@@ -79,7 +79,7 @@ describe("PUT /api/community/daemon/diagnostics/:reportId/bundle", () => {
expect(upload).not.toHaveBeenCalled();
});
- it("ignores the false creation flag and drains an existing report for the authenticated machine", async () => {
+ it("uploads an existing report for the authenticated machine", async () => {
const api = await loadSubject();
const response = await api.PUT(request(), context);
diff --git a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.test.ts b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.test.ts
index b99bbf9f2..a576875a8 100644
--- a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.test.ts
+++ b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.test.ts
@@ -20,7 +20,7 @@ vi.mock("@/lib/middleware/community-daemon-auth", () => ({
return NextResponse.json({ error: "unauthorized" }, { status: 401 });
}
return handler(request, {
- env: { DB: {}, BUG_REPORTS: { privateBucket: true }, BUG_REPORTS_ENABLED: "false" },
+ env: { DB: {}, BUG_REPORTS: { privateBucket: true } },
machineId: "cm_original",
userId: "owner_1",
credentialId: "cred_1",
@@ -74,7 +74,7 @@ describe("PATCH /api/community/daemon/diagnostics/:reportId", () => {
expect(fail).not.toHaveBeenCalled();
});
- it.each(DAEMON_FAILURE_CODES)("accepts daemon failure code %s while the creation flag is false", async (failureCode) => {
+ it.each(DAEMON_FAILURE_CODES)("accepts daemon failure code %s for an existing report", async (failureCode) => {
const api = await loadSubject();
const response = await api.PATCH(request({ status: "failed", failureCode }), context);
diff --git a/src/web/src/app/api/community/diagnostics/[reportId]/route.test.ts b/src/web/src/app/api/community/diagnostics/[reportId]/route.test.ts
index f72ebd5b2..594da94ba 100644
--- a/src/web/src/app/api/community/diagnostics/[reportId]/route.test.ts
+++ b/src/web/src/app/api/community/diagnostics/[reportId]/route.test.ts
@@ -9,7 +9,7 @@ vi.mock("@/lib/middleware/auth", () => ({
withAuth: (handler: any) => async (req: NextRequest, context?: any) => {
const params = context?.params instanceof Promise ? await context.params : context?.params;
return handler(req, {
- env: { DB: {}, BUG_REPORTS_ENABLED: "false" },
+ env: { DB: {} },
userId: "owner_1",
params,
@@ -78,7 +78,7 @@ describe("GET /api/community/diagnostics/:reportId", () => {
expect(timeoutPending).not.toHaveBeenCalled();
});
- it("scopes the read by immutable owner even while the creation flag is false", async () => {
+ it("scopes an existing report read by immutable owner", async () => {
getForOwner.mockResolvedValue(row({ deadlineAt: NOW + 1 }));
const response = await GET(request, context);
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 9de072dcc..6607c5575 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
@@ -144,31 +144,12 @@ describe("BotList — bug-report feature entry", () => {
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", () => {
+ it("always renders exactly one Report a problem action per bot", () => {
const bots = [bot({ id: "b1" }), bot({ id: "b2", name: "Maya" })]
useBotsMock.mockReturnValue({
bots,
isLoading: false,
- data: { bots, features: { bugReports: true } },
+ data: { bots },
})
const renderer = render()
@@ -176,6 +157,16 @@ describe("BotList — bug-report feature entry", () => {
(node) => node.props?.["data-testid"] === "bot-report-problem-item",
)
expect(reportItems).toHaveLength(2)
+ expect(renderer.root
+ .findAll((node) => ["bot-reset-session-item", "bot-report-problem-item"]
+ .includes(node.props?.["data-testid"]))
+ .map((node) => node.props["data-testid"]))
+ .toEqual([
+ "bot-reset-session-item",
+ "bot-report-problem-item",
+ "bot-reset-session-item",
+ "bot-report-problem-item",
+ ])
expect(reportItems.map((item) => item.props.children).join(" ")).toContain("Report a problem")
expect(bugReportDialogMock).not.toHaveBeenCalled()
diff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsx
index d4cd3baa1..89d14a174 100644
--- a/src/web/src/components/community/bots/bot-list.tsx
+++ b/src/web/src/components/community/bots/bot-list.tsx
@@ -47,7 +47,6 @@ import {
updateCommunityOnboardingResources,
useCommunityOnboarding,
} from "@/lib/community-onboarding"
-import { bugReportsFeatureEnabled } from "@/hooks/community/use-bot-bug-report"
import { tid } from "@/lib/community/testids"
/**
@@ -81,7 +80,6 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
const searchParams = useSearchParams()
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
@@ -523,23 +521,21 @@ 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)}
>
<RotateCcw className="size-4" /> Reset
</DropdownMenuItem>
+ <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
variant="destructive"
onClick={() => setConfirmDelete(bot)}
@@ -573,7 +569,7 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
open={activityOpen}
onOpenChange={setActivityOpen}
/>
- {bugReportsEnabled && bugReportBot && (
+ {bugReportBot && (
<BugReportDialog
key={bugReportBot.id}
bot={bugReportBot}
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
index b7b732091..e6f1d9ad0 100644
--- a/src/web/src/components/community/bots/bug-report-dialog.test.ts
+++ b/src/web/src/components/community/bots/bug-report-dialog.test.ts
@@ -34,7 +34,7 @@ function render(overrides: Record<string, unknown> = {}) {
phase: "confirm",
isSubmitting: false,
reportId: null,
- failureCode: null,
+ errorCode: null,
onConfirm,
onOpenChange,
...overrides,
@@ -61,36 +61,16 @@ describe("BugReportDialog", () => {
vi.unstubAllGlobals()
})
- it("discloses allowlisted sources, exclusions, retention, and runtime-stderr residual risk before submit", () => {
+ it("explains the report in plain language before submit", () => {
const renderer = render()
const copy = text(renderer)
- for (const allowed of ["daemon", "FSM", "status"]) expect(copy).toContain(allowed)
+ expect(copy).toContain("only program logs needed to diagnose the problem")
+ expect(copy).toContain("We won’t read or upload your agent’s local chat history or files.")
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")
+ for (const jargon of ["daemon", "FSM", "PII", "stderr", "allowlisted"]) {
+ expect(copy).not.toContain(jargon)
+ }
expect(renderer.root.findAllByType("input")).toHaveLength(0)
expect(renderer.root.findAllByType("textarea")).toHaveLength(0)
expect(onConfirm).not.toHaveBeenCalled()
@@ -99,6 +79,7 @@ describe("BugReportDialog", () => {
it("submits only from explicit confirmation and disables repeat confirmation", () => {
const renderer = render()
const submit = renderer.root.findByProps({ "data-testid": "bot-report-problem-submit" })
+ expect(submit.props.children).toBe("Confirm")
act(() => submit.props.onClick())
expect(onConfirm).toHaveBeenCalledTimes(1)
@@ -106,6 +87,55 @@ describe("BugReportDialog", () => {
expect(pending.root.findByProps({ "data-testid": "bot-report-problem-submit" }).props.disabled).toBe(true)
})
+ it("offers only Close after the report is uploaded", () => {
+ const renderer = render({ phase: "uploaded", reportId: "dbr_test123" })
+
+ expect(renderer.root.findAllByProps({
+ "data-testid": "bot-report-problem-submit",
+ })).toHaveLength(0)
+ expect(text(renderer)).toContain("Close")
+ expect(text(renderer)).not.toContain("Report another problem")
+ expect(onConfirm).not.toHaveBeenCalled()
+ })
+
+ it("offers Close + Try again after timeout, never Report another problem", () => {
+ const renderer = render({ phase: "timeout", reportId: "dbr_test123" })
+ const submit = renderer.root.findByProps({ "data-testid": "bot-report-problem-submit" })
+ expect(submit.props.children).toBe("Try again")
+ expect(text(renderer)).toContain("Close")
+ expect(text(renderer)).not.toContain("Report another problem")
+ })
+
+ it("shows rate-limit title + body with Close only — no Try again that rehits the bucket", () => {
+ const renderer = render({
+ phase: "failed",
+ reportId: null,
+ errorCode: "rate_limited",
+ })
+ expect(text(renderer)).toContain("A report was sent recently")
+ expect(text(renderer)).toContain("You can send another report in a minute.")
+ expect(text(renderer)).not.toContain("Report failed")
+ expect(text(renderer)).toContain("Close")
+ expect(text(renderer)).not.toContain("Try again")
+ expect(renderer.root.findAllByProps({ "data-testid": "bot-report-problem-submit" })).toHaveLength(0)
+ })
+
+ it.each([
+ ["network_error", "Unable to connect — check your network"],
+ ["target_unavailable", "Diagnostics aren't available for this bot right now."],
+ ["nonce_conflict", "That report already belongs to another bot. Try again."],
+ ] as const)("shows semantic %s copy with Close + Try again", (errorCode, copy) => {
+ const renderer = render({
+ phase: "failed",
+ reportId: null,
+ errorCode,
+ })
+ expect(text(renderer)).toContain(copy)
+ expect(text(renderer)).toContain("Close")
+ expect(renderer.root.findByProps({ "data-testid": "bot-report-problem-submit" }).props.children)
+ .toBe("Try again")
+ })
+
it.each([
["collecting", "Collecting diagnostics"],
["uploaded", "Report uploaded"],
@@ -115,7 +145,7 @@ describe("BugReportDialog", () => {
const renderer = render({
phase,
reportId: "dbr_test123",
- failureCode: phase === "failed" ? "offline" : null,
+ errorCode: phase === "failed" ? "offline" : null,
})
expect(renderer.root.findByProps({ "data-testid": "bot-report-problem-status" })).toBeTruthy()
expect(text(renderer)).toContain(expected)
@@ -125,7 +155,7 @@ describe("BugReportDialog", () => {
const renderer = render({
phase: "failed",
reportId: "dbr_offline",
- failureCode: "offline",
+ errorCode: "offline",
errorDetail: "Bearer secret at /Users/private should leak",
})
expect(text(renderer)).toContain("Bring the daemon online")
diff --git a/src/web/src/components/community/bots/bug-report-dialog.tsx b/src/web/src/components/community/bots/bug-report-dialog.tsx
index 3e6bbcb16..4b9577db7 100644
--- a/src/web/src/components/community/bots/bug-report-dialog.tsx
+++ b/src/web/src/components/community/bots/bug-report-dialog.tsx
@@ -12,9 +12,9 @@ import {
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import {
- bugReportFailureMessage,
- type BugReportFailureCode,
+ bugReportErrorMessage,
type BugReportPhase,
+ type BugReportUiErrorCode,
useBotBugReport,
} from "@/hooks/community/use-bot-bug-report"
import { tid } from "@/lib/community/testids"
@@ -27,7 +27,7 @@ type DialogViewProps = {
phase: BugReportPhase
isSubmitting: boolean
reportId: string | null
- failureCode: BugReportFailureCode | null
+ errorCode: BugReportUiErrorCode | null
onConfirm: () => void | Promise<void>
onOpenChange: (open: boolean) => void
}
@@ -36,7 +36,8 @@ type BugReportDialogProps =
| (Pick<DialogViewProps, "bot" | "open" | "onOpenChange"> & { phase?: never })
| DialogViewProps
-function statusTitle(phase: BugReportPhase): string {
+function statusTitle(phase: BugReportPhase, errorCode: BugReportUiErrorCode | null): string {
+ if (phase === "failed" && errorCode === "rate_limited") return "A report was sent recently"
if (phase === "collecting") return "Collecting diagnostics"
if (phase === "uploaded") return "Report uploaded"
if (phase === "timeout") return "Collection timed out"
@@ -78,15 +79,15 @@ function ReportIdCopy({ reportId }: { reportId: string }) {
}
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"
+ const submitLabel = props.phase === "failed" || props.phase === "timeout"
? "Try again"
- : terminal
- ? "Report another problem"
- : props.isSubmitting
- ? "Submitting…"
- : "Confirm and collect"
+ : props.isSubmitting
+ ? "Submitting…"
+ : "Confirm"
+ const showSubmit = props.phase !== "collecting"
+ && props.phase !== "uploaded"
+ && !(props.phase === "failed" && props.errorCode === "rate_limited")
return (
<AlertDialog open={props.open} onOpenChange={props.onOpenChange}>
@@ -95,16 +96,12 @@ function BugReportDialogView(props: DialogViewProps) {
<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.
+ We’ll upload only program logs needed to diagnose the problem.
</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.
+ We won’t read or upload your agent’s local chat history or files.
</span>
+ <span className="block">Reports are deleted after 7 days.</span>
</AlertDialogDescription>
</AlertDialogHeader>
@@ -113,10 +110,10 @@ function BugReportDialogView(props: DialogViewProps) {
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>
+ <p className="font-medium text-foreground">{statusTitle(props.phase, props.errorCode)}</p>
{props.phase === "failed" && (
<p className="mt-1 text-muted-foreground">
- {bugReportFailureMessage(props.failureCode)}
+ {bugReportErrorMessage(props.errorCode)}
</p>
)}
{props.reportId && (
@@ -127,7 +124,7 @@ function BugReportDialogView(props: DialogViewProps) {
<AlertDialogFooter>
<AlertDialogCancel>Close</AlertDialogCancel>
- {props.phase !== "collecting" && (
+ {showSubmit && (
<Button
data-testid={tid.botReportProblemSubmit}
disabled={props.isSubmitting}
@@ -155,7 +152,7 @@ function ConnectedBugReportDialog({
phase={state.phase}
isSubmitting={state.phase === "submitting"}
reportId={state.reportId}
- failureCode={state.failureCode}
+ errorCode={state.errorCode}
onConfirm={confirm}
onOpenChange={onOpenChange}
/>
diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.ts
index 982bece1c..eddb187ce 100644
--- a/src/web/src/env.d.ts
+++ b/src/web/src/env.d.ts
@@ -29,7 +29,6 @@ declare namespace Cloudflare {
BETTER_AUTH_SECRET: string
BETTER_AUTH_URL: string
CACHE_KV: KVNamespace
- BUG_REPORTS_ENABLED?: string
RUNTIME_MODEL_OPTIONS?: string
MIN_CLI_VERSION?: string
}
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
index 4227b0d90..7c7b92506 100644
--- a/src/web/src/hooks/community/use-bot-bug-report.test.ts
+++ b/src/web/src/hooks/community/use-bot-bug-report.test.ts
@@ -2,14 +2,15 @@ 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 { ApiError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
import {
BUG_REPORT_POLL_INTERVAL_MS,
- bugReportFailureMessage,
- bugReportsFeatureEnabled,
+ bugReportErrorMessage,
buildBugReportCreateRequest,
buildBugReportStatusRequest,
bugReportReducer,
+ createActionFromApiError,
initialBugReportState,
projectOwnerBugReport,
shouldPollBugReport,
@@ -97,14 +98,6 @@ afterEach(() => {
})
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",
@@ -163,11 +156,11 @@ describe("bug-report frontend adapter", () => {
["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)
+ expect(bugReportErrorMessage(code)).toBe(expected)
})
it("uses one fixed generic message for unknown codes instead of reflecting arbitrary detail", () => {
- expect(bugReportFailureMessage("Bearer secret /Users/private")).toBe(
+ expect(bugReportErrorMessage("Bearer secret /Users/private")).toBe(
"The report could not be completed. Try again.",
)
})
@@ -186,6 +179,87 @@ describe("bug-report client state", () => {
expect(doubleConfirm).toEqual(first)
})
+ it.each([
+ [0, "network_error", false, "Unable to connect — check your network"],
+ [404, "target_unavailable", false, "Diagnostics aren't available for this bot right now."],
+ [409, "nonce_conflict", true, "That report already belongs to another bot. Try again."],
+ [429, "rate_limited", true, "You can send another report in a minute."],
+ ] as const)("maps create HTTP %s to semantic %s (terminal=%s)", (status, code, terminal, message) => {
+ const action = createActionFromApiError(new ApiError("server detail must not leak", status))
+ expect(action).toEqual({ type: "create_rejected", code })
+
+ const started = {
+ ...initialBugReportState,
+ phase: "submitting" as const,
+ clientNonce: "nonce-create",
+ }
+ const failed = bugReportReducer(started, action)
+ expect(failed).toMatchObject({
+ phase: "failed",
+ terminal,
+ errorCode: code,
+ clientNonce: "nonce-create",
+ })
+ expect(bugReportErrorMessage(code)).toBe(message)
+ })
+
+ it.each([
+ [500, "Something went wrong — please try again"],
+ [502, "upstream"],
+ ] as const)("maps create HTTP %s to unknown internal_error", (status, msg) => {
+ const action = createActionFromApiError(new ApiError(msg, status))
+ expect(action).toEqual({ type: "create_error" })
+ expect(bugReportReducer({
+ ...initialBugReportState,
+ phase: "submitting",
+ clientNonce: "nonce-unknown",
+ }, action)).toMatchObject({
+ phase: "failed",
+ terminal: false,
+ errorCode: "internal_error",
+ })
+ })
+
+ it("maps non-ApiError create failures to unknown internal_error", () => {
+ expect(createActionFromApiError(new TypeError("connection dropped"))).toEqual({
+ type: "create_error",
+ })
+ })
+
+ it.each([
+ ["network_error", false, "nonce-create"],
+ ["target_unavailable", false, "nonce-create"],
+ ["nonce_conflict", true, "nonce-new"],
+ ["rate_limited", true, "nonce-new"],
+ ] as const)("create %s retry nonce: reuse=%s", (code, expectNewNonce, expectedNonce) => {
+ const failed = bugReportReducer({
+ ...initialBugReportState,
+ phase: "submitting",
+ clientNonce: "nonce-create",
+ }, { type: "create_rejected", code })
+ const randomUUID = vi.fn(() => "nonce-new")
+ const retry = startBugReportAttempt(failed, randomUUID)
+ if (expectNewNonce) {
+ expect(randomUUID).toHaveBeenCalledTimes(1)
+ } else {
+ expect(randomUUID).not.toHaveBeenCalled()
+ }
+ expect(retry.clientNonce).toBe(expectedNonce)
+ })
+
+ it("never projects client request codes onto OwnerBugReport.failureCode", () => {
+ for (const code of ["rate_limited", "target_unavailable", "nonce_conflict", "network_error"]) {
+ expect(projectOwnerBugReport({
+ reportId: "dbr_clientcode123",
+ status: "failed",
+ deadlineAt: 5_000,
+ completedAt: 1_000,
+ failureCode: code,
+ objectExpired: false,
+ })).toBeNull()
+ }
+ })
+
it("reuses the nonce after an ambiguous POST failure and adopts an existing pending id", () => {
const started = {
...initialBugReportState,
@@ -279,7 +353,7 @@ describe("bug-report client state", () => {
terminal: true,
clientNonce: "nonce-old",
reportId: "dbr_old",
- failureCode: "offline",
+ errorCode: "offline",
}
const randomUUID = vi.fn(() => "nonce-new")
const next = startBugReportAttempt(failed, randomUUID)
@@ -325,6 +399,176 @@ describe("useBotBugReport", () => {
renderer.unmount()
})
+ it("starts fresh after a completed report is closed and reopened", async () => {
+ apiFetchMock.mockResolvedValueOnce({
+ delivery: "accepted",
+ report: { ...pendingReport(), status: "uploaded", completedAt: 2_000 },
+ })
+
+ const hook = renderBugReportHook()
+ await act(async () => {
+ await hook.result.current.confirm()
+ })
+ expect(hook.result.current.state).toMatchObject({
+ phase: "uploaded",
+ terminal: true,
+ reportId: "dbr_pending",
+ })
+
+ hook.setOpen(false)
+ expect(hook.result.current.state).toEqual(initialBugReportState)
+
+ hook.setOpen(true)
+ expect(hook.result.current.state).toEqual(initialBugReportState)
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ hook.renderer.unmount()
+ })
+
+ it.each([
+ [
+ "uploaded",
+ {
+ delivery: "accepted",
+ report: { ...pendingReport(), status: "uploaded" as const, completedAt: 2_000 },
+ },
+ { phase: "uploaded", reportId: "dbr_pending" },
+ ],
+ [
+ "failed",
+ {
+ delivery: "accepted",
+ report: {
+ ...pendingReport(),
+ status: "failed" as const,
+ failureCode: "collection_failed" as const,
+ completedAt: 2_000,
+ },
+ },
+ { phase: "failed", reportId: "dbr_pending", errorCode: "collection_failed" },
+ ],
+ ] as const)("resets when create resolves %s after the dialog already closed", async (_label, envelope, expected) => {
+ let resolveCreate!: (value: unknown) => void
+ apiFetchMock
+ .mockImplementationOnce(
+ () => new Promise((resolve) => {
+ resolveCreate = resolve
+ }),
+ )
+ .mockResolvedValueOnce(envelope)
+
+ const hook = renderBugReportHook()
+ await act(async () => {
+ void hook.result.current.confirm()
+ })
+ expect(hook.result.current.state.phase).toBe("submitting")
+
+ hook.setOpen(false)
+ expect(hook.result.current.state.phase).toBe("submitting")
+
+ await act(async () => {
+ resolveCreate(envelope)
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+ expect(hook.result.current.state).toEqual(initialBugReportState)
+
+ hook.setOpen(true)
+ expect(hook.result.current.state).toEqual(initialBugReportState)
+ await act(async () => {
+ await hook.result.current.confirm()
+ })
+ expect(hook.result.current.state).toMatchObject(expected)
+ expect(apiFetchMock.mock.calls.filter(([, init]) =>
+ (init as RequestInit | undefined)?.method === "POST",
+ )).toHaveLength(2)
+ hook.renderer.unmount()
+ })
+
+ it("keeps the same collecting report across close/reopen and resumes GET without a new POST", async () => {
+ apiFetchMock
+ .mockResolvedValueOnce({ delivery: "accepted", report: pendingReport() })
+ .mockResolvedValue({ report: pendingReport() })
+
+ const hook = renderBugReportHook()
+ await act(async () => {
+ await hook.result.current.confirm()
+ })
+ await flushMicrotasks()
+ expect(hook.result.current.state).toMatchObject({
+ phase: "collecting",
+ reportId: "dbr_pending",
+ clientNonce: "00000000-0000-4000-8000-000000000001",
+ terminal: false,
+ })
+ const postsBeforeClose = apiFetchMock.mock.calls.filter(([, init]) =>
+ (init as RequestInit | undefined)?.method === "POST",
+ ).length
+ expect(postsBeforeClose).toBe(1)
+ const getsBeforeClose = apiFetchMock.mock.calls.filter(([, init]) =>
+ (init as RequestInit | undefined)?.method === "GET",
+ ).length
+ expect(getsBeforeClose).toBeGreaterThanOrEqual(1)
+
+ hook.setOpen(false)
+ expect(hook.result.current.state).toMatchObject({
+ phase: "collecting",
+ reportId: "dbr_pending",
+ clientNonce: "00000000-0000-4000-8000-000000000001",
+ })
+ const getsWhileClosed = apiFetchMock.mock.calls.filter(([, init]) =>
+ (init as RequestInit | undefined)?.method === "GET",
+ ).length
+
+ hook.setOpen(true)
+ await flushMicrotasks()
+ await vi.waitFor(() => {
+ const getsAfterReopen = apiFetchMock.mock.calls.filter(([, init]) =>
+ (init as RequestInit | undefined)?.method === "GET",
+ ).length
+ expect(getsAfterReopen).toBeGreaterThan(getsWhileClosed)
+ })
+
+ await act(async () => {
+ await hook.result.current.confirm()
+ })
+ await flushMicrotasks()
+
+ const postsAfterReopen = apiFetchMock.mock.calls.filter(([, init]) =>
+ (init as RequestInit | undefined)?.method === "POST",
+ )
+ expect(postsAfterReopen).toHaveLength(1)
+ expect(globalThis.crypto.randomUUID).toHaveBeenCalledTimes(1)
+ expect(hook.result.current.state).toMatchObject({
+ phase: "collecting",
+ reportId: "dbr_pending",
+ clientNonce: "00000000-0000-4000-8000-000000000001",
+ })
+ hook.renderer.unmount()
+ })
+
+ it.each([
+ [0, "network_error", false],
+ [404, "target_unavailable", false],
+ [409, "nonce_conflict", true],
+ [429, "rate_limited", true],
+ ] as const)("keeps create HTTP %s as %s instead of wiping to internal_error", async (status, code, terminal) => {
+ apiFetchMock.mockRejectedValueOnce(new ApiError("server detail must not leak", status))
+
+ const { renderer, result } = renderBugReportHook()
+ await act(async () => {
+ await result.current.confirm()
+ })
+ expect(result.current.state).toMatchObject({
+ phase: "failed",
+ terminal,
+ errorCode: code,
+ })
+ expect(bugReportErrorMessage(result.current.state.errorCode)).not.toBe(
+ bugReportErrorMessage("internal_error"),
+ )
+ renderer.unmount()
+ })
+
it("retries an ambiguous POST with the same nonce, then polls the adopted pending id", async () => {
apiFetchMock
.mockRejectedValueOnce(new TypeError("connection dropped"))
@@ -510,9 +754,9 @@ describe("useBotBugReport", () => {
expect(hook.result.current.state).toMatchObject({
phase: "failed",
terminal: true,
- failureCode: "internal_error",
+ errorCode: "internal_error",
})
- expect(bugReportFailureMessage(hook.result.current.state.failureCode)).toBe(
+ expect(bugReportErrorMessage(hook.result.current.state.errorCode)).toBe(
"The report could not be completed. Try again.",
)
expect(JSON.stringify(hook.result.current.state)).not.toMatch(
diff --git a/src/web/src/hooks/community/use-bot-bug-report.ts b/src/web/src/hooks/community/use-bot-bug-report.ts
index 8822b5517..b3f47c1e4 100644
--- a/src/web/src/hooks/community/use-bot-bug-report.ts
+++ b/src/web/src/hooks/community/use-bot-bug-report.ts
@@ -3,6 +3,7 @@
import { useCallback, useEffect, useRef, useState } from "react"
import { useQuery, useQueryClient } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
+import { ApiError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
import {
DiagnosticReportFailureCodeSchema,
@@ -11,7 +12,17 @@ import {
export const BUG_REPORT_POLL_INTERVAL_MS = 1_000
-export type BugReportFailureCode = DiagnosticReportFailureCode
+const CLIENT_ERROR_CODES = [
+ "rate_limited",
+ "target_unavailable",
+ "nonce_conflict",
+ "network_error",
+] as const
+
+type BugReportClientErrorCode = (typeof CLIENT_ERROR_CODES)[number]
+
+export type BugReportUiErrorCode = DiagnosticReportFailureCode | BugReportClientErrorCode
+
export type BugReportPhase =
| "confirm"
| "submitting"
@@ -25,7 +36,7 @@ export type OwnerBugReport = {
status: "pending" | "uploaded" | "failed"
deadlineAt: number
completedAt: number | null
- failureCode: BugReportFailureCode | null
+ failureCode: DiagnosticReportFailureCode | null
objectExpired: boolean
}
@@ -36,7 +47,7 @@ export type BugReportState = {
reportId: string | null
deadlineAt: number | null
completedAt: number | null
- failureCode: BugReportFailureCode | null
+ errorCode: BugReportUiErrorCode | null
objectExpired: boolean
}
@@ -47,19 +58,23 @@ export const initialBugReportState: BugReportState = {
reportId: null,
deadlineAt: null,
completedAt: null,
- failureCode: null,
+ errorCode: null,
objectExpired: false,
}
-type BugReportAction =
+type CreateBugReportFailureAction =
| { type: "create_error" }
+ | { type: "create_rejected"; code: BugReportClientErrorCode }
+
+type BugReportAction =
+ | CreateBugReportFailureAction
| { type: "poll_error" }
| { type: "invalid_payload" }
| { type: "deadline" }
| { type: "created"; delivery: "accepted" | "unknown"; report: OwnerBugReport }
| { type: "status"; report: OwnerBugReport }
-const failureMessages: Record<BugReportFailureCode, string> = {
+const errorMessages: Record<BugReportUiErrorCode, 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.",
@@ -72,23 +87,47 @@ const failureMessages: Record<BugReportFailureCode, string> = {
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.",
+ rate_limited: "You can send another report in a minute.",
+ target_unavailable: "Diagnostics aren't available for this bot right now.",
+ nonce_conflict: "That report already belongs to another bot. Try again.",
+ network_error: "Unable to connect — check your network",
}
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 {
+function isServerFailureCode(value: unknown): value is DiagnosticReportFailureCode {
return DiagnosticReportFailureCodeSchema.safeParse(value).success
}
-function isTimestamp(value: unknown): value is number {
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
+function isClientErrorCode(value: unknown): value is BugReportClientErrorCode {
+ return typeof value === "string"
+ && (CLIENT_ERROR_CODES as readonly string[]).includes(value)
+}
+
+function isUiErrorCode(value: unknown): value is BugReportUiErrorCode {
+ return isClientErrorCode(value) || isServerFailureCode(value)
+}
+
+export function createActionFromApiError(error: unknown): CreateBugReportFailureAction {
+ if (error instanceof ApiError) {
+ if (error.isNetworkError || error.status === 0) {
+ return { type: "create_rejected", code: "network_error" }
+ }
+ if (error.isRateLimit) return { type: "create_rejected", code: "rate_limited" }
+ if (error.status === 404) return { type: "create_rejected", code: "target_unavailable" }
+ if (error.status === 409) return { type: "create_rejected", code: "nonce_conflict" }
+ }
+ return { type: "create_error" }
}
-export function bugReportsFeatureEnabled(value: unknown): boolean {
- if (!isRecord(value) || !isRecord(value.features)) return false
- return value.features.bugReports === true
+function isCreateRejectedTerminal(code: BugReportClientErrorCode): boolean {
+ return code === "rate_limited" || code === "nonce_conflict"
+}
+
+function isTimestamp(value: unknown): value is number {
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
}
export function buildBugReportCreateRequest(agentId: string, clientNonce: string) {
@@ -119,10 +158,10 @@ export function projectOwnerBugReport(value: unknown): OwnerBugReport | null {
if (value.completedAt !== null && value.completedAt !== undefined && !isTimestamp(value.completedAt)) {
return null
}
- if (value.failureCode !== null && value.failureCode !== undefined && !isFailureCode(value.failureCode)) {
+ if (value.failureCode !== null && value.failureCode !== undefined && !isServerFailureCode(value.failureCode)) {
return null
}
- if (value.status === "failed" && !isFailureCode(value.failureCode)) return null
+ if (value.status === "failed" && !isServerFailureCode(value.failureCode)) return null
if (value.status !== "failed" && value.failureCode !== null && value.failureCode !== undefined) {
return null
}
@@ -137,8 +176,8 @@ export function projectOwnerBugReport(value: unknown): OwnerBugReport | null {
}
}
-export function bugReportFailureMessage(code: unknown): string {
- return isFailureCode(code) ? failureMessages[code] : failureMessages.internal_error
+export function bugReportErrorMessage(code: unknown): string {
+ return isUiErrorCode(code) ? errorMessages[code] : errorMessages.internal_error
}
export function startBugReportAttempt(
@@ -147,7 +186,7 @@ export function startBugReportAttempt(
): BugReportState {
if (state.phase === "submitting" || state.phase === "collecting") return state
if (!state.terminal && state.clientNonce) {
- return { ...state, phase: "submitting", failureCode: null }
+ return { ...state, phase: "submitting", errorCode: null }
}
return {
...initialBugReportState,
@@ -162,7 +201,7 @@ function stateForReport(state: BugReportState, report: OwnerBugReport): BugRepor
reportId: report.reportId,
deadlineAt: report.deadlineAt,
completedAt: report.completedAt,
- failureCode: report.failureCode,
+ errorCode: report.failureCode,
objectExpired: report.objectExpired,
}
if (report.status === "pending") {
@@ -183,13 +222,21 @@ export function bugReportReducer(state: BugReportState, action: BugReportAction)
return stateForReport(state, action.report)
}
if (action.type === "create_error") {
- return { ...state, phase: "failed", terminal: false, failureCode: "internal_error" }
+ return { ...state, phase: "failed", terminal: false, errorCode: "internal_error" }
+ }
+ if (action.type === "create_rejected") {
+ return {
+ ...state,
+ phase: "failed",
+ terminal: isCreateRejectedTerminal(action.code),
+ errorCode: action.code,
+ }
}
if (action.type === "invalid_payload") {
- return { ...state, phase: "failed", terminal: true, failureCode: "internal_error" }
+ return { ...state, phase: "failed", terminal: true, errorCode: "internal_error" }
}
if (action.type === "deadline") {
- return { ...state, phase: "timeout", terminal: true, failureCode: "timeout" }
+ return { ...state, phase: "timeout", terminal: true, errorCode: "timeout" }
}
return state
}
@@ -254,8 +301,8 @@ export function useBotBugReport({ agentId, open }: { agentId: string; open: bool
? "accepted"
: "unknown"
apply({ type: "created", delivery, report })
- } catch {
- apply({ type: "create_error" })
+ } catch (error) {
+ apply(createActionFromApiError(error))
}
}, [agentId, apply, replaceState])
@@ -312,6 +359,11 @@ export function useBotBugReport({ agentId, open }: { agentId: string; open: bool
})
}, [open, queryClient, reportId])
+ useEffect(() => {
+ if (open || !state.terminal) return
+ replaceState(initialBugReportState)
+ }, [open, replaceState, state.terminal])
+
useEffect(() => {
if (!reportId) return
return () => {
diff --git a/src/web/src/lib/community/diagnostic-feature.test.ts b/src/web/src/lib/community/diagnostic-feature.test.ts
deleted file mode 100644
index 4e5a457e8..000000000
--- a/src/web/src/lib/community/diagnostic-feature.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { describe, expect, it } from "vitest";
-import {
- isBugReportsEnabled,
- projectBugReportsFeature,
-} from "./diagnostic-feature";
-
-describe("diagnostic report feature flag", () => {
- it.each([
- [undefined, false],
- ["", false],
- ["false", false],
- ["TRUE", false],
- ["1", false],
- [true, false],
- ["true", true],
- ])("treats only the exact string true as enabled", (value, expected) => {
- expect(isBugReportsEnabled({ BUG_REPORTS_ENABLED: value } as never)).toBe(expected);
- });
-
- it("projects one boolean and never exposes the raw environment value", () => {
- const projected = projectBugReportsFeature({
- BUG_REPORTS_ENABLED: "true",
- BUG_REPORTS: { privateBinding: true },
- API_TOKEN: "secret",
- } as never);
-
- expect(projected).toEqual({ bugReports: true });
- expect(Object.keys(projected)).toEqual(["bugReports"]);
- expect(JSON.stringify(projected)).not.toMatch(/BUG_REPORTS|TOKEN|privateBinding|secret/);
- });
-});
diff --git a/src/web/src/lib/community/diagnostic-feature.ts b/src/web/src/lib/community/diagnostic-feature.ts
deleted file mode 100644
index 8394ea1b0..000000000
--- a/src/web/src/lib/community/diagnostic-feature.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-export function isBugReportsEnabled(
- env: object,
-): boolean {
- return (env as { BUG_REPORTS_ENABLED?: unknown }).BUG_REPORTS_ENABLED === "true";
-}
-
-export function projectBugReportsFeature(
- env: object,
-): { bugReports: boolean } {
- return { bugReports: isBugReportsEnabled(env) };
-}
diff --git a/src/web/src/lib/community/diagnostic-upload.test.ts b/src/web/src/lib/community/diagnostic-upload.test.ts
index 37d8ca069..714277839 100644
--- a/src/web/src/lib/community/diagnostic-upload.test.ts
+++ b/src/web/src/lib/community/diagnostic-upload.test.ts
@@ -52,7 +52,7 @@ interface DiagnosticUploadModule {
bucket: R2Port;
queries: QueryPort;
now: () => number;
- fixedLengthStream: (sizeBytes: number) => {
+ fixedLengthStream?: (sizeBytes: number) => {
readable: ReadableStream<Uint8Array>;
writable: WritableStream<Uint8Array>;
};
@@ -72,6 +72,8 @@ interface DiagnosticUploadModule {
};
}
+const fixedLengthBodies = new WeakSet<ReadableStream<Uint8Array>>();
+
async function loadSubject(): Promise<DiagnosticUploadModule> {
return vi.importActual<DiagnosticUploadModule>("./diagnostic-upload.js");
}
@@ -143,10 +145,38 @@ function strictFixedLengthFactory(calls: number[]) {
if (seen !== expected) throw new Error("fixed length underflow");
},
});
+ fixedLengthBodies.add(transform.readable);
return transform;
};
}
+function bodyToBytes(body: ReadableStream<Uint8Array> | ArrayBuffer | ArrayBufferView): Promise<Uint8Array> {
+ if (body instanceof ArrayBuffer) return Promise.resolve(new Uint8Array(body));
+ if (ArrayBuffer.isView(body)) {
+ return Promise.resolve(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
+ }
+ if (!(body instanceof ReadableStream) || !fixedLengthBodies.has(body)) {
+ return Promise.reject(new TypeError("R2 put rejected non-fixed-length stream"));
+ }
+ return (async () => {
+ const chunks: Uint8Array[] = [];
+ const reader = body.getReader();
+ while (true) {
+ const next = await reader.read();
+ if (next.done) break;
+ chunks.push(next.value);
+ }
+ const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
+ const bytes = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return bytes;
+ })();
+}
+
function queryFake() {
return {
getPending: vi.fn(async () => row()),
@@ -165,7 +195,11 @@ function queryFake() {
function r2Fake() {
const objects = new Map<string, { body: Uint8Array; sha256: string }>();
const claims = new Map<string, Promise<void>>();
- const put = vi.fn(async (key: string, body: ReadableStream<Uint8Array>, options: Record<string, unknown>) => {
+ const put = vi.fn(async (
+ key: string,
+ body: ReadableStream<Uint8Array> | ArrayBuffer | ArrayBufferView,
+ options: Record<string, unknown>,
+ ) => {
const existingClaim = claims.get(key);
const isWinner = !objects.has(key) && existingClaim === undefined;
let releaseClaim: (() => void) | undefined;
@@ -173,15 +207,8 @@ function r2Fake() {
claims.set(key, new Promise<void>((resolve) => { releaseClaim = resolve; }));
}
try {
- const chunks: Uint8Array[] = [];
- const reader = body.getReader();
- while (true) {
- const next = await reader.read();
- if (next.done) break;
- chunks.push(next.value);
- }
- const merged = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));
- const checksum = createHash("sha256").update(merged).digest("hex");
+ const bytes = await bodyToBytes(body);
+ const checksum = createHash("sha256").update(bytes).digest("hex");
expect((options.sha256 as ArrayBuffer).byteLength).toBe(32);
const claimed = Buffer.from(options.sha256 as ArrayBuffer).toString("hex");
if (checksum !== claimed) throw new Error("R2 checksum mismatch");
@@ -189,7 +216,7 @@ function r2Fake() {
await existingClaim;
return null;
}
- objects.set(key, { body: merged, sha256: checksum });
+ objects.set(key, { body: bytes, sha256: checksum });
return { key };
} finally {
if (isWinner) {
@@ -214,6 +241,116 @@ function r2Fake() {
describe("B2d diagnostic upload service", () => {
beforeEach(() => vi.restoreAllMocks());
+ it("Node/default path buffers a fixed-length body when FixedLengthStream is missing", async () => {
+ const api = await loadSubject();
+ const host = globalThis as { FixedLengthStream?: unknown };
+ const previous = host.FixedLengthStream;
+ Reflect.deleteProperty(host, "FixedLengthStream");
+
+ try {
+ const queries = queryFake();
+ const bucket = r2Fake();
+ const service = api.createDiagnosticUploadService({
+ bucket,
+ queries,
+ now: () => NOW,
+ });
+ await expect(service.upload({
+ reportId: REPORT_ID,
+ machineId: MACHINE_ID,
+ sizeBytes: 6,
+ sha256: SHA256,
+ body: bytes(),
+ })).resolves.toEqual({ kind: "terminal", status: "uploaded" });
+ expect(bucket.put.mock.calls[0]![1]).toBeInstanceOf(Uint8Array);
+ expect((bucket.put.mock.calls[0]![1] as Uint8Array).byteLength).toBe(6);
+ expect(queries.finalize).toHaveBeenCalledTimes(1);
+ } finally {
+ if (previous === undefined) Reflect.deleteProperty(host, "FixedLengthStream");
+ else host.FixedLengthStream = previous;
+ }
+ });
+
+ it.each([
+ ["under length", "bun", 6, SHA256],
+ ["over length", "bundled!", 6, SHA256],
+ ["same-length wrong SHA", "nope!!", 6, SHA256],
+ ] as const)(
+ "Node/default path rejects %s before R2 put",
+ async (_label, payload, sizeBytes, sha256) => {
+ const api = await loadSubject();
+ const host = globalThis as { FixedLengthStream?: unknown };
+ const previous = host.FixedLengthStream;
+ Reflect.deleteProperty(host, "FixedLengthStream");
+
+ try {
+ const queries = queryFake();
+ const bucket = r2Fake();
+ const service = api.createDiagnosticUploadService({
+ bucket,
+ queries,
+ now: () => NOW,
+ });
+ await expect(service.upload({
+ reportId: REPORT_ID,
+ machineId: MACHINE_ID,
+ sizeBytes,
+ sha256,
+ body: bytes(payload),
+ })).resolves.toEqual({ kind: "terminal", status: "failed" });
+ expect(bucket.put).not.toHaveBeenCalled();
+ expect(queries.fail).toHaveBeenCalledWith(expect.objectContaining({
+ failureCode: "invalid_upload",
+ }));
+ } finally {
+ if (previous === undefined) Reflect.deleteProperty(host, "FixedLengthStream");
+ else host.FixedLengthStream = previous;
+ }
+ },
+ );
+
+ it("default factory prefers globalThis.FixedLengthStream when present (Workers)", async () => {
+ const api = await loadSubject();
+ const host = globalThis as {
+ FixedLengthStream?: new (n: number) => {
+ readable: ReadableStream<Uint8Array>;
+ writable: WritableStream<Uint8Array>;
+ };
+ };
+ const previous = host.FixedLengthStream;
+ const calls: number[] = [];
+ host.FixedLengthStream = class {
+ readable: ReadableStream<Uint8Array>;
+ writable: WritableStream<Uint8Array>;
+ constructor(expected: number) {
+ const pair = strictFixedLengthFactory(calls)(expected);
+ this.readable = pair.readable;
+ this.writable = pair.writable;
+ }
+ };
+
+ try {
+ const queries = queryFake();
+ const bucket = r2Fake();
+ const service = api.createDiagnosticUploadService({
+ bucket,
+ queries,
+ now: () => NOW,
+ });
+ await expect(service.upload({
+ reportId: REPORT_ID,
+ machineId: MACHINE_ID,
+ sizeBytes: 6,
+ sha256: SHA256,
+ body: bytes(),
+ })).resolves.toEqual({ kind: "terminal", status: "uploaded" });
+ expect(calls).toEqual([6]);
+ } finally {
+ if (previous === undefined) Reflect.deleteProperty(host, "FixedLengthStream");
+ else host.FixedLengthStream = previous;
+ }
+ });
+
it("authorizes the immutable machine snapshot before R2 and streams a fixed-length conditional Standard object", async () => {
const api = await loadSubject();
const queries = queryFake();
diff --git a/src/web/src/lib/community/diagnostic-upload.ts b/src/web/src/lib/community/diagnostic-upload.ts
index 2b49fc904..9f8de5d9c 100644
--- a/src/web/src/lib/community/diagnostic-upload.ts
+++ b/src/web/src/lib/community/diagnostic-upload.ts
@@ -43,10 +43,12 @@ export interface DiagnosticUploadQueryPort {
timeout(input: { reportId: string; ownerUserId: string; nowMs: number }): Promise<ReportRow | null>;
}
+type R2PutBody = ReadableStream<Uint8Array> | ArrayBuffer | ArrayBufferView;
+
interface R2Port {
put(
key: string,
- body: ReadableStream<Uint8Array>,
+ body: R2PutBody,
options: R2PutOptions,
): Promise<R2Object | object | null>;
head(key: string): Promise<Pick<R2Object, "size" | "checksums"> | null>;
@@ -58,6 +60,60 @@ type FixedLengthFactory = (sizeBytes: number) => {
writable: WritableStream<Uint8Array>;
};
+type FixedLengthStreamCtor = new (
+ expectedLength: number | bigint,
+) => {
+ readable: ReadableStream<Uint8Array>;
+ writable: WritableStream<Uint8Array>;
+};
+
+function hasNativeFixedLengthStream(): boolean {
+ return typeof (globalThis as typeof globalThis & {
+ FixedLengthStream?: FixedLengthStreamCtor;
+ }).FixedLengthStream === "function";
+}
+
+function createFixedLengthStream(sizeBytes: number): {
+ readable: ReadableStream<Uint8Array>;
+ writable: WritableStream<Uint8Array>;
+} {
+ const GlobalFixedLengthStream = (globalThis as typeof globalThis & {
+ FixedLengthStream?: FixedLengthStreamCtor;
+ }).FixedLengthStream;
+ if (typeof GlobalFixedLengthStream !== "function") {
+ throw new TypeError("FixedLengthStream is not available");
+ }
+ return new GlobalFixedLengthStream(sizeBytes);
+}
+
+async function readExactBody(
+ body: ReadableStream<Uint8Array>,
+ sizeBytes: number,
+ sha256: string,
+): Promise<{ kind: "ok"; bytes: Uint8Array } | { kind: "invalid" } | { kind: "error" }> {
+ const reader = body.getReader();
+ const hash = createHash("sha256");
+ const bytes = new Uint8Array(sizeBytes);
+ let seen = 0;
+ try {
+ while (true) {
+ const next = await reader.read();
+ if (next.done) break;
+ if (seen + next.value.byteLength > sizeBytes) {
+ await reader.cancel().catch(() => {});
+ return { kind: "invalid" };
+ }
+ bytes.set(next.value, seen);
+ seen += next.value.byteLength;
+ hash.update(next.value);
+ }
+ if (seen !== sizeBytes || hash.digest("hex") !== sha256) return { kind: "invalid" };
+ return { kind: "ok", bytes };
+ } catch {
+ return { kind: "error" };
+ }
+}
+
function exactSha256Bytes(hex: string): ArrayBuffer | null {
if (!/^[0-9a-f]{64}$/.test(hex)) return null;
const bytes = new Uint8Array(32);
@@ -115,8 +171,12 @@ export function createDiagnosticUploadService(args: {
fixedLengthStream?: FixedLengthFactory;
}) {
const now = args.now ?? Date.now;
- const fixedLengthStream: FixedLengthFactory = args.fixedLengthStream
- ?? ((sizeBytes) => new FixedLengthStream(sizeBytes));
+
+ const resolveStreamFactory = (): FixedLengthFactory | null => {
+ if (args.fixedLengthStream) return args.fixedLengthStream;
+ if (hasNativeFixedLengthStream()) return createFixedLengthStream;
+ return null;
+ };
const convergeFailure = async (input: {
reportId: string;
@@ -243,107 +303,134 @@ export function createDiagnosticUploadService(args: {
}
const r2Key = `bug-reports/${report.ownerUserId}/${input.reportId}.ndjson.gz`;
- const fixed = fixedLengthStream(input.sizeBytes);
- const writer = fixed.writable.getWriter();
- const reader = input.body.getReader();
- const hash = createHash("sha256");
- let seen = 0;
- let localInvalid = false;
+ const putOptions = {
+ onlyIf: { etagDoesNotMatch: "*" },
+ sha256: sha256Bytes,
+ storageClass: "Standard",
+ httpMetadata: {
+ contentType: "application/x-ndjson",
+ contentEncoding: "gzip",
+ },
+ } as const;
+
+ let createdByThisRequest = false;
let destinationFailed = false;
- let destinationDetached = false;
- let pumpFinished = false;
+ const streamFactory = resolveStreamFactory();
- const pump = (async () => {
- try {
- while (true) {
- const next = await reader.read();
- if (next.done) break;
- seen += next.value.byteLength;
- if (seen > input.sizeBytes) {
+ if (streamFactory) {
+ const fixed = streamFactory(input.sizeBytes);
+ const writer = fixed.writable.getWriter();
+ const reader = input.body.getReader();
+ const hash = createHash("sha256");
+ let seen = 0;
+ let localInvalid = false;
+ let destinationDetached = false;
+ let pumpFinished = false;
+
+ const pump = (async () => {
+ try {
+ while (true) {
+ const next = await reader.read();
+ if (next.done) break;
+ seen += next.value.byteLength;
+ if (seen > input.sizeBytes) {
+ localInvalid = true;
+ await reader.cancel().catch(() => {});
+ break;
+ }
+ hash.update(next.value);
+ if (!destinationFailed && !destinationDetached) {
+ try {
+ await writer.write(next.value);
+ } catch {
+ if (!destinationDetached) destinationFailed = true;
+ }
+ }
+ }
+ if (!localInvalid && (seen !== input.sizeBytes || hash.digest("hex") !== input.sha256)) {
localInvalid = true;
- await reader.cancel().catch(() => {});
- break;
}
- hash.update(next.value);
- if (!destinationFailed && !destinationDetached) {
+ } catch {
+ localInvalid = true;
+ }
+
+ try {
+ if (destinationDetached) {
+ // The destination settled before source validation completed. Its
+ // settlement handler already released the writer.
+ } else if (localInvalid || destinationFailed) {
try {
- await writer.write(next.value);
+ await writer.abort();
} catch {
- if (!destinationDetached) destinationFailed = true;
+ destinationFailed = true;
+ }
+ } else {
+ try {
+ await writer.close();
+ } catch {
+ destinationFailed = true;
}
}
+ } finally {
+ pumpFinished = true;
}
- if (!localInvalid && (seen !== input.sizeBytes || hash.digest("hex") !== input.sha256)) {
- localInvalid = true;
- }
- } catch {
- localInvalid = true;
- }
+ })();
- try {
- if (destinationDetached) {
- // The destination settled before source validation completed. Its
- // settlement handler already released the writer.
- } else if (localInvalid || destinationFailed) {
- try {
- await writer.abort();
- } catch {
- destinationFailed = true;
+ const put = Promise.resolve(args.bucket.put(r2Key, fixed.readable, putOptions)).then(
+ async (result) => {
+ if (!pumpFinished) {
+ destinationDetached = true;
+ try {
+ await writer.abort();
+ } catch {
+ destinationFailed = true;
+ }
}
- } else {
+ return result;
+ },
+ async (error) => {
+ destinationDetached = true;
try {
- await writer.close();
+ await writer.abort(error);
} catch {
destinationFailed = true;
}
- }
- } finally {
- pumpFinished = true;
- }
- })();
+ throw error;
+ },
+ );
- const put = Promise.resolve(args.bucket.put(r2Key, fixed.readable, {
- onlyIf: { etagDoesNotMatch: "*" },
- sha256: sha256Bytes,
- storageClass: "Standard",
- httpMetadata: {
- contentType: "application/x-ndjson",
- contentEncoding: "gzip",
- },
- })).then(async (result) => {
- if (!pumpFinished) {
- destinationDetached = true;
- try {
- await writer.abort();
- } catch {
- destinationFailed = true;
- }
+ const [pumpResult, putResult] = await Promise.allSettled([pump, put]);
+ if (localInvalid) {
+ return convergeFailure({
+ reportId: input.reportId,
+ machineId: input.machineId,
+ failureCode: "invalid_upload",
+ nowMs,
+ });
+ }
+ if (pumpResult.status === "rejected" || putResult.status === "rejected") {
+ return { kind: "retryable" };
}
- return result;
- }, async (error) => {
- destinationDetached = true;
+ createdByThisRequest = putResult.value !== null;
+ } else {
+ const buffered = await readExactBody(input.body, input.sizeBytes, input.sha256);
+ if (buffered.kind === "invalid") {
+ return convergeFailure({
+ reportId: input.reportId,
+ machineId: input.machineId,
+ failureCode: "invalid_upload",
+ nowMs,
+ });
+ }
+ if (buffered.kind === "error") return { kind: "retryable" };
try {
- await writer.abort(error);
+ const putResult = await args.bucket.put(r2Key, buffered.bytes, putOptions);
+ createdByThisRequest = putResult !== null;
} catch {
- destinationFailed = true;
+ return { kind: "retryable" };
}
- throw error;
- });
-
- const [pumpResult, putResult] = await Promise.allSettled([pump, put]);
- if (localInvalid) {
- return convergeFailure({
- reportId: input.reportId,
- machineId: input.machineId,
- failureCode: "invalid_upload",
- nowMs,
- });
- }
- if (pumpResult.status === "rejected" || putResult.status === "rejected") {
- return { kind: "retryable" };
}
- const createdByThisRequest = putResult.value !== null;
if (createdByThisRequest && destinationFailed) return { kind: "retryable" };
if (!createdByThisRequest) {
let head: Awaited<ReturnType<R2Port["head"]>>;
diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.ts
index 11edb6692..904ca4c11 100644
--- a/src/web/src/lib/use-user-ws.test.ts
+++ b/src/web/src/lib/use-user-ws.test.ts
@@ -564,6 +564,40 @@ describe("useUserWs", () => {
expect(onMessage).toHaveBeenCalledWith(valid)
})
+ it("consumes the raw pong liveness response without reporting a dropped frame", async () => {
+ setupTokenFetch()
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
+ const onMessage = vi.fn()
+ await mountHook(onMessage, { requestDaemonStatusOnAuth: false })
+ const ws = MockWebSocket.instances[0]
+ ws.simulateOpen()
+ warn.mockClear()
+
+ ws.simulateRawMessage("pong")
+
+ expect(onMessage).not.toHaveBeenCalled()
+ expect(warn).not.toHaveBeenCalled()
+ })
+
+ it("refreshes the liveness deadline when a raw pong arrives", async () => {
+ setupTokenFetch()
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
+ await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const ws = MockWebSocket.instances[0]
+ ws.simulateOpen()
+ warn.mockClear()
+
+ await vi.advanceTimersByTimeAsync(29_000)
+ ws.simulateRawMessage("pong")
+ await vi.advanceTimersByTimeAsync(29_000)
+
+ expect(ws.closed).toBe(false)
+ expect(warn).not.toHaveBeenCalled()
+
+ await vi.advanceTimersByTimeAsync(2_000)
+ expect(ws.closed).toBe(true)
+ })
+
it("consumes duplicate auth.ok frames once per generation", async () => {
setupTokenFetch()
const onAuthenticated = vi.fn()
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index 9bf05b18d..77e780337 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -188,6 +188,7 @@ export function useUserWs(
reportDroppedFrame("invalid-json")
return
}
+ if (e.data === "pong") return
let parsed: unknown
try {
parsed = JSON.parse(e.data)
diff --git a/src/web/wrangler.toml b/src/web/wrangler.toml
index 5bb4cbcaf..4db1bfef6 100644
--- a/src/web/wrangler.toml
+++ b/src/web/wrangler.toml
@@ -95,6 +95,5 @@ binding = "CACHE_KV"
id = "3aaa92b4c2c74185b888977e5552e9bf"
[vars]
-BUG_REPORTS_ENABLED = "false"
RUNTIME_MODEL_OPTIONS = '{"claude":["claude-opus-4-6","claude-sonnet-4-6","claude-haiku-4-5"],"codex":["gpt-5.4","gpt-5.3-codex"]}'
MIN_CLI_VERSION = "0.0.159"
diff --git a/src/ws-do/package.json b/src/ws-do/package.json
index 506e4050e..bdb3e130f 100644
--- a/src/ws-do/package.json
+++ b/src/ws-do/package.json
@@ -3,7 +3,7 @@
"version": "0.1.2",
"private": true,
"scripts": {
- "dev": "wrangler dev --persist-to ../web/.wrangler/state",
+ "dev": "node ../../scripts/dev-with-wrangler-registry.mjs ../../.wrangler/registry wrangler dev --persist-to ../web/.wrangler/state",
"deploy": "wrangler deploy",
"knip": "knip",
"test": "vitest run --passWithNoTests",
diff --git a/src/ws-do/src/routes/community-machine-delivery.test.ts b/src/ws-do/src/routes/community-machine-delivery.test.ts
index 0c07c0ea0..1e0c173d4 100644
--- a/src/ws-do/src/routes/community-machine-delivery.test.ts
+++ b/src/ws-do/src/routes/community-machine-delivery.test.ts
@@ -11,6 +11,7 @@ const sharedMocks = getSharedMocks()
const mockHashCredential = sharedMocks.hashCredential
const mockDoNameFromHash = sharedMocks.doNameFromHash
const mockGetActiveDoNamesForMachine = sharedMocks.getActiveDoNamesForMachine
+const mockWithD1Retry = sharedMocks.withD1Retry
const loggerMocks = {
child: sharedMocks.loggerChild,
debug: sharedMocks.loggerDebug,
@@ -106,6 +107,8 @@ describe("ws-do router", () => {
beforeEach(() => {
mockGetActiveDoNamesForMachine.mockReset()
mockGetActiveDoNamesForMachine.mockResolvedValue([])
+ mockWithD1Retry.mockReset()
+ mockWithD1Retry.mockImplementation(async (fn) => fn())
})
it("zero active doNames → { sent: 0 } without touching any DO", async () => {
@@ -239,5 +242,62 @@ describe("ws-do router", () => {
expect(await res.json()).toEqual({ error: "failed to resolve machine" })
expect(doMock.stubFetch).not.toHaveBeenCalled()
})
+
+ it("retries a transient SQLITE_BUSY lookup before forwarding the wake", async () => {
+ mockGetActiveDoNamesForMachine
+ .mockRejectedValueOnce(new Error("SQLITE_BUSY_SNAPSHOT: database is locked"))
+ .mockResolvedValueOnce(["do-abc"])
+ mockWithD1Retry.mockImplementation(async (fn) => {
+ try {
+ return await fn()
+ } catch {
+ return fn()
+ }
+ })
+ doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
+
+ const res = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-agent-wake",
+ { method: "POST", body: JSON.stringify({ type: "agent:wake" }) },
+ ), env as any)
+
+ expect(mockGetActiveDoNamesForMachine).toHaveBeenCalledTimes(2)
+ expect(mockWithD1Retry).toHaveBeenCalledWith(expect.any(Function), {
+ route: "ws-do:agent-wake-machine-resolution",
+ })
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(1)
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 1 })
+ })
+
+ it("maps exhausted SQLITE_BUSY retries to the existing 503 response", async () => {
+ mockGetActiveDoNamesForMachine.mockRejectedValue(
+ new Error("SQLITE_BUSY_SNAPSHOT: database is locked"),
+ )
+ mockWithD1Retry.mockImplementation(async (fn) => {
+ let lastError: unknown
+ for (let attempt = 0; attempt < 4; attempt++) {
+ try {
+ return await fn()
+ } catch (error) {
+ lastError = error
+ }
+ }
+ throw lastError
+ })
+
+ const res = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-agent-wake",
+ { method: "POST", body: JSON.stringify({ type: "agent:wake" }) },
+ ), env as any)
+
+ expect(mockGetActiveDoNamesForMachine).toHaveBeenCalledTimes(4)
+ expect(mockWithD1Retry).toHaveBeenCalledWith(expect.any(Function), {
+ route: "ws-do:agent-wake-machine-resolution",
+ })
+ expect(res.status).toBe(503)
+ expect(await res.json()).toEqual({ error: "failed to resolve machine" })
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
})
})
diff --git a/src/ws-do/src/routes/community-machine-delivery.ts b/src/ws-do/src/routes/community-machine-delivery.ts
index 0c7b12951..b75cd046a 100644
--- a/src/ws-do/src/routes/community-machine-delivery.ts
+++ b/src/ws-do/src/routes/community-machine-delivery.ts
@@ -1,4 +1,4 @@
-import { queries } from "@alook/shared"
+import { queries, withD1Retry } from "@alook/shared"
import type { RouterContext } from "../router-context"
export async function handleMachinePush({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
@@ -71,7 +71,10 @@ export async function handleMachineWake({ request, env, url, traceId, log }: Rou
try {
const shared = await import("@alook/shared")
const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
- doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
+ doNames = await withD1Retry(
+ () => queries.communityMachine.getActiveDoNamesForMachine(db, machineId),
+ { route: "ws-do:agent-wake-machine-resolution" },
+ )
} catch (err) {
reqLog.error("failed to resolve machine doNames for agent wake", { err })
return Response.json({ error: "failed to resolve machine" }, { status: 503 })
diff --git a/src/ws-do/src/routes/test-harness.ts b/src/ws-do/src/routes/test-harness.ts
index 880f0f422..160292b37 100644
--- a/src/ws-do/src/routes/test-harness.ts
+++ b/src/ws-do/src/routes/test-harness.ts
@@ -12,6 +12,7 @@ const sharedMocks = vi.hoisted(() => {
const hashCredential = vi.fn(async (bearer: string) => `sha256:${bearer}`)
const doNameFromHash = vi.fn((hash: string) => hash.slice(0, 32))
const getActiveDoNamesForMachine = vi.fn(async (_db: unknown, _machineId: string) => [] as string[])
+ const withD1Retry = vi.fn(async <T>(fn: () => Promise<T>, _opts?: unknown): Promise<T> => fn())
const debug = vi.fn()
const info = vi.fn()
const warn = vi.fn()
@@ -23,6 +24,7 @@ const sharedMocks = vi.hoisted(() => {
hashCredential,
doNameFromHash,
getActiveDoNamesForMachine,
+ withD1Retry,
logger,
loggerChild: child,
loggerDebug: debug,
@@ -38,6 +40,9 @@ vi.mock("@alook/shared", async () => {
...actual,
createDb: () => ({}),
createLogger: () => sharedMocks.logger,
+ withD1Retry: <T>(fn: () => Promise<T>, opts?: unknown): Promise<T> => (
+ sharedMocks.withD1Retry(fn, opts) as Promise<T>
+ ),
queries: {
...actual.queries,
communityMachine: {