Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Record turn phase timings, process CPU buckets and event-loop lag for diagnostics (#5977)

Milind Soni55fb7c14c4a5
diff --git a/electron/diagnostics.mjs b/electron/diagnostics.mjs
index 6ffa42d114..a4dda955a0 100644
--- a/electron/diagnostics.mjs
+++ b/electron/diagnostics.mjs
@@ -277,6 +277,7 @@ export function buildDiagnosticsReport({
desktopLogTail,
updaterLogTail,
logTail,
+ performance,
now = new Date().toISOString(),
} = {}) {
const lines = [];
@@ -300,6 +301,14 @@ export function buildDiagnosticsReport({
}
if (!shown) lines.push("(no configuration summary available)");
lines.push("");
+ // The server's timings (GET /api/diagnostics/performance): numbers, fixed codes and opaque ids, scrubbed again here.
+ if (typeof performance === "string" && performance.trim()) {
+ for (const line of redactSecretsInLine(performance).split(/\r?\n/)) lines.push(line);
+ } else {
+ lines.push("## Performance");
+ lines.push("(server timings unavailable)");
+ }
+ lines.push("");
lines.push("## Desktop crash events — privacy-safe metadata only");
if (desktopLogTail && desktopLogTail.trim()) {
for (const line of redactSecretsInLine(desktopLogTail).split(/\r?\n/)) lines.push(line);
diff --git a/electron/diagnostics.test.mjs b/electron/diagnostics.test.mjs
index 7dfbf7b569..523bed243d 100644
--- a/electron/diagnostics.test.mjs
+++ b/electron/diagnostics.test.mjs
@@ -61,6 +61,15 @@ describe("buildDiagnosticsReport", () => {
expect(report).toContain("(updater log unavailable)");
});
+ it("carries the server's performance lines, scrubbed again, and says when the server gave none", () => {
+ const performance = "## Performance (timings only: no messages, names, files or addresses)\nLast hour: 3 turns, 0 failed\nOPENAI_API_KEY=sk-proj-abcdefghijklmnopqrstuvwxyz";
+ const report = buildDiagnosticsReport({ appInfo, performance });
+ expect(report).toContain("## Performance (timings only: no messages, names, files or addresses)\nLast hour: 3 turns, 0 failed");
+ expect(report).not.toContain("sk-proj-abcdefghijklmnopqrstuvwxyz");
+ expect(report.indexOf("## Performance")).toBeLessThan(report.indexOf("## Desktop crash events"));
+ expect(buildDiagnosticsReport({ appInfo })).toContain("## Performance\n(server timings unavailable)");
+ });
+
it("includes updater diagnostics separately and redacts signed redirects and headers", () => {
const report = buildDiagnosticsReport({
appInfo,
diff --git a/electron/main.mjs b/electron/main.mjs
index 28013eb606..95f9f31a28 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -761,8 +761,8 @@ async function gatherDiagnostics() {
})
.then((res) => (res.ok ? res.json() : null))
.catch(() => null);
- const logPath = path.join(LOG_DIR, "server.log");
- const log = readSafeLogTail(logPath);
+ const performance = await fetch(`http://127.0.0.1:${SERVER_PORT}/api/diagnostics/performance`, { signal: AbortSignal.timeout(3_000) }).then((res) => (res.ok ? res.json() : null)).then((body) => (typeof body?.text === "string" ? body.text : "")).catch(() => "");
+ const log = readSafeLogTail(path.join(LOG_DIR, "server.log"));
const desktopLog = readSafeLogTail(DESKTOP_CRASH_LOG);
const updaterLog = readSafeLogTail(path.join(LOG_DIR, "updater.log"));
return buildDiagnosticsReport({
@@ -775,7 +775,7 @@ async function gatherDiagnostics() {
packaged: app.isPackaged,
uptimeSeconds: Math.round(process.uptime()),
},
- configSummary: serverStatus ?? {},
+ configSummary: serverStatus ?? {}, performance,
desktopLogTail: desktopLog?.tail ?? "",
updaterLogTail: updaterLog?.tail ?? "",
logTail: log?.tail ?? "",
diff --git a/server/cloud-health.test.ts b/server/cloud-health.test.ts
index 5a24134a54..fe652bab78 100644
--- a/server/cloud-health.test.ts
+++ b/server/cloud-health.test.ts
@@ -322,6 +322,18 @@ describe("GET /api/cloud/health", () => {
expect((await send("GET", again, sign(again))).body.incidents).toEqual([]);
});
+ it("still answers 200, with perf null and one warning a minute, when the performance recorder throws", async () => {
+ const warned: string[] = [];
+ const w = world({ perf: () => { throw new TypeError("boom at /Users/ada/secret"); }, log: (line) => warned.push(line) });
+ const { sign, send } = routes(w);
+ const target = `${CLOUD_HEALTH_PATH}?after=0`;
+ const answer = await send("GET", target, sign(target));
+ expect(answer.status).toBe(200);
+ expect(answer.body).toMatchObject({ v: 1, perf: null });
+ w.health.report(undefined);
+ expect(warned).toEqual(["cloud health: perf left out: TypeError"]);
+ });
+
it("refuses a wrong key, another path or query, a stale or replayed request, and anything but GET", async () => {
const w = world();
const { sign, send } = routes(w);
diff --git a/server/cloud-health.ts b/server/cloud-health.ts
index beb8cd939c..7b345764c0 100644
--- a/server/cloud-health.ts
+++ b/server/cloud-health.ts
@@ -14,6 +14,7 @@ import type { ValueReport } from "./host/value-ledger.ts";
import type { ProviderSnapshot, RuntimeEvent } from "./contracts.ts";
import { createCloudSpeed, type CloudSpeed } from "./cloud-speed.ts";
import { classifyError } from "./drivers/retry.ts";
+import type { PerfHealth } from "./perf/perf-report.ts";
import type { Message, StoreChange } from "./store.ts";
/** The report's largest JSON body; incidents past it wait for the next poll. */
@@ -256,6 +257,10 @@ export interface CloudHealthDeps {
room?: () => RoomReport;
/** CPU steal and pressure, boot and wake times, and how long messages wait for their engine. */
speed?: CloudSpeed;
+ /** Turn phase timings, usage-limit holds, process buckets and event-loop lag: at most PERF_HEALTH_MAX_BYTES. A throw
+ * reads as null: the Admin restarts a home whose health read fails, so this optional part never fails it. */
+ perf?: () => PerfHealth | null;
+ log?: (line: string) => void;
now?: () => number;
}
@@ -276,6 +281,13 @@ export function createCloudHealth(deps: CloudHealthDeps) {
deps.bus.subscribe((event) => { ledger.noteEvent(event); speed.noteEvent(event); });
const connectors = backgroundLookup(deps.connectors, CONNECTORS_TTL_MS, now);
const version = match(VERSION, deps.version) ?? "unknown", image = match(IMAGE, deps.image);
+ let perfWarnedAt = -Infinity;
+ const perf = () => {
+ try { return deps.perf?.() ?? null; } catch (error) {
+ if (now() - perfWarnedAt >= 60_000) { perfWarnedAt = now(); (deps.log ?? console.warn)(`cloud health: perf left out: ${error instanceof Error ? error.name : "error"}`); }
+ return null;
+ }
+ };
const engines = () => {
const used = new Set(deps.store.bots.flatMap((bot) => bot.modelSelection ? [bot.modelSelection.instanceId] : []));
@@ -304,7 +316,7 @@ export function createCloudHealth(deps: CloudHealthDeps) {
turns: read.turns, routines: read.routines, engines: engines(), connectors: connectorState(),
browser: { available: browser.available, installing: browser.installing, interrupted: browser.interrupted },
box: boxSummary(deps.box?.()),
- firstHour: first?.firstHour ?? null, value: first?.value ?? null, room: deps.room?.() ?? null, speed: speed.report(),
+ firstHour: first?.firstHour ?? null, value: first?.value ?? null, room: deps.room?.() ?? null, speed: speed.report(), perf: perf(),
system: { ...memory, rssBytes: process.memoryUsage.rss(), load1: loadavg()[0] ?? 0, cpus: availableParallelism(), disk: diskBytes(deps.dataDir), eventLogWritable: writable(deps.eventsDir) },
};
let budget = CLOUD_HEALTH_MAX_BYTES - JSON.stringify({ ...base, cursor: ledger.cursor(read.seq), truncated: true, incidents: [] }).length;
diff --git a/server/cloud-home-server.test.ts b/server/cloud-home-server.test.ts
index bf833fd7ab..8860ef3c6e 100644
--- a/server/cloud-home-server.test.ts
+++ b/server/cloud-home-server.test.ts
@@ -440,6 +440,11 @@ it("tells the Admin's signed health read a failed turn's code, never its words,
const report = await read();
expect(report.status).toBe(200);
expect(report.body).toMatchObject({ v: 1, turns: { failed24h: expect.any(Number) }, engines: expect.arrayContaining([expect.objectContaining({ kind: "claudeAgent", used: true })]) });
+ expect(report.body.perf).toMatchObject({ v: 1, h24: { turns: expect.any(Number), failed: expect.any(Number) }, holds: expect.any(Array) });
+ expect(report.body.perf.h24.turns + Object.values(report.body.perf.h24.limits as Record<string, number>).reduce((sum, count) => sum + count, 0)).toBeGreaterThanOrEqual(1);
+ expect(report.body.perf.h24.limits).toMatchObject({ "claudeAgent:engine": expect.any(Number) });
+ expect(report.body.perf.live).toEqual([]);
+ expect(JSON.stringify(report.body.perf).length).toBeLessThanOrEqual(8 * 1024);
expect(report.body.incidents).toContainEqual(expect.objectContaining({ kind: "turn", code: "quota", engine: "claudeAgent", botId, count: 1 }));
for (const planted of ["weekly limit", "[email protected]", "Secret Merger Plans", "Tallyspoon Ops", "Draft the ACME", "[email protected]"]) {
expect(JSON.stringify(report.body), planted).not.toContain(planted);
diff --git a/server/devs-report.ts b/server/devs-report.ts
index 07b41263e8..72a7d4e12c 100644
--- a/server/devs-report.ts
+++ b/server/devs-report.ts
@@ -9,7 +9,7 @@ import { clip, oneLine } from "./host/text-clip.ts";
* platform, 262,144 for diagnostics and a 600 KB body. */
export const DEVS_REPORT_LIMITS = {
description: 10_000, message: 3_000, summary: 2_000, seen: 3_000, steps: 2_000,
- field: 40, diagnostics: 48_000, problems: 20, problemChars: 300, logLines: 80, logLineChars: 400, body: 600 * 1024,
+ field: 40, diagnostics: 48_000, problems: 20, problemChars: 300, performanceLines: 40, performanceChars: 1_200, logLines: 80, logLineChars: 400, body: 600 * 1024,
} as const;
/** The fields today's Admin reads for the person's address, and the reply-to one it is gaining; it ignores fields it
@@ -65,6 +65,8 @@ export interface DevsReportInput {
/** Why no bot wrote a summary. */
noSummary?: string;
problems: string[];
+ /** Turn timings, usage limits and process use: numbers, fixed codes and opaque ids only. */
+ performance?: string[];
log: string[];
/** One line per cloud computer used since the server started: its opaque id and counts, nothing it ran. */
cloudComputers?: string[];
@@ -154,6 +156,7 @@ function diagnose(input: DevsReportInput, redact: (text: string) => string): str
const problems = input.problems.slice(-DEVS_REPORT_LIMITS.problems).map((line) => oneLine(redact(line), DEVS_REPORT_LIMITS.problemChars));
lines.push(...(problems.length ? problems : ["(none)"]));
if (input.cloudComputers?.length) lines.push("", "## Cloud computers since the server started", ...input.cloudComputers.slice(0, DEVS_REPORT_LIMITS.problems).map((line) => oneLine(redact(line), DEVS_REPORT_LIMITS.problemChars)));
+ if (input.performance?.length) lines.push("", ...input.performance.slice(0, DEVS_REPORT_LIMITS.performanceLines).map((line) => oneLine(redact(line), DEVS_REPORT_LIMITS.performanceChars)));
lines.push("", "## Server warnings and errors, newest last");
const log = input.log.slice(-DEVS_REPORT_LIMITS.logLines).map((line) => oneLine(redact(line), DEVS_REPORT_LIMITS.logLineChars));
lines.push(...(log.length ? log : ["(none since the server started)"]));
diff --git a/server/engine-memory.ts b/server/engine-memory.ts
index 21f55450a5..792effcd0a 100644
--- a/server/engine-memory.ts
+++ b/server/engine-memory.ts
@@ -266,6 +266,9 @@ export class EngineMemory {
this.arm();
}
+ /** The engine processes tracked now, with the threads each runs: for the performance sampler's buckets. */
+ enginePids(): Array<{ pid: number; threads: string[] }> { return [...this.engines].map(([pid, engine]) => ({ pid, threads: [...engine.threads] })); }
+
/** A thread's session now runs in this already tracked engine process. */
attach(child: ChildProcess, threadId: string): void {
if (child.pid) this.engines.get(child.pid)?.threads.add(threadId);
diff --git a/server/host/devs-reports.ts b/server/host/devs-reports.ts
index bb526617b9..5dad5e7985 100644
--- a/server/host/devs-reports.ts
+++ b/server/host/devs-reports.ts
@@ -111,6 +111,8 @@ export interface DevsReportsDeps {
/** The language a line for this person is written in; absent, the one set on this server. */
lineLanguage?: LineLanguage;
recentLog: RecentLog;
+ /** Timing lines for these conversations and bots: numbers, fixed codes and opaque ids only. */
+ performance?(filter: { threadIds: readonly string[]; botIds: readonly string[] }): string[];
send(payload: DevsReportPayload): Promise<SendOutcome>;
/** Asks the MausBot team about reports this app sent (devs-report-send.ts `askReportStatus`); null: no answer this time. */
askStatus(question: ReportStatusQuestion): Promise<ReportStatusAnswer | null>;
@@ -170,6 +172,10 @@ function withoutPastes(message: string): string {
const TURN_NOTE = "\n\n[From OpenMausBot, not the person: this message tags @devs, so it is a bug report for the MausBot team, OpenMausBot's developers. Call report_bug once, first: what the person says went wrong; what you saw yourself in this conversation (errors, failed tools, stuck steps), or that you saw nothing unusual; and steps to reproduce. Leave out passwords, keys, tokens and file contents; OpenMausBot adds the app's own diagnostics. Then tell the person, word for word, the line report_bug returns, and help with the problem if you can.]";
const iso = (at: number) => new Date(at).toISOString();
+/** The report goes out even when the timings fail: their lines, or one saying they are missing. */
+function performanceLines(read: NonNullable<DevsReportsDeps["performance"]>, threadId: string, botIds: string[]): string[] {
+ try { return read({ threadIds: [threadId], botIds }); } catch { return ["## Performance", "(timings unavailable)"]; }
+}
const firstLine = (text: string | undefined) => (text ?? "").split("\n").map((line) => line.trim()).find(Boolean) ?? "";
/** What went wrong in this conversation lately, as rows the server wrote: failed turns, failed tools, stops, notices. */
@@ -350,6 +356,7 @@ export function createDevsReports(deps: DevsReportsDeps) {
bots: bots.map((bot) => reported(bot, entry.threadId)),
...("bot" in author ? { summary: { by: author.bot.name, text: author.summary } } : { noSummary: author.why }),
problems: conversationProblems(store.activePath(entry.threadId)), log: deps.recentLog(), cloudComputers: cloudComputerCounters.lines(), contactEmail: contact,
+ ...(deps.performance ? { performance: performanceLines(deps.performance, entry.threadId, bots.map((bot) => bot.id)) } : {}),
}, secrets());
return { payload, ...(contact ? { contact } : {}) };
}
diff --git a/server/index.ts b/server/index.ts
index ba50e85191..1f914167ea 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -646,7 +646,7 @@ import { createPersonReplies } from "./person-replies.ts";
import { lendingPerson, lendingPersonKey, personKey, relayedPersonKey } from "./person-key.ts";
import { createOutsideLineage, OUTSIDE_STAYS_HERE } from "./host/outside-lineage.ts"; import { OUTSIDE_REFUSAL, outsideRouteRefused } from "./host/outside-fence.ts"; import { createOutsideWrites } from "./host/outside-writes.ts";
import { teamAiOwner } from "./host/team-ai-owner.ts"; import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { createTeamAwayHost } from "./host/team-away-host.ts"; import { createPlaceInbox, guestNameIn, placeInboxViewer } from "./host/place-inbox.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";
-import { createDevsReports } from "./host/devs-reports.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";
+import { createDevsReports } from "./host/devs-reports.ts"; import { createPerfHost } from "./perf/perf-host.ts"; import { createPerfDiagnosticsRoutes } from "./routes/perf-diagnostics.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";
import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { selfThreadRefusal } from "./host/self-threads.ts"; import { lookedAfterBy } from "./host/looked-after.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts"; import { createTurnCallSignals } from "./host/turn-call-signals.ts";
import { createThreadRoutes } from "./routes/threads.ts";
import { createWebhookRoutes } from "./routes/webhooks.ts";
@@ -2085,7 +2085,7 @@ function settleDirectFollowup(generation: string | undefined, outcome: DirectTur
const directTurnBots = new Map<string, BotRecord>();
const turnPromptBytes = new Map<string, { stable: number; volatile: number }>();
let providerFleetReloading = false;
-const turnResources = new TurnResources(); engineMemory.useTurnOrder(createTurnOrder({ turn: (threadId) => directRequestOwners.get(threadId), unattended: (threadId) => isUnattended(store.botByThread(threadId)?.id, threadId), running: (threadId) => coordinator.runningIn(threadId), roomLine: (threadId) => [...(groupTurnOperations.get(store.groupByThread(threadId)?.id ?? "") ?? [])].some((operation) => operation.threadId === threadId && operation.requestMessageId !== undefined) })); const waitWords = createWaitWords({ language: (threadId) => threadLanguage(threadId), starter: () => cloudPlanTier.starter(), held: (threadId, why) => coordinator.held(threadId, why), changed: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useWaits(waitWords);
+const turnResources = new TurnResources(); engineMemory.useTurnOrder(createTurnOrder({ turn: (threadId) => directRequestOwners.get(threadId), unattended: (threadId) => isUnattended(store.botByThread(threadId)?.id, threadId), running: (threadId) => coordinator.runningIn(threadId), roomLine: (threadId) => [...(groupTurnOperations.get(store.groupByThread(threadId)?.id ?? "") ?? [])].some((operation) => operation.threadId === threadId && operation.requestMessageId !== undefined) })); const waitWords = createWaitWords({ language: (threadId) => threadLanguage(threadId), starter: () => cloudPlanTier.starter(), held: (threadId, why) => { coordinator.held(threadId, why); perf.noteHeld(threadId, why.startsWith("plan") ? "plan-limit" : "memory"); }, changed: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useWaits(waitWords);
const sharedComputerControl = new SharedComputerControl(turnResources, (owner) => store.botByThread(owner.threadId)?.name);
const phoneHold = createPhoneHold({ onChange: (held) => { phoneGate.holdChanged(held); phoneScreen.holdChanged(held); } });
const phoneGate = createPhoneGate({ enabled: usbPhoneTakeoverOn, hold: phoneHold, resources: turnResources, claim: claimTurnResource }); onConfigSaved((_before, after) => endHoldUnlessOn(phoneHold, after));
@@ -2830,7 +2830,7 @@ const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPers
const imageTools = createImageToolRoutes({ config: () => cfg, dataDir: DATA_DIR, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });
const noAiNotice = createNoAiNotice({ team: CLOUD_TEAM, dataDir: DATA_DIR, people: () => teamOwners.people?.list() ?? [], personName: teamHost.personName, inbox: () => teamMessages.inbox, language: personLanguages.forLine, threadLanguage: conversationLanguage });
const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });
-const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });
+const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), wholeMachine: Boolean(CLOUD_HOME) }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });
const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,
defaults: () => [cfg.defaultModelSelection, cfg.newBotDefaults?.profile.modelSelection], engineName: id => registry.get(id)?.displayName ?? id,
log: line => console.warn(line) });
@@ -2848,7 +2848,7 @@ const phones = createPhones({
active: (turn) => internalCapabilityIsActive(turn as InternalCapability),
});
const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterAwake = createStarterAwake({ dataDir: DATA_DIR, starter: () => cloudPlanTier.starter(), bots: () => store.bots, changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterCaps = createStarterCaps({ starter: () => cloudPlanTier.starter(), awake: starterAwake, waitsOnOthers: (threadId) => coordinator.outstandingFor(threadId).length > 0, laneOwned: (threadId) => burst.laneOwned(threadId), botName: (botId) => store.bot(botId)?.name, pausedLine: (language, limit) => serverLine(language, "server.botPaused", { limit }), refused: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useCap(starterCaps.engine); const botHolds = createBotHolds({ dataDir: DATA_DIR, bots: () => store.bots, line: (language, key, params) => serverLine(language, key, params), changed: () => broadcast({ kind: "config", ...configStatus() }) }); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.
-const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,
+const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, perf: perf.health, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,
engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),
connectors: () => emailHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),
browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.dayPressure() } : {}) } });
@@ -8513,7 +8513,7 @@ async function beginTurn(
drainQueuedSends();
}
} catch (cause) {
- let e = cause;
+ let e = cause; perf.noteNotStarted(threadId, cause instanceof TurnNotStartedError ? cause.turnId : null, cause instanceof TurnUsageLimitRefusedError ? { limit: cause.scope, engine: registry.get(instanceId)?.driverKind ?? null, resetsAt: cause.resetsAt } : cause instanceof TurnAuthenticationRefusedError ? { signedOut: true } : {});
// Only the driver can prove a task was never submitted; an error string is not that proof.
const mayRecover = e instanceof TurnNotStartedError &&
directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId);
@@ -8775,7 +8775,7 @@ async function stopBotForEmergencyApprovalDowngrade(botId: string): Promise<void
const engineName = (engine: string) => engineLabel(engine, registry.get(engine) ?? undefined);
const limitClock = new LimitResetClock({ file: join(DATA_DIR, "limit-holds.json"), accounts: () => planAccountsFromInstances(instanceConfigs(cfg)), onChange: () => routines?.retimeLimitResets(),
- waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")) }); const limitTakeover = createLimitTakeover({ file: join(DATA_DIR, "limit-notices.json"), holdsFile: join(DATA_DIR, "limit-takeover-holds.json"), configs: () => instanceConfigs(cfg), context: selectionContext, blockedUntil: (engine) => limitClock.blockedUntil(engine), resetAt: (engine) => limitClock.resetAt(engine), enabled: () => quotaSwitchEnabled(), where: CLOUD_HOME ? "on the Cloud" : "on this computer", signedOutNow: (id) => registry.knownSnapshot(id)?.authenticated === false, signedOutNoticed: () => registry.forgetSnapshots(), botsOn: (id) => store.bots.filter((bot) => !bot.hidden && bot.modelSelection.instanceId === id), engineName, engines: () => selectableInstances(registry.instances().map((engine) => ({ instanceId: engine.instanceId, driverKind: engine.driverKind, displayName: engine.displayName, enabled: engine.enabled, access: registry.access(engine.instanceId), models: engine.models, snapshot: registry.knownSnapshot(engine.instanceId) ?? { state: "unavailable" as const, reason: "not read yet" }, capabilities: engine.adapter.capabilities }))), chosen: (botId) => [...(store.bot(botId)?.fallback ?? []), ...(cfg.automaticRecovery?.backup ? [cfg.automaticRecovery.backup] : [])], signedOutChosen: (botId) => { const bot = store.bot(botId); return bot ? startupBackups(bot, cfg.automaticRecovery) : []; }, tell: (about, text) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), record: (failover) => limitFailovers.record(failover) }); registry.onSignedIn((instanceId) => limitTakeover.signedIn(instanceId));
+ waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")) }); const limitTakeover = createLimitTakeover({ file: join(DATA_DIR, "limit-notices.json"), holdsFile: join(DATA_DIR, "limit-takeover-holds.json"), configs: () => instanceConfigs(cfg), context: selectionContext, blockedUntil: (engine) => limitClock.blockedUntil(engine), resetAt: (engine) => limitClock.resetAt(engine), enabled: () => quotaSwitchEnabled(), where: CLOUD_HOME ? "on the Cloud" : "on this computer", signedOutNow: (id) => registry.knownSnapshot(id)?.authenticated === false, signedOutNoticed: () => registry.forgetSnapshots(), botsOn: (id) => store.bots.filter((bot) => !bot.hidden && bot.modelSelection.instanceId === id), engineName, engines: () => selectableInstances(registry.instances().map((engine) => ({ instanceId: engine.instanceId, driverKind: engine.driverKind, displayName: engine.displayName, enabled: engine.enabled, access: registry.access(engine.instanceId), models: engine.models, snapshot: registry.knownSnapshot(engine.instanceId) ?? { state: "unavailable" as const, reason: "not read yet" }, capabilities: engine.adapter.capabilities }))), chosen: (botId) => [...(store.bot(botId)?.fallback ?? []), ...(cfg.automaticRecovery?.backup ? [cfg.automaticRecovery.backup] : [])], signedOutChosen: (botId) => { const bot = store.bot(botId); return bot ? startupBackups(bot, cfg.automaticRecovery) : []; }, tell: (about, text) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), record: (failover) => { limitFailovers.record(failover); perf.noteFailover(failover.threadId, failover.why === "signed-out" ? "signed-out" : "limit"); } }); registry.onSignedIn((instanceId) => limitTakeover.signedIn(instanceId));
const limitFailovers = new LimitFailovers({ file: join(DATA_DIR, "limit-failovers.json"), blockedUntil: (engine) => limitClock.blockedUntil(engine), signedOut: (engine) => limitTakeover.stillSignedOut(engine), engineName,
threadModel: (botId, threadId) => store.projectBotForTask(botId, threadId)?.modelSelection ?? null,
note: (threadId, line, text) => store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${line}`, ok: true, ...(text ? { nameCode: text.key, nameParams: text.params } : {}) } }),
@@ -9491,7 +9491,7 @@ const appTriggers = createAppTriggerHost({ store, webhooks, webhookBase: () => w
audit: (row) => appendDecision(DATA_DIR, { ...row, decision: "auto-approved", source: "routine" }) });
tieAutomationsToBots(store, { routines: routines!, webhooks, apps: appTriggers.manager, waits: botWaits });
ROUTES.push(appTriggers.routes); ROUTES.unshift(createMoveFreezeRoutes({ freeze: moveFreeze, automationsOff: () => switchAutomationsOff({ routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }), restart: () => { restartRequested = true; gracefulShutdown(); }, busy: createMoveWaits({ bots: () => store.bots, rooms: () => store.groups, answering: (id) => watchdog.answering(id), turn: botHasActiveTurn, runs: () => routines?.listRuns() ?? [], roomWorking: (id) => { const group = store.group(id); return Boolean(group && groupIsWorking(group)); }, handoffs: () => coordinator.active(), exists: (node) => !(!node.parentId && node.groupId ? roomRootProblem(node) : roomHandoffProblem(node)), signingIn: () => providerAuthSessions.active }) }));
-ROUTES.push(createLimitResetRoutes({ clock: limitClock, routines: routines!, requests: routineRequests, engineName, threadEngine: (botId, threadId) => turnSelection(botId, threadId)?.instanceId,
+ROUTES.push(createPerfDiagnosticsRoutes({ text: perf.text })); ROUTES.push(createLimitResetRoutes({ clock: limitClock, routines: routines!, requests: routineRequests, engineName, threadEngine: (botId, threadId) => turnSelection(botId, threadId)?.instanceId,
threadTitle: (botId, threadId) => store.bot(botId) && !store.bot(botId)!.hidden ? store.taskByThread(botId, threadId)?.title ?? null : null,
created: (id, auth) => cloudRoutineAuthors?.wrote(id, auth.kind === "session" ? actorKey(auth) : CLOUD_NOBODY_KEY) }));
@@ -15407,7 +15407,7 @@ const gracefulShutdown = createGracefulShutdown({
() => flushAllMemoryJournals(),
() => flushUsageLedger(DATA_DIR),
() => flushDecisionLog(DATA_DIR),
- () => flushAdminActivity(DATA_DIR),
+ () => flushAdminActivity(DATA_DIR), () => perf.stop(),
() => bus.flush(),
() => closeMessageSearch(),
],
diff --git a/server/perf/day-ledger.ts b/server/perf/day-ledger.ts
new file mode 100644
index 0000000000..820bb88aeb
--- /dev/null
+++ b/server/perf/day-ledger.ts
@@ -0,0 +1,156 @@
+// The last day of turn timings by hour: one histogram per phase and per tool kind, and counts. Bounded at 25 hours of
+// fixed-size slots whatever the traffic.
+import { addTo, countOf, emptyHistogram, histogramQuantile, mergeInto, parseHistogram, PHASES, type Histogram, type Phase, type PhaseStats } from "./phases.ts";
+import { activeMs, counter, isLimitScope, isRetryCode, isToolKind, KIND, type LimitScope, type ToolKind, type TurnTiming } from "./turn-record.ts";
+
+const HOUR = 3_600_000;
+export const DAY_HOURS = 24;
+/** A turn counts as slow past each of these (ms) of its time less any wait on a person. */
+export const SLOW_TURN_MS = [60_000, 300_000, 900_000] as const;
+const REASONS_KEPT = 12, LIMIT_KEYS_KEPT = 12;
+
+interface ToolSlot { hist: Histogram; errors: number; open: number }
+interface Slot {
+ hour: number;
+ turns: number;
+ failed: number;
+ slow: number[];
+ phases: Partial<Record<Phase, Histogram>>;
+ tools: Partial<Record<ToolKind, ToolSlot>>;
+ retries: { turns: number; n: number; backoffMs: number; why: Record<string, number> };
+ /** Turns a usage limit refused, by `<engine kind>:<scope>`. */
+ limits: Record<string, number>;
+ failovers: number;
+}
+
+const emptySlot = (hour: number): Slot => ({ hour, turns: 0, failed: 0, slow: SLOW_TURN_MS.map(() => 0), phases: {}, tools: {},
+ retries: { turns: 0, n: 0, backoffMs: 0, why: counter() }, limits: counter(), failovers: 0 });
+
+const bump = (map: Record<string, number>, key: string, cap: number, by = 1) => {
+ if (!Object.hasOwn(map, key) && Object.keys(map).length >= cap) key = "other";
+ map[key] = (map[key] ?? 0) + by;
+};
+
+export interface ToolAggregate { kind: ToolKind; n: number; errors: number; open: number; ms: number; p95: number; max: number }
+export interface DayAggregate {
+ turns: number;
+ failed: number;
+ phases: Partial<Record<Phase, PhaseStats>>;
+ slow: number[];
+ tools: ToolAggregate[];
+ retries: { turns: number; n: number; backoffMs: number; why: Record<string, number> };
+ limits: Record<string, number>;
+ failovers: number;
+}
+
+const statsOf = (histogram: Histogram): PhaseStats =>
+ ({ p50: histogramQuantile(histogram, 0.5), p95: histogramQuantile(histogram, 0.95), max: histogram.max, n: countOf(histogram) });
+
+export function createDayLedger(now: () => number) {
+ const slots = new Map<number, Slot>();
+ const slot = (at: number): Slot => {
+ const hour = Math.floor(at / HOUR);
+ let found = slots.get(hour);
+ if (!found) {
+ found = emptySlot(hour);
+ slots.set(hour, found);
+ for (const key of slots.keys()) if (key <= hour - DAY_HOURS) slots.delete(key);
+ }
+ return found;
+ };
+
+ return {
+ noteTool(kind: ToolKind, ms: number, ok: boolean, open: boolean, at = now()) {
+ const tools = slot(at).tools;
+ const entry = tools[kind] ??= { hist: emptyHistogram(), errors: 0, open: 0 };
+ addTo(entry.hist, ms);
+ if (!ok) entry.errors += 1;
+ if (open) entry.open += 1;
+ },
+ noteTurn(turn: TurnTiming) {
+ const into = slot(turn.endedAt);
+ into.turns += 1;
+ if (!turn.ok) into.failed += 1;
+ for (const phase of PHASES) {
+ const ms = turn.ms[phase];
+ if (ms !== undefined) addTo(into.phases[phase] ??= emptyHistogram(), ms);
+ }
+ const active = activeMs(turn);
+ SLOW_TURN_MS.forEach((edge, index) => { if (active > edge) into.slow[index]! += 1; });
+ if (turn.retries) {
+ into.retries.turns += 1; into.retries.n += turn.retries; into.retries.backoffMs += turn.backoffMs;
+ for (const why of turn.retryWhy ?? []) bump(into.retries.why, why, REASONS_KEPT);
+ }
+ if (turn.limit) bump(into.limits, `${turn.engine ?? "unknown"}:${turn.limit}`, LIMIT_KEYS_KEPT);
+ if (turn.failover) into.failovers += 1;
+ },
+ /** A usage limit refused a turn before it started: no turn to time, but the refusal counts. */
+ noteRefusal(engine: string | null, scope: LimitScope, at = now()) {
+ bump(slot(at).limits, `${engine ?? "unknown"}:${scope}`, LIMIT_KEYS_KEPT);
+ },
+ read(windowMs: number = DAY_HOURS * HOUR): DayAggregate {
+ const from = Math.floor((now() - windowMs) / HOUR);
+ const phases: Partial<Record<Phase, Histogram>> = {};
+ const tools: Partial<Record<ToolKind, ToolSlot>> = {};
+ const out: DayAggregate = { turns: 0, failed: 0, phases: {}, slow: SLOW_TURN_MS.map(() => 0), tools: [],
+ retries: { turns: 0, n: 0, backoffMs: 0, why: counter() }, limits: counter(), failovers: 0 };
+ for (const entry of slots.values()) {
+ if (entry.hour <= from) continue;
+ out.turns += entry.turns; out.failed += entry.failed; out.failovers += entry.failovers;
+ entry.slow.forEach((count, index) => { out.slow[index]! += count; });
+ for (const [phase, histogram] of Object.entries(entry.phases) as Array<[Phase, Histogram]>) mergeInto(phases[phase] ??= emptyHistogram(), histogram);
+ for (const [kind, tool] of Object.entries(entry.tools) as Array<[ToolKind, ToolSlot]>) {
+ const into = tools[kind] ??= { hist: emptyHistogram(), errors: 0, open: 0 };
+ mergeInto(into.hist, tool.hist); into.errors += tool.errors; into.open += tool.open;
+ }
+ out.retries.turns += entry.retries.turns; out.retries.n += entry.retries.n; out.retries.backoffMs += entry.retries.backoffMs;
+ for (const [why, count] of Object.entries(entry.retries.why)) bump(out.retries.why, why, REASONS_KEPT, count);
+ for (const [key, count] of Object.entries(entry.limits)) bump(out.limits, key, LIMIT_KEYS_KEPT, count);
+ }
+ for (const phase of PHASES) if (phases[phase]) out.phases[phase] = statsOf(phases[phase]);
+ out.tools = (Object.entries(tools) as Array<[ToolKind, ToolSlot]>)
+ .map(([kind, tool]) => ({ kind, n: countOf(tool.hist), errors: tool.errors, open: tool.open, ms: tool.hist.sum, p95: histogramQuantile(tool.hist, 0.95), max: tool.hist.max }))
+ .sort((left, right) => right.ms - left.ms);
+ return out;
+ },
+ save: (): Slot[] => [...slots.values()],
+ load(saved: unknown) {
+ if (!Array.isArray(saved)) return;
+ const oldest = Math.floor(now() / HOUR) - DAY_HOURS;
+ for (const raw of saved.slice(-DAY_HOURS - 1) as Array<Record<string, unknown>>) {
+ const parsed = parseSlot(raw);
+ if (parsed && parsed.hour > oldest) slots.set(parsed.hour, parsed);
+ }
+ },
+ };
+}
+export type DayLedger = ReturnType<typeof createDayLedger>;
+
+const whole = (value: unknown): number => (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0);
+const codes = (value: unknown, accept: (key: string) => boolean, cap: number): Record<string, number> => {
+ const out = counter();
+ for (const [key, count] of Object.entries((value && typeof value === "object" ? value : {}) as Record<string, unknown>).slice(0, cap)) {
+ if (accept(key)) out[key] = whole(count);
+ }
+ return out;
+};
+const limitKey = (key: string) => key === "other" || (isLimitScope(key.slice(key.lastIndexOf(":") + 1)) && KIND.test(key.slice(0, key.lastIndexOf(":"))));
+const reasonKey = (key: string) => isRetryCode(key);
+
+function parseSlot(raw: Record<string, unknown> | null): Slot | null {
+ if (!raw || typeof raw !== "object" || !Number.isSafeInteger(raw.hour)) return null;
+ const slot = emptySlot(raw.hour as number);
+ slot.turns = whole(raw.turns); slot.failed = whole(raw.failed); slot.failovers = whole(raw.failovers);
+ if (Array.isArray(raw.slow)) slot.slow = SLOW_TURN_MS.map((_, index) => whole((raw.slow as unknown[])[index]));
+ for (const phase of PHASES) {
+ const value = (raw.phases as Record<string, unknown> | undefined)?.[phase];
+ if (value) slot.phases[phase] = parseHistogram(value);
+ }
+ for (const [kind, value] of Object.entries((raw.tools ?? {}) as Record<string, Record<string, unknown>>)) {
+ if (isToolKind(kind) && value) slot.tools[kind] = { hist: parseHistogram(value.hist), errors: whole(value.errors), open: whole(value.open) };
+ }
+ const retries = (raw.retries ?? {}) as Record<string, unknown>;
+ slot.retries = { turns: whole(retries.turns), n: whole(retries.n), backoffMs: whole(retries.backoffMs), why: codes(retries.why, reasonKey, REASONS_KEPT) };
+ slot.limits = codes(raw.limits, limitKey, LIMIT_KEYS_KEPT);
+ return slot;
+}
diff --git a/server/perf/perf-host.test.ts b/server/perf/perf-host.test.ts
new file mode 100644
index 0000000000..8607647897
--- /dev/null
+++ b/server/perf/perf-host.test.ts
@@ -0,0 +1,123 @@
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import type { EngineLimitsReport } from "../../shared/limit-reset.ts";
+import type { RuntimeEvent } from "../contracts.ts";
+import { createPerfDiagnosticsRoutes, PERF_DIAGNOSTICS_PATH } from "../routes/perf-diagnostics.ts";
+import { PASS, type RouteContext } from "../routes/table.ts";
+import { createPerfHost, LOG_EVERY_MS, PERF_FILE, PERF_UNAVAILABLE, rateLimitedLog } from "./perf-host.ts";
+import { createProcessSampler } from "./process-sampler.ts";
+
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+describe("slow-event log lines", () => {
+ it("prints one line per kind a minute and counts the ones held back", () => {
+ let clock = 0;
+ const lines: string[] = [];
+ const say = rateLimitedLog((line) => lines.push(line), () => clock);
+ say("turn", "a");
+ say("turn", "b");
+ say("tool", "c");
+ clock += LOG_EVERY_MS;
+ say("turn", "d");
+ expect(lines).toEqual(["[perf] a", "[perf] c", "[perf] d (+1 more since the last)"]);
+ });
+
+ it("says when a usage-limit hold starts and ends, and reads no limits before the limit clock exists", () => {
+ const dir = mkdtempSync(join(tmpdir(), "perf-host-"));
+ dirs.push(dir);
+ let clock = 1_800_000_000_000;
+ let limits: EngineLimitsReport | null = null;
+ const lines: string[] = [];
+ const sampler = createProcessSampler({ list: () => null, intervalMs: 60_000, scope: "tree", now: () => clock });
+ const host = createPerfHost({
+ dataDir: dir, timer: false, sampler, wholeMachine: false, now: () => clock, log: (line) => lines.push(line),
+ limits: () => { if (!limits) throw new ReferenceError("not made yet"); return limits; },
+ bus: { subscribe: () => () => {} }, store: { onChange: () => () => {}, botByThread: () => null },
+ });
+ expect(host.health()?.holds).toEqual([]);
+ host.checkHolds();
+ limits = { checkedAt: clock, engines: [{ engine: "claude-2", name: "Ada's Claude", driver: "claude", window: "weekly", usedPercent: 100, resetsAt: clock + 3_600_000, blocked: true }] };
+ expect(host.health()?.holds).toEqual([{ driver: "claude", window: "weekly", usedPercent: 100, resetsAt: clock + 3_600_000, blocked: true, held: false }]);
+ expect(host.text()).toContain("Usage limits now: claude weekly 100% refusing work until");
+ host.checkHolds();
+ host.checkHolds();
+ clock += LOG_EVERY_MS;
+ limits = { checkedAt: clock, engines: [] };
+ host.checkHolds();
+ expect(lines).toEqual(["[perf] usage limit hold started: claude:weekly", "[perf] usage limit hold ended: claude:weekly"]);
+ host.stop();
+ });
+});
+
+describe("the host's guard rails", () => {
+ it("saves the turns since the last write when the server shuts down", () => {
+ const dir = mkdtempSync(join(tmpdir(), "perf-host-"));
+ dirs.push(dir);
+ const listeners: Array<(event: RuntimeEvent) => void> = [];
+ const sampler = createProcessSampler({ list: () => null, intervalMs: 60_000, scope: "tree" });
+ const host = createPerfHost({ dataDir: dir, timer: false, sampler, wholeMachine: false, log: () => {},
+ bus: { subscribe: (listener) => { listeners.push(listener); return () => {}; } }, store: { onChange: () => () => {}, botByThread: () => null } });
+ host.timings.flush();
+ for (const type of ["turn.started", "turn.completed"]) for (const listener of listeners) listener({ eventId: "e", provider: "codex", threadId: "th_1", createdAt: "", turnId: "tu_1", type, ok: true } as RuntimeEvent);
+ expect(JSON.parse(readFileSync(join(dir, PERF_FILE), "utf8")).ring).toEqual([]);
+ host.stop();
+ expect(JSON.parse(readFileSync(join(dir, PERF_FILE), "utf8")).ring).toMatchObject([{ turnId: "tu_1", threadId: "th_1" }]);
+ });
+
+ it("a recorder that throws costs a log line, never its caller: no event, report or export fails, on every platform", () => {
+ const dir = mkdtempSync(join(tmpdir(), "perf-host-"));
+ dirs.push(dir);
+ const lines: string[] = [];
+ const listeners: Array<(event: RuntimeEvent) => void> = [];
+ // The view builder itself fails: a limits report whose engines cannot be read, which every view reads on every platform.
+ const unreadable = { checkedAt: 0, get engines(): EngineLimitsReport["engines"] { throw new RangeError("x"); } };
+ const sampler = createProcessSampler({ list: () => null, intervalMs: 60_000, scope: "tree" });
+ const host = createPerfHost({ dataDir: dir, timer: false, sampler, wholeMachine: false, log: (line) => lines.push(line), limits: () => unreadable,
+ bus: { subscribe: (listener) => { listeners.push(listener); return () => {}; } }, store: { onChange: () => () => {}, botByThread: () => { throw new Error("store"); } } });
+ expect(() => listeners[0]!({ eventId: "e", provider: "codex", threadId: "th_1", createdAt: "", turnId: "tu_1", type: "turn.started" } as RuntimeEvent)).not.toThrow();
+ expect(host.health()).toBeNull();
+ expect(host.lines({ threadIds: [], botIds: [] })).toEqual(PERF_UNAVAILABLE);
+ expect(host.text()).toBe(PERF_UNAVAILABLE.join("\n"));
+ expect(host.health()).toBeNull();
+ expect(lines).toEqual(["[perf] the performance recorder failed (event): Error", "[perf] the performance recorder failed (health): RangeError",
+ "[perf] the performance recorder failed (lines): RangeError", "[perf] the performance recorder failed (text): RangeError"]);
+ });
+
+ it("a sampler that throws leaves out the health read where it runs, and is a clean no-op on Windows", () => {
+ const dir = mkdtempSync(join(tmpdir(), "perf-host-"));
+ dirs.push(dir);
+ const lines: string[] = [];
+ const broken = { report: () => { throw new RangeError("x"); }, start() {}, stop() {}, sampleNow: async () => {} } as unknown as ReturnType<typeof createProcessSampler>;
+ const host = createPerfHost({ dataDir: dir, timer: false, sampler: broken, wholeMachine: false, log: (line) => lines.push(line),
+ bus: { subscribe: () => () => {} }, store: { onChange: () => () => {}, botByThread: () => null } });
+ if (process.platform === "win32") {
+ expect(host.health()).toMatchObject({ v: 1, process: null });
+ expect(host.text()).toContain("Processes: not sampled yet");
+ expect(lines).toEqual([]);
+ } else {
+ expect(host.health()).toBeNull();
+ expect(host.text()).toBe(PERF_UNAVAILABLE.join("\n"));
+ expect(lines).toEqual(["[perf] the performance recorder failed (health): RangeError", "[perf] the performance recorder failed (text): RangeError"]);
+ }
+ });
+});
+
+describe("GET /api/diagnostics/performance", () => {
+ it("answers with the text and passes every other request on", async () => {
+ const route = createPerfDiagnosticsRoutes({ text: () => "## Performance\nLast hour: 0 turns" });
+ const sent: Array<{ status: number; body: unknown }> = [];
+ const headers: Record<string, string> = {};
+ const context = (path: string, method = "GET") => ({
+ path, method, res: { setHeader: (name: string, value: string) => { headers[name] = value; } },
+ json: (_res: unknown, status: number, body: unknown) => { sent.push({ status, body }); },
+ }) as unknown as RouteContext;
+ expect(await route(context("/api/limit-resets"))).toBe(PASS);
+ expect(await route(context(PERF_DIAGNOSTICS_PATH, "POST"))).toBe(PASS);
+ await route(context(PERF_DIAGNOSTICS_PATH));
+ expect(sent).toEqual([{ status: 200, body: { text: "## Performance\nLast hour: 0 turns" } }]);
+ expect(headers["cache-control"]).toBe("no-store");
+ });
+});
diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.ts
new file mode 100644
index 0000000000..70ed8a440a
--- /dev/null
+++ b/server/perf/perf-host.ts
@@ -0,0 +1,109 @@
+// The server's one performance recorder: turn timings from the bus and the store, the process sampler, rate-limited log
+// lines for slow events, and the views the health read, a @devs report and the desktop's diagnostics take from them.
+import { join } from "node:path";
+
+import type { EngineLimitsReport } from "../../shared/limit-reset.ts";
+import type { RuntimeEvent } from "../contracts.ts";
+import type { StoreChange } from "../store.ts";
+import { duration, limitHolds, perfHealth, perfLines, turnLine, type PerfHealth } from "./perf-report.ts";
+import { createProcessSampler, linuxProcessList, LINUX_SAMPLE_MS, nodeUtilization, OTHER_SAMPLE_MS, psProcessList, type ProcessSampler } from "./process-sampler.ts";
+import type { FailoverWhy } from "./turn-record.ts";
+import { createTurnTimings, type Refusal, type SlowNote, type TurnTimings } from "./turn-timings.ts";
+
+export const PERF_FILE = "perf-timings.json";
+/** One line per kind of slow event at most this often; the ones held back are counted on the next. */
+export const LOG_EVERY_MS = 60_000;
+const RECENT_IN_REPORT = 10;
+
+export interface PerfHostDeps {
+ dataDir: string;
+ bus: { subscribe(listener: (event: RuntimeEvent) => void): () => void };
+ store: { onChange(listener: (change: StoreChange) => void): () => void; botByThread(threadId: string): { id: string } | null };
+ /** The limit clock's report, once it exists. */
+ limits?: () => EngineLimitsReport | null | undefined;
+ /** A Cloud home's machine is all its own: every process it shows is sampled. Elsewhere only the server's own tree. */
+ wholeMachine: boolean;
+ log?: (line: string) => void;
+ /** Tests: no sampler timer. */
+ timer?: false;
+ now?: () => number;
+ sampler?: ProcessSampler;
+ /** The engine processes the server tracks, with the threads each runs (engine-memory, on a Cloud home). */
+ engines?: () => ReadonlyArray<{ pid: number; threads: readonly string[] }>;
+}
+
+/** What a report shows when the recorder failed: diagnostics never fail because of it. */
+export const PERF_UNAVAILABLE = ["## Performance", "(timings unavailable: the recorder failed; see the server log)"];
+
+/** A log line per kind at most every LOG_EVERY_MS. */
+export function rateLimitedLog(log: (line: string) => void, now: () => number) {
+ const last = new Map<string, { at: number; held: number }>();
+ return (kind: string, line: string) => {
+ const entry = last.get(kind);
+ if (entry && now() - entry.at < LOG_EVERY_MS) { entry.held += 1; return; }
+ log(`[perf] ${line}${entry?.held ? ` (+${entry.held} more since the last)` : ""}`);
+ last.set(kind, { at: now(), held: 0 });
+ };
+}
+
+export function slowLine(note: SlowNote, now: number): string {
+ if (note.kind === "turn") return `slow turn ${turnLine(note.turn)}`;
+ if (note.kind === "tool") return `slow tool call: ${note.tool} ${duration(note.ms)} ${note.ok ? "ok" : "failed or left open"} engine ${note.engine ?? "?"} bot ${note.botId ?? "?"} thread ${note.threadId ?? "?"}`;
+ return `usage limit refused a turn: engine ${note.engine ?? "?"} scope ${note.scope}${note.resetsAt ? ` resets in ${duration(Math.max(0, note.resetsAt - now))}` : ""}`;
+}
+
+export function createPerfHost(deps: PerfHostDeps) {
+ const now = deps.now ?? Date.now;
+ const say = rateLimitedLog(deps.log ?? ((line) => console.warn(line)), now);
+ const timings: TurnTimings = createTurnTimings({
+ file: join(deps.dataDir, PERF_FILE), now, botOf: (threadId) => deps.store.botByThread(threadId)?.id ?? null,
+ slow: (note) => say(note.kind, slowLine(note, now())),
+ });
+ /** Runs `read`, or logs once a minute and returns `fallback`: nothing the recorder does may fail its caller. */
+ const guarded = <T>(what: string, read: () => T, fallback: T): T => {
+ try { return read(); } catch (error) { say(`failed:${what}`, `the performance recorder failed (${what}): ${error instanceof Error ? error.name : "error"}`); return fallback; }
+ };
+ deps.store.onChange((change) => { if (change.type === "message") guarded("message", () => timings.noteMessage(change.threadId, change.message), undefined); });
+ deps.bus.subscribe((event) => guarded("event", () => timings.noteEvent(event), undefined));
+
+ /** The limit clock is made after this host; until it is, there are no limits to read. */
+ const limits = () => { try { return deps.limits?.() ?? null; } catch { return null; } };
+ let held = new Set<string>();
+ const watchHolds = () => {
+ const current = new Set(limitHolds(limits()).filter((hold) => hold.blocked).map((hold) => `${hold.driver}:${hold.window ?? "?"}`));
+ for (const key of current) if (!held.has(key)) say(`hold:${key}`, `usage limit hold started: ${key}`);
+ for (const key of held) if (!current.has(key)) say(`hold:${key}`, `usage limit hold ended: ${key}`);
+ held = current;
+ };
+ const enginePids = () => new Map((deps.engines?.() ?? []).map(({ pid, threads }) => [pid, threads.map(timings.engineOf).find((kind) => kind !== null) ?? "unknown"] as const));
+ const linux = process.platform === "linux", windows = process.platform === "win32";
+ const sampler = deps.sampler ?? createProcessSampler({
+ list: linux ? () => linuxProcessList() : psProcessList, intervalMs: linux ? LINUX_SAMPLE_MS : OTHER_SAMPLE_MS,
+ scope: deps.wholeMachine && linux ? "all" : "tree", utilization: nodeUtilization(), now, engines: enginePids,
+ stalled: (ms) => say("loop", `event loop stalled: the ${linux ? 60 : 300}s sampler fired ${duration(ms)} late`), afterSample: watchHolds,
+ });
+ if (deps.timer !== false && !windows) sampler.start();
+
+ const sources = () => ({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: limits(), process: windows ? null : sampler.report() });
+ return {
+ timings,
+ sampler,
+ noteHeld: (threadId: string, why: "plan-limit" | "memory") => guarded("held", () => timings.noteHeld(threadId, why), undefined),
+ noteFailover: (threadId: string, why: FailoverWhy) => guarded("failover", () => timings.noteFailover(threadId, why), undefined),
+ noteNotStarted: (threadId: string, turnId: string | null, refusal?: Refusal) => guarded("refused", () => timings.noteNotStarted(threadId, turnId, refusal), undefined),
+ /** Logs a usage-limit hold that started or ended since the last check; the sampler runs it after each sample. */
+ checkHolds: watchHolds,
+ health: (): PerfHealth | null => guarded("health", () => perfHealth(sources()), null),
+ /** For a @devs report: these conversations' and bots' latest turns, then everything else. */
+ lines(filter: { threadIds: readonly string[]; botIds: readonly string[] }): string[] {
+ return guarded("lines", () => perfLines(sources(), timings.recent({ ...filter, limit: RECENT_IN_REPORT }), "Latest turns in this conversation or of its bots, newest last:"), PERF_UNAVAILABLE);
+ },
+ /** For the desktop's diagnostics export: every bot's latest turns. */
+ text(): string {
+ return guarded("text", () => perfLines(sources(), timings.recent({ limit: RECENT_IN_REPORT }), "Latest turns, newest last:"), PERF_UNAVAILABLE).join("\n");
+ },
+ /** The graceful shutdown: no more samples, and the turns since the last save written now. */
+ stop() { sampler.stop(); guarded("save", () => timings.flush(), undefined); },
+ };
+}
+export type PerfHost = ReturnType<typeof createPerfHost>;
diff --git a/server/perf/perf-privacy.test.ts b/server/perf/perf-privacy.test.ts
new file mode 100644
index 0000000000..fe320dd1ec
--- /dev/null
+++ b/server/perf/perf-privacy.test.ts
@@ -0,0 +1,215 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import type { EngineLimitsReport } from "../../shared/limit-reset.ts";
+import { createCloudHealth } from "../cloud-health.ts";
+import type { RuntimeEvent } from "../contracts.ts";
+import { buildDevsReport } from "../devs-report.ts";
+import type { StoreChange } from "../store.ts";
+import { createPerfHost, PERF_FILE } from "./perf-host.ts";
+import { PERF_HEALTH_MAX_BYTES, perfHealth } from "./perf-report.ts";
+import { createProcessSampler, type ProcessList } from "./process-sampler.ts";
+import { createTurnTimings } from "./turn-timings.ts";
+
+const START = 1_800_000_000_000;
+const SECRETS = [
+ "sk-ant-api03-PRIVATEPRIVATEPRIVATE1234567890", "ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "hunter2-password", "[email protected]",
+ "/Users/ada/Projects/acme-merger/plan.md", "acme-merger", "https://intranet.acme.test/q?token=abc", "intranet.acme.test",
+ "Summarize the merger plan", "acme-internal", "Tallyspoon", "OMB_SECRET_VALUE_42", "lookup_customer", "Ada's Claude",
+];
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+async function seeded() {
+ let clock = START, mono = 0;
+ const dir = mkdtempSync(join(tmpdir(), "perf-privacy-"));
+ dirs.push(dir);
+ const busListeners = new Set<(event: RuntimeEvent) => void>(), storeListeners = new Set<(change: StoreChange) => void>();
+ const logged: string[] = [];
+ const lists: ProcessList[] = [];
+ const procRows = (cpu: number) => [
+ { pid: 100, ppid: 1, name: "node", cpuMs: cpu, rssBytes: 1e8, start: "a" },
+ { pid: 200, ppid: 100, name: "claude", cpuMs: cpu * 2, rssBytes: 3e8, start: "b" },
+ { pid: 201, ppid: 200, name: "/users/ada/projects/acme-merger/bin/sk-ant-api03-privateprivateprivate1234567890", cpuMs: cpu, rssBytes: 1e7, start: "c" },
+ { pid: 202, ppid: 200, name: "https://intranet.acme.test/q?token=abc", cpuMs: cpu, rssBytes: 1e7, start: "d" },
+ ];
+ const sampler = createProcessSampler({ list: () => lists.shift() ?? null, intervalMs: 60_000, scope: "tree", serverPid: 100, now: () => clock, monotonic: () => mono });
+ const limits: EngineLimitsReport = { checkedAt: START, engines: [
+ { engine: "[email protected]", name: "Ada's Claude", driver: "claude", window: "5-hour", usedPercent: 100, resetsAt: START + 7_200_000, blocked: true, held: true },
+ ] };
+ const perf = createPerfHost({
+ dataDir: dir, timer: false, now: () => clock, sampler, wholeMachine: false, limits: () => limits, log: (line) => logged.push(line),
+ bus: { subscribe: (listener) => { busListeners.add(listener); return () => busListeners.delete(listener); } },
+ store: { onChange: (listener) => { storeListeners.add(listener); return () => storeListeners.delete(listener); },
+ botByThread: (threadId) => ({ id: threadId === "thread_ok" ? "bot_ok" : "[email protected]" }) },
+ });
+ const emit = (threadId: string, event: Record<string, unknown>) => {
+ for (const listener of busListeners) listener({ eventId: "e", provider: "claudeAgent", threadId, createdAt: "", turnId: "turn_1", ...event } as RuntimeEvent);
+ };
+ const message = (threadId: string, text: string) => {
+ for (const listener of storeListeners) listener({ type: "message", threadId, message: { id: "m", at: clock, role: "user", kind: "text", text } } as unknown as StoreChange);
+ };
+ const advance = (ms: number) => { clock += ms; mono += ms; };
+
+ lists.push({ rows: procRows(1_000), reapedMs: null, totalMs: null });
+ await sampler.sampleNow();
+ advance(60_000);
+ lists.push({ rows: procRows(9_000), reapedMs: null, totalMs: null });
+ await sampler.sampleNow();
+
+ for (const threadId of ["thread_ok", "/Users/ada/Projects/acme-merger/plan.md", "https://intranet.acme.test/q?token=abc"]) {
+ message(threadId, `${SECRETS.join(" ")} please`);
+ advance(4_000);
+ emit(threadId, { type: "turn.started" });
+ emit(threadId, { type: "session.started", sessionId: "[email protected]", model: "Ada's Claude" });
+ emit(threadId, { type: "content.delta", streamKind: "assistant_text", delta: SECRETS.join("\n") });
+ emit(threadId, { type: "item.started", itemType: "tool", itemId: "x1", title: "mcp__acme-internal__lookup_customer", input: SECRETS.join(" ") });
+ emit(threadId, { type: "item.started", itemType: "tool", itemId: "x2", title: "cat /Users/ada/Projects/acme-merger/plan.md", summary: "cat /Users/ada/Projects/acme-merger/plan.md" });
+ emit(threadId, { type: "request.opened", requestType: "permission", tool: "Bash", summary: SECRETS.join(" "), command: { command: "curl https://intranet.acme.test/q?token=abc", cwd: "/Users/ada/Projects/acme-merger" } });
+ advance(200_000);
+ emit(threadId, { type: "request.resolved", behavior: "allow", source: "user" });
+ emit(threadId, { type: "item.completed", itemType: "tool", itemId: "x1", ok: false, output: SECRETS.join(" ") });
+ emit(threadId, { type: "turn.wait_started", resource: "browser:bot-Tallyspoon", holder: { name: "Tallyspoon", task: "Summarize the merger plan" } });
+ advance(150_000);
+ emit(threadId, { type: "turn.wait_ended", resource: "browser:bot-Tallyspoon", waitedMs: 150_000, outcome: "acquired" });
+ emit(threadId, { type: "turn.retrying", attempt: 1, delayMs: 5_000, reason: "Error at https://intranet.acme.test/q?token=abc for [email protected]" });
+ emit(threadId, { type: "runtime.error", message: SECRETS.join(" "), limit: "engine", limitResetsAt: START + 7_200_000 });
+ perf.noteFailover(threadId, "limit");
+ advance(10_000);
+ emit(threadId, { type: "turn.completed", ok: false, stopReason: "OMB_SECRET_VALUE_42 at /Users/ada/Projects/acme-merger/plan.md" });
+ }
+ const poisoned = { provider: "claudeAgent --token sk-ant-api03-PRIVATEPRIVATEPRIVATE1234567890", turnId: "turn_poisoned" };
+ emit("thread_ok", { type: "turn.started", ...poisoned });
+ emit("thread_ok", { type: "runtime.error", message: "x", limit: "engine", ...poisoned });
+ emit("thread_ok", { type: "turn.completed", ok: false, stopReason: "quota", ...poisoned });
+ perf.noteNotStarted("thread_ok", null, { limit: "credits", engine: "hunter2-password at https://intranet.acme.test/q?token=abc" });
+ emit("thread_ok", { type: "turn.started", turnId: "turn_live" });
+ emit("thread_ok", { type: "item.started", itemType: "tool", itemId: "y", title: "mcp__acme-internal__lookup_customer", turnId: "turn_live" });
+ advance(30_000);
+ return { perf, logged, dir };
+}
+
+const leaks = (text: string) => SECRETS.filter((secret) => text.toLowerCase().includes(secret.toLowerCase()));
+
+describe("performance diagnostics carry no content", () => {
+ it("the health read's perf field, the @devs diagnostics, the copied text, the log lines and the saved file hold none of the seeded secrets", async () => {
+ const { perf, logged, dir } = await seeded();
+ perf.timings.flush();
+ const health = JSON.stringify(perf.health());
+ const lines = perf.lines({ threadIds: ["thread_ok"], botIds: ["bot_ok"] });
+ const report = buildDevsReport({
+ installId: "inst_1", appVersion: "0.1.160", platform: "linux x64", os: "linux 6 x64", runsOn: "My Cloud", node: "v24", uptimeSeconds: 60, now: START,
+ threadId: "thread_ok", messageId: "m_1", where: "a chat", message: "@devs it is slow", words: "it is slow", bots: [], noSummary: "none", problems: [], log: [],
+ performance: lines,
+ }, []);
+ const text = perf.text();
+ const saved = readFileSync(join(dir, PERF_FILE), "utf8");
+ expect(logged.length).toBeGreaterThan(0);
+ expect(health).toContain('"turns":4');
+ expect(perf.timings.recent().find((turn) => turn.turnId === "turn_poisoned")).toMatchObject({ engine: null, limit: "engine" });
+ expect(Object.keys(perf.timings.day().limits).sort()).toEqual(["claudeAgent:engine", "unknown:credits", "unknown:engine"]);
+ expect(report.diagnostics).toContain("## Performance");
+ expect(report.diagnostics).toContain("thread_ok");
+ expect(text).toContain("mcp ");
+ for (const [where, body] of Object.entries({ health, diagnostics: report.diagnostics, text, log: logged.join("\n"), saved })) {
+ expect(leaks(body), where).toEqual([]);
+ }
+ });
+
+ it("rides the signed health report as `perf`, and is null where no recorder is wired", async () => {
+ const { perf } = await seeded();
+ const store = { onChange: () => () => {}, botByThread: () => null, bots: [] };
+ const bus = { subscribe: () => () => {} };
+ const base = { store, bus, engines: () => [], dataDir: tmpdir(), eventsDir: tmpdir(), version: "0.1.160", image: undefined, connectors: () => null,
+ browser: () => ({ available: true, installing: false, interrupted: 0 }), now: () => START };
+ expect(createCloudHealth(base).report(undefined).perf).toBeNull();
+ const report = createCloudHealth({ ...base, perf: perf.health }).report(undefined);
+ expect(report.perf).toMatchObject({ v: 1, h24: { turns: 4, failovers: 3, limits: { "claudeAgent:engine": 3 } }, holds: [{ driver: "claude", window: "5-hour", blocked: true }] });
+ expect(leaks(JSON.stringify(report.perf))).toEqual([]);
+ });
+});
+
+describe("a tampered file read back", () => {
+ it("passes nothing but checked fields: every string a secret, every key a trap", () => {
+ const dir = mkdtempSync(join(tmpdir(), "perf-tampered-"));
+ dirs.push(dir);
+ const file = join(dir, PERF_FILE);
+ const bad = SECRETS.join(" ");
+ const hour = Math.floor(START / 3_600_000);
+ writeFileSync(file, JSON.stringify({ v: 1,
+ ring: [{ startedAt: START - 5_000, endedAt: START - 1_000, ok: true, stop: bad, turnId: bad, threadId: "/Users/ada/Projects/acme-merger/plan.md", botId: "[email protected]",
+ engine: "https://intranet.acme.test/q?token=abc", queueWhy: bad, retryWhy: [bad, "__proto__", "constructor"], limit: bad, failover: bad, retries: 1, backoffMs: 1,
+ ms: { total: 4_000, [bad]: 1, __proto__: { polluted: 1 } }, tools: [{ kind: bad, n: 1 }, { kind: "browser", n: 1, ms: 9, max: 9, errors: 0, open: 0, extra: bad }] }],
+ day: [{ hour, turns: 1, failed: 0, slow: [0, 0, 0], failovers: 0, phases: { total: { counts: [bad], max: 1, sum: 1 } },
+ tools: { [bad]: { hist: {} }, constructor: { hist: {} } }, retries: { turns: 1, n: 1, backoffMs: 1, why: { [bad]: 1, toString: 2, overloaded: 1 } },
+ limits: { [bad]: 1, "constructor:engine": 1, [`${bad}:engine`]: 1 } }] }));
+ const timings = createTurnTimings({ file, now: () => START });
+ const out = JSON.stringify({ recent: timings.recent(), hour: timings.window(), day: timings.day(),
+ health: perfHealth({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: null, process: null }) });
+ expect(leaks(out)).toEqual([]);
+ expect(timings.recent()[0]).toMatchObject({ threadId: null, botId: null, engine: null, stop: "ok", retryWhy: ["other", "other", "other"], tools: [{ kind: "browser" }] });
+ expect({ ...timings.day().retries.why }).toEqual({ overloaded: 1 });
+ expect({ ...timings.day().limits }).toEqual({ "constructor:engine": 1 });
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();
+ });
+});
+
+describe("the perf field's size", () => {
+ it("stays under PERF_HEALTH_MAX_BYTES with every part at its fullest", () => {
+ let clock = START;
+ const big = createTurnTimings({ now: () => clock });
+ const kinds = ["mcp__browser__a", "mcp__computer__a", "Bash", "Read", "WebSearch", "WebFetch", "mcp__x__y", "remember", "routine", "publish_page",
+ "show_widget", "delegate", "phone_tap", "TodoWrite", "generate_image", "mcp__data__q", "GMAIL_SEND_EMAIL", "anything"];
+ for (let turn = 0; turn < 300; turn++) {
+ const threadId = `thread_${turn}`;
+ big.noteEvent({ eventId: "e", provider: "someVeryLongEngineKindName-abcdefghijk", threadId, createdAt: "", turnId: `t${turn}`, type: "turn.started" });
+ kinds.forEach((title, index) => big.noteEvent({ eventId: "e", provider: "p", threadId, createdAt: "", turnId: `t${turn}`, type: "item.started", itemType: "tool", itemId: `i${index}`, title }));
+ for (let retry = 0; retry < 4; retry++) big.noteEvent({ eventId: "e", provider: "p", threadId, createdAt: "", turnId: `t${turn}`, type: "turn.retrying", attempt: retry, delayMs: 1000, reason: `reason_${(turn * 4 + retry) % 20}` });
+ big.noteEvent({ eventId: "e", provider: `engine${turn % 20}`, threadId, createdAt: "", turnId: `t${turn}`, type: "runtime.error", message: "m", limit: (["engine", "model", "credits"] as const)[turn % 3] });
+ clock += 1_234_567;
+ if (turn < 250) big.noteEvent({ eventId: "e", provider: "p", threadId, createdAt: "", turnId: `t${turn}`, type: "turn.completed", ok: turn % 2 === 0 });
+ }
+ clock = START + 250 * 1_234_567;
+ const proc = { at: clock, intervalS: 60, scope: "all" as const, samples: 60, browsers: 9, unseen60mS: 1234.5,
+ buckets: Array.from({ length: 12 }, (_, index) => ({ bucket: `engine:someVeryLongEngineKindName${index}` as const, procs: 99, cpu5mS: 1234.5, cpu60mS: 12345.6, peakPct: 100, rssMB: 4096 })),
+ loop: { eluPct: 100, eluMaxPct: 100, driftP95Ms: 123_456, driftMaxMs: 1_234_567 } };
+ const limits: EngineLimitsReport = { checkedAt: 0, engines: Array.from({ length: 20 }, (_, index) => ({ engine: `e${index}`, name: "n", driver: "claude" as const,
+ window: "weekly" as const, usedPercent: 100, resetsAt: START + index, blocked: true, held: true })) };
+ const body = perfHealth({ hour: big.window(), day: big.day(), live: big.live(), limits, process: proc });
+ const bytes = JSON.stringify(body).length;
+ console.log(`perf health, every part full: ${bytes} bytes (budget ${PERF_HEALTH_MAX_BYTES})`);
+ expect(bytes).toBeLessThanOrEqual(PERF_HEALTH_MAX_BYTES);
+ expect(body.h24.tools.length).toBeGreaterThan(0);
+ });
+});
+
+describe("the recorder's cost", () => {
+ it("handles a busy day's events in microseconds each, and its memory stays bounded", () => {
+ let clock = START;
+ const timings = createTurnTimings({ now: () => clock });
+ const events: Array<Record<string, unknown>> = [];
+ for (let index = 0; index < 40; index++) events.push({ type: "content.delta", streamKind: "assistant_text", delta: "token " });
+ for (let index = 0; index < 8; index++) events.push({ type: "item.started", itemType: "tool", itemId: `i${index}`, title: "Bash", summary: "ls" }, { type: "item.completed", itemType: "tool", itemId: `i${index}`, ok: true });
+ const turns = 5_000;
+ const started = performance.now();
+ for (let turn = 0; turn < turns; turn++) {
+ const threadId = `thread_${turn % 50}`;
+ const base = { eventId: "e", provider: "claudeAgent", threadId, createdAt: "", turnId: `t${turn}` };
+ timings.noteMessage(threadId, { at: clock, role: "user", kind: "text" } as never);
+ timings.noteEvent({ ...base, type: "turn.started" } as RuntimeEvent);
+ for (const event of events) { clock += 10; timings.noteEvent({ ...base, ...event } as RuntimeEvent); }
+ timings.noteEvent({ ...base, type: "turn.completed", ok: true } as RuntimeEvent);
+ }
+ const elapsed = performance.now() - started;
+ const perEventUs = (elapsed * 1000) / (turns * (events.length + 2));
+ const reportStarted = performance.now();
+ for (let index = 0; index < 100; index++) { timings.window(); timings.day(); }
+ const reportMs = (performance.now() - reportStarted) / 100;
+ console.log(`recorder: ${perEventUs.toFixed(2)} µs per event over ${turns * (events.length + 2)} events; window()+day() ${reportMs.toFixed(2)} ms`);
+ expect(perEventUs).toBeLessThan(50);
+ expect(reportMs).toBeLessThan(50);
+ expect(timings.recent()).toHaveLength(200);
+ expect(timings.live()).toHaveLength(0);
+ });
+});
diff --git a/server/perf/perf-report.ts b/server/perf/perf-report.ts
new file mode 100644
index 0000000000..e707aa2b26
--- /dev/null
+++ b/server/perf/perf-report.ts
@@ -0,0 +1,115 @@
+// The timings as the Admin's health read carries them (compact JSON under PERF_HEALTH_MAX_BYTES) and as people read them
+// (plain lines for a @devs report and the desktop's diagnostics). Built only from the turn records' checked fields, the
+// process buckets and the limit clock's driver kinds, windows and times: nothing else reaches either.
+import type { EngineLimitsReport } from "../../shared/limit-reset.ts";
+import type { DayAggregate } from "./day-ledger.ts";
+import { SLOW_TURN_MS } from "./day-ledger.ts";
+import { PHASES, type Phase, type PhaseStats } from "./phases.ts";
+import type { ProcessReport } from "./process-sampler.ts";
+import type { LiveTurnView, WindowStats } from "./turn-timings.ts";
+import type { TurnTiming } from "./turn-record.ts";
+
+/** The health report's `perf` field is at most this many bytes of JSON; parts are dropped, least useful first, to fit. */
+export const PERF_HEALTH_MAX_BYTES = 8 * 1024;
+export const PERF_HEALTH_VERSION = 1;
+const LIVE_SHOWN = 5, TOOLS_SHOWN = 8, HOLDS_SHOWN = 8;
+const LIMIT_DRIVERS = new Set(["claude", "codex", "grok", "opencode"]);
+const WINDOWS = new Set(["5-hour", "weekly", "other"]);
+
+export interface LimitHold { driver: string; window: string | null; usedPercent: number | null; resetsAt: number | null; blocked: boolean; held: boolean }
+
+export interface PerfSources {
+ hour: WindowStats;
+ day: DayAggregate;
+ live: LiveTurnView[];
+ limits: EngineLimitsReport | null | undefined;
+ process: ProcessReport | null;
+}
+
+/** Engines refusing work, or within 10 points of their limit: driver kind, window, use and reset time only. */
+export function limitHolds(report: EngineLimitsReport | null | undefined): LimitHold[] {
+ return (report?.engines ?? []).filter((limit) => LIMIT_DRIVERS.has(limit.driver) && (limit.blocked || (limit.usedPercent ?? 0) >= 90)).map((limit) => ({
+ driver: limit.driver, window: limit.window && WINDOWS.has(limit.window) ? limit.window : null,
+ usedPercent: typeof limit.usedPercent === "number" ? Math.round(limit.usedPercent) : null,
+ resetsAt: typeof limit.resetsAt === "number" && Number.isFinite(limit.resetsAt) ? limit.resetsAt : null, blocked: limit.blocked === true, held: limit.held === true,
+ })).slice(0, HOLDS_SHOWN);
+}
+
+const phasesOf = (phases: Partial<Record<Phase, PhaseStats>>) => Object.fromEntries(PHASES.flatMap((phase) => (phases[phase] ? [[phase, phases[phase]]] : [])));
+
+export function perfHealth(sources: PerfSources) {
+ const { hour, day } = sources;
+ const body = {
+ v: PERF_HEALTH_VERSION,
+ slowEdgesMs: [...SLOW_TURN_MS],
+ h1: { turns: hour.turns, failed: hour.failed, partial: hour.partial, slow: hour.slow, phases: phasesOf(hour.phases) },
+ h24: { turns: day.turns, failed: day.failed, slow: day.slow, phases: phasesOf(day.phases), tools: day.tools.slice(0, TOOLS_SHOWN), retries: day.retries, limits: day.limits, failovers: day.failovers },
+ live: sources.live.slice(0, LIVE_SHOWN),
+ holds: limitHolds(sources.limits),
+ process: sources.process,
+ };
+ const size = () => JSON.stringify(body).length;
+ if (size() > PERF_HEALTH_MAX_BYTES && body.process) body.process = { ...body.process, buckets: body.process.buckets.slice(0, 6) };
+ if (size() > PERF_HEALTH_MAX_BYTES) body.h24.tools = body.h24.tools.slice(0, 4);
+ if (size() > PERF_HEALTH_MAX_BYTES) body.live = body.live.slice(0, 2);
+ if (size() > PERF_HEALTH_MAX_BYTES) body.process = null;
+ return body;
+}
+export type PerfHealth = ReturnType<typeof perfHealth>;
+
+/** 850ms, 14s, 6m12s, 1h03m. */
+export function duration(ms: number): string {
+ if (ms < 1000) return `${Math.round(ms)}ms`;
+ const seconds = Math.round(ms / 1000);
+ if (seconds < 60) return ms < 10_000 ? `${(ms / 1000).toFixed(1)}s` : `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes}m${String(seconds % 60).padStart(2, "0")}s`;
+ return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`;
+}
+const iso = (at: number) => new Date(at).toISOString().replace(/\.\d{3}Z$/, "Z");
+const phaseLine = (phases: Partial<Record<Phase, PhaseStats>>) =>
+ PHASES.flatMap((phase) => { const stats = phases[phase]; return stats ? [`${phase} p50 ${duration(stats.p50)} p95 ${duration(stats.p95)} max ${duration(stats.max)}`] : []; }).join("; ");
+const slowLine = (slow: number[]) => SLOW_TURN_MS.map((edge, index) => `${slow[index] ?? 0} over ${duration(edge)}`).join(", ");
+const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? "" : "s"}`;
+const counts = (map: Record<string, number>) => Object.entries(map).sort((a, b) => b[1] - a[1]).map(([key, count]) => `${key} ${count}`).join(", ");
+
+export function turnLine(turn: TurnTiming): string {
+ const parts = PHASES.filter((phase) => phase !== "total" && turn.ms[phase] !== undefined)
+ .map((phase) => `${phase} ${duration(turn.ms[phase]!)}${phase === "queue" && turn.queueWhy ? ` (${turn.queueWhy})` : ""}`);
+ const tools = turn.tools.map((tool) => `${tool.kind} ${tool.n}x ${duration(tool.ms)}${tool.errors ? ` ${tool.errors} failed` : ""}${tool.open ? ` ${tool.open} left open` : ""}`);
+ const extra = [
+ turn.retries ? `retries ${turn.retries} (${(turn.retryWhy ?? []).join(", ")}), backoff ${duration(turn.backoffMs)}` : "",
+ turn.limit ? `usage limit (${turn.limit})${turn.limitResetsAt ? ` resets ${iso(turn.limitResetsAt)}` : ""}` : "",
+ turn.failover ? `moved to a backup AI (${turn.failover})` : "",
+ ].filter(Boolean);
+ return `${iso(turn.startedAt)} bot ${turn.botId ?? "?"} thread ${turn.threadId ?? "?"} ${turn.engine ?? "?"} ${turn.stop} ${duration(turn.ms.total ?? 0)}: ${parts.join(", ")}`
+ + (tools.length ? ` [${tools.join("; ")}]` : "") + (extra.length ? `; ${extra.join("; ")}` : "");
+}
+
+/** Plain lines for people: the last hour and day, what runs now, usage limits, processes and the given recent turns. */
+export function perfLines(sources: PerfSources, recent: readonly TurnTiming[], recentTitle: string): string[] {
+ const { hour, day } = sources;
+ const lines = ["## Performance (timings only: no messages, names, files or addresses)"];
+ lines.push(`Last hour: ${plural(hour.turns, "turn")}, ${hour.failed} failed${hour.partial ? " (only the latest 200 kept)" : ""}; slow: ${slowLine(hour.slow)}`);
+ if (hour.turns) lines.push(` ${phaseLine(hour.phases)}`);
+ lines.push(`Last 24 h: ${plural(day.turns, "turn")}, ${day.failed} failed; slow: ${slowLine(day.slow)}`);
+ if (day.turns) lines.push(` ${phaseLine(day.phases)}`);
+ if (day.tools.length) lines.push(` Tool kinds by time: ${day.tools.slice(0, TOOLS_SHOWN).map((tool) =>
+ `${tool.kind} ${duration(tool.ms)} (${plural(tool.n, "call")}, p95 ${duration(tool.p95)}, max ${duration(tool.max)}${tool.errors ? `, ${tool.errors} failed` : ""}${tool.open ? `, ${tool.open} left open` : ""})`).join("; ")}`);
+ if (day.retries.n) lines.push(` Retries: ${day.retries.n} in ${plural(day.retries.turns, "turn")}, ${duration(day.retries.backoffMs)} of backoff (${counts(day.retries.why)})`);
+ if (Object.keys(day.limits).length || day.failovers) lines.push(` Usage limits refused: ${counts(day.limits) || "none"}; moved to a backup AI: ${day.failovers}`);
+ const holds = limitHolds(sources.limits);
+ lines.push(`Usage limits now: ${holds.length ? holds.map((hold) => `${hold.driver} ${hold.window ?? "?"} ${hold.usedPercent ?? "?"}%${hold.blocked ? " refusing work" : ""}${hold.resetsAt ? ` until ${iso(hold.resetsAt)}` : ""}`).join("; ") : "none near or at a limit"}`);
+ lines.push(`Running now: ${sources.live.length ? sources.live.slice(0, LIVE_SHOWN).map((turn) =>
+ `bot ${turn.botId ?? "?"} thread ${turn.threadId ?? "?"} ${turn.engine ?? "?"} ${duration(turn.ageMs)}, ${turn.state}${turn.tool ? ` (${turn.tool})` : ""} for ${duration(turn.stateMs)}`).join("; ") : "no turn"}`);
+ const proc = sources.process;
+ if (proc && proc.samples) {
+ lines.push(`Processes, last hour (${proc.scope === "all" ? "every process here" : "this app's own"}, sampled every ${proc.intervalS}s): ${proc.buckets.map((bucket) =>
+ `${bucket.bucket} ${bucket.cpu60mS}s CPU (5 min ${bucket.cpu5mS}s, peak ${bucket.peakPct}% of a core, ${bucket.procs} running, ${bucket.rssMB} MB)`).join("; ")}`);
+ lines.push(` Browsers running: ${proc.browsers}${proc.unseen60mS !== null ? `; CPU no sample accounts for: ${proc.unseen60mS}s` : ""}`);
+ lines.push(`Event loop: busy ${proc.loop.eluPct ?? "?"}% (max ${proc.loop.eluMaxPct ?? "?"}%), timer late p95 ${duration(proc.loop.driftP95Ms)}, max ${duration(proc.loop.driftMaxMs)}`);
+ } else lines.push("Processes: not sampled yet");
+ lines.push(recentTitle);
+ lines.push(...(recent.length ? recent.map((turn) => ` ${turnLine(turn)}`) : [" (none)"]));
+ return lines;
+}
diff --git a/server/perf/phases.ts b/server/perf/phases.ts
new file mode 100644
index 0000000000..ac7aca5acd
--- /dev/null
+++ b/server/perf/phases.ts
@@ -0,0 +1,81 @@
+// The phases a bot turn's time is split into, and the fixed-bucket histograms they are counted in. Numbers only.
+
+/**
+ * `queue`: from the person's message being stored to its turn starting. `handshake`: from the turn starting to its engine's
+ * session starting (absent on a warm engine). `ttft`: from the turn starting to the engine's first output (a token, a tool
+ * call or an ask). The rest split the turn's whole time (`total`) with nothing counted twice: `model` (the engine thinking
+ * and streaming), `tool` (at least one tool call open), `resource` (queued for a computer or a browser), `person` (an
+ * approval or a question waiting on someone), `retry` (from a retry's announcement to the engine's next event).
+ */
+export const PHASES = ["queue", "handshake", "ttft", "model", "tool", "resource", "person", "retry", "total"] as const;
+export type Phase = (typeof PHASES)[number];
+export type PhaseMs = Partial<Record<Phase, number>>;
+
+/** Upper bucket edges, ms; one more bucket counts everything slower. A percentile read from them is the edge of its
+ * bucket (never above the largest value seen), so it reads high by at most the step to that edge: x1.28 from 100 ms to
+ * 5 s, where handshakes and first tokens fall, x1.5 elsewhere, and up to 50 ms below 50 ms. */
+export const BUCKET_EDGES_MS = [
+ 50, 75, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1_000, 1_250, 1_600, 2_000, 2_500, 3_200, 4_000, 5_000,
+ 7_500, 10_000, 15_000, 20_000, 30_000, 45_000, 60_000, 90_000, 120_000, 180_000, 240_000, 300_000, 450_000, 600_000,
+ 900_000, 1_200_000, 1_800_000, 2_700_000, 3_600_000, 5_400_000, 7_200_000,
+] as const;
+const BUCKETS = BUCKET_EDGES_MS.length + 1;
+
+export interface Histogram { counts: number[]; max: number; sum: number }
+
+export const emptyHistogram = (): Histogram => ({ counts: Array.from({ length: BUCKETS }, () => 0), max: 0, sum: 0 });
+
+export function bucketOf(ms: number): number {
+ let low = 0, high: number = BUCKET_EDGES_MS.length;
+ while (low < high) {
+ const mid = (low + high) >> 1;
+ if (ms <= BUCKET_EDGES_MS[mid]!) high = mid; else low = mid + 1;
+ }
+ return low;
+}
+
+export function addTo(histogram: Histogram, ms: number): void {
+ const value = Math.max(0, Math.round(ms));
+ histogram.counts[bucketOf(value)]! += 1;
+ histogram.max = Math.max(histogram.max, value);
+ histogram.sum += value;
+}
+
+export function mergeInto(into: Histogram, from: Histogram): void {
+ for (let index = 0; index < BUCKETS; index++) into.counts[index]! += from.counts[index] ?? 0;
+ into.max = Math.max(into.max, from.max);
+ into.sum += from.sum;
+}
+
+export const countOf = (histogram: Histogram): number => histogram.counts.reduce((sum, count) => sum + count, 0);
+
+/** The edge of the bucket holding the q-th value, never above the largest value seen. */
+export function histogramQuantile(histogram: Histogram, q: number): number {
+ const total = countOf(histogram);
+ if (!total) return 0;
+ const rank = Math.max(1, Math.ceil(q * total));
+ let seen = 0;
+ for (let index = 0; index < BUCKETS; index++) {
+ seen += histogram.counts[index]!;
+ if (seen >= rank) return Math.min(BUCKET_EDGES_MS[index] ?? histogram.max, histogram.max);
+ }
+ return histogram.max;
+}
+
+/** Exact nearest-rank percentile of a list. */
+export function exactQuantile(sorted: readonly number[], q: number): number {
+ if (!sorted.length) return 0;
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1))]!;
+}
+
+export interface PhaseStats { p50: number; p95: number; max: number; n: number }
+
+/** A histogram read back from disk: anything malformed counts as empty. */
+export function parseHistogram(value: unknown): Histogram {
+ const raw = value as Partial<Histogram> | null;
+ const counts = Array.isArray(raw?.counts) && raw.counts.length === BUCKETS && raw.counts.every((count) => Number.isSafeInteger(count) && count >= 0)
+ ? [...raw.counts] : null;
+ if (!counts) return emptyHistogram();
+ const finite = (number: unknown) => (typeof number === "number" && Number.isFinite(number) && number >= 0 ? number : 0);
+ return { counts, max: finite(raw?.max), sum: finite(raw?.sum) };
+}
diff --git a/server/perf/process-buckets.ts b/server/perf/process-buckets.ts
new file mode 100644
index 0000000000..f2e9e52573
--- /dev/null
+++ b/server/perf/process-buckets.ts
@@ -0,0 +1,124 @@
+// Which part of a home a process belongs to, from its executable's name and its parent alone. Privacy invariant: the name
+// is read, matched against fixed lists and dropped; only the bucket leaves this file. Never an argument, a path, an
+// environment value or the name itself.
+
+export type ProcessBucket = "server" | `engine:${string}` | "browser" | "computer" | "mcp" | "build" | "commands" | "other";
+
+export interface ProcessRow {
+ pid: number;
+ ppid: number;
+ /** The executable's base name, lower-cased: the kernel's 15-character `comm` on Linux. */
+ name: string;
+ /** User plus system CPU time so far, ms. */
+ cpuMs: number;
+ rssBytes: number;
+ /** Tells a pid apart from an earlier process that had it (its start time, as the source gives it). */
+ start: string;
+}
+
+/** Engine CLIs by executable name, as the drivers' kinds name them. */
+const ENGINE_NAMES: Readonly<Record<string, string>> = {
+ claude: "claudeAgent", codex: "codex", opencode: "opencodeGo", grok: "grokAgent", gemini: "geminiAgent", kimi: "kimiAgent",
+ droid: "droidAgent", "cursor-agent": "cursorAgent", qwen: "qwenAgent", hermes: "hermesAgent", cline: "clineAgent",
+ copilot: "copilotAgent", kiro: "kiroAgent", "kiro-cli": "kiroAgent", devin: "devinAgent", pi: "piAgent", omp: "ompAgent",
+ vibe: "mistralVibeAgent", antigravity: "antigravityAgent", goose: "gooseAgent",
+};
+const BROWSER_PREFIXES = ["chrom", "google chrome", "headless_shell", "chrome-headless", "camoufox", "firefox", "msedge", "microsoft edge"];
+const COMPUTER_NAMES = new Set(["xvfb", "xvnc", "x11vnc", "websockify", "vncserver", "novnc", "ssh", "sshpass", "xdotool", "ffmpeg", "xfce4-session", "xfwm4"]);
+const COMPUTER_PREFIXES = ["tigervnc", "qemu-system", "cua"];
+const BUILD_NAMES = new Set(["npm", "pnpm", "yarn", "pip", "pip3", "cargo", "rustc", "go", "make", "cmake", "ninja", "gcc", "g++", "cc", "cc1",
+ "cc1plus", "clang", "clang++", "ld", "collect2", "as", "tsc", "esbuild", "vite", "webpack", "node-gyp", "git", "apt", "apt-get", "dpkg", "gradle", "mvn"]);
+/** What an MCP server runs as when an engine (or the server, for a chat-runtime turn) starts it. */
+const RUNTIMES = new Set(["node", "npx", "npm exec", "uv", "uvx", "python", "python3", "bun", "deno", "docker", "java"]);
+const RUNTIME_PREFIXES = ["python3."];
+
+export function nameBucket(name: string): ProcessBucket | null {
+ if (Object.hasOwn(ENGINE_NAMES, name)) return `engine:${ENGINE_NAMES[name]!}`;
+ if (BROWSER_PREFIXES.some((prefix) => name.startsWith(prefix))) return "browser";
+ if (COMPUTER_NAMES.has(name) || COMPUTER_PREFIXES.some((prefix) => name.startsWith(prefix))) return "computer";
+ if (BUILD_NAMES.has(name)) return "build";
+ return null;
+}
+
+const runtime = (name: string) => RUNTIMES.has(name) || RUNTIME_PREFIXES.some((prefix) => name.startsWith(prefix));
+const INHERITED: ReadonlySet<ProcessBucket> = new Set(["browser", "computer", "mcp", "build", "commands"]);
+
+const ENGINE_KIND = /^[A-Za-z][A-Za-z0-9-]{0,47}$/;
+
+/**
+ * Every row's bucket. A pid the server knows runs an engine is that engine, whatever its executable (an engine started
+ * through `node`); a row named on a list is that; a runtime an engine or the server started is an MCP server; anything
+ * else under an engine or the server is a command a bot ran; below those, a row takes its parent's. With `treeOnly`,
+ * rows that do not descend from the server are left out.
+ */
+export function classifyProcesses(rows: readonly ProcessRow[], serverPid: number, treeOnly: boolean, engines: ReadonlyMap<number, string> = new Map()): Map<number, ProcessBucket> {
+ const byPid = new Map(rows.map((row) => [row.pid, row]));
+ const out = new Map<number, ProcessBucket | null>();
+ const visit = (row: ProcessRow, depth: number): ProcessBucket | null => {
+ const known = out.get(row.pid);
+ if (known !== undefined) return known;
+ let bucket: ProcessBucket | null;
+ if (row.pid === serverPid) bucket = "server";
+ else {
+ const parent = row.ppid !== row.pid && depth < 64 ? byPid.get(row.ppid) : undefined;
+ const above = parent ? visit(parent, depth + 1) : null;
+ const engineKind = engines.get(row.pid);
+ const named: ProcessBucket | null = engineKind !== undefined ? `engine:${ENGINE_KIND.test(engineKind) ? engineKind : "unknown"}` : nameBucket(row.name);
+ if (treeOnly && above === null) bucket = null;
+ else if (named) bucket = named;
+ else if (above === "server" || above?.startsWith("engine:")) bucket = runtime(row.name) ? "mcp" : "commands";
+ else if (above && INHERITED.has(above)) bucket = above;
+ else bucket = "other";
+ }
+ out.set(row.pid, bucket);
+ return bucket;
+ };
+ for (const row of rows) visit(row, 0);
+ return new Map([...out].filter((entry): entry is [number, ProcessBucket] => entry[1] !== null));
+}
+
+const CLOCK_TICKS = 100, PAGE_BYTES = 4096;
+
+/** One `/proc/<pid>/stat` line: comm may hold spaces and parentheses, so fields count from its last ")". */
+export function parseProcStat(pid: number, text: string): ProcessRow | null {
+ const open = text.indexOf("("), close = text.lastIndexOf(")");
+ if (open < 0 || close < open) return null;
+ const fields = text.slice(close + 2).split(" ");
+ const ppid = Number(fields[1]), user = Number(fields[11]), system = Number(fields[12]), start = fields[19], rss = Number(fields[21]);
+ if (!Number.isInteger(ppid) || !Number.isFinite(user) || !Number.isFinite(system) || !start) return null;
+ return { pid, ppid, name: text.slice(open + 1, close).toLowerCase(), cpuMs: ((user + system) * 1000) / CLOCK_TICKS, rssBytes: (Number.isFinite(rss) ? rss : 0) * PAGE_BYTES, start };
+}
+
+/** `/proc/self/stat`'s CPU time of children this process waited for, ms. */
+export function parseReapedChildrenMs(text: string): number | null {
+ const fields = text.slice(text.lastIndexOf(")") + 2).split(" ");
+ const user = Number(fields[13]), system = Number(fields[14]);
+ return Number.isFinite(user) && Number.isFinite(system) ? ((user + system) * 1000) / CLOCK_TICKS : null;
+}
+
+/** `ps`'s cumulative CPU time: `[[dd-]hh:]mm:ss[.ss]`. */
+export function parsePsTime(text: string): number | null {
+ const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+(?:\.\d+)?)$/.exec(text.trim());
+ if (!match) return null;
+ const [, days, hours, minutes, seconds] = match;
+ return ((Number(days ?? 0) * 24 + Number(hours ?? 0)) * 60 + Number(minutes)) * 60_000 + Number(seconds) * 1000;
+}
+
+/** One line of `ps -axo pid=,ppid=,rss=,time=,comm=`: rss in KiB, comm the executable's path (macOS), last so it may hold spaces. */
+export function parsePsLine(line: string): ProcessRow | null {
+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(line);
+ if (!match) return null;
+ const cpuMs = parsePsTime(match[4]!);
+ if (cpuMs === null) return null;
+ const path = match[5]!;
+ const pid = Number(match[1]);
+ return { pid, ppid: Number(match[2]), name: path.slice(path.lastIndexOf("/") + 1).toLowerCase(), cpuMs, rssBytes: Number(match[3]) * 1024, start: `ps:${pid}` };
+}
+
+/** The cgroup's (or, outside one, the machine's) CPU time so far, ms: cgroup v2's usage_usec, else v1's cpuacct.usage. */
+export function parseCgroupCpuMs(v2: string | null, v1: string | null): number | null {
+ const usec = v2 ? /^usage_usec (\d+)$/m.exec(v2)?.[1] : undefined;
+ if (usec !== undefined) return Number(usec) / 1000;
+ const nsec = v1?.trim();
+ return nsec && /^\d+$/.test(nsec) ? Number(nsec) / 1e6 : null;
+}
diff --git a/server/perf/process-sampler.test.ts b/server/perf/process-sampler.test.ts
new file mode 100644
index 0000000000..ca53764b28
--- /dev/null
+++ b/server/perf/process-sampler.test.ts
@@ -0,0 +1,134 @@
+import { describe, expect, it } from "vitest";
+import { classifyProcesses, parseCgroupCpuMs, parseProcStat, parsePsLine, parsePsTime, parseReapedChildrenMs, type ProcessRow } from "./process-buckets.ts";
+import { createProcessSampler, linuxProcessList, type ProcessList } from "./process-sampler.ts";
+
+const SERVER = 100;
+const row = (pid: number, ppid: number, name: string, cpuMs = 0, rssBytes = 1_048_576): ProcessRow => ({ pid, ppid, name, cpuMs, rssBytes, start: `s${pid}` });
+
+/** /proc/<pid>/stat as the kernel writes it: utime, stime, starttime and rss at their places after the comm. */
+const statLine = (pid: number, comm: string, ppid: number, utime: number, stime: number, rssPages = 256, cutime = 0, cstime = 0) =>
+ `${pid} (${comm}) S ${ppid} ${pid} ${pid} 0 -1 4194304 100 0 0 0 ${utime} ${stime} ${cutime} ${cstime} 20 0 1 0 5555 1000000 ${rssPages} 18446744073709551615`;
+
+describe("process buckets, from the executable's name and parent only", () => {
+ it("names the server, engines, browsers, a cloud computer, MCP servers, builds and a bot's commands", () => {
+ const rows = [
+ row(1, 0, "tini"), row(SERVER, 1, "node"), row(200, SERVER, "claude"), row(201, 200, "node"), row(202, 200, "bash"), row(203, 202, "python3"),
+ row(204, 202, "pnpm"), row(205, 204, "node"), row(300, SERVER, "chrome"), row(301, 300, "chrome"), row(302, 1, "headless_shell"),
+ row(400, 1, "xvfb"), row(401, SERVER, "uvx"), row(500, 1, "sshd"), row(600, SERVER, "codex"),
+ ];
+ const buckets = classifyProcesses(rows, SERVER, false);
+ expect(Object.fromEntries(buckets)).toEqual({
+ 1: "other", 100: "server", 200: "engine:claudeAgent", 201: "mcp", 202: "commands", 203: "commands", 204: "build", 205: "build",
+ 300: "browser", 301: "browser", 302: "browser", 400: "computer", 401: "mcp", 500: "other", 600: "engine:codex",
+ });
+ const tree = classifyProcesses(rows, SERVER, true);
+ expect([...tree.keys()].sort((a, b) => a - b)).toEqual([100, 200, 201, 202, 203, 204, 205, 300, 301, 401, 600]);
+ });
+
+ it("never takes a bucket from an object's prototype", () => {
+ const rows = ["constructor", "__proto__", "toString", "hasOwnProperty", "valueOf"].map((name, index) => row(200 + index, 1, name));
+ expect(new Set(classifyProcesses(rows, SERVER, false).values())).toEqual(new Set(["other"]));
+ });
+
+ it("files a pid the server knows runs an engine under that engine, whatever its executable", () => {
+ const rows = [row(SERVER, 1, "node"), row(200, SERVER, "node"), row(201, 200, "node"), row(202, SERVER, "node"), row(203, SERVER, "node")];
+ const buckets = classifyProcesses(rows, SERVER, true, new Map([[200, "geminiAgent"], [203, "claude --key sk-x"]]));
+ expect(Object.fromEntries(buckets)).toEqual({ 100: "server", 200: "engine:geminiAgent", 201: "mcp", 202: "mcp", 203: "engine:unknown" });
+ });
+
+ it("survives a parent loop and a missing parent", () => {
+ expect(Object.fromEntries(classifyProcesses([row(7, 8, "a"), row(8, 7, "b"), row(9, 999, "bash")], SERVER, false))).toEqual({ 7: "other", 8: "other", 9: "other" });
+ });
+
+ it("parses /proc stat lines (a comm with spaces and parentheses), ps lines and CPU counters", () => {
+ expect(parseProcStat(42, statLine(42, "Web Content (x)", 7, 150, 50))).toEqual({ pid: 42, ppid: 7, name: "web content (x)", cpuMs: 2_000, rssBytes: 256 * 4096, start: "5555" });
+ expect(parseProcStat(1, "garbage")).toBeNull();
+ expect(parseReapedChildrenMs(statLine(1, "node", 0, 0, 0, 1, 300, 200))).toBe(5_000);
+ expect(parsePsTime("1:02.50")).toBe(62_500);
+ expect(parsePsTime("2-01:00:00")).toBe((49 * 3600) * 1000);
+ expect(parsePsTime("nope")).toBeNull();
+ expect(parsePsLine(" 812 1 20480 0:03.10 /Applications/Google Chrome.app/Contents/MacOS/Google Chrome Helper (Renderer)"))
+ .toEqual({ pid: 812, ppid: 1, name: "google chrome helper (renderer)", cpuMs: 3_100, rssBytes: 20480 * 1024, start: "ps:812" });
+ expect(parseCgroupCpuMs("usage_usec 2500000\nuser_usec 1\n", null)).toBe(2_500);
+ expect(parseCgroupCpuMs(null, "7000000000\n")).toBe(7_000);
+ expect(parseCgroupCpuMs(null, null)).toBeNull();
+ });
+
+ it("reads every process /proc lists, and nothing but each one's stat line", () => {
+ const read: string[] = [];
+ const files: Record<string, string> = {
+ "/proc/100/stat": statLine(100, "node", 1, 10, 10), "/proc/200/stat": statLine(200, "claude", 100, 20, 0),
+ "/proc/self/stat": statLine(100, "node", 1, 10, 10, 1, 7, 3), "/sys/fs/cgroup/cpu.stat": "usage_usec 9000000\n",
+ };
+ const list = linuxProcessList((path) => { read.push(path); return files[path] ?? null; }, () => ["100", "200", "self", "stat", "300"]);
+ expect(list.rows.map((entry) => entry.name)).toEqual(["node", "claude"]);
+ expect(list).toMatchObject({ reapedMs: 100, totalMs: 9_000 });
+ expect(read.every((path) => /^\/proc\/(\d+|self)\/stat$|^\/sys\/fs\/cgroup\//.test(path))).toBe(true);
+ });
+});
+
+describe("the sampler", () => {
+ it("answers who used the CPU in the last five and sixty minutes, with each bucket's peak", async () => {
+ let clock = 1_800_000_000_000, mono = 0;
+ let lists: ProcessList[] = [];
+ const sampler = createProcessSampler({ list: () => lists.shift() ?? null, intervalMs: 60_000, scope: "all", serverPid: SERVER, now: () => clock, monotonic: () => mono, utilization: () => 0.05 });
+ const step = async (rows: ProcessRow[], totalMs: number | null = null, reapedMs: number | null = null) => {
+ lists = [{ rows, totalMs, reapedMs }];
+ await sampler.sampleNow();
+ clock += 60_000; mono += 60_000;
+ };
+ // An idle server, and once every five minutes a minute of one full core in a build.
+ let serverCpu = 0, buildCpu = 0, total = 0;
+ for (let minute = 0; minute <= 60; minute++) {
+ serverCpu += 600; total += 600;
+ const building = minute % 5 === 1;
+ if (building) { buildCpu += 60_000; total += 60_000; }
+ const rows = [row(SERVER, 1, "node", serverCpu), row(200, SERVER, "claude", 1_000)];
+ if (building) rows.push(row(900 + minute, 200, "make", 60_000));
+ await step(rows, total + 1_000 * minute, null);
+ }
+ clock -= 60_000;
+ const report = sampler.report();
+ const byName = Object.fromEntries(report.buckets.map((bucket) => [bucket.bucket, bucket]));
+ expect(byName.build).toMatchObject({ cpu60mS: 720, peakPct: 100, procs: 0 });
+ expect(byName.server).toMatchObject({ cpu60mS: 36, cpu5mS: 3, peakPct: 1, procs: 1, rssMB: 1 });
+ expect(byName["engine:claudeAgent"]).toMatchObject({ cpu60mS: 0, procs: 1 });
+ expect(report.buckets[0]!.bucket).toBe("build");
+ expect(report.unseen60mS).toBe(60);
+ expect(report.loop).toMatchObject({ eluPct: 5, eluMaxPct: 5 });
+ expect(report).toMatchObject({ scope: "all", intervalS: 60, samples: 60, browsers: 0 });
+ expect(JSON.stringify(report)).not.toMatch(/make|claude"|node/);
+ });
+
+ it("counts CPU of a server child that came and went between samples, and browsers by instance", async () => {
+ let lists: ProcessList[] = [];
+ let clock = 0;
+ const sampler = createProcessSampler({ list: () => lists.shift() ?? null, intervalMs: 60_000, scope: "tree", serverPid: SERVER, now: () => clock, monotonic: () => clock });
+ lists = [{ rows: [row(SERVER, 1, "node"), row(210, SERVER, "bash", 1_000)], reapedMs: 0, totalMs: null }];
+ await sampler.sampleNow();
+ clock += 60_000;
+ lists = [{ rows: [row(SERVER, 1, "node"), row(300, SERVER, "chrome"), row(301, 300, "chrome"), row(302, SERVER, "chromium")], reapedMs: 9_000, totalMs: null }];
+ await sampler.sampleNow();
+ const report = sampler.report();
+ expect(report.buckets.find((bucket) => bucket.bucket === "commands")).toMatchObject({ cpu60mS: 8 });
+ expect(report.browsers).toBe(2);
+ expect(report.unseen60mS).toBeNull();
+ });
+});
+
+describe("the sampler's cost", () => {
+ it("parses, classifies and diffs 500 processes in well under a few milliseconds", async () => {
+ const stats = Array.from({ length: 500 }, (_, index) => statLine(1000 + index, index % 7 ? "node" : "chrome", index ? 1000 + Math.floor(index / 3) : SERVER, index, index));
+ let rounds = 0;
+ const sampler = createProcessSampler({ intervalMs: 60_000, scope: "all", serverPid: SERVER, list: () => ({ rows: stats.flatMap((text, index) => {
+ const parsed = parseProcStat(1000 + index, text);
+ return parsed ? [{ ...parsed, cpuMs: parsed.cpuMs + rounds * 10 }] : [];
+ }), reapedMs: null, totalMs: null }) });
+ const started = performance.now();
+ for (; rounds < 50; rounds++) await sampler.sampleNow();
+ const each = (performance.now() - started) / 50;
+ console.log(`process sample of 500 rows: ${each.toFixed(2)} ms (stat files already read)`);
+ expect(each).toBeLessThan(25);
+ expect(sampler.report().buckets.length).toBeGreaterThan(0);
+ });
+});
diff --git a/server/perf/process-sampler.ts b/server/perf/process-sampler.ts
new file mode 100644
index 0000000000..5a2a53867f
--- /dev/null
+++ b/server/perf/process-sampler.ts
@@ -0,0 +1,190 @@
+// Who used the CPU here lately, by process bucket, and how responsive the server's event loop was. One sample
+// a minute on Linux from /proc (a few hundred small file reads), one every five minutes elsewhere from a single `ps`; no
+// other process, no network. The event loop is read from the sampler's own timer (how late it fired) and Node's
+// utilization counter, never a fast timer of its own. Memory: the last sample's rows and an hour of per-bucket totals.
+import { execFile } from "node:child_process";
+import { readdirSync, readFileSync } from "node:fs";
+import { performance } from "node:perf_hooks";
+
+import { exactQuantile } from "./phases.ts";
+import {
+ classifyProcesses, parseCgroupCpuMs, parseProcStat, parsePsLine, parseReapedChildrenMs, type ProcessBucket, type ProcessRow,
+} from "./process-buckets.ts";
+
+export const LINUX_SAMPLE_MS = 60_000;
+export const OTHER_SAMPLE_MS = 5 * 60_000;
+const HOUR = 3_600_000, FIVE_MINUTES = 5 * 60_000;
+const BUCKETS_SHOWN = 12;
+
+export interface ProcessList {
+ rows: ProcessRow[];
+ /** CPU time of children the server waited for, so far (Linux), ms. */
+ reapedMs: number | null;
+ /** The whole home's CPU time so far (its cgroup, or the machine), ms. */
+ totalMs: number | null;
+}
+
+interface Sample { at: number; windowMs: number; cpu: Partial<Record<ProcessBucket, number>>; total: number | null; driftMs: number; elu: number | null }
+
+export interface BucketReport { bucket: ProcessBucket; procs: number; cpu5mS: number; cpu60mS: number; peakPct: number; rssMB: number }
+export interface ProcessReport {
+ at: number | null;
+ intervalS: number;
+ /** "all": every process this server can see (a Cloud home's machine is all its own); "tree": the server and what it started. */
+ scope: "all" | "tree";
+ samples: number;
+ buckets: BucketReport[];
+ browsers: number;
+ /** CPU the home used in the last hour that no sampled process accounts for (processes that came and went between samples), s. */
+ unseen60mS: number | null;
+ loop: { eluPct: number | null; eluMaxPct: number | null; driftP95Ms: number; driftMaxMs: number };
+}
+
+const readText = (path: string): string | null => { try { return readFileSync(path, "utf8"); } catch { return null; } };
+
+/** Every process /proc shows, read synchronously: one stat file each. */
+export function linuxProcessList(read: (path: string) => string | null = readText, list: () => string[] = () => readdirSync("/proc")): ProcessList {
+ const rows: ProcessRow[] = [];
+ let names: string[] = [];
+ try { names = list(); } catch {}
+ for (const name of names) {
+ if (!/^\d+$/.test(name)) continue;
+ const text = read(`/proc/${name}/stat`);
+ const row = text === null ? null : parseProcStat(Number(name), text);
+ if (row) rows.push(row);
+ }
+ const self = read("/proc/self/stat");
+ return { rows, reapedMs: self === null ? null : parseReapedChildrenMs(self), totalMs: parseCgroupCpuMs(read("/sys/fs/cgroup/cpu.stat"), read("/sys/fs/cgroup/cpuacct/cpuacct.usage")) };
+}
+
+/** One `ps` over every process: the fallback where there is no /proc (macOS). */
+export function psProcessList(): Promise<ProcessList | null> {
+ return new Promise((resolve) => {
+ execFile("ps", ["-axo", "pid=,ppid=,rss=,time=,comm="], { timeout: 10_000, maxBuffer: 4 * 1024 * 1024, windowsHide: true }, (error, stdout) => {
+ if (error) return resolve(null);
+ const rows = stdout.split("\n").flatMap((line) => { const row = parsePsLine(line); return row ? [row] : []; });
+ resolve({ rows, reapedMs: null, totalMs: null });
+ });
+ });
+}
+
+export interface ProcessSamplerOptions {
+ list: () => ProcessList | null | Promise<ProcessList | null>;
+ intervalMs: number;
+ scope: "all" | "tree";
+ serverPid?: number;
+ now?: () => number;
+ monotonic?: () => number;
+ /** Node's event-loop utilization since the previous call, 0–1; null where not available. */
+ utilization?: () => number | null;
+ /** The sampler's timer fired this much later than it was due. */
+ stalled?: (driftMs: number) => void;
+ /** The engine processes the server started, by pid, with their engine kinds. */
+ engines?: () => ReadonlyMap<number, string>;
+ /** After each timed sample: other once-a-sample checks ride the same timer. */
+ afterSample?: () => void;
+}
+
+export function nodeUtilization(): () => number | null {
+ let previous = performance.eventLoopUtilization();
+ return () => {
+ const current = performance.eventLoopUtilization();
+ const delta = performance.eventLoopUtilization(current, previous);
+ previous = current;
+ return Number.isFinite(delta.utilization) ? delta.utilization : null;
+ };
+}
+
+export function createProcessSampler(options: ProcessSamplerOptions) {
+ const now = options.now ?? Date.now, monotonic = options.monotonic ?? (() => performance.now());
+ const serverPid = options.serverPid ?? process.pid;
+ const samples: Sample[] = [];
+ let previous: { at: number; rows: Map<number, { start: string; cpuMs: number; bucket: ProcessBucket; ppid: number }>; reapedMs: number | null; totalMs: number | null } | null = null;
+ let latest: { at: number; procs: Partial<Record<ProcessBucket, number>>; rss: Partial<Record<ProcessBucket, number>>; browsers: number } | null = null;
+ let timer: ReturnType<typeof setTimeout> | null = null, due = 0, running = false;
+
+ const take = (list: ProcessList, driftMs: number) => {
+ const at = monotonic();
+ const buckets = classifyProcesses(list.rows, serverPid, options.scope === "tree", options.engines?.());
+ const cpu: Partial<Record<ProcessBucket, number>> = {}, procs: Partial<Record<ProcessBucket, number>> = {}, rss: Partial<Record<ProcessBucket, number>> = {};
+ const rows = new Map<number, { start: string; cpuMs: number; bucket: ProcessBucket; ppid: number }>();
+ let browsers = 0;
+ const browserPids = new Set(list.rows.filter((row) => buckets.get(row.pid) === "browser").map((row) => row.pid));
+ for (const row of list.rows) {
+ const bucket = buckets.get(row.pid);
+ if (!bucket) continue;
+ procs[bucket] = (procs[bucket] ?? 0) + 1;
+ rss[bucket] = (rss[bucket] ?? 0) + row.rssBytes;
+ if (bucket === "browser" && !browserPids.has(row.ppid)) browsers += 1;
+ const before = previous?.rows.get(row.pid);
+ const used = before && before.start === row.start && row.cpuMs >= before.cpuMs ? row.cpuMs - before.cpuMs : previous ? row.cpuMs : 0;
+ cpu[bucket] = (cpu[bucket] ?? 0) + used;
+ rows.set(row.pid, { start: row.start, cpuMs: row.cpuMs, bucket, ppid: row.ppid });
+ }
+ if (previous && list.reapedMs !== null && previous.reapedMs !== null) {
+ let reaped = list.reapedMs - previous.reapedMs;
+ for (const [pid, before] of previous.rows) if (before.ppid === serverPid && !rows.has(pid)) reaped -= before.cpuMs;
+ if (reaped > 0) cpu.commands = (cpu.commands ?? 0) + reaped;
+ }
+ if (previous) {
+ const total = list.totalMs !== null && previous.totalMs !== null ? Math.max(0, list.totalMs - previous.totalMs) : null;
+ samples.push({ at: now(), windowMs: Math.max(1, at - previous.at), cpu, total, driftMs, elu: options.utilization?.() ?? null });
+ while (samples.length && samples[0]!.at <= now() - HOUR) samples.shift();
+ } else options.utilization?.();
+ previous = { at, rows, reapedMs: list.reapedMs, totalMs: list.totalMs };
+ latest = { at: now(), procs, rss, browsers };
+ };
+
+ const tick = async () => {
+ const driftMs = Math.max(0, monotonic() - due);
+ if (driftMs >= 2_000) options.stalled?.(Math.round(driftMs));
+ await sampleNow(driftMs);
+ try { options.afterSample?.(); } catch {}
+ schedule();
+ };
+ const schedule = () => {
+ due = monotonic() + options.intervalMs;
+ timer = setTimeout(() => void tick(), options.intervalMs);
+ timer.unref?.();
+ };
+ const sampleNow = async (driftMs = 0) => {
+ if (running) return;
+ running = true;
+ try {
+ const list = await options.list();
+ if (list) take(list, driftMs);
+ } catch {} finally { running = false; }
+ };
+
+ return {
+ start() { if (!timer) { void sampleNow(); schedule(); } },
+ stop() { if (timer) clearTimeout(timer); timer = null; },
+ sampleNow,
+ report(): ProcessReport {
+ const at = now();
+ const since = (ms: number) => samples.filter((sample) => sample.at > at - ms);
+ const hour = since(HOUR), five = since(FIVE_MINUTES);
+ const sum = (list: Sample[], bucket: ProcessBucket) => list.reduce((total, sample) => total + (sample.cpu[bucket] ?? 0), 0);
+ const names = new Set<ProcessBucket>([...Object.keys(latest?.procs ?? {}), ...hour.flatMap((sample) => Object.keys(sample.cpu))] as ProcessBucket[]);
+ const buckets = [...names].map((bucket) => ({
+ bucket, procs: latest?.procs[bucket] ?? 0, cpu5mS: round1(sum(five, bucket) / 1000), cpu60mS: round1(sum(hour, bucket) / 1000),
+ peakPct: Math.round(Math.max(0, ...hour.map((sample) => ((sample.cpu[bucket] ?? 0) / sample.windowMs) * 100))),
+ rssMB: Math.round((latest?.rss[bucket] ?? 0) / 1_048_576),
+ })).sort((left, right) => right.cpu60mS - left.cpu60mS || right.rssMB - left.rssMB).slice(0, BUCKETS_SHOWN);
+ const totals = hour.filter((sample) => sample.total !== null);
+ const seen = (sample: Sample) => Object.values(sample.cpu).reduce<number>((total, ms) => total + (ms ?? 0), 0);
+ const unseen = totals.length ? totals.reduce((total, sample) => total + Math.max(0, (sample.total ?? 0) - seen(sample)), 0) : null;
+ const drifts = hour.map((sample) => sample.driftMs).sort((left, right) => left - right);
+ const elus = hour.flatMap((sample) => (sample.elu === null ? [] : [sample.elu]));
+ return {
+ at: latest?.at ?? null, intervalS: Math.round(options.intervalMs / 1000), scope: options.scope, samples: hour.length, buckets,
+ browsers: latest?.browsers ?? 0, unseen60mS: unseen === null ? null : round1(unseen / 1000),
+ loop: { eluPct: elus.length ? Math.round(elus.at(-1)! * 100) : null, eluMaxPct: elus.length ? Math.round(Math.max(...elus) * 100) : null,
+ driftP95Ms: Math.round(exactQuantile(drifts, 0.95)), driftMaxMs: Math.round(drifts.at(-1) ?? 0) },
+ };
+ },
+ };
+}
+export type ProcessSampler = ReturnType<typeof createProcessSampler>;
+
+const round1 = (value: number) => Math.round(value * 10) / 10;
diff --git a/server/perf/turn-record.ts b/server/perf/turn-record.ts
new file mode 100644
index 0000000000..0fa4bc22c0
--- /dev/null
+++ b/server/perf/turn-record.ts
@@ -0,0 +1,108 @@
+// One finished bot turn's timings, as the ring keeps them and the reports read them. Privacy invariant: ids that match
+// the opaque-id pattern, engine kinds, fixed codes and numbers only. Never a tool's name as the engine wrote it (an ACP
+// or Codex tool title can be the command itself), a stop reason's words, a prompt or a path.
+import { traceToolLook, type TraceToolIcon } from "../../shared/usage-trace.ts";
+import { PHASES, type PhaseMs } from "./phases.ts";
+
+export type ToolKind = TraceToolIcon;
+const TOOL_KINDS: ReadonlySet<string> = new Set<ToolKind>(["search", "web", "browser", "computer", "phone", "files", "terminal", "memory",
+ "routine", "page", "widget", "bots", "plan", "image", "data", "app", "mcp", "tool"]);
+/** Why a turn's start waited: the plan's limit on turns at once, memory, another turn in its conversation, or nothing
+ * the server held it for (its dispatch: picking the AI, preparing the turn). */
+export type QueueWhy = "plan-limit" | "memory" | "behind-turn" | "dispatch";
+const QUEUE_WHY: ReadonlySet<string> = new Set<QueueWhy>(["plan-limit", "memory", "behind-turn", "dispatch"]);
+export type LimitScope = "engine" | "model" | "credits";
+const LIMIT_SCOPES: ReadonlySet<string> = new Set<LimitScope>(["engine", "model", "credits"]);
+export type FailoverWhy = "limit" | "signed-out";
+
+/** Stop reasons drivers settle a turn with that may be shown as they are; any other becomes "other". */
+const STOP_CODES: ReadonlySet<string> = new Set(["ok", "interrupted", "auth_required", "rpc_error", "shutdown_timeout", "provider_safety",
+ "update_required", "spawn_error", "quota", "tool_error", "exit_before_result", "error_during_execution", "error", "failed", "cap",
+ "max_tokens", "stalled", "stdin_write_failed", "timeout", "waiting_on_person", "other"]);
+/** Why drivers say they retry (classifyError's reasons and the chat runtime's own); any other becomes "other". */
+const RETRY_CODES: ReadonlySet<string> = new Set(["rate_limited", "overloaded", "server_error", "connection_reset", "timeout", "auth", "quota",
+ "unknown_model", "invalid_request", "not_found", "interrupted", "unknown", "provider_safety", "terminal_exit", "tool_limit", "request_too_large",
+ "tool_use_failed", "stream_truncated", "api_error", "max_output_tokens", "compression", "retry", "other"]);
+
+export const ID = /^[A-Za-z0-9_-]{1,64}$/;
+export const KIND = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;
+export const CODE = /^[a-z0-9][a-z0-9_-]{0,47}$/;
+export const matchOr = <T extends string | null>(pattern: RegExp, value: unknown, fallback: T): string | T =>
+ typeof value === "string" && pattern.test(value) ? value : fallback;
+
+export interface ToolStat { kind: ToolKind; n: number; ms: number; max: number; errors: number; open: number }
+
+export interface TurnTiming {
+ turnId: string | null;
+ threadId: string | null;
+ botId: string | null;
+ engine: string | null;
+ startedAt: number;
+ endedAt: number;
+ ok: boolean;
+ stop: string;
+ ms: PhaseMs;
+ queueWhy?: QueueWhy;
+ retries: number;
+ /** What the engine said its retry delays would be, summed. */
+ backoffMs: number;
+ retryWhy?: string[];
+ limit?: LimitScope;
+ limitResetsAt?: number;
+ failover?: FailoverWhy;
+ /** By total time, at most TOOL_KINDS_KEPT. */
+ tools: ToolStat[];
+}
+
+export const TOOL_KINDS_KEPT = 6;
+export const RETRY_WHY_KEPT = 4;
+
+/** A tool call's kind from its engine-given name: a shell command when the engine sent one, else the trace view's icon. */
+export function toolKindOf(title: string | undefined, summary: string | undefined): ToolKind {
+ if (summary) return "terminal";
+ return title ? traceToolLook(title).icon : "tool";
+}
+
+export const stopCode = (ok: boolean, stopReason: unknown): string =>
+ ok ? "ok" : typeof stopReason === "string" && STOP_CODES.has(stopReason) ? stopReason : stopReason ? "other" : "failed";
+
+export const retryCode = (reason: unknown): string => (typeof reason === "string" && RETRY_CODES.has(reason) ? reason : "other");
+
+const count = (value: unknown, max = 1e10): number =>
+ typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.min(Math.round(value), max) : 0;
+
+/** A record read back from disk, every field checked again; null when it is not one. */
+export function parseTurnTiming(value: unknown): TurnTiming | null {
+ const raw = value as Record<string, unknown> | null;
+ if (!raw || typeof raw !== "object" || typeof raw.startedAt !== "number" || typeof raw.endedAt !== "number") return null;
+ const ms: PhaseMs = {};
+ const rawMs = (raw.ms ?? {}) as Record<string, unknown>;
+ for (const phase of PHASES) if (typeof rawMs[phase] === "number") ms[phase] = count(rawMs[phase]);
+ const tools = (Array.isArray(raw.tools) ? raw.tools : []).flatMap((tool: Record<string, unknown>) =>
+ tool && TOOL_KINDS.has(tool.kind as string)
+ ? [{ kind: tool.kind as ToolKind, n: count(tool.n), ms: count(tool.ms), max: count(tool.max), errors: count(tool.errors), open: count(tool.open) }]
+ : []).slice(0, TOOL_KINDS_KEPT);
+ const retryWhy = Array.isArray(raw.retryWhy) ? raw.retryWhy.map(retryCode).slice(0, RETRY_WHY_KEPT) : [];
+ return {
+ turnId: matchOr(ID, raw.turnId, null), threadId: matchOr(ID, raw.threadId, null), botId: matchOr(ID, raw.botId, null),
+ engine: matchOr(KIND, raw.engine, null), startedAt: count(raw.startedAt, 1e14), endedAt: count(raw.endedAt, 1e14), ok: raw.ok === true,
+ stop: stopCode(raw.ok === true, raw.stop), ms,
+ ...(QUEUE_WHY.has(raw.queueWhy as string) ? { queueWhy: raw.queueWhy as QueueWhy } : {}),
+ retries: count(raw.retries, 1e6), backoffMs: count(raw.backoffMs), ...(retryWhy.length ? { retryWhy } : {}),
+ ...(LIMIT_SCOPES.has(raw.limit as string) ? { limit: raw.limit as LimitScope } : {}),
+ ...(typeof raw.limitResetsAt === "number" ? { limitResetsAt: count(raw.limitResetsAt, 1e14) } : {}),
+ ...(raw.failover === "limit" || raw.failover === "signed-out" ? { failover: raw.failover } : {}),
+ tools,
+ };
+}
+
+export const isRetryCode = (value: string): boolean => RETRY_CODES.has(value);
+
+/** A turn's time less its wait on a person: what "slow" is judged on, so an unanswered card never makes a turn slow. */
+export const activeMs = (turn: Pick<TurnTiming, "ms">): number => Math.max(0, (turn.ms.total ?? 0) - (turn.ms.person ?? 0));
+
+/** A count map safe for keys from outside (`__proto__`, `constructor`): no prototype to fall through to. */
+export const counter = (): Record<string, number> => Object.create(null) as Record<string, number>;
+
+export const isToolKind = (value: unknown): value is ToolKind => TOOL_KINDS.has(value as string);
+export const isLimitScope = (value: unknown): value is LimitScope => LIMIT_SCOPES.has(value as string);
diff --git a/server/perf/turn-timings.test.ts b/server/perf/turn-timings.test.ts
new file mode 100644
index 0000000000..e97d6e1bc1
--- /dev/null
+++ b/server/perf/turn-timings.test.ts
@@ -0,0 +1,304 @@
+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import type { RuntimeEvent } from "../contracts.ts";
+import { createTurnTimings, LIVE_TTL_MS, RING_CAP, type SlowNote } from "./turn-timings.ts";
+
+const START = 1_800_000_000_000;
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+function world(options: { file?: string; slowTurnMs?: number; slowToolMs?: number } = {}) {
+ let clock = START;
+ const slow: SlowNote[] = [];
+ const timings = createTurnTimings({ now: () => clock, botOf: () => "bot_1", slow: (note) => slow.push(note), ...options });
+ const emit = (event: { type: string } & Record<string, unknown>, threadId = "thread_1", turnId = "turn_1") =>
+ timings.noteEvent({ eventId: "e", provider: "claudeAgent", threadId, createdAt: "", turnId, ...event } as RuntimeEvent);
+ const say = (threadId = "thread_1", extra: Record<string, unknown> = {}) =>
+ timings.noteMessage(threadId, { at: clock, role: "user", kind: "text", ...extra } as never);
+ return { timings, emit, say, slow, advance: (ms: number) => { clock += ms; }, now: () => clock };
+}
+
+describe("a turn's time, split into phases", () => {
+ it("counts each moment once: model, tool, person, resource and retry add up to the whole turn", () => {
+ const w = world();
+ w.say();
+ w.advance(2_000);
+ w.emit({ type: "turn.started" });
+ w.advance(1_500);
+ w.emit({ type: "session.started", sessionId: null });
+ w.advance(500);
+ w.emit({ type: "content.delta", streamKind: "assistant_text", delta: "x" });
+ w.advance(3_000);
+ w.emit({ type: "item.started", itemType: "tool", itemId: "a", title: "mcp__browser__navigate" });
+ w.advance(1_000);
+ w.emit({ type: "request.opened", requestType: "permission", tool: "Bash", summary: "s" });
+ w.advance(10_000);
+ w.emit({ type: "request.resolved", behavior: "allow", source: "user" });
+ w.advance(4_000);
+ w.emit({ type: "item.completed", itemType: "tool", itemId: "a", ok: true });
+ w.emit({ type: "turn.wait_started", resource: "computer:box:bx_1" });
+ w.advance(6_000);
+ w.emit({ type: "turn.wait_ended", resource: "computer:box:bx_1", waitedMs: 6_000, outcome: "acquired" });
+ w.emit({ type: "turn.retrying", attempt: 1, delayMs: 2_000, reason: "overloaded" });
+ w.advance(2_500);
+ w.emit({ type: "content.delta", streamKind: "assistant_text", delta: "y" });
+ w.advance(1_000);
+ w.emit({ type: "turn.completed", ok: true });
+ const [turn] = w.timings.recent();
+ expect(turn).toMatchObject({
+ botId: "bot_1", threadId: "thread_1", turnId: "turn_1", engine: "claudeAgent", ok: true, stop: "ok", queueWhy: "dispatch",
+ retries: 1, backoffMs: 2_000, retryWhy: ["overloaded"],
+ ms: { queue: 2_000, handshake: 1_500, ttft: 2_000, total: 29_500, model: 6_000, tool: 5_000, person: 10_000, resource: 6_000, retry: 2_500 },
+ tools: [{ kind: "browser", n: 1, ms: 15_000, max: 15_000, errors: 0, open: 0 }],
+ });
+ const { model = 0, tool = 0, person = 0, resource = 0, retry = 0, total } = turn!.ms;
+ expect(model + tool + person + resource + retry).toBe(total);
+ });
+
+ it("names why the start waited: another turn, the plan's limit, memory", () => {
+ const w = world();
+ w.emit({ type: "turn.started" });
+ w.say();
+ w.advance(5_000);
+ w.emit({ type: "turn.completed", ok: true });
+ w.emit({ type: "turn.started" }, "thread_1", "turn_2");
+ w.emit({ type: "turn.completed", ok: true }, "thread_1", "turn_2");
+ w.say("thread_2");
+ w.timings.noteHeld("thread_2", "plan-limit");
+ w.advance(60_000);
+ w.emit({ type: "turn.started" }, "thread_2", "turn_3");
+ w.emit({ type: "turn.completed", ok: true }, "thread_2", "turn_3");
+ expect(w.timings.recent().map((turn) => [turn.turnId, turn.queueWhy, turn.ms.queue])).toEqual([
+ ["turn_1", undefined, undefined], ["turn_2", "behind-turn", 5_000], ["turn_3", "plan-limit", 60_000],
+ ]);
+ });
+
+ it("ignores messages that never wait for a turn of their own", () => {
+ const w = world();
+ w.say("thread_1", { steered: true });
+ w.say("thread_1", { from: { botId: "bot_2" } });
+ w.emit({ type: "turn.started" });
+ w.emit({ type: "turn.completed", ok: true });
+ expect(w.timings.recent()[0]!.ms.queue).toBeUndefined();
+ });
+
+ it("files tool calls by kind only, counts failures, and calls still open at the end as left open", () => {
+ const w = world();
+ w.emit({ type: "turn.started" });
+ w.emit({ type: "item.started", itemType: "tool", itemId: "s", title: "pnpm test --filter secret-project", summary: "pnpm test" });
+ w.advance(3_000);
+ w.emit({ type: "item.completed", itemType: "tool", itemId: "s", ok: false });
+ w.emit({ type: "item.started", itemType: "tool", itemId: "m", title: "mcp__acme-internal__lookup_customer" });
+ w.emit({ type: "item.started", itemType: "tool", itemId: "c", title: "mcp__computer__screenshot" });
+ w.advance(7_000);
+ w.emit({ type: "turn.completed", ok: false, stopReason: "Something with words in it" });
+ const [turn] = w.timings.recent();
+ expect(turn!.stop).toBe("other");
+ expect(turn!.tools).toEqual([
+ { kind: "mcp", n: 1, ms: 7_000, max: 7_000, errors: 1, open: 1 },
+ { kind: "computer", n: 1, ms: 7_000, max: 7_000, errors: 1, open: 1 },
+ { kind: "terminal", n: 1, ms: 3_000, max: 3_000, errors: 1, open: 0 },
+ ]);
+ expect(turn!.ms).toMatchObject({ tool: 10_000, total: 10_000 });
+ });
+
+ it("marks a usage limit and a move to a backup AI, and reports slow turns, tool calls and limits", () => {
+ const w = world({ slowTurnMs: 60_000, slowToolMs: 30_000 });
+ w.emit({ type: "turn.started" });
+ w.emit({ type: "item.started", itemType: "tool", itemId: "b", title: "mcp__browser__click" });
+ w.advance(45_000);
+ w.emit({ type: "item.completed", itemType: "tool", itemId: "b", ok: true });
+ w.advance(20_000);
+ w.emit({ type: "runtime.error", message: "You've hit your limit", limit: "engine", limitResetsAt: START + 3_600_000 });
+ w.timings.noteFailover("thread_1", "limit");
+ w.emit({ type: "turn.completed", ok: false, stopReason: "quota" });
+ expect(w.timings.recent()[0]).toMatchObject({ limit: "engine", limitResetsAt: START + 3_600_000, failover: "limit", stop: "quota" });
+ expect(w.slow.map((note) => note.kind)).toEqual(["tool", "limit", "turn"]);
+ expect(w.timings.day()).toMatchObject({ turns: 1, failed: 1, limits: { "claudeAgent:engine": 1 }, failovers: 1, slow: [1, 0, 0] });
+ });
+
+ it("shows what a running turn is doing now and for how long", () => {
+ const w = world();
+ w.emit({ type: "turn.started" });
+ w.advance(1_000);
+ w.emit({ type: "item.started", itemType: "tool", itemId: "b", title: "mcp__browser__navigate" });
+ w.advance(37 * 60_000);
+ expect(w.timings.live()).toEqual([{ botId: "bot_1", threadId: "thread_1", engine: "claudeAgent", ageMs: 37 * 60_000 + 1_000, state: "tool", stateMs: 37 * 60_000, tool: "browser" }]);
+ });
+
+ it("gives exact percentiles for the last hour and bucketed ones for the day", () => {
+ const w = world();
+ for (let index = 1; index <= 20; index++) {
+ w.emit({ type: "turn.started" }, "thread_1", `t${index}`);
+ w.advance(index * 1_000);
+ w.emit({ type: "turn.completed", ok: true }, "thread_1", `t${index}`);
+ }
+ expect(w.timings.window().phases.total).toEqual({ p50: 10_000, p95: 19_000, max: 20_000, n: 20 });
+ const day = w.timings.day().phases.total!;
+ expect(day.n).toBe(20);
+ expect(day.max).toBe(20_000);
+ expect(day.p50).toBeGreaterThanOrEqual(10_000);
+ expect(day.p95).toBe(20_000);
+ w.advance(2 * 3_600_000);
+ expect(w.timings.window().turns).toBe(0);
+ expect(w.timings.day().turns).toBe(20);
+ });
+});
+
+describe("the ring and its file", () => {
+ it("keeps the latest RING_CAP turns, survives a restart and drops anything malformed in the file", () => {
+ const dir = mkdtempSync(join(tmpdir(), "perf-timings-"));
+ dirs.push(dir);
+ const file = join(dir, "perf-timings.json");
+ const w = world({ file });
+ for (let index = 0; index < RING_CAP + 25; index++) {
+ w.emit({ type: "turn.started" }, "thread_1", `t${index}`);
+ w.advance(100);
+ w.emit({ type: "turn.completed", ok: true }, "thread_1", `t${index}`);
+ }
+ w.timings.flush();
+ expect(statSync(file).size).toBeLessThan(150_000);
+ const saved = JSON.parse(readFileSync(file, "utf8"));
+ saved.ring.push({ startedAt: 1, endedAt: 2, threadId: "../../etc/passwd", engine: "claude --api-key=sk-x", tools: [{ kind: "rm -rf /", n: 1 }] });
+ writeFileSync(file, JSON.stringify(saved));
+ const again = createTurnTimings({ file, now: w.now });
+ const recent = again.recent();
+ expect(recent).toHaveLength(RING_CAP);
+ expect(recent[0]!.turnId).toBe("t26");
+ expect(recent.at(-1)).toMatchObject({ threadId: null, engine: null, tools: [] });
+ expect(again.day().turns).toBe(RING_CAP + 25);
+ });
+});
+
+describe("turns that never ran", () => {
+ it("a start refused by a usage limit with a backup AI: one refused record with its limit, the backup's turn with the move, nothing left running", () => {
+ const w = world();
+ w.say();
+ w.emit({ type: "turn.started" }, "thread_1", "turn_refused");
+ w.advance(2_000);
+ w.timings.noteNotStarted("thread_1", "turn_refused", { limit: "engine", engine: "claudeAgent", resetsAt: START + 3_600_000 });
+ w.timings.noteFailover("thread_1", "limit");
+ w.advance(500);
+ w.timings.noteEvent({ eventId: "e", provider: "codex", threadId: "thread_1", createdAt: "", turnId: "turn_backup", type: "turn.started" } as RuntimeEvent);
+ w.advance(3_000);
+ w.timings.noteEvent({ eventId: "e", provider: "codex", threadId: "thread_1", createdAt: "", turnId: "turn_backup", type: "turn.completed", ok: true } as RuntimeEvent);
+ expect(w.timings.recent().map(({ turnId, engine, stop, limit, failover }) => ({ turnId, engine, stop, limit, failover }))).toEqual([
+ { turnId: "turn_refused", engine: "claudeAgent", stop: "quota", limit: "engine", failover: undefined },
+ { turnId: "turn_backup", engine: "codex", stop: "ok", limit: undefined, failover: "limit" },
+ ]);
+ expect(w.timings.day()).toMatchObject({ turns: 2, limits: { "claudeAgent:engine": 1 }, failovers: 1 });
+ expect(w.timings.live()).toEqual([]);
+ expect(w.slow.map((note) => note.kind)).toEqual(["limit"]);
+ });
+
+ it("a start refused with no backup leaves no phantom running turn", () => {
+ const w = world();
+ w.emit({ type: "turn.started" }, "thread_1", "turn_refused");
+ w.timings.noteNotStarted("thread_1", "turn_refused", { signedOut: true });
+ expect(w.timings.live()).toEqual([]);
+ expect(w.timings.recent()).toMatchObject([{ turnId: "turn_refused", stop: "auth_required", ok: false }]);
+ });
+
+ it("the server's own refusal before any engine ran counts the limit, times no turn, and leaves another thread's turn alone", () => {
+ const w = world();
+ w.emit({ type: "turn.started" }, "thread_2", "turn_other");
+ w.timings.noteNotStarted("thread_1", "signed-out-1", { limit: "model", engine: "claudeAgent" });
+ w.timings.noteNotStarted("thread_2", "not-that-turn", {});
+ expect(w.timings.day()).toMatchObject({ turns: 0, limits: { "claudeAgent:model": 1 } });
+ expect(w.timings.live()).toHaveLength(1);
+ });
+
+ it("a turn replaced by a new one in its thread is finished as stopped, not dropped", () => {
+ const w = world();
+ w.emit({ type: "turn.started" }, "thread_1", "turn_a");
+ w.advance(1_000);
+ w.emit({ type: "turn.started" }, "thread_1", "turn_b");
+ expect(w.timings.recent()).toMatchObject([{ turnId: "turn_a", stop: "other", ok: false, ms: { total: 1_000 } }]);
+ expect(w.timings.live()).toMatchObject([{ state: "model" }]);
+ });
+});
+
+describe("a message whose turn never starts", () => {
+ it("does not time the next turn from it, three hours on", () => {
+ for (const end of ["refused", "failure row", "age"] as const) {
+ const w = world();
+ w.say();
+ if (end === "refused") w.timings.noteNotStarted("thread_1", null);
+ if (end === "failure row") w.timings.noteMessage("thread_1", { at: w.now(), role: "bot", kind: "activity", tool: { name: "error: x", ok: false } } as never);
+ w.advance(3 * 3_600_000);
+ w.say();
+ w.advance(1_000);
+ w.emit({ type: "turn.started" });
+ w.emit({ type: "turn.completed", ok: true });
+ expect(w.timings.recent()[0]!.ms.queue, end).toBe(1_000);
+ }
+ });
+
+ it("keeps the wait across the server's own notices while the turn waits", () => {
+ const w = world();
+ w.say();
+ w.timings.noteHeld("thread_1", "memory");
+ w.timings.noteMessage("thread_1", { at: w.now(), role: "bot", kind: "activity", tool: { name: "notice: Waiting for memory", ok: true } } as never);
+ w.advance(90_000);
+ w.emit({ type: "turn.started" });
+ w.emit({ type: "turn.completed", ok: true });
+ expect(w.timings.recent()[0]).toMatchObject({ queueWhy: "memory", ms: { queue: 90_000 } });
+ });
+});
+
+describe("what counts as slow, and odd clocks", () => {
+ it("time waiting on a person never makes a turn slow, and is still reported", () => {
+ const w = world({ slowTurnMs: 60_000 });
+ w.emit({ type: "turn.started" });
+ w.emit({ type: "request.opened", requestType: "question", tool: "AskUserQuestion", summary: "s" });
+ w.advance(20 * 60_000);
+ w.emit({ type: "request.resolved", behavior: "answer", source: "user" });
+ w.advance(30_000);
+ w.emit({ type: "turn.completed", ok: true });
+ expect(w.timings.recent()[0]!.ms).toMatchObject({ person: 20 * 60_000, total: 20 * 60_000 + 30_000 });
+ expect(w.timings.day().slow).toEqual([0, 0, 0]);
+ expect(w.timings.window().slow).toEqual([0, 0, 0]);
+ expect(w.slow).toEqual([]);
+ });
+
+ it("a clock set back mid-turn gives zero, never a negative duration", () => {
+ const w = world();
+ w.emit({ type: "turn.started" });
+ w.advance(-10_000);
+ w.emit({ type: "session.started", sessionId: null });
+ w.emit({ type: "content.delta", streamKind: "assistant_text", delta: "x" });
+ const [live] = w.timings.live();
+ expect(live!.ageMs).toBe(0);
+ expect(live!.stateMs).toBe(0);
+ w.emit({ type: "turn.completed", ok: true });
+ const { ms } = w.timings.recent()[0]!;
+ expect(Object.values(ms).every((value) => value >= 0)).toBe(true);
+ expect(ms).toMatchObject({ handshake: 0, ttft: 0, total: 0 });
+ });
+
+ it("a turn past the live limit leaves the running list; one waiting on a person is finished as such", () => {
+ const w = world();
+ w.emit({ type: "turn.started" }, "thread_1", "lost");
+ w.emit({ type: "turn.started" }, "thread_2", "asking");
+ w.emit({ type: "request.opened", requestType: "question", tool: "AskUserQuestion", summary: "s" }, "thread_2", "asking");
+ w.advance(LIVE_TTL_MS + 1);
+ expect(w.timings.live()).toEqual([]);
+ expect(w.timings.recent()).toMatchObject([{ turnId: "asking", stop: "waiting_on_person", ms: { person: LIVE_TTL_MS + 1 } }]);
+ });
+
+ it("keys from outside never reach an object's prototype", () => {
+ const w = world();
+ w.emit({ type: "turn.started" });
+ for (const reason of ["constructor", "__proto__", "toString", "hasOwnProperty", "rate_limited"]) w.emit({ type: "turn.retrying", attempt: 1, delayMs: 0, reason });
+ w.emit({ type: "turn.completed", ok: false, stopReason: "constructor" });
+ w.timings.noteNotStarted("thread_9", null, { limit: "engine", engine: "__proto__" });
+ w.timings.noteNotStarted("thread_9", null, { limit: "engine", engine: "constructor" });
+ const day = w.timings.day();
+ expect({ ...day.retries.why }).toEqual({ other: 4 });
+ expect(w.timings.recent()[0]).toMatchObject({ retryWhy: ["other", "other", "other", "other"], stop: "other" });
+ expect(Object.keys(day.limits).sort()).toEqual(["constructor:engine", "unknown:engine"]);
+ expect(JSON.stringify(day)).not.toContain("native code");
+ });
+});
diff --git a/server/perf/turn-timings.ts b/server/perf/turn-timings.ts
new file mode 100644
index 0000000000..8d06a51626
--- /dev/null
+++ b/server/perf/turn-timings.ts
@@ -0,0 +1,326 @@
+// Where each bot turn's time went, from the runtime events the server already has: no timer of its own beyond one
+// debounced save, no process, no network. O(1) work per event; bounded memory (RING_CAP finished turns, LIVE_CAP live
+// ones, the day ledger's fixed slots). Privacy invariant: only a TurnTiming's checked fields leave it.
+import { readFileSync } from "node:fs";
+
+import { writeFileAtomic } from "../atomic.ts";
+import type { RuntimeEvent } from "../contracts.ts";
+import type { Message } from "../store.ts";
+import { createDayLedger, DAY_HOURS, SLOW_TURN_MS } from "./day-ledger.ts";
+import { exactQuantile, PHASES, type Phase, type PhaseMs, type PhaseStats } from "./phases.ts";
+import {
+ activeMs, ID, isLimitScope, KIND, matchOr, parseTurnTiming, retryCode, RETRY_WHY_KEPT, stopCode, TOOL_KINDS_KEPT, toolKindOf,
+ type FailoverWhy, type LimitScope, type QueueWhy, type ToolKind, type ToolStat, type TurnTiming,
+} from "./turn-record.ts";
+
+export const RING_CAP = 200;
+const LIVE_CAP = 200, PENDING_CAP = 500, OPEN_TOOLS_CAP = 64;
+/** A turn whose end never came is taken as over after this long: dropped, or, while it waits on a person, finished as such. */
+export const LIVE_TTL_MS = 6 * 3_600_000;
+/** A person's message waits for its turn at most this long before it is no longer timed. */
+export const PENDING_TTL_MS = 2 * 3_600_000;
+/** A move to a backup AI marks the thread's next turn only if that turn starts this soon after. */
+const FAILOVER_TTL_MS = 10 * 60_000;
+/** The file is written at most this often, and only after a turn ends. */
+export const SAVE_EVERY_MS = 60_000;
+const HOUR = 3_600_000;
+
+/** What a live turn is doing now; the turn's time is the sum of the time spent in each. */
+export type LiveState = "model" | "tool" | "resource" | "person" | "retry";
+const STATE_PHASE: Record<LiveState, Phase> = { model: "model", tool: "tool", resource: "resource", person: "person", retry: "retry" };
+
+interface Live {
+ key: string;
+ turnId: string | null;
+ threadId: string | null;
+ botId: string | null;
+ engine: string | null;
+ startedAt: number;
+ queueMs?: number;
+ queueWhy?: QueueWhy;
+ sessionAt: number | null;
+ firstOutputAt: number | null;
+ state: LiveState;
+ stateSince: number;
+ spent: Record<LiveState, number>;
+ openTools: Map<string, { kind: ToolKind; at: number }>;
+ requests: number;
+ waits: number;
+ retrying: boolean;
+ retries: number;
+ backoffMs: number;
+ retryWhy: string[];
+ limit?: LimitScope;
+ limitResetsAt?: number;
+ failover?: FailoverWhy;
+ tools: Map<ToolKind, ToolStat>;
+}
+
+export interface LiveTurnView { botId: string | null; threadId: string | null; engine: string | null; ageMs: number; state: LiveState; stateMs: number; tool?: ToolKind; queueMs?: number }
+
+export interface WindowStats { turns: number; failed: number; phases: Partial<Record<Phase, PhaseStats>>; slow: number[]; partial: boolean }
+
+/** What refused a turn before it ran: a usage limit (and on which engine), or a sign-in that expired. */
+export interface Refusal { limit?: LimitScope; engine?: string | null; resetsAt?: number; signedOut?: boolean }
+
+/** A slow event worth one log line: a slow turn (its time less any wait on a person), a slow tool call, a usage limit refusing a turn. */
+export type SlowNote =
+ | { kind: "turn"; turn: TurnTiming }
+ | { kind: "tool"; tool: ToolKind; ms: number; ok: boolean; engine: string | null; botId: string | null; threadId: string | null }
+ | { kind: "limit"; engine: string | null; scope: LimitScope; resetsAt?: number };
+
+export interface TurnTimingsOptions {
+ /** The saved ring and day; absent: memory only. */
+ file?: string;
+ botOf?: (threadId: string) => string | null;
+ now?: () => number;
+ slow?: (note: SlowNote) => void;
+ /** A turn past this is reported to `slow`. */
+ slowTurnMs?: number;
+ /** A tool call past this is reported to `slow`. */
+ slowToolMs?: number;
+}
+
+const stateOf = (live: Live): LiveState =>
+ live.requests > 0 ? "person" : live.waits > 0 ? "resource" : live.retrying ? "retry" : live.openTools.size > 0 ? "tool" : "model";
+
+const PERSON_MESSAGE = (message: Pick<Message, "role" | "kind" | "steered" | "aside" | "from" | "peerAsk" | "automation">) =>
+ message.role === "user" && message.kind === "text" && !message.steered && !message.aside && !message.from?.botId && !message.peerAsk && !message.automation;
+
+export function createTurnTimings(options: TurnTimingsOptions = {}) {
+ const now = options.now ?? Date.now;
+ const slowTurnMs = options.slowTurnMs ?? 300_000, slowToolMs = options.slowToolMs ?? 120_000;
+ const day = createDayLedger(now);
+ const ring: TurnTiming[] = [];
+ const live = new Map<string, Live>();
+ const pending = new Map<string, { at: number; behind: boolean }>();
+ const held = new Map<string, QueueWhy>();
+ const failovers = new Map<string, { why: FailoverWhy; at: number }>();
+ let savedAt = -Infinity, saveTimer: ReturnType<typeof setTimeout> | null = null;
+
+ const remember = <V>(map: Map<string, V>, key: string, value: V, cap: number) => {
+ map.delete(key);
+ map.set(key, value);
+ if (map.size > cap) map.delete(map.keys().next().value as string);
+ };
+ const shift = (turn: Live, at: number) => {
+ turn.spent[turn.state] += Math.max(0, at - turn.stateSince);
+ turn.stateSince = at;
+ turn.state = stateOf(turn);
+ };
+
+ const save = () => {
+ saveTimer = null;
+ if (!options.file) return;
+ savedAt = now();
+ try { writeFileAtomic(options.file, JSON.stringify({ v: 1, ring, day: day.save() }), { mode: 0o600, durable: false }); } catch {}
+ };
+ const saveSoon = () => {
+ if (!options.file || saveTimer) return;
+ saveTimer = setTimeout(save, Math.max(0, savedAt + SAVE_EVERY_MS - now()));
+ saveTimer.unref?.();
+ };
+ if (options.file) {
+ try {
+ const saved = JSON.parse(readFileSync(options.file, "utf8")) as { v?: number; ring?: unknown[]; day?: unknown };
+ if (saved?.v === 1) {
+ for (const raw of (Array.isArray(saved.ring) ? saved.ring : []).slice(-RING_CAP)) {
+ const turn = parseTurnTiming(raw);
+ if (turn) ring.push(turn);
+ }
+ day.load(saved.day);
+ }
+ } catch {}
+ }
+
+ const sweep = (at: number) => {
+ for (const [key, turn] of live) {
+ if (turn.startedAt >= at - LIVE_TTL_MS) break;
+ live.delete(key);
+ if (turn.requests > 0) finish(turn, false, "waiting_on_person", at);
+ }
+ };
+ const clearWaiting = (threadId: string) => { pending.delete(threadId); held.delete(threadId); };
+
+ const start = (event: RuntimeEvent, at: number) => {
+ const threadId = event.threadId;
+ sweep(at);
+ const replaced = live.get(threadId);
+ if (replaced) { live.delete(threadId); finish(replaced, false, "other", at); }
+ const waiting = pending.get(threadId);
+ const why = held.get(threadId);
+ clearWaiting(threadId);
+ const moved = failovers.get(threadId);
+ failovers.delete(threadId);
+ const failover = moved && at - moved.at <= FAILOVER_TTL_MS ? moved.why : undefined;
+ const queueMs = waiting && at - waiting.at <= PENDING_TTL_MS ? Math.max(0, at - waiting.at) : undefined;
+ const turn: Live = {
+ key: threadId, turnId: matchOr(ID, event.turnId, null), threadId: matchOr(ID, threadId, null),
+ botId: matchOr(ID, options.botOf?.(threadId), null), engine: matchOr(KIND, event.provider, null), startedAt: at,
+ ...(queueMs !== undefined ? { queueMs, queueWhy: why ?? (waiting!.behind ? "behind-turn" : "dispatch") } : {}),
+ sessionAt: null, firstOutputAt: null, state: "model", stateSince: at, spent: { model: 0, tool: 0, resource: 0, person: 0, retry: 0 },
+ openTools: new Map(), requests: 0, waits: 0, retrying: false, retries: 0, backoffMs: 0, retryWhy: [], tools: new Map(),
+ ...(failover ? { failover } : {}),
+ };
+ remember(live, threadId, turn, LIVE_CAP);
+ };
+
+ const toolEnded = (turn: Live, call: { kind: ToolKind; at: number }, at: number, ok: boolean, open: boolean) => {
+ const ms = Math.max(0, at - call.at);
+ const stat = turn.tools.get(call.kind) ?? { kind: call.kind, n: 0, ms: 0, max: 0, errors: 0, open: 0 };
+ stat.n += 1; stat.ms += ms; stat.max = Math.max(stat.max, ms);
+ if (!ok) stat.errors += 1;
+ if (open) stat.open += 1;
+ turn.tools.set(call.kind, stat);
+ day.noteTool(call.kind, ms, ok, open, at);
+ if (ms >= slowToolMs) options.slow?.({ kind: "tool", tool: call.kind, ms, ok: ok && !open, engine: turn.engine, botId: turn.botId, threadId: turn.threadId });
+ };
+
+ function finish(turn: Live, ok: boolean, stopReason: unknown, at: number) {
+ shift(turn, at);
+ for (const call of turn.openTools.values()) toolEnded(turn, call, at, false, true);
+ const ms: PhaseMs = { total: Math.max(0, at - turn.startedAt) };
+ if (turn.queueMs !== undefined) ms.queue = turn.queueMs;
+ if (turn.sessionAt !== null) ms.handshake = Math.max(0, turn.sessionAt - turn.startedAt);
+ if (turn.firstOutputAt !== null) ms.ttft = Math.max(0, turn.firstOutputAt - turn.startedAt);
+ for (const [state, spent] of Object.entries(turn.spent) as Array<[LiveState, number]>) if (spent > 0 || state === "model") ms[STATE_PHASE[state]] = spent;
+ const record: TurnTiming = {
+ turnId: turn.turnId, threadId: turn.threadId, botId: turn.botId, engine: turn.engine, startedAt: turn.startedAt, endedAt: at,
+ ok, stop: stopCode(ok, stopReason), ms, ...(turn.queueWhy ? { queueWhy: turn.queueWhy } : {}),
+ retries: turn.retries, backoffMs: turn.backoffMs, ...(turn.retryWhy.length ? { retryWhy: turn.retryWhy } : {}),
+ ...(turn.limit ? { limit: turn.limit } : {}), ...(turn.limitResetsAt ? { limitResetsAt: turn.limitResetsAt } : {}),
+ ...(turn.failover ? { failover: turn.failover } : {}),
+ tools: [...turn.tools.values()].sort((left, right) => right.ms - left.ms).slice(0, TOOL_KINDS_KEPT),
+ };
+ ring.push(record);
+ if (ring.length > RING_CAP) ring.splice(0, ring.length - RING_CAP);
+ day.noteTurn(record);
+ if (activeMs(record) >= slowTurnMs) options.slow?.({ kind: "turn", turn: record });
+ saveSoon();
+ }
+
+ return {
+ noteEvent(event: RuntimeEvent) {
+ const at = now();
+ if (event.type === "turn.started") {
+ const current = live.get(event.threadId);
+ if (!current || (event.turnId && current.turnId !== matchOr(ID, event.turnId, null))) start(event, at);
+ return;
+ }
+ if (event.type === "runtime.error" && isLimitScope(event.limit)) {
+ const turn = live.get(event.threadId);
+ if (turn) { turn.limit = event.limit; if (typeof event.limitResetsAt === "number") turn.limitResetsAt = event.limitResetsAt; }
+ options.slow?.({ kind: "limit", engine: turn?.engine ?? matchOr(KIND, event.provider, null), scope: event.limit, ...(typeof event.limitResetsAt === "number" ? { resetsAt: event.limitResetsAt } : {}) });
+ }
+ const turn = live.get(event.threadId);
+ if (!turn || (event.turnId && turn.turnId && event.turnId !== turn.turnId)) return;
+ if (turn.retrying && event.type !== "turn.retrying") turn.retrying = false;
+ switch (event.type) {
+ case "session.started": turn.sessionAt ??= at; break;
+ case "content.delta": case "item.started": case "request.opened": turn.firstOutputAt ??= at; break;
+ case "item.completed": if (event.itemType === "assistant_text") turn.firstOutputAt ??= at; break;
+ }
+ switch (event.type) {
+ case "turn.completed": live.delete(event.threadId); return finish(turn, event.ok, event.stopReason, at);
+ case "item.started":
+ if (event.itemType === "tool" && turn.openTools.size < OPEN_TOOLS_CAP) turn.openTools.set(event.itemId ?? `#${turn.openTools.size}`, { kind: toolKindOf(event.title, event.summary), at });
+ break;
+ case "item.completed": {
+ if (event.itemType !== "tool") break;
+ const id = event.itemId && turn.openTools.has(event.itemId) ? event.itemId : turn.openTools.keys().next().value;
+ const call = id === undefined ? undefined : turn.openTools.get(id);
+ if (call && id !== undefined) { shift(turn, at); turn.openTools.delete(id); toolEnded(turn, call, at, event.ok, false); }
+ break;
+ }
+ case "request.opened": turn.requests += 1; break;
+ case "request.resolved": turn.requests = Math.max(0, turn.requests - 1); break;
+ case "turn.wait_started": turn.waits += 1; break;
+ case "turn.wait_ended": turn.waits = Math.max(0, turn.waits - 1); break;
+ case "turn.retrying":
+ turn.retries += 1;
+ turn.backoffMs += Math.max(0, Math.min(Number(event.delayMs) || 0, HOUR));
+ if (turn.retryWhy.length < RETRY_WHY_KEPT) turn.retryWhy.push(retryCode(event.reason));
+ turn.retrying = true;
+ break;
+ }
+ if (stateOf(turn) !== turn.state) shift(turn, at);
+ },
+ /** Every message the store appends: a person's message starts their wait for a turn; a reply or a failure row while
+ * no turn runs ends that wait unanswered. Other bot rows do not: wait notices are posted while the turn waits. */
+ noteMessage(threadId: string, message: Pick<Message, "at" | "role" | "kind" | "steered" | "aside" | "from" | "peerAsk" | "automation" | "tool">) {
+ if (message.role !== "user") {
+ if (!live.has(threadId) && (message.kind === "text" || message.tool?.ok === false)) clearWaiting(threadId);
+ return;
+ }
+ const waiting = pending.get(threadId);
+ if (!PERSON_MESSAGE(message) || (waiting && message.at - waiting.at <= PENDING_TTL_MS)) return;
+ remember(pending, threadId, { at: message.at, behind: live.has(threadId) }, PENDING_CAP);
+ },
+ /**
+ * A turn this thread was dispatching never ran (`turnId`, the id the driver refused it under). Its wait ends; a turn
+ * the engine had already announced under that id is finished as refused; a usage limit counts even with no turn.
+ */
+ noteNotStarted(threadId: string, turnId: string | null, refusal: Refusal = {}) {
+ const at = now();
+ clearWaiting(threadId);
+ const turn = live.get(threadId);
+ const engine = refusal.engine === undefined ? turn?.engine ?? null : matchOr(KIND, refusal.engine, null);
+ const limit = isLimitScope(refusal.limit) ? refusal.limit : undefined;
+ const resetsAt = typeof refusal.resetsAt === "number" && Number.isFinite(refusal.resetsAt) ? refusal.resetsAt : undefined;
+ if (limit) options.slow?.({ kind: "limit", engine, scope: limit, ...(resetsAt ? { resetsAt } : {}) });
+ if (turn && turnId !== null && turn.turnId === matchOr(ID, turnId, null)) {
+ live.delete(threadId);
+ if (limit) { turn.limit = limit; if (resetsAt) turn.limitResetsAt = resetsAt; }
+ return finish(turn, false, limit ? "quota" : refusal.signedOut ? "auth_required" : "other", at);
+ }
+ if (limit) { day.noteRefusal(engine, limit, at); saveSoon(); }
+ },
+ /** This thread's next turn waits for a place: under the plan's limit on turns at once, or for memory. */
+ noteHeld(threadId: string, why: "plan-limit" | "memory") { remember(held, threadId, why, PENDING_CAP); },
+ /** This thread moved to another AI: a usage limit, or its AI signed out. */
+ noteFailover(threadId: string, why: FailoverWhy) {
+ const turn = live.get(threadId);
+ if (turn) turn.failover = why; else remember(failovers, threadId, { why, at: now() }, PENDING_CAP);
+ },
+ /** The latest finished turns, newest last, in these threads or of these bots when given. */
+ recent(filter: { threadIds?: readonly string[]; botIds?: readonly string[]; limit?: number } = {}): TurnTiming[] {
+ const threads = new Set(filter.threadIds ?? []), bots = new Set(filter.botIds ?? []);
+ const all = !threads.size && !bots.size;
+ const picked = ring.filter((turn) => all || (turn.threadId !== null && threads.has(turn.threadId)) || (turn.botId !== null && bots.has(turn.botId)));
+ return picked.slice(-(filter.limit ?? RING_CAP)).map((turn) => ({ ...turn, ms: { ...turn.ms }, tools: turn.tools.map((tool) => ({ ...tool })) }));
+ },
+ /** Exact percentiles over the turns that ended in the last `windowMs`, from the ring; `partial` when the ring is full
+ * and its oldest turn ended inside the window, so turns before it are missing. */
+ window(windowMs = HOUR): WindowStats {
+ const from = now() - windowMs;
+ const turns = ring.filter((turn) => turn.endedAt > from);
+ const phases: Partial<Record<Phase, PhaseStats>> = {};
+ for (const phase of PHASES) {
+ const values = turns.flatMap((turn) => (turn.ms[phase] === undefined ? [] : [turn.ms[phase]])).sort((left, right) => left - right);
+ if (values.length) phases[phase] = { p50: exactQuantile(values, 0.5), p95: exactQuantile(values, 0.95), max: values.at(-1)!, n: values.length };
+ }
+ const slow = SLOW_TURN_MS.map((edge) => turns.filter((turn) => activeMs(turn) > edge).length);
+ return { turns: turns.length, failed: turns.filter((turn) => !turn.ok).length, phases, slow, partial: ring.length >= RING_CAP && ring[0]!.endedAt > from };
+ },
+ day: (windowMs = DAY_HOURS * HOUR) => day.read(windowMs),
+ live(): LiveTurnView[] {
+ const at = now();
+ sweep(at);
+ return [...live.values()].map((turn) => {
+ const oldest = turn.openTools.values().next().value;
+ return { botId: turn.botId, threadId: turn.threadId, engine: turn.engine, ageMs: Math.max(0, at - turn.startedAt), state: turn.state, stateMs: Math.max(0, at - turn.stateSince),
+ ...(oldest ? { tool: oldest.kind } : {}), ...(turn.queueMs !== undefined ? { queueMs: turn.queueMs } : {}) };
+ }).sort((left, right) => right.ageMs - left.ageMs);
+ },
+ /** The engine kind this thread's turns run on, from its live turn or its latest finished one. */
+ engineOf(threadId: string): string | null {
+ const turn = live.get(threadId);
+ if (turn) return turn.engine;
+ for (let index = ring.length - 1; index >= 0; index--) if (ring[index]!.threadId === threadId) return ring[index]!.engine;
+ return null;
+ },
+ /** Writes now (tests, and a clean exit). */
+ flush() { if (saveTimer) clearTimeout(saveTimer); save(); },
+ };
+}
+export type TurnTimings = ReturnType<typeof createTurnTimings>;
diff --git a/server/routes/perf-diagnostics.ts b/server/routes/perf-diagnostics.ts
new file mode 100644
index 0000000000..19f91d2a73
--- /dev/null
+++ b/server/routes/perf-diagnostics.ts
@@ -0,0 +1,13 @@
+// GET /api/diagnostics/performance: the performance recorder's plain lines for the desktop's diagnostics export. Admin
+// scope (request-auth's default), so on a Cloud home a bot's shell, a service-trust loopback caller, never reaches it.
+import { PASS, type RouteHandler } from "./table.ts";
+
+export const PERF_DIAGNOSTICS_PATH = "/api/diagnostics/performance";
+
+export function createPerfDiagnosticsRoutes(deps: { text(): string }): RouteHandler {
+ return async ({ res, path, method, json }) => {
+ if (path !== PERF_DIAGNOSTICS_PATH || method !== "GET") return PASS;
+ res.setHeader("cache-control", "no-store");
+ return json(res, 200, { text: deps.text() });
+ };
+}