Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(diagnostics): add report control plane

Gusea47212c5228
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.ts
index 74206b314..d52c2b070 100644
--- a/src/daemon/src/daemon/createDaemon.test.ts
+++ b/src/daemon/src/daemon/createDaemon.test.ts
@@ -10,6 +10,7 @@ import {
emitImplicitTypingStopOnSend,
parseRuntimeRawTraceAgentIds,
} from "./createDaemon";
+import { AgentRouter } from "../manager/agentRouter";
import type { Driver } from "../types";
import type { Logger } from "../logger";
@@ -43,10 +44,19 @@ vi.mock("../timeline/index.js", async (importOriginal) => {
const startupSweepDirs: string[] = [];
afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
timelineSweepHarness.reset();
for (const dir of startupSweepDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
+function spyOnRouterCommandEntry() {
+ return vi.spyOn(
+ AgentRouter.prototype as unknown as { onCommand(command: unknown): Promise<void> },
+ "onCommand",
+ );
+}
+
/** Stub logger — records calls per level, and hands out tagged children that report into the same store. */
function stubLogger(): Logger & { calls: Record<"debug" | "info" | "warn" | "error", Array<[string, string, unknown[]]>> } {
const calls: Record<"debug" | "info" | "warn" | "error", Array<[string, string, unknown[]]>> = {
@@ -129,6 +139,100 @@ function factory(sockets: FakeSocket[]) {
}
describe("createDaemon", () => {
+ it("consumes diagnostics before Router and invokes the injected handler once", async () => {
+ const sockets: FakeSocket[] = [];
+ const routerEntry = spyOnRouterCommandEntry();
+ const handleDiagnosticCommand = vi.fn(async () => {});
+ const reportDiagnosticFailure = vi.fn(async () => {});
+ vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request) => {
+ const url = String(input);
+ if (url.includes("/api/community/daemon/bots")) {
+ return Response.json({
+ bots: [{ id: "bot_1", name: "Bot", discriminator: "0001" }],
+ });
+ }
+ return Response.json({ woken: 0 });
+ }));
+ const daemon = await createDaemon({
+ machineKey: "cmk_diagnostics",
+ serverUrl: "http://localhost:9999",
+ serverWsUrl: "ws://x",
+ webSocketFactory: factory(sockets) as any,
+ runtimeReport: [],
+ driverFor: () => fakeDriver,
+ capabilities: [],
+ handleDiagnosticCommand,
+ reportDiagnosticFailure,
+ } as Parameters<typeof createDaemon>[0]);
+ sockets[0].emit("open");
+ const command = {
+ type: "diagnostics:collect",
+ reportId: "dbr_0123456789abcdef",
+ agentId: "bot_1",
+ fromMs: 1_700_000_000_000,
+ deadlineAt: 1_700_087_000_000,
+ };
+
+ sockets[0].emit("message", JSON.stringify(command));
+
+ await vi.waitFor(() => expect(handleDiagnosticCommand).toHaveBeenCalledOnce());
+ expect(handleDiagnosticCommand).toHaveBeenCalledWith(command);
+ expect(reportDiagnosticFailure).not.toHaveBeenCalled();
+ expect(routerEntry).not.toHaveBeenCalledWith(command);
+ expect(fakeDriver.start).not.toHaveBeenCalled();
+ expect(fakeDriver.stop).not.toHaveBeenCalled();
+ await daemon.stop();
+ });
+
+ it.each([
+ ["missing", undefined],
+ ["sync throw", vi.fn(() => { throw new Error("private sync detail"); })],
+ ["async reject", vi.fn(async () => { throw new Error("private async detail"); })],
+ ])("keeps %s diagnostics handler failure out of Router/Manager/FSM", async (_label, handler) => {
+ const sockets: FakeSocket[] = [];
+ const routerEntry = spyOnRouterCommandEntry();
+ const reportDiagnosticFailure = vi.fn(async () => {});
+ const startCalls = (fakeDriver.start as ReturnType<typeof vi.fn>).mock.calls.length;
+ const stopCalls = (fakeDriver.stop as ReturnType<typeof vi.fn>).mock.calls.length;
+ vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request) => {
+ const url = String(input);
+ return url.includes("/api/community/daemon/bots")
+ ? Response.json({ bots: [{ id: "bot_1", name: "Bot", discriminator: "0001" }] })
+ : Response.json({ woken: 0 });
+ }));
+ const daemon = await createDaemon({
+ machineKey: "cmk_diagnostics_failure",
+ serverUrl: "http://localhost:9999",
+ serverWsUrl: "ws://x",
+ webSocketFactory: factory(sockets) as any,
+ runtimeReport: [],
+ driverFor: () => fakeDriver,
+ capabilities: [],
+ handleDiagnosticCommand: handler,
+ reportDiagnosticFailure,
+ } as Parameters<typeof createDaemon>[0]);
+ sockets[0].emit("open");
+
+ sockets[0].emit("message", JSON.stringify({
+ type: "diagnostics:collect",
+ reportId: "dbr_0123456789abcdef",
+ agentId: "bot_1",
+ fromMs: 1_700_000_000_000,
+ deadlineAt: 1_700_087_000_000,
+ }));
+
+ await vi.waitFor(() => expect(reportDiagnosticFailure).toHaveBeenCalledOnce());
+ expect(reportDiagnosticFailure).toHaveBeenCalledWith({
+ reportId: "dbr_0123456789abcdef",
+ failureCode: "diagnostics_unavailable",
+ });
+ expect(JSON.stringify(reportDiagnosticFailure.mock.calls)).not.toMatch(/private|detail/);
+ expect(routerEntry).not.toHaveBeenCalledWith(expect.objectContaining({ type: "diagnostics:collect" }));
+ expect((fakeDriver.start as ReturnType<typeof vi.fn>).mock.calls).toHaveLength(startCalls);
+ expect((fakeDriver.stop as ReturnType<typeof vi.fn>).mock.calls).toHaveLength(stopCalls);
+ await daemon.stop();
+ });
+
it("dials the WS control plane with Authorization: Bearer <machineKey>", async () => {
const sockets: FakeSocket[] = [];
const daemon = await createDaemon({
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index 81f3df5ee..54108c1c5 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -40,6 +40,11 @@ import type { Driver, LaunchContext } from "../types.js";
import type { RuntimeConfig } from "../runtimeConfig.js";
import type { UnreadNotice, HostCommand } from "../server/contract.js";
import { formatHandle } from "@alook/shared/lib/discriminator";
+import type { DiagnosticCollectCommand } from "@alook/shared";
+import {
+ createDiagnosticsCommandListener,
+ type DiagnosticFailureReport,
+} from "./diagnosticsCommand.js";
// Cold-start warmup backoff schedule (ms).
const WARMUP_BACKOFF_MS = [250, 500, 1000, 2000, 4000] as const;
@@ -282,6 +287,10 @@ export interface CreateDaemonOptions {
* exactly one logger tree instead of two independent ones.
*/
logger?: Logger;
+ /** B2b interception seam; B2c supplies the local collector/uploader. */
+ handleDiagnosticCommand?: (command: DiagnosticCollectCommand) => void | Promise<void>;
+ /** Fixed-code failure callback used when diagnostics is not available. */
+ reportDiagnosticFailure?: (failure: DiagnosticFailureReport) => void | Promise<void>;
}
export interface RunningDaemon {
@@ -849,10 +858,14 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
`You have unread messages in channel ${notice.channel}.`,
});
- // Register the bot-cache pre-hook. `onCommand` supports multiple listeners
- // in FIFO order — this one runs before the AgentRouter's listener (which
- // router.start() appends), so bot:* frames mutate the cache before the
- // router dispatches. No monkey-patching required.
+ // Register the diagnostics consumer first: its synchronous channel-owned
+ // sentinel claims diagnostics before either the bot-cache observer or the
+ // AgentRouter can see them. The bot-cache observer remains immediately
+ // before router.start()'s listener for ordinary bot:* frames.
+ channel.onCommand(createDiagnosticsCommandListener({
+ handleDiagnosticCommand: opts.handleDiagnosticCommand,
+ reportDiagnosticFailure: opts.reportDiagnosticFailure,
+ }));
channel.onCommand((cmd) => {
handleBotFrame(cmd);
});
diff --git a/src/daemon/src/daemon/diagnosticsCommand.test.ts b/src/daemon/src/daemon/diagnosticsCommand.test.ts
new file mode 100644
index 000000000..f9457a44e
--- /dev/null
+++ b/src/daemon/src/daemon/diagnosticsCommand.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it, vi } from "vitest";
+import { WS_CONTROL_COMMAND_CONSUMED } from "../server/wsControlChannel";
+import { createDiagnosticsCommandListener } from "./diagnosticsCommand";
+
+const command = {
+ type: "diagnostics:collect" as const,
+ reportId: "dbr_0123456789abcdef",
+ agentId: "bot_1",
+ fromMs: 1_700_000_000_000,
+ deadlineAt: 1_700_087_000_000,
+};
+
+async function settle(): Promise<void> {
+ await Promise.resolve();
+ await Promise.resolve();
+}
+
+describe("diagnostics-only daemon command consumer", () => {
+ it("claims diagnostics synchronously and completes through the injected handler", async () => {
+ const handleDiagnosticCommand = vi.fn(async () => {});
+ const reportDiagnosticFailure = vi.fn(async () => {});
+ const listener = createDiagnosticsCommandListener({
+ handleDiagnosticCommand,
+ reportDiagnosticFailure,
+ });
+
+ const result = listener(command);
+
+ expect(result).toBe(WS_CONTROL_COMMAND_CONSUMED);
+ await settle();
+ expect(handleDiagnosticCommand).toHaveBeenCalledOnce();
+ expect(handleDiagnosticCommand).toHaveBeenCalledWith(command);
+ expect(reportDiagnosticFailure).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["missing", undefined],
+ ["sync throw", vi.fn(() => { throw new Error("private sync detail"); })],
+ ["async reject", vi.fn(async () => { throw new Error("private async detail"); })],
+ ])("claims before returning and reports %s handler failure exactly once", async (_label, handler) => {
+ const reportDiagnosticFailure = vi.fn(async () => {});
+ const listener = createDiagnosticsCommandListener({
+ handleDiagnosticCommand: handler,
+ reportDiagnosticFailure,
+ });
+
+ const result = listener(command);
+
+ expect(result).toBe(WS_CONTROL_COMMAND_CONSUMED);
+ await settle();
+ expect(reportDiagnosticFailure).toHaveBeenCalledOnce();
+ expect(reportDiagnosticFailure).toHaveBeenCalledWith({
+ reportId: command.reportId,
+ failureCode: "diagnostics_unavailable",
+ });
+ expect(JSON.stringify(reportDiagnosticFailure.mock.calls)).not.toMatch(/private|detail/);
+ });
+
+ it("does not claim any non-diagnostics HostCommand", () => {
+ const reportDiagnosticFailure = vi.fn();
+ const listener = createDiagnosticsCommandListener({ reportDiagnosticFailure });
+
+ expect(listener({ type: "agent:stop", agentId: "bot_1" })).toBeUndefined();
+ expect(reportDiagnosticFailure).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/daemon/src/daemon/diagnosticsCommand.ts b/src/daemon/src/daemon/diagnosticsCommand.ts
new file mode 100644
index 000000000..9000dc34c
--- /dev/null
+++ b/src/daemon/src/daemon/diagnosticsCommand.ts
@@ -0,0 +1,55 @@
+import type { DiagnosticCollectCommand } from "@alook/shared";
+import type { HostCommand } from "../server/contract.js";
+import { WS_CONTROL_COMMAND_CONSUMED } from "../server/wsControlChannel.js";
+
+export type DiagnosticFailureReport = Readonly<{
+ reportId: string;
+ failureCode: "diagnostics_unavailable";
+}>;
+
+export type DiagnosticsCommandListenerOptions = Readonly<{
+ handleDiagnosticCommand?: (
+ command: DiagnosticCollectCommand,
+ ) => void | Promise<void>;
+ reportDiagnosticFailure?: (
+ failure: DiagnosticFailureReport,
+ ) => void | Promise<void>;
+}>;
+
+function reportUnavailable(
+ options: DiagnosticsCommandListenerOptions,
+ reportId: string,
+): void {
+ if (!options.reportDiagnosticFailure) return;
+ try {
+ Promise.resolve(options.reportDiagnosticFailure({
+ reportId,
+ failureCode: "diagnostics_unavailable",
+ })).catch(() => { });
+ } catch {
+ // Reporting is best-effort and must never re-enter the WS dispatcher.
+ }
+}
+
+export function createDiagnosticsCommandListener(
+ options: DiagnosticsCommandListenerOptions,
+) {
+ return (command: HostCommand): void | typeof WS_CONTROL_COMMAND_CONSUMED => {
+ if (command.type !== "diagnostics:collect") return;
+
+ const handler = options.handleDiagnosticCommand;
+ if (!handler) {
+ reportUnavailable(options, command.reportId);
+ return WS_CONTROL_COMMAND_CONSUMED;
+ }
+
+ try {
+ Promise.resolve(handler(command)).catch(() => {
+ reportUnavailable(options, command.reportId);
+ });
+ } catch {
+ reportUnavailable(options, command.reportId);
+ }
+ return WS_CONTROL_COMMAND_CONSUMED;
+ };
+}
diff --git a/src/daemon/src/server/wsControlChannel.test.ts b/src/daemon/src/server/wsControlChannel.test.ts
index c33cc5e68..043fa9467 100644
--- a/src/daemon/src/server/wsControlChannel.test.ts
+++ b/src/daemon/src/server/wsControlChannel.test.ts
@@ -1,5 +1,5 @@
-import { describe, it, expect } from "vitest";
-import { WsControlChannel } from "./wsControlChannel";
+import { describe, it, expect, vi } from "vitest";
+import { WS_CONTROL_COMMAND_CONSUMED, WsControlChannel } from "./wsControlChannel";
import type { WebSocketLike, HostReady, AgentSessionReport, HostCommand } from "./contract";
import type { Logger } from "../logger";
@@ -557,6 +557,81 @@ describe("WsControlChannel — downlink HostCommand validation (convergence #6)"
expect(received).toHaveLength(1);
expect((received[0] as typeof realReset).config).toEqual(frame.config);
});
+
+ it("stops listener broadcast synchronously only for the server-owned consume sentinel", async () => {
+ const { ch, sockets } = makeChannel();
+ const consumedSecond = vi.fn();
+ ch.onCommand(() => WS_CONTROL_COMMAND_CONSUMED);
+ ch.onCommand(consumedSecond);
+ ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [] }));
+ ch.connect();
+ sockets[0].emit("open");
+
+ sockets[0].emit("message", JSON.stringify(realStop));
+
+ expect(consumedSecond).not.toHaveBeenCalled();
+
+ const normal = makeChannel();
+ const first = vi.fn(async () => {});
+ const second = vi.fn();
+ normal.ch.onCommand(first);
+ normal.ch.onCommand(second);
+ normal.ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [] }));
+ normal.ch.connect();
+ normal.sockets[0].emit("open");
+ normal.sockets[0].emit("message", JSON.stringify(realStop));
+ await Promise.resolve();
+
+ expect(first).toHaveBeenCalledOnce();
+ expect(second).toHaveBeenCalledOnce();
+ });
+
+ it("dispatches one exact diagnostics command field-for-field", () => {
+ const command = {
+ type: "diagnostics:collect",
+ reportId: "dbr_0123456789abcdef",
+ agentId: "bot_1",
+ fromMs: 1_700_000_000_000,
+ deadlineAt: 1_700_087_000_000,
+ } as const;
+ const { sockets, received } = driven();
+
+ sockets[0].emit("message", JSON.stringify(command));
+
+ expect(received).toEqual([command]);
+ });
+
+ it("drops diagnostics commands with missing or unknown top-level fields", () => {
+ for (const command of [
+ {
+ type: "diagnostics:collect",
+ agentId: "bot_1",
+ fromMs: 1_700_000_000_000,
+ deadlineAt: 1_700_087_000_000,
+ },
+ {
+ type: "diagnostics:collect",
+ reportId: "dbr_0123456789abcdef",
+ agentId: "bot_1",
+ fromMs: 1_700_000_000_000,
+ deadlineAt: 1_700_087_000_000,
+ objectKey: "attacker-controlled",
+ },
+ ]) {
+ const logger = stubLogger();
+ const { ch, sockets } = makeChannel({ logger });
+ const received: HostCommand[] = [];
+ ch.onCommand((value) => received.push(value));
+ ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [] }));
+ ch.connect();
+ sockets[0].emit("open");
+
+ sockets[0].emit("message", JSON.stringify(command));
+
+ expect(received).toEqual([]);
+ expect(logger.calls.warn.some(([message]) => message === "dropped malformed HostCommand frame")).toBe(true);
+ }
+ });
});
describe("WsControlChannel — logging", () => {
diff --git a/src/daemon/src/server/wsControlChannel.ts b/src/daemon/src/server/wsControlChannel.ts
index 203cbbac0..700ca35e0 100644
--- a/src/daemon/src/server/wsControlChannel.ts
+++ b/src/daemon/src/server/wsControlChannel.ts
@@ -41,6 +41,16 @@ export type { WebSocketLike, WebSocketFactory } from "./contract.js";
export type ControlChannelStatus = "idle" | "connecting" | "open" | "reconnecting" | "closed";
+/**
+ * A synchronous, channel-owned dispatch result used by a pre-router consumer
+ * to claim one command. Promises never consume: the decision must be visible
+ * before the dispatcher advances to the next FIFO listener.
+ */
+export const WS_CONTROL_COMMAND_CONSUMED = Symbol("ws-control-command-consumed");
+type CommandListener = (
+ cmd: HostCommand,
+) => void | Promise<void> | typeof WS_CONTROL_COMMAND_CONSUMED;
+
/** Heartbeat: how often we ping the server WebSocket. */
const DEFAULT_PING_INTERVAL_MS = 15_000;
/** Heartbeat: how long we wait for a pong before declaring the socket dead. */
@@ -140,7 +150,7 @@ export class WsControlChannel implements HostControlChannel {
private statusValue: ControlChannelStatus = "idle";
// Multiple listeners so consumers can layer behavior (e.g. bot-cache pre-hook
// + AgentRouter's real handler) without monkey-patching this class.
- private commandCbs: Array<(cmd: HostCommand) => void | Promise<void>> = [];
+ private commandCbs: CommandListener[] = [];
private resyncHooks: Array<() => void> = [];
private ws: WebSocketLike | null = null;
private attempt = 0;
@@ -181,7 +191,7 @@ export class WsControlChannel implements HostControlChannel {
* run in FIFO order on each inbound frame. This lets a pre-hook (bot cache)
* observe frames before the AgentRouter's dispatcher without wrapping them.
*/
- onCommand(cb: (cmd: HostCommand) => void | Promise<void>): void {
+ onCommand(cb: CommandListener): void {
this.commandCbs.push(cb);
}
@@ -399,7 +409,9 @@ export class WsControlChannel implements HostControlChannel {
// listener that throws would surface as an unhandled promise rejection
// and, under Node ≥15 defaults, could terminate the daemon.
try {
- Promise.resolve(cb(cmd)).catch((err: unknown) => {
+ const result = cb(cmd);
+ if (result === WS_CONTROL_COMMAND_CONSUMED) break;
+ Promise.resolve(result).catch((err: unknown) => {
this.log.warn("command listener threw", { type: cmd.type, err: describeErr(err) });
});
} catch (err) {
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 478e23e30..dbc12b69f 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -27,6 +27,8 @@ import type { RuntimeConfig } from "./runtime-config";
import type { ChannelType, StoredChannelType } from "./utils/community-roles";
import { CHANNEL_TRAITS } from "./utils/community-roles";
import { parseNameAndTag } from "./lib/discriminator";
+import { DiagnosticCollectCommandSchema } from "./diagnostics-contract";
+import type { DiagnosticCollectCommand } from "./diagnostics-contract";
/* ------------------------------------------------------------------ */
/* Identifiers */
@@ -793,7 +795,8 @@ export type HostCommand =
| {
type: "bot:removed";
botId: AgentId;
- };
+ }
+ | DiagnosticCollectCommand;
/**
* Runtime descriptor carried by every `ready` frame. `status` defaults to
@@ -1429,6 +1432,7 @@ export const HostCommandSchema = z.discriminatedUnion("type", [
type: z.literal("bot:removed"),
botId: z.string().min(1),
}),
+ DiagnosticCollectCommandSchema,
]);
// Z2 — type↔schema lockstep. The `[T] extends [U]` tuple-wrap defeats union
diff --git a/src/shared/src/db/queries/community/diagnostic-report.ts b/src/shared/src/db/queries/community/diagnostic-report.ts
index 0b1c8d662..dd8c64fdb 100644
--- a/src/shared/src/db/queries/community/diagnostic-report.ts
+++ b/src/shared/src/db/queries/community/diagnostic-report.ts
@@ -8,9 +8,11 @@ import {
} from "../../community-machine-schema";
import { user } from "../../schema";
import type { Database } from "../../index";
+import {
+ DIAGNOSTIC_REPORT_COLLECTION_WINDOW_MS,
+ DIAGNOSTIC_REPORT_DEADLINE_WINDOW_MS,
+} from "../../../diagnostics-contract";
-const COLLECTION_WINDOW_MS = 86_400_000;
-const DEADLINE_WINDOW_MS = 600_000;
const OBJECT_RETENTION_MS = 604_800_000;
const diagnosticOwner = alias(user, "diagnostic_owner");
@@ -56,8 +58,8 @@ async function tryInsertPendingDiagnosticReport(
input: CreateDiagnosticReportInput,
reportId: string
): Promise<DiagnosticReportRow | null> {
- const fromMs = input.nowMs - COLLECTION_WINDOW_MS;
- const deadlineAt = input.nowMs + DEADLINE_WINDOW_MS;
+ const fromMs = input.nowMs - DIAGNOSTIC_REPORT_COLLECTION_WINDOW_MS;
+ const deadlineAt = input.nowMs + DIAGNOSTIC_REPORT_DEADLINE_WINDOW_MS;
const rateBucket = Math.floor(input.nowMs / 60_000);
const liveTarget = db
@@ -215,10 +217,10 @@ export async function createOrGetPendingDiagnosticReport(
input: CreateDiagnosticReportInput
): Promise<CreateDiagnosticReportResult> {
assertSafeEpoch(input.nowMs);
- if (input.nowMs < COLLECTION_WINDOW_MS) {
+ if (input.nowMs < DIAGNOSTIC_REPORT_COLLECTION_WINDOW_MS) {
throw new RangeError("nowMs is too early for the diagnostic collection window");
}
- if (!Number.isSafeInteger(input.nowMs + DEADLINE_WINDOW_MS)) {
+ if (!Number.isSafeInteger(input.nowMs + DIAGNOSTIC_REPORT_DEADLINE_WINDOW_MS)) {
throw new RangeError("diagnostic deadline exceeds the safe integer range");
}
diff --git a/src/shared/src/diagnostics-contract.ts b/src/shared/src/diagnostics-contract.ts
new file mode 100644
index 000000000..3de02d0bd
--- /dev/null
+++ b/src/shared/src/diagnostics-contract.ts
@@ -0,0 +1,82 @@
+import { z } from "zod";
+import {
+ DIAGNOSTIC_REPORT_FAILURE_CODES,
+ type DiagnosticReportFailureCode,
+} from "./db/community-machine-schema";
+
+export { DIAGNOSTIC_REPORT_FAILURE_CODES };
+export type { DiagnosticReportFailureCode };
+
+export const DIAGNOSTIC_REPORT_COLLECTION_WINDOW_MS = 86_400_000;
+export const DIAGNOSTIC_REPORT_DEADLINE_WINDOW_MS = 600_000;
+export const DIAGNOSTIC_COLLECT_SPAN_MS =
+ DIAGNOSTIC_REPORT_COLLECTION_WINDOW_MS + DIAGNOSTIC_REPORT_DEADLINE_WINDOW_MS;
+
+const SafeEpochSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
+const AgentIdSchema = z.string().min(1).regex(/^[A-Za-z0-9_-]+$/);
+
+export const DiagnosticReportIdSchema = z.string().regex(/^dbr_[A-Za-z0-9_-]+$/);
+export const DiagnosticReportFailureCodeSchema = z.enum(DIAGNOSTIC_REPORT_FAILURE_CODES);
+
+export const DiagnosticReportCreateRequestSchema = z
+ .object({
+ clientNonce: z.string().min(16).max(64).regex(/^[A-Za-z0-9_-]+$/),
+ })
+ .strict();
+
+export const DiagnosticCollectPayloadSchema = z
+ .object({
+ reportId: DiagnosticReportIdSchema,
+ agentId: AgentIdSchema,
+ fromMs: SafeEpochSchema,
+ deadlineAt: SafeEpochSchema,
+ })
+ .strict();
+
+export const DiagnosticCollectCommandSchema = z
+ .object({
+ type: z.literal("diagnostics:collect"),
+ reportId: DiagnosticReportIdSchema,
+ agentId: AgentIdSchema,
+ fromMs: SafeEpochSchema,
+ deadlineAt: SafeEpochSchema,
+ })
+ .strict()
+ .refine(
+ (command) => command.deadlineAt - command.fromMs === DIAGNOSTIC_COLLECT_SPAN_MS,
+ { message: "diagnostic collection span must match v1" },
+ );
+
+const OwnerDiagnosticReportBase = {
+ reportId: DiagnosticReportIdSchema,
+ deadlineAt: SafeEpochSchema,
+} as const;
+
+export const OwnerDiagnosticReportSchema = z.discriminatedUnion("status", [
+ z.object({
+ ...OwnerDiagnosticReportBase,
+ status: z.literal("pending"),
+ completedAt: z.null(),
+ failureCode: z.null(),
+ objectExpired: z.literal(false),
+ }).strict(),
+ z.object({
+ ...OwnerDiagnosticReportBase,
+ status: z.literal("uploaded"),
+ completedAt: SafeEpochSchema,
+ failureCode: z.null(),
+ objectExpired: z.boolean(),
+ }).strict(),
+ z.object({
+ ...OwnerDiagnosticReportBase,
+ status: z.literal("failed"),
+ completedAt: SafeEpochSchema,
+ failureCode: DiagnosticReportFailureCodeSchema,
+ objectExpired: z.literal(false),
+ }).strict(),
+]);
+
+export type DiagnosticReportCreateRequest = z.infer<typeof DiagnosticReportCreateRequestSchema>;
+export type DiagnosticCollectPayload = z.infer<typeof DiagnosticCollectPayloadSchema>;
+export type DiagnosticCollectCommand = z.infer<typeof DiagnosticCollectCommandSchema>;
+export type OwnerDiagnosticReport = z.infer<typeof OwnerDiagnosticReportSchema>;
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index dc7896414..d619c1688 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -67,6 +67,10 @@ export type {
CreateMachineTokenResponse,
} from "./api-types";
+// Diagnostic report contract (neutral schemas/constants shared by HTTP, WS,
+// daemon, and the D1 query layer).
+export * from "./diagnostics-contract";
+
// Constants
export {
AgentStatus,
diff --git a/src/shared/test/community-cli-contract.test.ts b/src/shared/test/community-cli-contract.test.ts
index 37d35ab53..3d5513ece 100644
--- a/src/shared/test/community-cli-contract.test.ts
+++ b/src/shared/test/community-cli-contract.test.ts
@@ -1,5 +1,14 @@
-import { describe, it, expect } from "vitest";
-import { parseRef, formatRef, formatCanonicalRef, formatSeq, parseSeq, DM_SERVER } from "../src/community-cli-contract";
+import { describe, it, expect, expectTypeOf } from "vitest";
+import {
+ parseRef,
+ formatRef,
+ formatCanonicalRef,
+ formatSeq,
+ parseSeq,
+ DM_SERVER,
+ HostCommandSchema,
+ type HostCommand,
+} from "../src/community-cli-contract";
describe("parseRef", () => {
it('parses "/studio#0042/general" as a plain channel ref', () => {
@@ -269,3 +278,28 @@ describe("formatCanonicalRef", () => {
expect(formatCanonicalRef({ type: "dm" })).toBeNull(); // no peerSegment
});
});
+
+describe("HostCommand diagnostics contract", () => {
+ it("keeps the diagnostics arm in the HostCommand type and runtime schema", () => {
+ type DiagnosticCommand = {
+ type: "diagnostics:collect";
+ reportId: string;
+ agentId: string;
+ fromMs: number;
+ deadlineAt: number;
+ };
+ expectTypeOf<Extract<HostCommand, { type: "diagnostics:collect" }>>()
+ .toEqualTypeOf<DiagnosticCommand>();
+
+ const command: DiagnosticCommand = {
+ type: "diagnostics:collect",
+ reportId: "dbr_0123456789abcdef",
+ agentId: "bot_1",
+ fromMs: 1_700_000_000_000,
+ deadlineAt: 1_700_087_000_000,
+ };
+ expect(HostCommandSchema.safeParse(command)).toEqual(
+ expect.objectContaining({ success: true }),
+ );
+ });
+});
diff --git a/src/shared/test/diagnostics-contract.test.ts b/src/shared/test/diagnostics-contract.test.ts
new file mode 100644
index 000000000..aa3edd9d5
--- /dev/null
+++ b/src/shared/test/diagnostics-contract.test.ts
@@ -0,0 +1,221 @@
+import { describe, expect, expectTypeOf, it } from "vitest";
+import * as Shared from "../src/index";
+import { HostCommandSchema } from "../src/community-cli-contract";
+import { DIAGNOSTIC_REPORT_FAILURE_CODES as DB_FAILURE_CODES } from "../src/db/community-machine-schema";
+import {
+ DIAGNOSTIC_COLLECT_SPAN_MS,
+ DIAGNOSTIC_REPORT_COLLECTION_WINDOW_MS,
+ DIAGNOSTIC_REPORT_DEADLINE_WINDOW_MS,
+ DIAGNOSTIC_REPORT_FAILURE_CODES,
+ DiagnosticCollectCommandSchema,
+ DiagnosticCollectPayloadSchema,
+ DiagnosticReportFailureCodeSchema,
+ DiagnosticReportCreateRequestSchema,
+ DiagnosticReportIdSchema,
+ OwnerDiagnosticReportSchema,
+} from "../src/diagnostics-contract";
+import type { DiagnosticReportFailureCode } from "../src/diagnostics-contract";
+import type { DiagnosticReportFailureCode as BarrelDiagnosticReportFailureCode } from "../src/index";
+
+const FROM_MS = 1_700_000_000_000;
+const DEADLINE_AT = FROM_MS + DIAGNOSTIC_COLLECT_SPAN_MS;
+const NONCE = "nonce_1234567890";
+
+const valid = {
+ type: "diagnostics:collect",
+ reportId: "dbr_0123456789abcdef",
+ agentId: "bot_1",
+ fromMs: FROM_MS,
+ deadlineAt: DEADLINE_AT,
+} as const;
+
+describe("shared diagnostics contract ownership", () => {
+ it("exports one frozen set of collection and deadline constants", () => {
+ expect(DIAGNOSTIC_REPORT_COLLECTION_WINDOW_MS).toBe(86_400_000);
+ expect(DIAGNOSTIC_REPORT_DEADLINE_WINDOW_MS).toBe(600_000);
+ expect(DIAGNOSTIC_COLLECT_SPAN_MS).toBe(87_000_000);
+ expect(DIAGNOSTIC_COLLECT_SPAN_MS).toBe(
+ DIAGNOSTIC_REPORT_COLLECTION_WINDOW_MS + DIAGNOSTIC_REPORT_DEADLINE_WINDOW_MS,
+ );
+ });
+
+ it("publishes the neutral schemas from the shared package barrel", () => {
+ expect(Shared.DiagnosticReportIdSchema).toBe(DiagnosticReportIdSchema);
+ expect(Shared.DiagnosticReportCreateRequestSchema).toBe(DiagnosticReportCreateRequestSchema);
+ expect(Shared.DiagnosticCollectPayloadSchema).toBe(DiagnosticCollectPayloadSchema);
+ expect(Shared.DiagnosticCollectCommandSchema).toBe(DiagnosticCollectCommandSchema);
+ expect(Shared.DiagnosticReportFailureCodeSchema).toBe(DiagnosticReportFailureCodeSchema);
+ expect(Shared.OwnerDiagnosticReportSchema).toBe(OwnerDiagnosticReportSchema);
+ expect(Shared.DIAGNOSTIC_REPORT_COLLECTION_WINDOW_MS).toBe(DIAGNOSTIC_REPORT_COLLECTION_WINDOW_MS);
+ expect(Shared.DIAGNOSTIC_REPORT_DEADLINE_WINDOW_MS).toBe(DIAGNOSTIC_REPORT_DEADLINE_WINDOW_MS);
+ expect(Shared.DIAGNOSTIC_COLLECT_SPAN_MS).toBe(DIAGNOSTIC_COLLECT_SPAN_MS);
+ expect(Shared.DIAGNOSTIC_REPORT_FAILURE_CODES).toBe(DIAGNOSTIC_REPORT_FAILURE_CODES);
+ });
+
+ it("re-exports the database-owned failure-code tuple without copying it", () => {
+ expect(DIAGNOSTIC_REPORT_FAILURE_CODES).toBe(DB_FAILURE_CODES);
+ expect(DiagnosticReportFailureCodeSchema.options).toEqual([...DB_FAILURE_CODES]);
+ expectTypeOf<DiagnosticReportFailureCode>().toEqualTypeOf<(typeof DB_FAILURE_CODES)[number]>();
+ expectTypeOf<BarrelDiagnosticReportFailureCode>().toEqualTypeOf<DiagnosticReportFailureCode>();
+ });
+});
+
+describe("diagnostic ids and owner create request", () => {
+ it.each([
+ "dbr_a",
+ "dbr_0123456789abcdef",
+ "dbr_A-Z_09",
+ ])("accepts safe report id %s", (reportId) => {
+ expect(DiagnosticReportIdSchema.safeParse(reportId).success).toBe(true);
+ });
+
+ it.each([
+ "dbr_",
+ "dbr_../secret",
+ "report_0123456789abcdef",
+ "dbr_has space",
+ ])("rejects unsafe report id %s", (reportId) => {
+ expect(DiagnosticReportIdSchema.safeParse(reportId).success).toBe(false);
+ });
+
+ it("matches the D1 nonce constraint and rejects unknown create fields", () => {
+ for (const clientNonce of ["a".repeat(16), NONCE, "A0_-".repeat(16)]) {
+ expect(DiagnosticReportCreateRequestSchema.safeParse({ clientNonce }).success).toBe(true);
+ }
+ for (const clientNonce of ["a".repeat(15), "a".repeat(65), "unsafe.nonce_1234", "unsafe nonce_1234"]) {
+ expect(DiagnosticReportCreateRequestSchema.safeParse({ clientNonce }).success).toBe(false);
+ }
+ expect(DiagnosticReportCreateRequestSchema.safeParse({
+ clientNonce: NONCE,
+ machineId: "cm_injected",
+ }).success).toBe(false);
+ });
+});
+
+describe("diagnostics:collect strict wire schema", () => {
+ it("accepts only the narrow payload before the command is constructed", () => {
+ const { type: _type, ...payload } = valid;
+ expect(DiagnosticCollectPayloadSchema.safeParse(payload)).toEqual({
+ success: true,
+ data: payload,
+ });
+ expect(DiagnosticCollectPayloadSchema.safeParse({ ...payload, type: valid.type }).success).toBe(false);
+ expect(DiagnosticCollectPayloadSchema.safeParse({ ...payload, machineId: "cm_injected" }).success).toBe(false);
+ });
+
+ it("accepts the exact frozen command without dropping a field", () => {
+ const parsed = DiagnosticCollectCommandSchema.safeParse(valid);
+ expect(parsed.success).toBe(true);
+ if (parsed.success) expect(parsed.data).toEqual(valid);
+ });
+
+ it("reuses the exact diagnostics command schema in HostCommandSchema", () => {
+ expect(HostCommandSchema.options).toContain(DiagnosticCollectCommandSchema);
+ expect(HostCommandSchema.safeParse(valid)).toEqual(
+ DiagnosticCollectCommandSchema.safeParse(valid),
+ );
+ });
+
+ it.each([
+ ["missing reportId", { ...valid, reportId: undefined }],
+ ["path-like reportId", { ...valid, reportId: "dbr_../secret" }],
+ ["wrong report prefix", { ...valid, reportId: "report_0123456789abcdef" }],
+ ["empty agentId", { ...valid, agentId: "" }],
+ ["fractional fromMs", { ...valid, fromMs: FROM_MS + 0.5 }],
+ ["negative fromMs", { ...valid, fromMs: -1 }],
+ ["unsafe fromMs", { ...valid, fromMs: Number.MAX_SAFE_INTEGER + 1 }],
+ ["fractional deadlineAt", { ...valid, deadlineAt: DEADLINE_AT + 0.5 }],
+ ["unsafe deadlineAt", { ...valid, deadlineAt: Number.MAX_SAFE_INTEGER + 1 }],
+ ["reversed window", { ...valid, deadlineAt: FROM_MS }],
+ ["underlong v1 window", { ...valid, deadlineAt: DEADLINE_AT - 1 }],
+ ["overlong window", { ...valid, deadlineAt: DEADLINE_AT + 1 }],
+ ["unknown top-level key", { ...valid, machineId: "cm_injected" }],
+ ])("rejects %s", (_label, command) => {
+ expect(DiagnosticCollectCommandSchema.safeParse(command).success).toBe(false);
+ expect(HostCommandSchema.safeParse(command).success).toBe(false);
+ });
+});
+
+describe("owner-safe diagnostic report projection", () => {
+ const ownerReport = {
+ reportId: valid.reportId,
+ status: "pending",
+ deadlineAt: valid.deadlineAt,
+ completedAt: null,
+ failureCode: null,
+ objectExpired: false,
+ } as const;
+
+ it.each([
+ ["pending", ownerReport],
+ ["uploaded", { ...ownerReport, status: "uploaded", completedAt: FROM_MS }],
+ ["failed", {
+ ...ownerReport,
+ status: "failed",
+ completedAt: FROM_MS,
+ failureCode: "offline",
+ }],
+ ])("accepts exactly the six public fields for %s", (_label, report) => {
+ const parsed = OwnerDiagnosticReportSchema.safeParse(report);
+ expect(parsed.success).toBe(true);
+ if (parsed.success) expect(parsed.data).toEqual(report);
+ expect(Object.keys(ownerReport)).toHaveLength(6);
+ });
+
+ it.each([
+ ["pending with completion", { ...ownerReport, completedAt: FROM_MS }],
+ ["pending with failure", { ...ownerReport, failureCode: "offline" }],
+ ["pending marked object-expired", { ...ownerReport, objectExpired: true }],
+ ["uploaded without completion", { ...ownerReport, status: "uploaded" }],
+ ["uploaded with failure", {
+ ...ownerReport,
+ status: "uploaded",
+ completedAt: FROM_MS,
+ failureCode: "offline",
+ }],
+ ["failed without completion or failure", { ...ownerReport, status: "failed" }],
+ ["failed with unknown failure", {
+ ...ownerReport,
+ status: "failed",
+ completedAt: FROM_MS,
+ failureCode: "private_failure",
+ }],
+ ["failed marked object-expired", {
+ ...ownerReport,
+ status: "failed",
+ completedAt: FROM_MS,
+ failureCode: "offline",
+ objectExpired: true,
+ }],
+ ["terminal fractional completion", {
+ ...ownerReport,
+ status: "failed",
+ completedAt: FROM_MS + 0.5,
+ failureCode: "offline",
+ }],
+ ["terminal negative completion", {
+ ...ownerReport,
+ status: "failed",
+ completedAt: -1,
+ failureCode: "offline",
+ }],
+ ["terminal unsafe completion", {
+ ...ownerReport,
+ status: "failed",
+ completedAt: Number.MAX_SAFE_INTEGER + 1,
+ failureCode: "offline",
+ }],
+ ])("rejects %s", (_label, report) => {
+ expect(OwnerDiagnosticReportSchema.safeParse(report).success).toBe(false);
+ });
+
+ it.each([
+ ["machineId", "cm_private"],
+ ["r2Key", "bug-reports/private.ndjson.gz"],
+ ["sha256", "a".repeat(64)],
+ ["sizeBytes", 123],
+ ["fromMs", FROM_MS],
+ ])("rejects private field %s", (key, value) => {
+ expect(OwnerDiagnosticReportSchema.safeParse({ ...ownerReport, [key]: value }).success).toBe(false);
+ });
+});
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
new file mode 100644
index 000000000..3dfd1ce57
--- /dev/null
+++ b/src/web/src/app/api/community/bots/[id]/diagnostics/route.test.ts
@@ -0,0 +1,321 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+
+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),
+}));
+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" },
+ userId: "owner_1",
+ email: "[email protected]",
+ params,
+ });
+ },
+}));
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ ...actual.queries,
+ communityDiagnosticReport: {
+ ...actual.queries.communityDiagnosticReport,
+ createOrGetPendingDiagnosticReport: (...args: unknown[]) => createOrGet(...args),
+ failPendingDiagnosticReport: (...args: unknown[]) => failPending(...args),
+ getDiagnosticReportForOwner: (...args: unknown[]) => getForOwner(...args),
+ },
+ },
+ };
+});
+
+import { POST } from "./route";
+import { queries } from "@alook/shared";
+
+const NOW = 1_700_086_400_000;
+const NONCE = "00000000-0000-4000-8000-000000000001";
+
+function row(overrides: Record<string, unknown> = {}) {
+ return {
+ id: "dbr_0123456789abcdef",
+ ownerUserId: "owner_1",
+ agentId: "bot_1",
+ machineId: "cm_original",
+ clientNonce: NONCE,
+ rateBucket: Math.floor(NOW / 60_000),
+ status: "pending",
+ failureCode: null,
+ fromMs: NOW - 86_400_000,
+ createdAt: NOW,
+ deadlineAt: NOW + 600_000,
+ completedAt: null,
+ r2Key: null,
+ sha256: null,
+ sizeBytes: null,
+ uploadedAt: null,
+ objectExpiresAt: null,
+ ...overrides,
+ };
+}
+
+function request(clientNonce = NONCE) {
+ return new NextRequest("http://localhost/api/community/bots/bot_1/diagnostics", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ clientNonce }),
+ });
+}
+
+function requestBody(body: unknown) {
+ return new NextRequest("http://localhost/api/community/bots/bot_1/diagnostics", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+}
+
+const context = { params: Promise.resolve({ id: "bot_1" }) };
+
+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" }],
+ ["unknown key", { clientNonce: NONCE, machineId: "cm_injected" }],
+ ])("rejects a strict body with %s before D1 or WS", async (_label, body) => {
+ const response = await POST(requestBody(body), context);
+
+ expect(response.status).toBe(400);
+ expect(createOrGet).not.toHaveBeenCalled();
+ expect(failPending).not.toHaveBeenCalled();
+ expect(getForOwner).not.toHaveBeenCalled();
+ expect(pushDiagnostic).not.toHaveBeenCalled();
+ });
+
+ it("rejects malformed JSON before D1 or WS", async () => {
+ const malformed = new NextRequest("http://localhost/api/community/bots/bot_1/diagnostics", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: "{",
+ });
+
+ const response = await POST(malformed, context);
+
+ expect(response.status).toBe(400);
+ expect(createOrGet).not.toHaveBeenCalled();
+ expect(failPending).not.toHaveBeenCalled();
+ expect(getForOwner).not.toHaveBeenCalled();
+ expect(pushDiagnostic).not.toHaveBeenCalled();
+ });
+
+ it("maps foreign, deleted, non-bot, or unbound atomic target failure to an owner-safe 404", async () => {
+ createOrGet.mockRejectedValue(
+ new queries.communityDiagnosticReport.DiagnosticReportTargetUnavailableError(),
+ );
+
+ const response = await POST(request(), context);
+
+ expect(response.status).toBe(404);
+ expect(await response.json()).toEqual({ error: "diagnostic target unavailable" });
+ expect(pushDiagnostic).not.toHaveBeenCalled();
+ expect(failPending).not.toHaveBeenCalled();
+ expect(getForOwner).not.toHaveBeenCalled();
+ });
+
+ it("creates through the atomic owner gate and returns 202 accepted pending", async () => {
+ const response = await POST(request(), context);
+
+ expect(createOrGet).toHaveBeenCalledWith({}, {
+ ownerUserId: "owner_1",
+ agentId: "bot_1",
+ clientNonce: NONCE,
+ nowMs: NOW,
+ });
+ expect(createOrGet.mock.calls[0]![1]).not.toHaveProperty("machineId");
+ expect(pushDiagnostic).toHaveBeenCalledWith(
+ expect.anything(),
+ "cm_original",
+ {
+ reportId: "dbr_0123456789abcdef",
+ agentId: "bot_1",
+ fromMs: NOW - 86_400_000,
+ deadlineAt: NOW + 600_000,
+ },
+ );
+ expect(response.status).toBe(202);
+ await expect(response.json()).resolves.toEqual({
+ delivery: "accepted",
+ report: {
+ reportId: "dbr_0123456789abcdef",
+ status: "pending",
+ deadlineAt: NOW + 600_000,
+ completedAt: null,
+ failureCode: null,
+ objectExpired: false,
+ },
+ });
+ });
+
+ it("turns definitive sent=0 into guarded offline and returns a 200 terminal envelope", async () => {
+ pushDiagnostic.mockResolvedValue({ kind: "offline" });
+ const failed = row({ status: "failed", failureCode: "offline", completedAt: NOW + 1 });
+ failPending.mockResolvedValue(failed);
+
+ const response = await POST(request(), context);
+
+ expect(failPending).toHaveBeenCalledWith({}, {
+ reportId: "dbr_0123456789abcdef",
+ machineId: "cm_original",
+ failureCode: "offline",
+ nowMs: NOW,
+ });
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({
+ delivery: "accepted",
+ report: {
+ reportId: "dbr_0123456789abcdef",
+ status: "failed",
+ deadlineAt: NOW + 600_000,
+ completedAt: NOW + 1,
+ failureCode: "offline",
+ objectExpired: false,
+ },
+ });
+ });
+
+ it("reads the authoritative owner row when the sent=0 offline CAS loses", async () => {
+ pushDiagnostic.mockResolvedValue({ kind: "offline" });
+ failPending.mockResolvedValue(null);
+ getForOwner.mockResolvedValue(row({
+ status: "failed",
+ failureCode: "timeout",
+ completedAt: NOW + 2,
+ }));
+
+ const response = await POST(request(), context);
+
+ expect(getForOwner).toHaveBeenCalledWith({}, {
+ reportId: "dbr_0123456789abcdef",
+ ownerUserId: "owner_1",
+ });
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toMatchObject({
+ delivery: "accepted",
+ report: { status: "failed", failureCode: "timeout", completedAt: NOW + 2 },
+ });
+ });
+
+ it("keeps delivery unknown when the sent=0 offline CAS loses to a still-pending row", async () => {
+ pushDiagnostic.mockResolvedValue({ kind: "offline" });
+ failPending.mockResolvedValue(null);
+ getForOwner.mockResolvedValue(row());
+
+ const response = await POST(request(), context);
+
+ expect(response.status).toBe(202);
+ await expect(response.json()).resolves.toMatchObject({
+ delivery: "unknown",
+ report: { reportId: "dbr_0123456789abcdef", status: "pending" },
+ });
+ });
+
+ it("keeps ambiguous delivery pending with the same id and returns 202 unknown", async () => {
+ pushDiagnostic.mockResolvedValue({ kind: "ambiguous" });
+
+ const response = await POST(request(), context);
+
+ expect(response.status).toBe(202);
+ expect(failPending).not.toHaveBeenCalled();
+ await expect(response.json()).resolves.toMatchObject({
+ delivery: "unknown",
+ report: { reportId: "dbr_0123456789abcdef", status: "pending" },
+ });
+ });
+
+ it("adopts a different-nonce existing pending report with 202 instead of conflict", async () => {
+ createOrGet.mockResolvedValue({ kind: "existing_pending", report: row({ clientNonce: "another_nonce_1234" }) });
+
+ const response = await POST(request(), context);
+
+ expect(response.status).toBe(202);
+ await expect(response.json()).resolves.toMatchObject({
+ delivery: "accepted",
+ report: { reportId: "dbr_0123456789abcdef", status: "pending" },
+ });
+ });
+
+ it("reuses a same-nonce row's original machine snapshot after rebind", async () => {
+ createOrGet.mockResolvedValue({ kind: "same_nonce", report: row({ machineId: "cm_original" }) });
+
+ await POST(request(), context);
+
+ expect(pushDiagnostic).toHaveBeenCalledWith(expect.anything(), "cm_original", expect.anything());
+ });
+
+ it("returns an already-terminal same-nonce row without redispatch", async () => {
+ createOrGet.mockResolvedValue({
+ kind: "same_nonce",
+ report: row({ status: "failed", failureCode: "offline", completedAt: NOW - 1 }),
+ });
+
+ const response = await POST(request(), context);
+
+ expect(response.status).toBe(200);
+ expect(pushDiagnostic).not.toHaveBeenCalled();
+ await expect(response.json()).resolves.toMatchObject({
+ delivery: "accepted",
+ report: { status: "failed", failureCode: "offline", completedAt: NOW - 1 },
+ });
+ });
+
+ it("returns 409 without an adoptable report for same nonce on another agent", async () => {
+ createOrGet.mockResolvedValue({ kind: "same_nonce", report: row({ agentId: "bot_other" }) });
+
+ const response = await POST(request(), context);
+
+ expect(response.status).toBe(409);
+ expect(pushDiagnostic).not.toHaveBeenCalled();
+ expect(await response.json()).toEqual({ error: "diagnostic nonce belongs to another bot" });
+ });
+
+ it("returns 429 for the authoritative rate-bucket winner without WS dispatch", async () => {
+ createOrGet.mockResolvedValue({ kind: "rate_limited", report: row({ id: "dbr_ratewinner1234" }) });
+
+ const response = await POST(request(), context);
+
+ expect(response.status).toBe(429);
+ expect(pushDiagnostic).not.toHaveBeenCalled();
+ expect(await response.json()).not.toHaveProperty("report");
+ });
+});
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
new file mode 100644
index 000000000..46e452b53
--- /dev/null
+++ b/src/web/src/app/api/community/bots/[id]/diagnostics/route.ts
@@ -0,0 +1,101 @@
+import { NextRequest } from "next/server";
+import {
+ DiagnosticReportCreateRequestSchema,
+ 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,
+ type OwnerDiagnosticReportSource,
+} from "@/lib/community/diagnostic-report";
+import { withAuth } from "@/lib/middleware/auth";
+import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers";
+
+function reportEnvelope(
+ delivery: "accepted" | "unknown",
+ report: OwnerDiagnosticReportSource,
+ nowMs: number,
+ status: number,
+) {
+ return writeJSON({
+ delivery,
+ report: projectOwnerDiagnosticReport(report, nowMs),
+ }, status);
+}
+
+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;
+ const nowMs = Date.now();
+ const db = getDb(ctx.env.DB);
+
+ let result: Awaited<ReturnType<
+ typeof queries.communityDiagnosticReport.createOrGetPendingDiagnosticReport
+ >>;
+ try {
+ result = await queries.communityDiagnosticReport.createOrGetPendingDiagnosticReport(db, {
+ ownerUserId: ctx.userId,
+ agentId,
+ clientNonce: body.clientNonce,
+ nowMs,
+ });
+ } catch (error) {
+ if (error instanceof queries.communityDiagnosticReport.DiagnosticReportTargetUnavailableError) {
+ return writeError("diagnostic target unavailable", 404);
+ }
+ throw error;
+ }
+
+ const report = result.report;
+ if (result.kind === "rate_limited") {
+ return writeError("diagnostic report rate limited", 429);
+ }
+ if (result.kind === "same_nonce" && report.agentId !== agentId) {
+ return writeError("diagnostic nonce belongs to another bot", 409);
+ }
+ if (report.status !== "pending") {
+ return reportEnvelope("accepted", report, nowMs, 200);
+ }
+ if (result.kind === "existing_pending") {
+ return reportEnvelope("accepted", report, nowMs, 202);
+ }
+
+ const delivery = await pushDiagnosticReportToMachine(ctx.env, report.machineId, {
+ reportId: report.id,
+ agentId: report.agentId,
+ fromMs: report.fromMs,
+ deadlineAt: report.deadlineAt,
+ });
+ if (delivery.kind === "delivered") {
+ return reportEnvelope("accepted", report, nowMs, 202);
+ }
+ if (delivery.kind === "ambiguous") {
+ return reportEnvelope("unknown", report, nowMs, 202);
+ }
+
+ const failed = await queries.communityDiagnosticReport.failPendingDiagnosticReport(db, {
+ reportId: report.id,
+ machineId: report.machineId,
+ failureCode: "offline",
+ nowMs,
+ });
+ if (failed) {
+ return reportEnvelope("accepted", failed, nowMs, 200);
+ }
+
+ const authoritative = await queries.communityDiagnosticReport.getDiagnosticReportForOwner(db, {
+ reportId: report.id,
+ ownerUserId: ctx.userId,
+ });
+ if (!authoritative) return writeError("diagnostic report not found", 404);
+ return authoritative.status === "pending"
+ ? reportEnvelope("unknown", authoritative, nowMs, 202)
+ : reportEnvelope("accepted", authoritative, nowMs, 200);
+});
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 37ca75c21..30adfc1b0 100644
--- a/src/web/src/app/api/community/bots/route.test.ts
+++ b/src/web/src/app/api/community/bots/route.test.ts
@@ -9,6 +9,7 @@ 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: {} } })),
@@ -41,6 +42,9 @@ 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) => {
@@ -151,6 +155,7 @@ 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 () => {
@@ -185,6 +190,22 @@ 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: [] })
+ 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: {} }))
})
})
diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.ts
index a6e04d61f..fcab9beb5 100644
--- a/src/web/src/app/api/community/bots/route.ts
+++ b/src/web/src/app/api/community/bots/route.ts
@@ -10,6 +10,7 @@ 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)
@@ -28,7 +29,10 @@ export const GET = withAuth(async (_req, ctx) => {
...bot,
dailyActivity: activityByBot.get(bot.id) ?? [],
}))
- return writeJSON({ bots: withActivity })
+ return writeJSON({
+ bots: withActivity,
+ features: projectBugReportsFeature(ctx.env),
+ })
})
export const POST = withAuth(async (req: NextRequest, ctx) => {
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
new file mode 100644
index 000000000..f72ebd5b2
--- /dev/null
+++ b/src/web/src/app/api/community/diagnostics/[reportId]/route.test.ts
@@ -0,0 +1,181 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+
+const getForOwner = vi.fn();
+const timeoutPending = vi.fn();
+
+vi.mock("@/lib/db", () => ({ getDb: () => ({}) }));
+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" },
+ userId: "owner_1",
+ email: "[email protected]",
+ params,
+ });
+ },
+}));
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ ...actual.queries,
+ communityDiagnosticReport: {
+ ...actual.queries.communityDiagnosticReport,
+ getDiagnosticReportForOwner: (...args: unknown[]) => getForOwner(...args),
+ timeoutPendingDiagnosticReport: (...args: unknown[]) => timeoutPending(...args),
+ },
+ },
+ };
+});
+
+import { GET } from "./route";
+
+const NOW = 1_700_087_000_000;
+
+function row(overrides: Record<string, unknown> = {}) {
+ return {
+ id: "dbr_0123456789abcdef",
+ ownerUserId: "owner_1",
+ agentId: "bot_1",
+ machineId: "cm_private",
+ clientNonce: "00000000-0000-4000-8000-000000000001",
+ rateBucket: 1,
+ status: "pending",
+ failureCode: null,
+ fromMs: NOW - 87_000_000,
+ createdAt: NOW - 600_000,
+ deadlineAt: NOW,
+ completedAt: null,
+ r2Key: null,
+ sha256: null,
+ sizeBytes: null,
+ uploadedAt: null,
+ objectExpiresAt: null,
+ ...overrides,
+ };
+}
+
+const request = new NextRequest("http://localhost/api/community/diagnostics/dbr_0123456789abcdef");
+const context = { params: Promise.resolve({ reportId: "dbr_0123456789abcdef" }) };
+
+describe("GET /api/community/diagnostics/:reportId", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(Date, "now").mockReturnValue(NOW);
+ });
+
+ it.each([
+ ["invalid", "report_0123456789abcdef"],
+ ["path-like", "dbr_../secret"],
+ ])("rejects an %s report id before owner lookup", async (_label, reportId) => {
+ const response = await GET(request, { params: Promise.resolve({ reportId }) });
+
+ expect(response.status).toBe(400);
+ expect(getForOwner).not.toHaveBeenCalled();
+ expect(timeoutPending).not.toHaveBeenCalled();
+ });
+
+ it("scopes the read by immutable owner even while the creation flag is false", async () => {
+ getForOwner.mockResolvedValue(row({ deadlineAt: NOW + 1 }));
+
+ const response = await GET(request, context);
+
+ expect(getForOwner).toHaveBeenCalledWith({}, {
+ reportId: "dbr_0123456789abcdef",
+ ownerUserId: "owner_1",
+ });
+ expect(response.status).toBe(200);
+ const body = await response.json();
+ expect(body).toEqual({
+ report: {
+ reportId: "dbr_0123456789abcdef",
+ status: "pending",
+ deadlineAt: NOW + 1,
+ completedAt: null,
+ failureCode: null,
+ objectExpired: false,
+ },
+ });
+ expect(JSON.stringify(body)).not.toMatch(/machine|clientNonce|r2|sha|size|fromMs/i);
+ });
+
+ it("returns 404 for another owner's report without a live bot or binding lookup", async () => {
+ getForOwner.mockResolvedValue(null);
+
+ const response = await GET(request, context);
+
+ expect(response.status).toBe(404);
+ expect(timeoutPending).not.toHaveBeenCalled();
+ });
+
+ it("lazily wins an expired pending timeout CAS and returns failed/timeout", async () => {
+ getForOwner.mockResolvedValue(row());
+ timeoutPending.mockResolvedValue(row({
+ status: "failed",
+ failureCode: "timeout",
+ completedAt: NOW,
+ }));
+
+ const response = await GET(request, context);
+
+ expect(timeoutPending).toHaveBeenCalledWith({}, {
+ reportId: "dbr_0123456789abcdef",
+ ownerUserId: "owner_1",
+ nowMs: NOW,
+ });
+ await expect(response.json()).resolves.toMatchObject({
+ report: { status: "failed", failureCode: "timeout", completedAt: NOW },
+ });
+ });
+
+ it("reads back the authoritative owner row when the timeout CAS loses", async () => {
+ getForOwner
+ .mockResolvedValueOnce(row())
+ .mockResolvedValueOnce(row({
+ status: "failed",
+ failureCode: "offline",
+ completedAt: NOW - 1,
+ }));
+ timeoutPending.mockResolvedValue(null);
+
+ const response = await GET(request, context);
+
+ expect(getForOwner).toHaveBeenCalledTimes(2);
+ expect(getForOwner).toHaveBeenLastCalledWith({}, {
+ reportId: "dbr_0123456789abcdef",
+ ownerUserId: "owner_1",
+ });
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toMatchObject({
+ report: { status: "failed", failureCode: "offline", completedAt: NOW - 1 },
+ });
+ });
+
+ it("derives objectExpired without inventing an expired database status", async () => {
+ getForOwner.mockResolvedValue(row({
+ status: "uploaded",
+ completedAt: NOW - 1_000,
+ uploadedAt: NOW - 1_000,
+ objectExpiresAt: NOW,
+ r2Key: "bug-reports/owner_1/dbr_0123456789abcdef.ndjson.gz",
+ sha256: "a".repeat(64),
+ sizeBytes: 100,
+ }));
+
+ const response = await GET(request, context);
+
+ await expect(response.json()).resolves.toEqual({
+ report: {
+ reportId: "dbr_0123456789abcdef",
+ status: "uploaded",
+ deadlineAt: NOW,
+ completedAt: NOW - 1_000,
+ failureCode: null,
+ objectExpired: true,
+ },
+ });
+ });
+});
diff --git a/src/web/src/app/api/community/diagnostics/[reportId]/route.ts b/src/web/src/app/api/community/diagnostics/[reportId]/route.ts
new file mode 100644
index 000000000..08187f39d
--- /dev/null
+++ b/src/web/src/app/api/community/diagnostics/[reportId]/route.ts
@@ -0,0 +1,33 @@
+import {
+ DiagnosticReportIdSchema,
+ queries,
+} from "@alook/shared";
+import { getDb } from "@/lib/db";
+import { projectOwnerDiagnosticReport } from "@/lib/community/diagnostic-report";
+import { withAuth } from "@/lib/middleware/auth";
+import { writeError, writeJSON } from "@/lib/middleware/helpers";
+
+export const GET = withAuth(async (_req, ctx) => {
+ const parsedId = DiagnosticReportIdSchema.safeParse(ctx.params?.reportId);
+ if (!parsedId.success) return writeError("invalid diagnostic report id", 400);
+
+ const db = getDb(ctx.env.DB);
+ const ownerInput = { reportId: parsedId.data, ownerUserId: ctx.userId };
+ let report = await queries.communityDiagnosticReport.getDiagnosticReportForOwner(db, ownerInput);
+ if (!report) return writeError("diagnostic report not found", 404);
+
+ const nowMs = Date.now();
+ if (report.status === "pending" && report.deadlineAt <= nowMs) {
+ const timedOut = await queries.communityDiagnosticReport.timeoutPendingDiagnosticReport(db, {
+ ...ownerInput,
+ nowMs,
+ });
+ report = timedOut ?? await queries.communityDiagnosticReport.getDiagnosticReportForOwner(
+ db,
+ ownerInput,
+ );
+ if (!report) return writeError("diagnostic report not found", 404);
+ }
+
+ return writeJSON({ report: projectOwnerDiagnosticReport(report, nowMs) });
+});
diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.ts
index a0906c8af..ae4a2a9ca 100644
--- a/src/web/src/env.d.ts
+++ b/src/web/src/env.d.ts
@@ -21,6 +21,7 @@ declare namespace Cloudflare {
CACHE_KV: KVNamespace
AUTH_OTP_RATE_LIMIT_MAX?: string
AUTH_OTP_RATE_LIMIT_WINDOW_SEC?: string
+ BUG_REPORTS_ENABLED?: string
RUNTIME_MODEL_OPTIONS?: string
MIN_CLI_VERSION?: string
DEVICE_CLIENT_IDS?: string
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 266874b15..8822b5517 100644
--- a/src/web/src/hooks/community/use-bot-bug-report.ts
+++ b/src/web/src/hooks/community/use-bot-bug-report.ts
@@ -4,25 +4,14 @@ 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"
+import {
+ DiagnosticReportFailureCodeSchema,
+ type DiagnosticReportFailureCode,
+} from "@alook/shared"
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 BugReportFailureCode = DiagnosticReportFailureCode
export type BugReportPhase =
| "confirm"
| "submitting"
@@ -90,7 +79,7 @@ function isRecord(value: unknown): value is Record<string, unknown> {
}
function isFailureCode(value: unknown): value is BugReportFailureCode {
- return typeof value === "string" && (FAILURE_CODES as readonly string[]).includes(value)
+ return DiagnosticReportFailureCodeSchema.safeParse(value).success
}
function isTimestamp(value: unknown): value is number {
diff --git a/src/web/src/lib/community/diagnostic-feature.test.ts b/src/web/src/lib/community/diagnostic-feature.test.ts
new file mode 100644
index 000000000..4e5a457e8
--- /dev/null
+++ b/src/web/src/lib/community/diagnostic-feature.test.ts
@@ -0,0 +1,31 @@
+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
new file mode 100644
index 000000000..8394ea1b0
--- /dev/null
+++ b/src/web/src/lib/community/diagnostic-feature.ts
@@ -0,0 +1,11 @@
+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-report-push.test.ts b/src/web/src/lib/community/diagnostic-report-push.test.ts
new file mode 100644
index 000000000..dfee51260
--- /dev/null
+++ b/src/web/src/lib/community/diagnostic-report-push.test.ts
@@ -0,0 +1,70 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const wsDoFetch = vi.fn();
+vi.mock("@/lib/broadcast", () => ({
+ wsDoFetch: (...args: unknown[]) => wsDoFetch(...args),
+}));
+
+import { pushDiagnosticReportToMachine } from "./diagnostic-report-push";
+
+const env = { WS_DO_WORKER: {}, DEV_WS_DO_URL: undefined } as unknown as Env;
+const command = {
+ reportId: "dbr_0123456789abcdef",
+ agentId: "bot_1",
+ fromMs: 1_700_000_000_000,
+ deadlineAt: 1_700_087_000_000,
+};
+
+describe("pushDiagnosticReportToMachine", () => {
+ beforeEach(() => wsDoFetch.mockReset());
+
+ it("uses only the purpose-built diagnostics route and narrow body", async () => {
+ wsDoFetch.mockResolvedValue(Response.json({ sent: 1 }));
+
+ const outcome = await pushDiagnosticReportToMachine(env, "cm one", command);
+
+ expect(outcome).toEqual({ kind: "delivered", sent: 1 });
+ const [, path, init, audit] = wsDoFetch.mock.calls[0]!;
+ expect(path).toBe("/community-machine/by-id/cm%20one/forward-diagnostics-collect");
+ expect(init.method).toBe("POST");
+ expect(JSON.parse(init.body as string)).toEqual(command);
+ expect(JSON.parse(init.body as string).type).toBeUndefined();
+ expect(audit).toEqual({ label: "cm one", type: "diagnostics:collect" });
+ });
+
+ it("distinguishes delivered, definite offline, and ambiguous transport", async () => {
+ wsDoFetch.mockResolvedValueOnce(Response.json({ sent: 2 }));
+ await expect(pushDiagnosticReportToMachine(env, "cm_1", command)).resolves.toEqual({
+ kind: "delivered",
+ sent: 2,
+ });
+
+ wsDoFetch.mockResolvedValueOnce(Response.json({ sent: 0 }));
+ await expect(pushDiagnosticReportToMachine(env, "cm_1", command)).resolves.toEqual({
+ kind: "offline",
+ });
+
+ wsDoFetch.mockResolvedValueOnce(new Response("unavailable", { status: 503 }));
+ await expect(pushDiagnosticReportToMachine(env, "cm_1", command)).resolves.toEqual({
+ kind: "ambiguous",
+ });
+
+ wsDoFetch.mockRejectedValueOnce(new Error("private network detail"));
+ await expect(pushDiagnosticReportToMachine(env, "cm_1", command)).resolves.toEqual({
+ kind: "ambiguous",
+ });
+ });
+
+ it.each([
+ ["missing sent", {}],
+ ["negative sent", { sent: -1 }],
+ ["fractional sent", { sent: 0.5 }],
+ ["string sent", { sent: "1" }],
+ ])("fails closed on a 2xx response with %s", async (_label, response) => {
+ wsDoFetch.mockResolvedValue(Response.json(response));
+
+ await expect(pushDiagnosticReportToMachine(env, "cm_1", command)).resolves.toEqual({
+ kind: "ambiguous",
+ });
+ });
+});
diff --git a/src/web/src/lib/community/diagnostic-report-push.ts b/src/web/src/lib/community/diagnostic-report-push.ts
new file mode 100644
index 000000000..63dd6779a
--- /dev/null
+++ b/src/web/src/lib/community/diagnostic-report-push.ts
@@ -0,0 +1,37 @@
+import type { DiagnosticCollectPayload } from "@alook/shared";
+import { wsDoFetch } from "@/lib/broadcast";
+
+export type DiagnosticDeliveryOutcome =
+ | { kind: "delivered"; sent: number }
+ | { kind: "offline" }
+ | { kind: "ambiguous" };
+
+export async function pushDiagnosticReportToMachine(
+ env: Env,
+ machineId: string,
+ payload: DiagnosticCollectPayload,
+): Promise<DiagnosticDeliveryOutcome> {
+ const path = `/community-machine/by-id/${encodeURIComponent(machineId)}/forward-diagnostics-collect`;
+ try {
+ const response = await wsDoFetch(
+ env,
+ path,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ },
+ { label: machineId, type: "diagnostics:collect" },
+ );
+ if (!response.ok) return { kind: "ambiguous" };
+ const result = await response.json() as { sent?: unknown };
+ if (!Number.isSafeInteger(result.sent) || (result.sent as number) < 0) {
+ return { kind: "ambiguous" };
+ }
+ return (result.sent as number) === 0
+ ? { kind: "offline" }
+ : { kind: "delivered", sent: result.sent as number };
+ } catch {
+ return { kind: "ambiguous" };
+ }
+}
diff --git a/src/web/src/lib/community/diagnostic-report.ts b/src/web/src/lib/community/diagnostic-report.ts
new file mode 100644
index 000000000..4a337a06e
--- /dev/null
+++ b/src/web/src/lib/community/diagnostic-report.ts
@@ -0,0 +1,32 @@
+import {
+ OwnerDiagnosticReportSchema,
+ type DiagnosticReportFailureCode,
+ type OwnerDiagnosticReport,
+} from "@alook/shared";
+
+export type OwnerDiagnosticReportSource = Readonly<{
+ id: string;
+ status: "pending" | "uploaded" | "failed";
+ failureCode: DiagnosticReportFailureCode | null;
+ deadlineAt: number;
+ completedAt: number | null;
+ objectExpiresAt: number | null;
+}>;
+
+/** Project a private D1 report row onto the exact owner-safe wire contract. */
+export function projectOwnerDiagnosticReport(
+ report: OwnerDiagnosticReportSource,
+ nowMs: number,
+): OwnerDiagnosticReport {
+ return OwnerDiagnosticReportSchema.parse({
+ reportId: report.id,
+ status: report.status,
+ deadlineAt: report.deadlineAt,
+ completedAt: report.completedAt,
+ failureCode: report.failureCode,
+ objectExpired:
+ report.status === "uploaded" &&
+ report.objectExpiresAt !== null &&
+ report.objectExpiresAt <= nowMs,
+ });
+}
diff --git a/src/web/wrangler.toml b/src/web/wrangler.toml
index 5d478e0d0..ff19ccdca 100644
--- a/src/web/wrangler.toml
+++ b/src/web/wrangler.toml
@@ -91,5 +91,6 @@ 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/src/index.test.ts b/src/ws-do/src/index.test.ts
index 994beb738..8f9770635 100644
--- a/src/ws-do/src/index.test.ts
+++ b/src/ws-do/src/index.test.ts
@@ -85,6 +85,7 @@ describe("ws-do router", () => {
"handleSinglePresence",
"handleMachinePush",
"handleMachineWake",
+ "handleMachineDiagnostics",
"handleMachineReset",
"handleMachineBatchReset",
"handleMachineModelSwitch",
diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.ts
index c0aad6c36..e623c9ee0 100644
--- a/src/ws-do/src/index.ts
+++ b/src/ws-do/src/index.ts
@@ -7,6 +7,7 @@ import {
handleUsersBroadcast,
} from "./routes/broadcast"
import { handleMachinePush, handleMachineWake } from "./routes/community-machine-delivery"
+import { handleMachineDiagnostics } from "./routes/community-machine-diagnostics"
import {
handleMachineBatchReset,
handleMachineForceClose,
@@ -61,6 +62,8 @@ export default {
if (response) return response
response = await handleMachineWake(context)
if (response) return response
+ response = await handleMachineDiagnostics(context)
+ if (response) return response
response = await handleMachineReset(context)
if (response) return response
response = await handleMachineBatchReset(context)
diff --git a/src/ws-do/src/routes/community-machine-diagnostics.test.ts b/src/ws-do/src/routes/community-machine-diagnostics.test.ts
new file mode 100644
index 000000000..97f0fff8c
--- /dev/null
+++ b/src/ws-do/src/routes/community-machine-diagnostics.test.ts
@@ -0,0 +1,96 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ createRouterTestContext,
+ getSharedMocks,
+ loadRouter,
+ type RouterHandler,
+ type RouterTestContext,
+} from "./test-harness";
+
+const getActiveDoNamesForMachine = getSharedMocks().getActiveDoNamesForMachine;
+const payload = {
+ reportId: "dbr_0123456789abcdef",
+ agentId: "bot_1",
+ fromMs: 1_700_000_000_000,
+ deadlineAt: 1_700_087_000_000,
+};
+
+describe("POST /community-machine/by-id/:machineId/forward-diagnostics-collect", () => {
+ let handler: RouterHandler;
+ let context: RouterTestContext;
+
+ beforeEach(async () => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ context = createRouterTestContext();
+ handler = await loadRouter();
+ getActiveDoNamesForMachine.mockReset().mockResolvedValue([]);
+ });
+
+ const request = (body: unknown) => new Request(
+ "http://localhost/community-machine/by-id/cm_1/forward-diagnostics-collect",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: typeof body === "string" ? body : JSON.stringify(body),
+ },
+ );
+
+ it.each([
+ ["malformed JSON", "{"],
+ ["missing reportId", { ...payload, reportId: undefined }],
+ ["path-like reportId", { ...payload, reportId: "dbr_../secret" }],
+ ["fractional epoch", { ...payload, fromMs: payload.fromMs + 0.5 }],
+ ["unknown key", { ...payload, objectKey: "attacker-controlled" }],
+ ])("strictly rejects %s before D1 or DO fanout", async (_label, body) => {
+ const response = await handler.fetch(request(body), context.env as never);
+
+ expect(response.status).toBe(400);
+ expect(getActiveDoNamesForMachine).not.toHaveBeenCalled();
+ expect(context.doMock.stubFetch).not.toHaveBeenCalled();
+ });
+
+ it("constructs the exact HostCommand and attempts every active credential", async () => {
+ getActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b", "do-c"]);
+ context.doMock.stubFetch
+ .mockResolvedValueOnce(Response.json({ sent: 0 }))
+ .mockRejectedValueOnce(new Error("credential transport failed"))
+ .mockResolvedValueOnce(Response.json({ sent: 1 }));
+
+ const response = await handler.fetch(request(payload), context.env as never);
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({ sent: 1 });
+ expect(context.doMock.stubFetch).toHaveBeenCalledTimes(3);
+ const forwarded = context.doMock.stubFetch.mock.calls.map(([value]) => value as Request);
+ expect(forwarded.every((value) => value.url === "http://internal/forward-diagnostics-collect")).toBe(true);
+ expect(await forwarded[0].clone().json()).toEqual({ type: "diagnostics:collect", ...payload });
+ expect(forwarded.some((value) => value.url.endsWith("/push"))).toBe(false);
+ });
+
+ it("returns definite offline only when every credential reports zero", async () => {
+ getActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b"]);
+ context.doMock.stubFetch
+ .mockResolvedValueOnce(Response.json({ sent: 0 }))
+ .mockResolvedValueOnce(Response.json({ sent: 0 }));
+
+ const response = await handler.fetch(request(payload), context.env as never);
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({ sent: 0 });
+ expect(context.doMock.stubFetch).toHaveBeenCalledTimes(2);
+ });
+
+ it("returns ambiguous when no delivery succeeds and any credential is non-definitive", async () => {
+ getActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b", "do-c"]);
+ context.doMock.stubFetch
+ .mockResolvedValueOnce(Response.json({ sent: 0 }))
+ .mockResolvedValueOnce(new Response("unavailable", { status: 503 }))
+ .mockResolvedValueOnce(Response.json({ sent: "one" }));
+
+ const response = await handler.fetch(request(payload), context.env as never);
+
+ expect(response.status).toBe(503);
+ expect(context.doMock.stubFetch).toHaveBeenCalledTimes(3);
+ });
+});
diff --git a/src/ws-do/src/routes/community-machine-diagnostics.ts b/src/ws-do/src/routes/community-machine-diagnostics.ts
new file mode 100644
index 000000000..8320af876
--- /dev/null
+++ b/src/ws-do/src/routes/community-machine-diagnostics.ts
@@ -0,0 +1,82 @@
+import {
+ createDb,
+ DiagnosticCollectCommandSchema,
+ DiagnosticCollectPayloadSchema,
+ queries,
+} from "@alook/shared";
+import type { RouterContext } from "../router-context";
+
+export async function handleMachineDiagnostics(
+ { request, env, url, traceId, log }: RouterContext,
+): Promise<Response | null> {
+ const match = url.pathname.match(
+ /^\/community-machine\/by-id\/([^/]+)\/forward-diagnostics-collect$/,
+ );
+ if (!match || request.method !== "POST") return null;
+
+ const machineId = decodeURIComponent(match[1]);
+ const reqLog = log.child({ traceId, machineId });
+
+ let raw: unknown;
+ try {
+ raw = await request.json();
+ } catch {
+ return Response.json({ error: "invalid payload" }, { status: 400 });
+ }
+ const payload = DiagnosticCollectPayloadSchema.safeParse(raw);
+ if (!payload.success) {
+ return Response.json({ error: "invalid payload" }, { status: 400 });
+ }
+ const command = DiagnosticCollectCommandSchema.safeParse({
+ type: "diagnostics:collect",
+ ...payload.data,
+ });
+ if (!command.success) {
+ return Response.json({ error: "invalid payload" }, { status: 400 });
+ }
+
+ let doNames: string[];
+ try {
+ const db = createDb((env as unknown as { DB: D1Database }).DB);
+ doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId);
+ } catch (err) {
+ reqLog.error("failed to resolve machine doNames for diagnostics", { err });
+ return Response.json({ error: "failed to resolve machine" }, { status: 503 });
+ }
+ if (doNames.length === 0) return Response.json({ sent: 0 });
+
+ const body = JSON.stringify(command.data);
+ let delivered = 0;
+ let ambiguous = false;
+ for (const doName of doNames) {
+ const id = env.WS_DO.idFromName(`community-machine:${doName}`);
+ const stub = env.WS_DO.get(id);
+ try {
+ const response = await stub.fetch(new Request(
+ "http://internal/forward-diagnostics-collect",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body,
+ },
+ ));
+ if (!response.ok) {
+ ambiguous = true;
+ continue;
+ }
+ const result = await response.json() as { sent?: unknown };
+ if (!Number.isSafeInteger(result.sent) || (result.sent as number) < 0) {
+ ambiguous = true;
+ continue;
+ }
+ delivered += result.sent as number;
+ } catch {
+ ambiguous = true;
+ }
+ }
+
+ if (delivered === 0 && ambiguous) {
+ return Response.json({ error: "diagnostic delivery ambiguous" }, { status: 503 });
+ }
+ return Response.json({ sent: delivered });
+}
diff --git a/src/ws-do/src/ws-durable/machine-control.test.ts b/src/ws-do/src/ws-durable/machine-control.test.ts
index 62adccb06..afd555800 100644
--- a/src/ws-do/src/ws-durable/machine-control.test.ts
+++ b/src/ws-do/src/ws-durable/machine-control.test.ts
@@ -295,6 +295,59 @@ describe("WebSocketDurableObject", () => {
expect(ws.send).toHaveBeenCalledWith(body)
})
+ it("strictly parses and forwards only the exact diagnostics HostCommand", async () => {
+ const { durable, getWebSockets } = createDO()
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ getWebSockets.mockReturnValue([ws])
+ const payload = {
+ type: "diagnostics:collect",
+ reportId: "dbr_0123456789abcdef",
+ agentId: "bot_1",
+ fromMs: 1_700_000_000_000,
+ deadlineAt: 1_700_087_000_000,
+ }
+
+ const response = await durable.fetch(new Request("http://internal/forward-diagnostics-collect", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(payload),
+ }))
+
+ expect(response.status).toBe(200)
+ await expect(response.json()).resolves.toEqual({ sent: 1 })
+ expect(ws.send).toHaveBeenCalledOnce()
+ expect(JSON.parse(ws.send.mock.calls[0]![0] as string)).toEqual(payload)
+ })
+
+ it.each([
+ ["malformed JSON", "{"],
+ ["missing field", JSON.stringify({ type: "diagnostics:collect", agentId: "bot_1" })],
+ ["unknown field", JSON.stringify({
+ type: "diagnostics:collect",
+ reportId: "dbr_0123456789abcdef",
+ agentId: "bot_1",
+ fromMs: 1_700_000_000_000,
+ deadlineAt: 1_700_087_000_000,
+ machineId: "cm_injected",
+ })],
+ ])("rejects diagnostics %s before reading sockets", async (_label, body) => {
+ const { durable, getWebSockets } = createDO()
+
+ const response = await durable.fetch(new Request("http://internal/forward-diagnostics-collect", {
+ method: "POST",
+ body,
+ }))
+
+ expect(response.status).toBe(400)
+ expect(getWebSockets).not.toHaveBeenCalled()
+ })
+
it("best-effort force-close counts only sockets whose send and close both complete", async () => {
const { durable, getWebSockets } = createDO()
const sendFails = createMockWebSocket()
diff --git a/src/ws-do/src/ws-durable/machine-control.ts b/src/ws-do/src/ws-durable/machine-control.ts
index 4723d98d5..72535cb04 100644
--- a/src/ws-do/src/ws-durable/machine-control.ts
+++ b/src/ws-do/src/ws-durable/machine-control.ts
@@ -1,4 +1,4 @@
-import { createDb, queries } from "@alook/shared"
+import { createDb, DiagnosticCollectCommandSchema, queries } from "@alook/shared"
import {
HANDLE_KEY,
IDENTITY_KEY,
@@ -99,6 +99,23 @@ export async function handleMachineControlFetch(
})
}
+ if (url.pathname === "/forward-diagnostics-collect" && request.method === "POST") {
+ let raw: unknown
+ try {
+ raw = await request.json()
+ } catch {
+ return new Response(JSON.stringify({ sent: 0 }), { status: 400 })
+ }
+ const command = DiagnosticCollectCommandSchema.safeParse(raw)
+ if (!command.success) {
+ return new Response(JSON.stringify({ sent: 0 }), { status: 400 })
+ }
+ const sent = forwardToCommunityMachine(context, JSON.stringify(command.data))
+ return new Response(JSON.stringify({ sent }), {
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+
return null
}