Skip to content
Python

feat(gui): Phase 3 screens: Usage tab, turn footer and ratings, coworker history, team wakes, run health

Devika Verma7515d3040999
diff --git a/coworker/server/manager.py b/coworker/server/manager.py
index ffb00a44..dea6ed2d 100644
--- a/coworker/server/manager.py
+++ b/coworker/server/manager.py
@@ -2771,6 +2771,26 @@ class SessionManager:
if c is not None:
cov[str(item["id"])] = c
out["coverage"] = cov
+ by_session = {team.lead_session: team.lead_actor, **{w.session_id: w.actor for w in team.workers}}
+ for it in out.get("items") or []:
+ c = cov.get(str(it.get("id")))
+ if c is None:
+ continue
+ # The shape the item card reads (OB-16): scans by name and area, each with
+ # its turn and step, and the findings with their evidence links.
+ it["coverage"] = {
+ "promised": c["promised"], "issues": c["issues"], "fine": c["fine"], "report": c["report"],
+ "scans": [{"scanner": sc["scanner"]["name"], "area": sc["area"], "exit_code": sc["exit_code"],
+ "ok": not sc["failed"], "found_something": sc["found_something"],
+ "session_id": sc["session_id"], "turn_id": sc["turn_id"], "turn_seq": sc["turn_seq"],
+ "step_seq": sc["seq"], "step_id": sc["step_id"],
+ "result_sha256": sc["result_sha256"], "actor": by_session.get(sc["session_id"])}
+ for sc in c["scans"]]}
+ fix = c.get("fix") or {}
+ it["findings"] = [{"id": f["seq"], "severity": f.get("severity"), "evidence": f.get("evidence") or [],
+ "step_call_id": f.get("step_call_id"), "session_id": f.get("session_id"),
+ "author": f.get("author"), "fixed_by": fix.get("fixed_by"),
+ "verified_by": fix.get("verified_by")} for f in c["findings"]]
except Exception: # noqa: BLE001 - the split never hides the rest of the summary
logger.exception("could not work out team %s wakes", team_id)
out.setdefault("wakes", [])
@@ -7033,7 +7053,7 @@ class SessionManager:
cards = {(s.get("attrs") or {}).get("for_call_id") for s in steps if s.get("kind") == "wait"
and (s.get("attrs") or {}).get("kind") == "approval" and (s.get("attrs") or {}).get("for_call_id")}
out.append({"turn_id": t["turn_id"], "seq": t.get("seq"), "status": t.get("status"),
- "first_message_id": t.get("first_message_id"), "last_message_id": t.get("last_message_id"),
+ "started_at": t.get("started_at"), "first_message_id": t.get("first_message_id"), "last_message_id": t.get("last_message_id"),
"duration_ms": t.get("duration_ms"), "active_ms": n["active_ms"], "total": n["total"],
"at_least": n["at_least"], "warn": n["warn"], "auto_approved": len(n["auto_approved"]),
"asked": len(cards), "live_checks": len(n["checks"]),
diff --git a/surfaces/gui/src/App.tsx b/surfaces/gui/src/App.tsx
index 21942893..50e3583b 100644
--- a/surfaces/gui/src/App.tsx
+++ b/surfaces/gui/src/App.tsx
@@ -93,6 +93,7 @@ import { RightRail } from "./components/RightRail";
import { SettingsView, type SetTab } from "./components/SettingsView";
import { PersonaView } from "./components/PersonaView";
import { AuditView } from "./components/AuditView";
+import { useSessionFooters } from "./components/TurnFooter";
import { InboxView } from "./components/InboxView";
import {
approvalItemFromPayload,
@@ -420,7 +421,10 @@ export function App() {
const [stepsOpen, setStepsOpen] = useState(false);
const [stepsKey, setStepsKey] = useState(0);
// A turn's answer opened the panel: the answer's time picks the turn (unix seconds).
- const [stepsAt, setStepsAt] = useState<{ ts?: number; n: number } | null>(null);
+ const [stepsAt, setStepsAt] = useState<{ ts?: number; turnId?: string; n: number } | null>(null);
+ // OB-5 (Phase 3): the footers under each answer, read again when a turn ends.
+ const [footKey, setFootKey] = useState(0);
+ const [footers, setFooter] = useSessionFooters(sessionId, footKey);
const [teamWorkerId, setTeamWorkerId] = useState<string | null>(null);
const [teamWorkerFilter, setTeamWorkerFilter] = useState<WorkerFilter | null>(null);
const [teamSummary, setTeamSummary] = useState<TeamSummary | null>(null);
@@ -1173,6 +1177,7 @@ export function App() {
case "turn_done":
setRunning(false);
setStepsKey((k) => k + 1);
+ setFootKey((k) => k + 1);
setReviewerPaused(false); // the pause is scoped to the turn
refreshSessions();
// Catch-all artifact refresh: files created via shell or on a brand-new session (whose
@@ -1658,6 +1663,20 @@ export function App() {
};
const openSessionFromInbox = (sid: string, ws: string, ag: string) => selectSession(sid, ws, ag);
+ // Phase 3: open one recorded turn's Steps, in its own session (Usage's heaviest turns,
+ // TeamView's events and evidence, an automation run's Steps).
+ const openTurnSteps = (sid: string, turnId: string) => {
+ const w = sessions.find((x) => x.session_id === sid);
+ const open = () => {
+ setStepsAt((prev) => ({ turnId, n: (prev?.n || 0) + 1 }));
+ setStepsOpen(true);
+ setTeamViewOpen(false);
+ setRailHidden(false);
+ };
+ if (sid === sessionId) return open();
+ if (!w) return;
+ void selectSession(w.session_id, w.workspace, w.agent).then(open);
+ };
const selectSession = async (id: string, ws: string, ag: string) => {
setSurface("session"); // selecting a conversation always returns to the conversation view
setTodo([]);
@@ -1855,6 +1874,18 @@ export function App() {
setShowGate(false);
selectSession(sessionId, ws, ag);
};
+ // OB-18: a run's Steps, at its first turn.
+ const openRunSteps = (sid: string, turnId: string, ws: string, ag: string, task?: { id: string; title: string }) => {
+ setRunContext(task ?? null);
+ setSurface("session");
+ setShowGate(false);
+ void selectSession(sid, ws, ag).then(() => {
+ setStepsAt((prev) => ({ turnId, n: (prev?.n || 0) + 1 }));
+ setStepsOpen(true);
+ setTeamViewOpen(false);
+ setRailHidden(false);
+ });
+ };
const runTaskNow = async (taskId: string, title?: string) => {
const r = await runAutomation(taskId);
if (!r || !r.ok) return;
@@ -2107,6 +2138,7 @@ export function App() {
{surface === "scheduled" ? (
<ScheduledView
onOpenRun={openRunSession}
+ onOpenRunSteps={openRunSteps}
onRunNow={runTaskNow}
initialOpenId={scheduledOpenId}
/>
@@ -2144,7 +2176,7 @@ export function App() {
}}
/>
) : surface === "audit" ? (
- <AuditView callId={auditCallId} />
+ <AuditView callId={auditCallId} onOpenTurn={openTurnSteps} />
) : surface === "inbox" ? (
<InboxView onOpenSession={openSessionFromInbox} />
) : surface === "persona" ? (
@@ -2362,8 +2394,11 @@ export function App() {
setSurface("audit");
}}
onUndoMemory={(id, previous) => void undoMemorySave(id, previous)}
- onOpenSteps={agent !== "chat" ? (ts) => {
- setStepsAt((prev) => ({ ts, n: (prev?.n || 0) + 1 }));
+ footers={agent !== "chat" ? footers : null}
+ footerSessionId={sessionId || undefined}
+ onFooterChange={setFooter}
+ onOpenSteps={agent !== "chat" ? (ts, turnId) => {
+ setStepsAt((prev) => ({ ts, turnId, n: (prev?.n || 0) + 1 }));
setStepsOpen(true);
setTeamViewOpen(false);
setRailHidden(false);
@@ -2644,7 +2679,7 @@ export function App() {
/>
</div>
<RightRail
- teamView={stepsOpen && sessionId ? <StepsPanel sessionId={sessionId} refreshKey={stepsKey} openAt={stepsAt} onClose={() => setStepsOpen(false)} onOpenSession={(id) => { const w = sessions.find(s => s.session_id === id); if (w) void selectSession(w.session_id, w.workspace, w.agent); }} /> : teamViewOpen ? <TeamView openKey={boardRailKey} board={boardOwner === sessionId ? board : null} summary={teamSummary?.lead_session === sessionId ? teamSummary : null} initialItem={boardDetailId} initialWorkerId={teamWorkerId} initialWorkerFilter={teamWorkerFilter} onOpenFullSession={(id) => { const w = sessions.find(s => s.session_id === id); if (w) void selectSession(w.session_id, w.workspace, w.agent); }} sessionId={sessionId} sessions={sessions} machine={machine} machineName={curSession?.machine_name} onClose={() => { setTeamViewOpen(false); setBoardDetailId(null); setTeamWorkerId(null); setTeamWorkerFilter(null); }} onRefresh={() => { void refreshBoard(); setBrowserRefreshKey(k => k + 1); }} /> : undefined}
+ teamView={stepsOpen && sessionId ? <StepsPanel sessionId={sessionId} refreshKey={stepsKey} openAt={stepsAt} onClose={() => setStepsOpen(false)} onOpenSession={(id) => { const w = sessions.find(s => s.session_id === id); if (w) void selectSession(w.session_id, w.workspace, w.agent); }} /> : teamViewOpen ? <TeamView openKey={boardRailKey} board={boardOwner === sessionId ? board : null} summary={teamSummary?.lead_session === sessionId ? teamSummary : null} initialItem={boardDetailId} initialWorkerId={teamWorkerId} initialWorkerFilter={teamWorkerFilter} onOpenFullSession={(id) => { const w = sessions.find(s => s.session_id === id); if (w) void selectSession(w.session_id, w.workspace, w.agent); }} sessionId={sessionId} sessions={sessions} machine={machine} machineName={curSession?.machine_name} onClose={() => { setTeamViewOpen(false); setBoardDetailId(null); setTeamWorkerId(null); setTeamWorkerFilter(null); }} onRefresh={() => { void refreshBoard(); setBrowserRefreshKey(k => k + 1); }} onOpenSteps={openTurnSteps} /> : undefined}
active={surface === "session" && agent !== "chat" && !railHidden}
sessionId={sessionId}
refreshKey={browserRefreshKey}
diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.ts
index 4e37b7d4..ebe4c67a 100644
--- a/surfaces/gui/src/api.ts
+++ b/surfaces/gui/src/api.ts
@@ -10,6 +10,7 @@ import {
toolResponseMessage,
} from "./cardPayloads";
import type { GroupedQuestion, QuestionOption, SessionInfo, WsEvent } from "./types";
+import type { DayBoundary, FeedbackWhere, RollupGroup, TurnFeedback, TurnFooter } from "./obs3";
declare const __COWORKER_DEV_TOKEN__: string;
@@ -3076,6 +3077,26 @@ export interface AutomationRun {
artifacts: string[];
error: string | null;
trigger: string;
+ // OB-18 (Phase 3): from the run's own recorded turns. Absent on older engines.
+ turns?: number;
+ total?: number | null;
+ at_least?: boolean;
+ active_ms?: number | null;
+ duration_ms?: number | null;
+ warn?: number | null;
+ checks?: string[];
+ check_titles?: string[];
+ health?: "ok" | "failed" | "skipped" | "did_not_finish" | "unknown";
+ first_turn_id?: string | null;
+ first_turn_seq?: number | null;
+}
+
+export interface FailedInARow {
+ count: number;
+ last_error: string | null;
+ run_id?: string;
+ session_id?: string;
+ turn_id?: string | null;
}
export async function getAutomations(): Promise<Automation[]> {
@@ -3145,7 +3166,7 @@ export async function createAutomation(payload: {
return res.json();
}
-export async function getAutomation(id: string): Promise<{ task: Automation; runs: AutomationRun[] }> {
+export async function getAutomation(id: string): Promise<{ task: Automation; runs: AutomationRun[]; failed_in_a_row?: FailedInARow | null }> {
const res = await fetch(`${httpBase()}/v1/automations/${encodeURIComponent(id)}`);
return res.json();
}
@@ -4504,6 +4525,10 @@ export interface RecordedTurn {
issues?: { warn: number; info: number };
// OB-7: team workers' turns this (lead) turn woke, worked out on read. Display only.
workers?: RecordedWorkerRow[];
+ // Format 1.3 (OB-17): why the turn started; absent before 1.3.
+ wake?: { reason?: string; kinds?: string[]; item_ids?: string[]; board_seq?: number | null; batched?: number | null;
+ deferred?: { by: string; ms: number } | null; by?: string | null } | null;
+ automation?: { task_id: string; run_id: string; trigger: string } | null;
}
// One worker turn under a lead's turn (OB-7). `tokens` are the worker's own, never the lead's.
@@ -4592,3 +4617,168 @@ export async function getTurnIssues(sessionId: string, turnId: string): Promise<
export async function markIssuesSeen(sessionId: string): Promise<void> {
await fetch(`${sessionApiBase(sessionId)}/v1/sessions/${encodeURIComponent(sessionId)}/issues/seen`, { method: "POST" });
}
+
+// -- Observability Phase 3: rollups over many turns (technical-design.md §4) -------------------
+// Every rollup goes to the machine that ran the work; the desktop sends its own local day
+// boundaries (TD3-2). Tokens only.
+
+export interface UsageRollup {
+ groups: RollupGroup[];
+ no_turn: { calls: number; total: number };
+ not_checked: number;
+ kept_from: number | null;
+ turns?: number;
+ deleted_session_turns?: number;
+ names?: Record<string, string>;
+ automations?: Record<string, string>;
+ machine?: { kind?: string; id?: string | null; name?: string };
+ // E28: a remote machine's last answer, served by the desktop while the machine is offline.
+ cached?: { as_of: number } | null;
+}
+
+export async function getUsageRollup(
+ q: { from: number; to: number; days?: DayBoundary[]; group?: string; persona_id?: string },
+ machineId?: string | null,
+): Promise<UsageRollup> {
+ const p = new URLSearchParams({ from: String(q.from), to: String(q.to), group: q.group || "all" });
+ if (q.days?.length) p.set("days", JSON.stringify(q.days));
+ if (q.persona_id) p.set("persona_id", q.persona_id);
+ const res = await fetch(`${engineBase(machineId)}/v1/observability/rollup?${p}`);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return res.json();
+}
+
+export interface HeavyTurn {
+ turn_id: string;
+ session_id: string;
+ title: string | null;
+ seq: number | null;
+ session_deleted: boolean;
+ persona_id: string | null;
+ model_ids: string[];
+ total: number;
+ at_least: boolean;
+ active_ms: number | null;
+ status: string;
+ found_open: boolean;
+ warn: number | null;
+ checks: string[];
+ started_at: number;
+ run_id?: string | null;
+ task_id?: string | null;
+}
+
+export async function getHeaviestTurns(from: number, to: number, machineId?: string | null, limit = 20): Promise<{ turns: HeavyTurn[]; names?: Record<string, string> }> {
+ const p = new URLSearchParams({ from: String(from), to: String(to), order: "tokens", limit: String(limit) });
+ const res = await fetch(`${engineBase(machineId)}/v1/observability/turns?${p}`);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return res.json();
+}
+
+export interface ApproverCounts {
+ checks: number;
+ allowed: number;
+ asked: number;
+ blocked: number;
+ could_not_run: number;
+ median_ms: number | null;
+}
+export interface ApproverStrip extends ApproverCounts {
+ overridden: number;
+ tokens: number;
+ shadow_checks: number;
+ by_reviewer: (ApproverCounts & { kind: string })[];
+ shown: boolean;
+}
+
+export async function getApproverStrip(from: number, to: number, machineId?: string | null): Promise<ApproverStrip> {
+ const res = await fetch(`${engineBase(machineId)}/v1/observability/approver?from=${from}&to=${to}`);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return res.json();
+}
+
+// OB-5: the numbers under each answer, and its rating.
+export async function getSessionFooters(sessionId: string): Promise<{ turns: TurnFooter[]; recording: boolean; where?: FeedbackWhere }> {
+ return recordingGet(sessionId, "/footers");
+}
+
+export async function putTurnFeedback(
+ sessionId: string,
+ turnId: string,
+ body: { rating: "up" | "down" | null; reasons?: string[]; note?: string },
+): Promise<{ feedback: TurnFeedback | null; where: FeedbackWhere; error?: string }> {
+ const res = await fetch(
+ `${sessionApiBase(sessionId)}/v1/sessions/${encodeURIComponent(sessionId)}/turns/${encodeURIComponent(turnId)}/feedback`,
+ { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) },
+ );
+ const data = await res.json();
+ if (!res.ok) throw new Error(data?.error || `HTTP ${res.status}`);
+ return data;
+}
+
+// OB-15: "How it's been doing", one row per coworker version, on the machine it lives on.
+export interface VersionFileChange {
+ path: string;
+ kind: "added" | "removed" | "edited";
+ lines?: number;
+ skill?: string;
+ from_version?: string | null;
+ to_version?: string | null;
+}
+export interface DoingRow {
+ fp: string | null;
+ current: boolean;
+ unknown_version: boolean;
+ first_seen: number | null;
+ last_seen: number | null;
+ before_kept: boolean;
+ runs: number;
+ automation_runs: number;
+ turns: number;
+ checked: number;
+ with_warn: number;
+ not_checked: number;
+ median_tokens: number | null;
+ at_least: boolean;
+ approvals_per_run: number | null;
+ up: number;
+ down: number;
+ too_few: boolean;
+ models: string[];
+ changed: { from: string; files: VersionFileChange[] } | null;
+ model_line?: { kind: "unchanged" | "changed" | "several"; models?: string[]; from?: string; to?: string };
+}
+export interface PersonaDoing {
+ persona_id: string;
+ kept_from: number | null;
+ min_runs: number;
+ rows: DoingRow[];
+ total: number;
+ runs: number;
+}
+
+export async function getPersonaDoing(personaId: string, machineId?: string | null, days = 30): Promise<PersonaDoing> {
+ const res = await fetch(`${engineBase(machineId)}/v1/personas/${encodeURIComponent(personaId)}/doing?days=${days}`);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return res.json();
+}
+
+export async function getPersonaVersionDiff(
+ personaId: string, from: string, to: string, machineId?: string | null,
+): Promise<{ files: (VersionFileChange & { diff: string })[]; error?: string }> {
+ const p = new URLSearchParams({ from, to });
+ const res = await fetch(`${engineBase(machineId)}/v1/personas/${encodeURIComponent(personaId)}/versions/diff?${p}`);
+ return res.json();
+}
+
+/** A recorded step by its tool call id (an evidence link, OB-16): the session's turns are
+ * searched newest first. Null when the call was not recorded. */
+export async function findStepByCall(sessionId: string, callId: string): Promise<{ step: RecordedStep; turn: RecordedTurn } | null> {
+ const turns = await getRecordedTurns(sessionId);
+ for (const turn of [...turns].reverse()) {
+ const steps = await getTurnSteps(sessionId, turn.turn_id);
+ const step = steps.find((s) => s.call_id === callId && s.kind === "tool");
+ if (step) return { step, turn };
+ }
+ return null;
+}
diff --git a/surfaces/gui/src/components/AuditView.tabs.test.tsx b/surfaces/gui/src/components/AuditView.tabs.test.tsx
new file mode 100644
index 00000000..430fba1f
--- /dev/null
+++ b/surfaces/gui/src/components/AuditView.tabs.test.tsx
@@ -0,0 +1,43 @@
+// OB-8: Activity gains a tab bar, Log | Usage; the Usage tab asks the machine with the
+// viewer's own day boundaries (TD3-2).
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+const empty = { groups: [], no_turn: { calls: 0, total: 0 }, not_checked: 0, kept_from: null };
+vi.mock("../api", () => ({
+ getAudit: vi.fn(async () => []),
+ getUsageRollup: vi.fn(async () => empty),
+ getHeaviestTurns: vi.fn(async () => ({ turns: [] })),
+ getApproverStrip: vi.fn(async () => ({ shown: false })),
+ getMachines: vi.fn(async () => ({ machines: [], armed: false })),
+}));
+vi.mock("./IntegrationsView", () => ({ PanelHead: ({ title }: { title: string }) => <h1>{title}</h1> }));
+
+import { getUsageRollup } from "../api";
+import { AuditView } from "./AuditView";
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("Activity tabs", () => {
+ it("opens on the Log, and Usage loads the period's rollups with day boundaries", async () => {
+ render(<AuditView />);
+ expect(screen.getByTestId("activity-tab-log").getAttribute("aria-selected")).toBe("true");
+ fireEvent.click(screen.getByTestId("activity-tab-usage"));
+ await waitFor(() => expect(screen.getByTestId("usage-tile-tokens")).toBeTruthy());
+ const calls = (getUsageRollup as any).mock.calls.map((c: any[]) => c[0]);
+ const byDay = calls.find((q: any) => q.group === "day,purpose");
+ expect(byDay.days).toHaveLength(7);
+ expect(byDay.from).toBe(byDay.days[0][1]);
+ expect(byDay.to).toBe(byDay.days[6][2]);
+ fireEvent.click(screen.getByTestId("usage-period-30d"));
+ await waitFor(() => expect((getUsageRollup as any).mock.calls.some((c: any[]) => c[0].days?.length === 30)).toBe(true));
+ });
+
+ it("a call filter always opens the Log", () => {
+ render(<AuditView callId="call_9" initialTab="usage" />);
+ expect(screen.getByTestId("activity-tab-log").getAttribute("aria-selected")).toBe("true");
+ });
+});
diff --git a/surfaces/gui/src/components/AuditView.tsx b/surfaces/gui/src/components/AuditView.tsx
index f8d25d48..1bf3e2bf 100644
--- a/surfaces/gui/src/components/AuditView.tsx
+++ b/surfaces/gui/src/components/AuditView.tsx
@@ -2,6 +2,7 @@ import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { getAudit, type AuditEvent } from "../api";
import { PanelHead } from "./IntegrationsView";
+import { UsagePage } from "./UsagePage";
// Activity — connector/browser tool history, restructured onto the IntegrationsView page shell
// (centered panel + PanelHead + cards), replacing the legacy `page-view` layout. Read-only:
@@ -12,7 +13,13 @@ const BTN_ACCENT = "text-ui px-3 py-1.5 rounded-lg bg-accent text-white shrink-0
// `callId` (OPE-238): opened from the "changes made without asking" summary — show that one
// tool call's rows, with the filter visible and clearable.
-export function AuditView({ callId }: { callId?: string } = {}) {
+// Phase 3 (OB-8): the page gains a tab bar, Log | Usage. A call filter always opens the Log.
+export function AuditView({ callId, initialTab = "log", onOpenTurn }: {
+ callId?: string;
+ initialTab?: "log" | "usage";
+ onOpenTurn?: (sessionId: string, turnId: string) => void;
+} = {}) {
+ const [tab, setTab] = useState<"log" | "usage">(callId ? "log" : initialTab);
const [events, setEvents] = useState<AuditEvent[]>([]);
const [sessionFilter, setSessionFilter] = useState("");
const [connectorFilter, setConnectorFilter] = useState("");
@@ -34,6 +41,7 @@ export function AuditView({ callId }: { callId?: string } = {}) {
useEffect(() => {
setCallFilter(callId || "");
refresh(callId || "");
+ if (callId) setTab("log");
}, [callId]);
return (
@@ -42,8 +50,17 @@ export function AuditView({ callId }: { callId?: string } = {}) {
<div className="max-w-4xl mx-auto px-7 py-6">
<PanelHead
title={t("audit.title")}
- sub={t("audit.sub")}
+ sub={tab === "usage" ? t("p3.usage.sub") : t("audit.sub")}
/>
+ <div className="p3-tabs mb-4" role="tablist" data-testid="activity-tabs">
+ <button role="tab" aria-selected={tab === "log"} data-testid="activity-tab-log" onClick={() => setTab("log")}>
+ {t("p3.usage.tab_log")}
+ </button>
+ <button role="tab" aria-selected={tab === "usage"} data-testid="activity-tab-usage" onClick={() => setTab("usage")}>
+ {t("p3.usage.tab_usage")}
+ </button>
+ </div>
+ {tab === "usage" ? <UsagePage onOpenTurn={onOpenTurn} /> : (<>
<div className="flex items-center gap-2 flex-wrap mb-4">
<input className={INPUT} placeholder={t("audit.placeholder_session")} value={sessionFilter} onChange={(e) => setSessionFilter(e.target.value)} />
@@ -78,6 +95,7 @@ export function AuditView({ callId }: { callId?: string } = {}) {
))}
</div>
)}
+ </>)}
</div>
</div>
</main>
diff --git a/surfaces/gui/src/components/PersonaDoing.test.tsx b/surfaces/gui/src/components/PersonaDoing.test.tsx
new file mode 100644
index 00000000..f23f1cbf
--- /dev/null
+++ b/surfaces/gui/src/components/PersonaDoing.test.tsx
@@ -0,0 +1,68 @@
+// OB-15: "How it's been doing" on the coworker page (technical-design.md §9).
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import i18n from "i18next";
+import type { DoingRow } from "../api";
+
+vi.mock("../api", () => ({
+ getPersonaDoing: vi.fn(),
+ getPersonaVersionDiff: vi.fn(),
+}));
+
+import { getPersonaDoing } from "../api";
+import { changedLine, PersonaDoing } from "./PersonaDoing";
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+const t = i18n.t.bind(i18n) as any;
+
+const row = (over: Partial<DoingRow> = {}): DoingRow => ({
+ fp: "9f3a21", current: true, unknown_version: false, first_seen: Date.UTC(2026, 9, 21), last_seen: Date.UTC(2026, 10, 4),
+ before_kept: false, runs: 15, automation_runs: 0, turns: 30, checked: 27, with_warn: 7, not_checked: 3,
+ median_tokens: 192_000, at_least: false, approvals_per_run: 0, up: 0, down: 0, too_few: false, models: ["model-x"],
+ changed: null, model_line: { kind: "unchanged", models: ["model-x"] }, ...over,
+});
+
+describe("changedLine", () => {
+ it("names a skill's version change and the instructions' line change, and the model", () => {
+ const r = row({
+ changed: { from: "7c10e4", files: [
+ { path: "manifest.md", kind: "edited", lines: 4 },
+ { path: "skills/semgrep-scan/SKILL.md", kind: "edited", lines: 0, skill: "semgrep-scan", from_version: "1.1", to_version: "1.2" },
+ ] },
+ model_line: { kind: "changed", from: "model-x", to: "model-y" },
+ });
+ expect(changedLine(r, t)).toBe("instructions edited (+4 lines) · skill semgrep-scan 1.1 → 1.2 · model changed: model-x → model-y");
+ expect(changedLine(row(), t)).toBe("the first version seen on this machine · model unchanged");
+ });
+});
+
+describe("PersonaDoing", () => {
+ it("one row per version: 'too few runs', 'before' the oldest kept day, and no ratings as — / —", async () => {
+ (getPersonaDoing as any).mockResolvedValue({
+ persona_id: "security", kept_from: Date.UTC(2026, 9, 6), min_runs: 10, total: 1, runs: 18,
+ rows: [row(), row({ fp: "7c10e4", current: false, runs: 3, too_few: true, median_tokens: null, before_kept: true, up: 2, down: 1 })],
+ });
+ render(<PersonaDoing personaId="security" />);
+ await waitFor(() => expect(screen.getAllByTestId("persona-doing-row")).toHaveLength(2));
+ const [a, b] = screen.getAllByTestId("persona-doing-row").map((r) => r.textContent || "");
+ expect(a).toContain("ⓕ9f3a21");
+ expect(a).toContain("current");
+ expect(a).toContain("192k");
+ expect(a).toContain("26%");
+ expect(a).toContain("— / —");
+ expect(b).toContain("too few runs to compare");
+ expect(b).toContain("before");
+ expect(b).toContain("2 / 1");
+ expect((screen.getByTestId("persona-doing-diff") as HTMLButtonElement).disabled).toBe(true);
+ });
+
+ it("renders nothing when the engine has no such endpoint", async () => {
+ (getPersonaDoing as any).mockResolvedValue({ id: "ops" });
+ const { container } = render(<PersonaDoing personaId="ops" />);
+ await waitFor(() => expect(getPersonaDoing).toHaveBeenCalled());
+ expect(container.textContent).toBe("");
+ });
+});
diff --git a/surfaces/gui/src/components/PersonaDoing.tsx b/surfaces/gui/src/components/PersonaDoing.tsx
new file mode 100644
index 00000000..2c99cc28
--- /dev/null
+++ b/surfaces/gui/src/components/PersonaDoing.tsx
@@ -0,0 +1,157 @@
+// Observability Phase 3, OB-15: "How it's been doing" on the coworker page (technical-design.md
+// §9, UX-059 ob15). One row per coworker version (fingerprint) over the last 30 days, on the
+// machine it lives on. A run is the turns of one session under one version (TD3-12); under 10
+// runs a row says "too few runs to compare" instead of medians (TD3-14). "What changed" comes
+// from the kept versions' file lists (E25c); "Show diff" from their kept files (TD3-13).
+
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { getPersonaDoing, getPersonaVersionDiff, type DoingRow, type PersonaDoing as Doing, type VersionFileChange } from "../api";
+import { formatTokens } from "../usage";
+import { shortDate } from "../obs3";
+
+type T = (k: string, o?: any) => string;
+
+export function PersonaDoing({ personaId, machineId, secClass }: { personaId: string; machineId?: string | null; secClass?: string }) {
+ const { t } = useTranslation();
+ const [doing, setDoing] = useState<Doing | null>(null);
+ const [diff, setDiff] = useState<{ fp: string; files: (VersionFileChange & { diff: string })[] } | null>(null);
+ useEffect(() => {
+ let live = true;
+ setDoing(null);
+ getPersonaDoing(personaId, machineId)
+ .then((d) => live && setDoing(d))
+ .catch(() => live && setDoing(null));
+ return () => {
+ live = false;
+ };
+ }, [personaId, machineId]);
+ if (!doing || !Array.isArray(doing.rows)) return null; // an older engine answers something else
+ const newest = doing.rows[0];
+ return (
+ <section data-testid="persona-doing">
+ <div className={`${secClass || ""} mb-1.5`}>{t("p3.doing.title")}</div>
+ <div className="rounded-xl2 border border-line bg-panel p-3">
+ {doing.rows.length === 0 ? (
+ <div className="text-meta text-faint">{t("p3.doing.none")}</div>
+ ) : (
+ <table className="p3-t">
+ <thead>
+ <tr>
+ <th>{t("p3.doing.version")}</th>
+ <th>{t("p3.doing.in_use")}</th>
+ <th className="n">{t("p3.doing.runs")}</th>
+ <th className="n">{t("p3.doing.median_tokens")}</th>
+ <th className="n">{t("p3.doing.with_issues")}</th>
+ <th className="n">{t("p3.doing.approvals")}</th>
+ <th className="n">👍 / 👎</th>
+ </tr>
+ </thead>
+ <tbody>
+ {doing.rows.map((r) => (
+ <DoingTr key={r.fp ?? "unknown"} r={r} t={t} />
+ ))}
+ </tbody>
+ </table>
+ )}
+ {newest && (
+ <div className="flex items-start gap-3 mt-3 text-meta" data-testid="persona-doing-changed">
+ <div className="flex-1 min-w-0">
+ <b className="font-medium">{t("p3.doing.what_changed", { fp: newest.fp ?? "—" })}</b>{" "}
+ <span className="text-muted">{changedLine(newest, t)}</span>
+ </div>
+ <button
+ className="text-meta px-2.5 py-1 rounded-lg border border-line"
+ disabled={!newest.changed || !newest.fp}
+ data-testid="persona-doing-diff"
+ onClick={async () => {
+ if (!newest.changed || !newest.fp) return;
+ if (diff?.fp === newest.fp) return setDiff(null);
+ const d = await getPersonaVersionDiff(personaId, newest.changed.from, newest.fp, machineId).catch(() => null);
+ if (d && !d.error) setDiff({ fp: newest.fp, files: d.files || [] });
+ }}
+ >
+ {diff ? t("p3.doing.hide_diff") : t("p3.doing.show_diff")}
+ </button>
+ </div>
+ )}
+ {diff && (
+ <div className="mt-2 space-y-2" data-testid="persona-doing-diff-body">
+ {diff.files.map((f) => (
+ <div key={f.path}>
+ <div className="font-mono text-meta text-muted">{f.path}</div>
+ <pre className="p3-diff">{f.diff || t("p3.doing.no_text_diff")}</pre>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ <div className="text-meta text-faint mt-1.5">{t("p3.doing.note", { n: doing.min_runs })}</div>
+ </section>
+ );
+}
+
+function DoingTr({ r, t }: { r: DoingRow; t: T }) {
+ const from = r.first_seen != null ? shortDate(r.first_seen) : "—";
+ const to = r.last_seen != null ? shortDate(r.last_seen) : "—";
+ return (
+ <tr data-testid="persona-doing-row">
+ <td>
+ <span className="font-mono">{r.unknown_version ? t("p3.doing.unknown_version") : `ⓕ${r.fp}`}</span>
+ {r.current && <span className="p3-chip ok ml-1.5">{t("p3.doing.current")}</span>}
+ </td>
+ <td>{r.before_kept ? t("p3.doing.before", { date: to }) : `${from} – ${to}`}</td>
+ <td className="n">
+ {r.runs}
+ {r.automation_runs > 0 && <span className="text-faint"> {t("p3.doing.automation_runs", { count: r.automation_runs })}</span>}
+ </td>
+ {r.too_few ? (
+ <td className="n text-faint" colSpan={1}>{t("p3.doing.too_few")}</td>
+ ) : (
+ <td className="n">{(r.at_least ? "≥ " : "") + formatTokens(r.median_tokens ?? 0)}</td>
+ )}
+ <td className="n">{r.checked ? `${Math.round((r.with_warn / r.checked) * 100)}%` : "—"}</td>
+ <td className="n">{r.approvals_per_run == null ? "—" : r.approvals_per_run.toFixed(1)}</td>
+ <td className="n">{r.up || r.down ? `${r.up} / ${r.down}` : "— / —"}</td>
+ </tr>
+ );
+}
+
+/** "skill semgrep-scan 1.1 → 1.2 · instructions edited (+4 lines) · model unchanged". */
+export function changedLine(r: DoingRow, t: T): string {
+ const parts: string[] = [];
+ if (!r.changed) parts.push(t("p3.doing.first_version"));
+ else {
+ const skills = new Map<string, VersionFileChange>();
+ for (const f of r.changed.files) {
+ if (f.skill) {
+ if (!skills.has(f.skill) || f.path.endsWith("SKILL.md")) skills.set(f.skill, f);
+ continue;
+ }
+ if (f.path === "manifest.md") {
+ parts.push(f.kind === "edited"
+ ? t("p3.doing.instructions_edited", { lines: (f.lines ?? 0) >= 0 ? `+${f.lines ?? 0}` : String(f.lines) })
+ : t(`p3.doing.instructions_${f.kind}`));
+ } else if (!f.path.startsWith("skills/")) {
+ parts.push(t(`p3.doing.file_${f.kind}`, { path: f.path }));
+ }
+ }
+ for (const f of r.changed.files) {
+ if (f.path.startsWith("skills/") && !f.skill) {
+ const name = f.path.split("/")[1];
+ if (name && !skills.has(name)) skills.set(name, { ...f, skill: name });
+ }
+ }
+ for (const [name, f] of skills) {
+ if (f.from_version && f.to_version && f.from_version !== f.to_version)
+ parts.push(t("p3.doing.skill_version", { skill: name, from: f.from_version, to: f.to_version }));
+ else parts.push(t(`p3.doing.skill_${f.kind}`, { skill: name }));
+ }
+ if (!r.changed.files.length) parts.push(t("p3.doing.no_file_change"));
+ }
+ const m = r.model_line;
+ if (m?.kind === "changed") parts.push(t("p3.doing.model_changed", { from: m.from, to: m.to }));
+ else if (m?.kind === "several") parts.push(t("p3.doing.models", { models: (m.models || []).join(", ") }));
+ else parts.push(t("p3.doing.model_unchanged"));
+ return parts.join(" · ");
+}
diff --git a/surfaces/gui/src/components/PersonaView.tsx b/surfaces/gui/src/components/PersonaView.tsx
index 75fa1470..20dee313 100644
--- a/surfaces/gui/src/components/PersonaView.tsx
+++ b/surfaces/gui/src/components/PersonaView.tsx
@@ -30,6 +30,7 @@ import { Icon } from "./Icon";
import { Markdown } from "./Markdown";
import { Toggle } from "./Toggle";
import { indexConnectors, labelFor, visualFor, type ConnectorMap } from "../connectors/visuals";
+import { PersonaDoing } from "./PersonaDoing";
const SEC_H = "text-label text-faint font-medium";
const TAG_CORE =
@@ -353,6 +354,9 @@ export function PersonaView({
</section>
)}
+ {/* Phase 3 OB-15: how each version of this coworker has been doing */}
+ <PersonaDoing personaId={personaId} machineId={mid} secClass={SEC_H} />
+
{/* defaults footer */}
<section className="flex flex-wrap gap-x-8 gap-y-2 text-ui">
{detail.recommended_models.length > 0 && (
diff --git a/surfaces/gui/src/components/Phase3Wiring.test.tsx b/surfaces/gui/src/components/Phase3Wiring.test.tsx
new file mode 100644
index 00000000..ab4a461e
--- /dev/null
+++ b/surfaces/gui/src/components/Phase3Wiring.test.tsx
@@ -0,0 +1,55 @@
+// Phase 3 wiring: each answer that ends a turn carries that turn's footer (OB-5), and the
+// Steps turn picker says why a turn started (OB-17).
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import i18n from "i18next";
+import { Transcript } from "./Transcript";
+import { wakeLine } from "./StepsPanel";
+import type { Item } from "../types";
+
+afterEach(cleanup);
+const t = i18n.t.bind(i18n) as any;
+
+const footer = (id: string, mid: string, total: number) => ({
+ turn_id: id, seq: 1, status: "completed", last_message_id: mid, duration_ms: 2000, total, at_least: false,
+ warn: 0, auto_approved: 0, asked: 0, feedback: null,
+});
+
+describe("Transcript footers", () => {
+ it("puts each turn's footer under its own answer, and opens Steps at that turn", () => {
+ const items: Item[] = [
+ { kind: "user", text: "one" },
+ { kind: "assistant", text: "first answer", mid: "m1" },
+ { kind: "user", text: "two" },
+ { kind: "assistant", text: "second answer", mid: "m2" },
+ ];
+ const open = vi.fn();
+ render(
+ <Transcript items={items} onApprove={() => {}} onOpenSteps={open} footerSessionId="s1"
+ footers={{ turns: [footer("t1", "m1", 1200), footer("t2", "m2", 3400)], recording: true }} />,
+ );
+ const tokens = screen.getAllByTestId("turn-footer-tokens").map((e) => e.textContent);
+ expect(tokens).toEqual(["1.2k tokens this turn", "3.4k tokens this turn"]);
+ fireEvent.click(screen.getAllByTestId("turn-footer-steps")[1]);
+ expect(open).toHaveBeenCalledWith(undefined, "t2");
+ // only the last turn's footer is always shown; older ones on hover (Q9)
+ const wraps = screen.getAllByTestId("turn-footer");
+ expect(wraps[0].className).not.toContain("last");
+ expect(wraps[1].className).toContain("last");
+ });
+
+ it("without footers nothing changes", () => {
+ render(<Transcript items={[{ kind: "assistant", text: "hi" }]} onApprove={() => {}} />);
+ expect(screen.queryByTestId("turn-footer")).toBeNull();
+ });
+});
+
+describe("wakeLine", () => {
+ it("says why a team turn started, and nothing for your own turns", () => {
+ const turn = (wake: any) => ({ wake } as any);
+ expect(wakeLine(turn({ reason: "review", batched: 4 }), t)).toBe("woke: Review batch");
+ expect(wakeLine(turn({ reason: "timer" }), t)).toBe("woke: Timer (sleep_for)");
+ expect(wakeLine(turn({ reason: "user" }), t)).toBeNull();
+ expect(wakeLine(turn(undefined), t)).toBeNull();
+ });
+});
diff --git a/surfaces/gui/src/components/ScheduledView.health.test.tsx b/surfaces/gui/src/components/ScheduledView.health.test.tsx
new file mode 100644
index 00000000..9452989b
--- /dev/null
+++ b/surfaces/gui/src/components/ScheduledView.health.test.tsx
@@ -0,0 +1,53 @@
+// OB-18: the run list's health, tokens and issues, and the "failed in a row" banner.
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { ScheduledView } from "./ScheduledView";
+
+const run = (id: string, over: Record<string, any> = {}) => ({
+ run_id: id, task_id: "task-brief", session_id: `__run__${id}`, started_at: 1_793_600_000, finished_at: 1_793_600_030,
+ status: "ok", result_text: null, artifacts: [], error: null, trigger: "schedule",
+ turns: 1, total: 6000, at_least: false, duration_ms: 30_000, warn: 0, checks: [], check_titles: [], health: "ok",
+ first_turn_id: `turn-${id}`, ...over,
+});
+
+vi.mock("../api", () => ({
+ announceAutomationsChanged: vi.fn(),
+ createAutomation: vi.fn(),
+ deleteAutomation: vi.fn(),
+ getAutomation: vi.fn(async () => ({
+ task: { id: "task-brief", title: "Morning brief", instructions: "brief", cron: "0 6 * * *", workspace: "/w", agent: "cowork",
+ enabled: true, seen_runs_at: 0, permissions: [] },
+ runs: [
+ run("run-4", { health: "failed", checks: ["tool_failed"], check_titles: ["A tool failed"] }),
+ run("run-3", { status: "error", error: "e2", health: "failed" }),
+ run("run-1", { total: null, turns: 0, first_turn_id: null, health: "unknown" }),
+ ],
+ failed_in_a_row: { count: 3, last_error: "A tool failed", run_id: "run-4", session_id: "__run__run-4", turn_id: "turn-run-4" },
+ })),
+ getAutomations: vi.fn().mockResolvedValue([]),
+ markAutomationSeen: vi.fn(async () => ({ ok: true })),
+ updateAutomation: vi.fn(),
+}));
+vi.mock("./AutomationQuickstart", () => ({ AutomationQuickstart: () => null }));
+vi.mock("./IntegrationsView", () => ({ PanelHead: ({ title }: { title: string }) => <h1>{title}</h1> }));
+
+afterEach(cleanup);
+
+describe("ScheduledView run health", () => {
+ it("shows each run's health, tokens and issues, the banner, and opens a run's Steps", async () => {
+ const steps = vi.fn();
+ render(<ScheduledView onOpenRun={vi.fn()} onRunNow={vi.fn()} initialOpenId="task-brief" onOpenRunSteps={steps} />);
+ await waitFor(() => expect(screen.getByTestId("runs-failed-banner")).toBeTruthy());
+ expect(screen.getByTestId("runs-failed-banner").textContent).toContain("Failed 3 runs in a row. Last error: A tool failed");
+ const rows = screen.getAllByTestId("run-health-row").map((r) => r.textContent || "");
+ expect(rows[0]).toContain("failed");
+ expect(rows[0]).toContain("(run said ok)");
+ expect(rows[0]).toContain("6k tokens");
+ expect(rows[0]).toContain("A tool failed");
+ expect(rows[1]).toContain("error");
+ expect(rows[2]).toContain("— tokens");
+ expect(rows[2]).toContain("not recorded");
+ fireEvent.click(screen.getAllByTestId("run-steps")[0]);
+ expect(steps).toHaveBeenCalledWith("__run__run-4", "turn-run-4", "/w", "cowork", { id: "task-brief", title: "Morning brief" });
+ });
+});
diff --git a/surfaces/gui/src/components/ScheduledView.tsx b/surfaces/gui/src/components/ScheduledView.tsx
index 4b5113d5..ee03d458 100644
--- a/surfaces/gui/src/components/ScheduledView.tsx
+++ b/surfaces/gui/src/components/ScheduledView.tsx
@@ -5,6 +5,7 @@ import {
deleteAutomation,
getAutomation,
getAutomations,
+ type FailedInARow,
markAutomationSeen,
announceAutomationsChanged,
updateAutomation,
@@ -14,6 +15,9 @@ import {
import { Icon } from "./Icon";
import { PanelHead } from "./IntegrationsView";
import { AutomationQuickstart } from "./AutomationQuickstart";
+import { formatTokens } from "../usage";
+import { formatDuration } from "./StepsPanel";
+import { healthTone } from "../obs3";
// Shared utility strings (the §28 page shell — mirrors IntegrationsView's constants).
const CARD = "rounded-xl2 border border-line bg-panel";
@@ -62,9 +66,11 @@ interface Props {
onRunNow: (taskId: string, title?: string) => void;
// Open directly on a task's detail (set by the run banner's "Back to runs").
initialOpenId?: string | null;
+ // OB-18 (Phase 3): a run's Steps, at its first recorded turn.
+ onOpenRunSteps?: (sessionId: string, turnId: string, workspace: string, agent: string, task?: { id: string; title: string }) => void;
}
-export function ScheduledView({ onOpenRun, onRunNow, initialOpenId }: Props) {
+export function ScheduledView({ onOpenRun, onRunNow, initialOpenId, onOpenRunSteps }: Props) {
const { t } = useTranslation();
const [tasks, setTasks] = useState<Automation[]>([]);
const [openId, setOpenId] = useState<string | null>(initialOpenId ?? null);
@@ -115,6 +121,7 @@ export function ScheduledView({ onOpenRun, onRunNow, initialOpenId }: Props) {
onBack={() => { setOpenId(null); refresh(); }}
onOpenRun={onOpenRun}
onRunNow={onRunNow}
+ onOpenRunSteps={onOpenRunSteps}
/>
);
}
@@ -279,9 +286,11 @@ function TaskDetail({
onBack,
onOpenRun,
onRunNow,
+ onOpenRunSteps,
}: {
id: string;
onBack: () => void;
+ onOpenRunSteps?: Props["onOpenRunSteps"];
onOpenRun: (
sessionId: string,
workspace: string,
@@ -293,6 +302,7 @@ function TaskDetail({
const { t: tt } = useTranslation();
const [task, setTask] = useState<Automation | null>(null);
const [runs, setRuns] = useState<AutomationRun[]>([]);
+ const [failedRow, setFailedRow] = useState<FailedInARow | null>(null);
const [editing, setEditing] = useState(false);
const [title, setTitle] = useState("");
const [instructions, setInstructions] = useState("");
@@ -315,6 +325,7 @@ function TaskDetail({
}
setTask(d.task);
setRuns(d.runs || []);
+ setFailedRow(d.failed_in_a_row ?? null);
setSeenMark((cur) => (cur === null ? d.task?.seen_runs_at ?? 0 : cur));
})
.catch(() => {});
@@ -475,6 +486,12 @@ function TaskDetail({
<div className="dim" style={{ marginBottom: 8, fontSize: 12.5 }}>
{tt("automations.runs_desc")}
</div>
+ {failedRow && (
+ <div className="p3-callout err" data-testid="runs-failed-banner">
+ <b>{tt("p3.runs.failed_in_a_row", { count: failedRow.count })}</b>{" "}
+ {tt("p3.runs.last_error", { error: failedRow.last_error || tt("p3.runs.unknown_error") })}
+ </div>
+ )}
{runs.length === 0 && <div className="dim">{tt("automations.no_runs")}</div>}
{runs.map((r) => (
<div
@@ -501,6 +518,31 @@ function TaskDetail({
{tt("automations.open_go")}
</span>
</div>
+ {r.health && (
+ <div className="sched-run-health" data-testid="run-health-row">
+ <span className={"p3-chip " + healthTone(r.health)} data-testid="run-health">{tt(`p3.runs.health.${r.health}`)}</span>
+ {r.health === "failed" && r.status === "ok" && <span className="dim">{tt("p3.runs.run_said_ok")}</span>}
+ {r.health === "did_not_finish" && <span className="dim">{tt("p3.runs.still_running")}</span>}
+ <span className="dim">{tt("p3.runs.duration", { time: formatDuration(r.duration_ms ?? null) })}</span>
+ <span className="dim" data-testid="run-tokens">
+ {r.total == null ? tt("p3.runs.tokens_none") : tt("p3.runs.tokens", { tokens: (r.at_least ? "≥ " : "") + formatTokens(r.total) })}
+ </span>
+ {(r.check_titles || r.checks || []).map((c, i) => (
+ <span key={i} className="steps-badge warn">{tt(`steps.issues.title.${(r.checks || [])[i] || c}`, { defaultValue: c })}</span>
+ ))}
+ {r.error && <span className="steps-badge err" title={r.error}>{tt("p3.runs.error")}</span>}
+ {r.turns === 0 && r.total == null && <span className="dim">{tt("p3.runs.not_recorded")}</span>}
+ {r.first_turn_id && onOpenRunSteps && (
+ <button className="p3-link ml-auto" data-testid="run-steps"
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpenRunSteps(r.session_id, r.first_turn_id!, task.workspace, task.agent, { id: task.id, title: task.title });
+ }}>
+ {tt("steps.open")}
+ </button>
+ )}
+ </div>
+ )}
{r.result_text && <div className="sched-run-peek">{r.result_text}</div>}
{r.error && <div className="mcp-error">{r.error}</div>}
</div>
diff --git a/surfaces/gui/src/components/StepsPanel.tsx b/surfaces/gui/src/components/StepsPanel.tsx
index 90e485f5..16c0ef90 100644
--- a/surfaces/gui/src/components/StepsPanel.tsx
+++ b/surfaces/gui/src/components/StepsPanel.tsx
@@ -22,11 +22,21 @@ import {
type TurnIssues,
} from "../api";
import { formatTokens } from "../usage";
+import { wakeKey } from "../obs3";
type T = (k: string, o?: any) => string;
const BUCKETS = ["waiting", "tools", "model", "auto_approver", "summary", "sandbox"] as const;
+/** Why a turn started (OB-17, format 1.3), for the turn picker: "woke: review batch". Nothing
+ * for a turn you started, or one recorded before 1.3. */
+export function wakeLine(turn: RecordedTurn, t: T): string | null {
+ const reason = turn.wake?.reason;
+ if (!reason || reason === "user" || reason === "unknown") return null;
+ const key = wakeKey(turn.wake);
+ return key ? t("p3.wake.woke", { reason: t(key) }) : null;
+}
+
/** 0.1s, 3.4s, 41s, 2m 14s: the panel's one duration format. */
export function formatDuration(ms: number | null | undefined): string {
if (ms == null || !Number.isFinite(ms)) return "—";
@@ -360,7 +370,7 @@ export function StepsPanel({
// A worker row's "Open worker session" (OB-7).
onOpenSession?: (sessionId: string) => void;
// Opened from a turn's answer: its time (unix seconds) picks the turn that produced it.
- openAt?: { ts?: number; n: number } | null;
+ openAt?: { ts?: number; turnId?: string; n: number } | null;
onClose: () => void;
}) {
const { t } = useTranslation();
@@ -397,7 +407,17 @@ export function StepsPanel({
// An answer's Steps link: the first turn that had not ended before that answer (the turns
// before it all ended earlier). The answer's time is in whole seconds, hence the second's slack.
useEffect(() => {
- if (!openAt || !turns || !turns.length || openAt.ts == null) return;
+ if (!openAt || !turns || !turns.length) return;
+ if (openAt.turnId) {
+ // A known turn (the OB-5 footer, Usage's heaviest turns, a team event).
+ const found = turns.findIndex((tn) => tn.turn_id === openAt.turnId);
+ if (found >= 0) {
+ setTurnIdx(found);
+ setTab("timeline");
+ return;
+ }
+ }
+ if (openAt.ts == null) return;
const at = openAt.ts * 1000 - 1000;
const idx = turns.findIndex((tn) => tn.duration_ms == null || tn.started_at + tn.duration_ms >= at);
setTurnIdx(idx < 0 ? turns.length - 1 : idx);
@@ -451,6 +471,7 @@ export function StepsPanel({
<button aria-label={t("steps.prev_turn")} disabled={turnIdx <= 0} onClick={() => setTurnIdx(turnIdx - 1)}>‹</button>
<span data-testid="steps-turn"><Help text={H(t, "turn")}>{t("steps.turn_of", { n: turnIdx + 1, total: turns.length })}</Help></span>
<button aria-label={t("steps.next_turn")} disabled={turnIdx >= turns.length - 1} onClick={() => setTurnIdx(turnIdx + 1)}>›</button>
+ {turn && wakeLine(turn, t) && <span className="steps-turn-wake text-faint" data-testid="steps-turn-wake">· {wakeLine(turn, t)}</span>}
</span>
);
diff --git a/surfaces/gui/src/components/TeamPhase3.test.tsx b/surfaces/gui/src/components/TeamPhase3.test.tsx
new file mode 100644
index 00000000..5b579ca4
--- /dev/null
+++ b/surfaces/gui/src/components/TeamPhase3.test.tsx
@@ -0,0 +1,65 @@
+// OB-16, OB-17: TeamView's wake split and events, a task's coverage and a finding's evidence.
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import i18n from "i18next";
+import type { TeamWake } from "../teamView";
+import { CoverageBlock, eventText, exitText, TeamEvents, WakeSplit } from "./TeamPhase3";
+
+afterEach(cleanup);
+const t = i18n.t.bind(i18n) as any;
+
+describe("WakeSplit", () => {
+ it("gives every reason its tokens, workers included, and adds up to the team total (V3-09)", () => {
+ const wakes: TeamWake[] = [
+ { reason: "timer", wakes: 11, total: 380_000, cache_read: 334_394, input: 368_593, by_role: { lead: { wakes: 11, total: 380_000 } } },
+ { reason: "assigned", wakes: 20, total: 300_000, cache_read: 180_000, input: 285_000, by_role: { worker: { wakes: 20, total: 300_000 } } },
+ { reason: "review", wakes: 9, total: 320_000, cache_read: 227_199, input: 310_397, by_role: { lead: { wakes: 9, total: 320_000 } } },
+ ];
+ render(<WakeSplit wakes={wakes} explained={{ turns: 58, explained: 57 }} t={t} />);
+ const text = screen.getByTestId("team-wake-split").textContent || "";
+ expect(text).toContain("Timer (sleep_for)");
+ expect(text).toContain("Assigned work");
+ expect(screen.getByTestId("team-wake-timer").textContent).toContain("91%");
+ expect(text).toContain("Team total");
+ expect(text).toContain("40"); // 11 + 20 + 9 wakes
+ expect(screen.getByTestId("team-wake-explained").textContent).toContain("57 of 58 turns have a known reason (98%)");
+ });
+});
+
+describe("TeamEvents", () => {
+ it("words each event and opens its turn's Steps; a cap hit with no turn opens the board", () => {
+ const steps = vi.fn();
+ const board = vi.fn();
+ const events = [
+ { kind: "wake_capped", severity: "warn" as const, at: 2, session_id: "lead", turn_id: "t12", deferred_ms: 360_000 },
+ { kind: "lead_polling", severity: "warn" as const, at: 1, session_id: "lead", turn_id: "t9", count: 9 },
+ { kind: "wake_cap_reached", severity: "warn" as const, at: 0, count: 60, held: ["w1"] },
+ ];
+ render(<TeamEvents events={events} t={t} onOpenSteps={steps} onOpenBoard={board} />);
+ expect(screen.getByTestId("team-event-wake_capped").textContent).toContain("this wake waited 6 min");
+ expect(screen.getByTestId("team-event-lead_polling").textContent).toContain("9 times with no board change");
+ fireEvent.click(screen.getByTestId("team-event-lead_polling"));
+ expect(steps).toHaveBeenCalledWith("lead", "t9");
+ fireEvent.click(screen.getByTestId("team-event-wake_cap_reached"));
+ expect(board).toHaveBeenCalled();
+ expect(eventText({ kind: "same_approval_twice", severity: "warn", at: null, tool: "run_shell", first_by: "lead", again_by: "maya" }, t))
+ .toBe("Same approval asked twice: run_shell (lead, then maya)");
+ });
+});
+
+describe("CoverageBlock", () => {
+ it("says a scanner's 'found something' exit, and the area that was never scanned (M3-R9, M3-R11)", () => {
+ expect(exitText({ exit_code: 1, found_something: true }, t)).toBe("exit 1 (found something)");
+ expect(exitText({ exit_code: 126, found_something: false }, t)).toBe("exit 126");
+ render(<CoverageBlock t={t} coverage={{
+ promised: ["code", "secrets"],
+ scans: [{ scanner: "semgrep", area: "code", exit_code: 1, ok: true, found_something: true, turn_seq: 3, step_seq: 9, actor: "Maya" }],
+ issues: [{ check: "no_findings_without_scan", text: "The report says no secret problems were found, but no secret scan ran." }],
+ }} />);
+ const text = screen.getByTestId("task-coverage").textContent || "";
+ expect(text).toContain("semgrep ran · exit 1 (found something)");
+ expect(text).toContain("Maya turn 3, step 9");
+ expect(text).toContain("no secret scan ran");
+ expect(text).toContain("no secret problems were found");
+ });
+});
diff --git a/surfaces/gui/src/components/TeamPhase3.tsx b/surfaces/gui/src/components/TeamPhase3.tsx
new file mode 100644
index 00000000..bd95d0f6
--- /dev/null
+++ b/surfaces/gui/src/components/TeamPhase3.tsx
@@ -0,0 +1,207 @@
+// Observability Phase 3 in TeamView (technical-design.md §10, §11; UX-059 ob16, ob17):
+// - "By wake reason": why each team turn started, its tokens (lead and workers together) and
+// cache-read share, split by role on hover. The rows add up to the team total (V3-09).
+// - "Team events that used to be silent": cap hits, long deferrals, watchdog nudges, lead
+// polling, an approval asked twice, a review before its prerequisite; each opens Steps.
+// - A security task's "Coverage for this task" and a finding's "Evidence".
+
+import { useEffect, useState } from "react";
+import { findStepByCall, type RecordedStep, type RecordedTurn } from "../api";
+import type { CoverageScan, TaskCoverage, TaskFinding, TeamEvent, TeamWake } from "../teamView";
+import { formatTokens } from "../usage";
+import { formatDuration } from "./StepsPanel";
+import { AREA_WORD, cacheShare, wakeKey } from "../obs3";
+
+type T = (k: string, o?: any) => string;
+
+export function WakeSplit({ wakes, explained, t }: { wakes: TeamWake[]; explained?: { turns: number; explained: number }; t: T }) {
+ if (!wakes.length) return null;
+ const total = wakes.reduce((n, w) => n + w.total, 0);
+ const count = wakes.reduce((n, w) => n + w.wakes, 0);
+ const cr = wakes.reduce((n, w) => n + w.cache_read, 0);
+ const inp = wakes.reduce((n, w) => n + w.input, 0);
+ return (
+ <section className="team-stats-section" data-testid="team-wake-split">
+ <h3>{t("p3.team.by_wake")}</h3>
+ <table className="p3-t">
+ <thead>
+ <tr><th>{t("p3.team.why")}</th><th className="n">{t("p3.team.wakes")}</th><th className="n">{t("teamview.tokens")}</th>
+ <th className="n">{t("p3.team.cache_reads")}</th><th>{t("p3.team.who")}</th></tr>
+ </thead>
+ <tbody>
+ {wakes.map((w) => {
+ const share = cacheShare(w.cache_read, w.input);
+ const roles = Object.entries(w.by_role || {});
+ const split = roles.map(([role, v]) => `${t(role === "lead" ? "teamview.lead" : "p3.team.worker")}: ${v.wakes} · ${formatTokens(v.total)}`).join("\n");
+ return (
+ <tr key={w.reason} title={split} data-testid={`team-wake-${w.reason}`}>
+ <td>{t(wakeKey({ reason: w.reason }) || "p3.wake.unknown")}</td>
+ <td className="n">{w.wakes}</td>
+ <td className="n">{(w.at_least ? "≥ " : "") + formatTokens(w.total)}</td>
+ <td className="n">{share == null ? "—" : `${share}%`}</td>
+ <td className="text-faint">{roles.map(([r]) => t(r === "lead" ? "teamview.lead" : "p3.team.worker")).join(", ")}</td>
+ </tr>
+ );
+ })}
+ <tr>
+ <td><b>{t("p3.team.total")}</b></td>
+ <td className="n"><b>{count}</b></td>
+ <td className="n"><b>{formatTokens(total)}</b></td>
+ <td className="n">{cacheShare(cr, inp) == null ? "—" : `${cacheShare(cr, inp)}%`}</td>
+ <td></td>
+ </tr>
+ </tbody>
+ </table>
+ {explained && explained.turns > 0 && (
+ <p className="team-totals" data-testid="team-wake-explained">
+ {t("p3.team.explained", { n: explained.explained, of: explained.turns, pct: Math.round((explained.explained / explained.turns) * 100) })}
+ </p>
+ )}
+ </section>
+ );
+}
+
+/** One event as a sentence (the i18n keys carry the words). */
+export function eventText(e: TeamEvent, t: T): string {
+ const mins = (ms?: number | null) => Math.max(1, Math.round((ms || 0) / 60000));
+ switch (e.kind) {
+ case "wake_capped":
+ return t("p3.ev.wake_capped", { min: mins(e.deferred_ms) });
+ case "wake_cap_reached":
+ return t("p3.ev.wake_cap_reached", { count: e.count ?? 60, held: (e.held || []).length });
+ case "deferred":
+ return t("p3.ev.deferred", { who: e.who, min: mins(e.deferred_ms), by: t(`p3.ev.by_${e.by}`, { defaultValue: e.by }) });
+ case "watchdog_nudged":
+ return t("p3.ev.watchdog_nudged", { items: (e.item_ids || []).join(", ") || "—" });
+ case "lead_polling":
+ return t("p3.ev.lead_polling", { count: e.count });
+ case "same_approval_twice":
+ return t("p3.ev.same_approval_twice", { tool: e.tool, first: e.first_by, again: e.again_by });
+ case "reviewed_before_prereq":
+ return t("p3.ev.reviewed_before_prereq", { item: e.item, pre: e.prerequisite, to: e.to || "review" });
+ default:
+ return e.kind;
+ }
+}
+
+export function TeamEvents({ events, t, onOpenSteps, onOpenBoard }: {
+ events: TeamEvent[];
+ t: T;
+ onOpenSteps?: (sessionId: string, turnId: string) => void;
+ onOpenBoard?: () => void;
+}) {
+ if (!events.length) return null;
+ return (
+ <section className="team-stats-section" data-testid="team-events">
+ <h3>{t("p3.team.events")}</h3>
+ <div className="flex flex-col gap-1.5">
+ {events.map((e, i) => {
+ const open = e.session_id && e.turn_id && onOpenSteps ? () => onOpenSteps(e.session_id!, e.turn_id!) : onOpenBoard;
+ return (
+ <button key={i} className="p3-event" disabled={!open} onClick={open} data-testid={`team-event-${e.kind}`}>
+ <span className={"steps-badge " + (e.severity === "warn" ? "warn" : "")}>{t(e.severity === "warn" ? "p3.team.issue" : "p3.team.info")}</span>
+ <span className="min-w-0 flex-1 text-left">{eventText(e, t)}</span>
+ {e.at != null && <span className="text-faint">{new Date(e.at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}</span>}
+ </button>
+ );
+ })}
+ </div>
+ <p className="team-totals">{t("p3.team.events_note")}</p>
+ </section>
+ );
+}
+
+// -- OB-16 ---------------------------------------------------------------------------------------
+
+/** "exit 1 (found something)" when the scanner's code means it found something (M3-R9). */
+export function exitText(s: { exit_code: number | null; found_something?: boolean }, t: T): string {
+ if (s.exit_code == null) return t("p3.cov.no_exit");
+ return s.found_something && s.exit_code !== 0 ? t("p3.cov.exit_found", { code: s.exit_code }) : t("p3.cov.exit", { code: s.exit_code });
+}
+
+export function CoverageBlock({ coverage, t, onOpenStep }: { coverage: TaskCoverage; t: T; onOpenStep?: (s: CoverageScan) => void }) {
+ if (coverage.not_checked) return (
+ <div className="team-stats-section" data-testid="task-coverage">
+ <h3>{t("p3.cov.title")}</h3>
+ <p className="team-totals">{t("p3.cov.not_checked")}</p>
+ </div>
+ );
+ const ran = new Set(coverage.scans.filter((s) => s.ok).map((s) => s.area));
+ return (
+ <div className="team-stats-section" data-testid="task-coverage">
+ <h3>{t("p3.cov.title")}</h3>
+ <div className="flex flex-col gap-1 text-meta">
+ {coverage.scans.map((s, i) => (
+ <div key={i} className={s.ok ? "" : "text-danger"}>
+ {s.ok ? "✓" : "✗"} {t(s.ok ? "p3.cov.ran" : "p3.cov.failed", { scanner: s.scanner })} · {exitText(s, t)}
+ {s.turn_seq != null && <span className="text-faint"> · {t("p3.cov.where", { actor: s.actor || "", turn: s.turn_seq, step: s.step_seq ?? "?" })}</span>}
+ {onOpenStep && s.session_id && s.turn_id && (
+ <button className="p3-link ml-2" onClick={() => onOpenStep(s)}>{t("p3.cov.open_step")}</button>
+ )}
+ </div>
+ ))}
+ {coverage.promised.filter((a) => !ran.has(a)).map((a) => (
+ <div key={a} className="text-danger">✗ {t("p3.cov.missing", { area: t(`p3.area.${a}`, { defaultValue: AREA_WORD[a] || a }) })}</div>
+ ))}
+ {(coverage.fine || []).filter((f) => !["scan_missing", "scanner_failed"].includes(f.check)).map((f) => (
+ <div key={f.check}>✓ {f.text}</div>
+ ))}
+ </div>
+ {coverage.issues.map((i, k) => (
+ // The engine's English sentence, as the Issues tab shows it (Phase 2 TD2-3 build note).
+ <div key={k} className="p3-callout err mt-2">{i.text}</div>
+ ))}
+ <p className="team-totals">{t("p3.cov.promised", { areas: coverage.promised.map((a) => t(`p3.area.${a}`, { defaultValue: a })).join(", ") })}</p>
+ </div>
+ );
+}
+
+export function EvidenceBlock({ finding, t, onOpenStep }: { finding: TaskFinding; t: T; onOpenStep?: (sessionId: string, turnId: string) => void }) {
+ const [found, setFound] = useState<{ step: RecordedStep; turn: RecordedTurn; session_id: string }[] | null>(null);
+ useEffect(() => {
+ let live = true;
+ const ev = finding.evidence || [];
+ Promise.all(ev.map((e) => findStepByCall(e.session_id, e.call_id).then((r) => (r ? { ...r, session_id: e.session_id } : null)).catch(() => null)))
+ .then((rows) => live && setFound(rows.filter(Boolean) as any))
+ .catch(() => live && setFound([]));
+ return () => {
+ live = false;
+ };
+ }, [finding]);
+ return (
+ <div className="team-stats-section" data-testid="finding-evidence">
+ <h3>{t("p3.ev2.title", { id: finding.id })}{finding.severity ? ` · ${finding.severity}` : ""}</h3>
+ {!(finding.evidence || []).length ? (
+ <p className="team-totals text-danger">{t("p3.ev2.none")}</p>
+ ) : found == null ? (
+ <p className="team-totals">{t("p3.usage.loading")}</p>
+ ) : found.length === 0 ? (
+ <p className="team-totals">{t("p3.ev2.no_recorded_step")}</p>
+ ) : (
+ found.map(({ step, turn, session_id }) => {
+ const a = step.attrs || {};
+ const sc = a.scanner?.name;
+ return (
+ <div key={step.step_id} className="flex items-start gap-3 text-meta py-1">
+ <div className="flex-1 min-w-0">
+ <b className="font-medium">{t("p3.ev2.found_by", { turn: turn.seq, step: step.seq ?? "?" })}</b>
+ <div className="font-mono text-muted">
+ {[sc || step.name, a.exit_code != null ? exitText({ exit_code: a.exit_code, found_something: a.exit_code === 1 && !!sc }, t) : null,
+ a.result_sha256 ? `output sha256:${String(a.result_sha256).slice(0, 4)}…${String(a.result_sha256).slice(-2)}` : null,
+ step.duration_ms != null ? formatDuration(step.duration_ms) : null].filter(Boolean).join(" · ")}
+ </div>
+ </div>
+ {onOpenStep && <button className="p3-link" onClick={() => onOpenStep(session_id, turn.turn_id)}>{t("p3.cov.open_step")}</button>}
+ </div>
+ );
+ })
+ )}
+ {finding.fixed_by && <p className="team-totals">{t("p3.ev2.fixed_by", { who: finding.fixed_by })}</p>}
+ {finding.verified_by && (
+ <p className={"team-totals" + (finding.verified_by === finding.fixed_by ? " text-danger" : "")}>
+ {finding.verified_by === finding.fixed_by ? t("p3.ev2.self_verified", { who: finding.verified_by }) : t("p3.ev2.verified_by", { who: finding.verified_by })}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/surfaces/gui/src/components/TeamView.tsx b/surfaces/gui/src/components/TeamView.tsx
index 6fe7a64b..8592077a 100644
--- a/surfaces/gui/src/components/TeamView.tsx
+++ b/surfaces/gui/src/components/TeamView.tsx
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
+import { CoverageBlock, EvidenceBlock, TeamEvents, WakeSplit } from "./TeamPhase3";
import {
getSessionMessages,
getInbox,
@@ -467,7 +468,11 @@ function WorkerRows({
);
}
-function Stats({ summary: s }: { summary: TeamSummary }) {
+function Stats({ summary: s, onOpenSteps, onOpenBoard }: {
+ summary: TeamSummary;
+ onOpenSteps?: (sessionId: string, turnId: string) => void;
+ onOpenBoard?: () => void;
+}) {
const { t } = useTranslation();
const [by, setBy] = useState<"worker" | "role">("worker"),
[chart, setChart] = useState(false);
@@ -637,6 +642,9 @@ function Stats({ summary: s }: { summary: TeamSummary }) {
<p>{t("teamview.no_usage")}</p>
))}
</section>
+ {/* Phase 3 OB-17: why each team turn started, and the events that used to be silent */}
+ <WakeSplit wakes={s.wakes || []} explained={s.wake_explained} t={t} />
+ <TeamEvents events={s.events || []} t={t} onOpenSteps={onOpenSteps} onOpenBoard={onOpenBoard} />
<section className="team-stats-section">
<h3>{t("teamview.needed_you")}</h3>
<table className="team-asks">
@@ -714,7 +722,10 @@ export function TeamView({
machineName,
onClose,
onRefresh,
+ onOpenSteps,
}: {
+ // Phase 3: open a member session's Steps at one turn (team events, evidence).
+ onOpenSteps?: (sessionId: string, turnId: string) => void;
summary: TeamSummary | null;
openKey?: number;
board?: Board | null;
@@ -857,6 +868,7 @@ export function TeamView({
workers={workers}
onWorker={openWorker}
onRefresh={onRefresh}
+ onOpenSteps={onOpenSteps}
/>
) : worker ? (
<WorkerConversation
@@ -950,7 +962,7 @@ export function TeamView({
/>
</>
) : (
- <Stats summary={summary} />
+ <Stats summary={summary} onOpenSteps={onOpenSteps} onOpenBoard={() => setTab("work")} />
)}
</div>
)}
@@ -992,12 +1004,14 @@ function TaskDetailPane({
workers,
onWorker,
onRefresh,
+ onOpenSteps,
}: {
task?: TeamTask;
leadSession: string;
workers: TeamWorker[];
onWorker: (worker: TeamWorker) => void;
onRefresh: () => void;
+ onOpenSteps?: (sessionId: string, turnId: string) => void;
}) {
const { t } = useTranslation();
const [detail, setDetail] = useState<BoardItemDetail | null>(null);
@@ -1045,6 +1059,14 @@ function TaskDetailPane({
data-testid="team-task-detail"
>
<h2>{task?.title || t("teamview.task_unavailable")}</h2>
+ {/* Phase 3 OB-16: what the security coworker scanned, and the evidence behind findings */}
+ {task?.coverage && (
+ <CoverageBlock coverage={task.coverage} t={t}
+ onOpenStep={onOpenSteps ? (sc) => sc.session_id && sc.turn_id && onOpenSteps(sc.session_id, sc.turn_id) : undefined} />
+ )}
+ {(task?.findings || []).map((f) => (
+ <EvidenceBlock key={String(f.id)} finding={f} t={t} onOpenStep={onOpenSteps} />
+ ))}
{task && task.elapsed_s > 0 && (
<>
<MetricBar
diff --git a/surfaces/gui/src/components/Transcript.tsx b/surfaces/gui/src/components/Transcript.tsx
index 878084b9..835d5668 100644
--- a/surfaces/gui/src/components/Transcript.tsx
+++ b/surfaces/gui/src/components/Transcript.tsx
@@ -9,6 +9,8 @@ import type { MessageSource } from "../api";
import { ConnectorMessageCard } from "./ConnectorMessageCard";
import { Icon } from "./Icon";
import { UnaskedSummary, unaskedTools } from "./UnaskedSummary";
+import { TurnFooterLine, type FootersState } from "./TurnFooter";
+import { turnForAnswer, type TurnFooter as TurnFooterData } from "../obs3";
// Long user pastes swallow the transcript (owner ask 2026-07-30): clamp past a generous
// threshold with a more…/less… toggle. Normal typed messages never see the control; the
@@ -498,8 +500,13 @@ interface Props {
// OPE-238: open Activity on one tool call's audit rows (from the "changes made without
// asking" summary). Without it the summary shows no audit links.
onOpenAudit?: (callId: string) => void;
- // UX-059 OB-1: open the Steps panel at the turn that ended with this answer (its time).
- onOpenSteps?: (ts?: number) => void;
+ // UX-059 OB-1: open the Steps panel at the turn that ended with this answer (its time),
+ // or at a given recorded turn (the OB-5 footer knows it).
+ onOpenSteps?: (ts?: number, turnId?: string) => void;
+ // OB-5 (Phase 3): the session's turn footers; with them each answer gets its footer line.
+ footers?: FootersState | null;
+ footerSessionId?: string;
+ onFooterChange?: (f: TurnFooterData) => void;
}
// The transcript index whose notice gets the Retry button: the tail error notice, looking
@@ -559,7 +566,7 @@ function McpNotice({
}
-export function Transcript({ items, running, streamingText, onRetry, onOpenConnectors, onUndoMemory, onAllowAnyway, onOpenAudit, onOpenSteps }: Props) {
+export function Transcript({ items, running, streamingText, onRetry, onOpenConnectors, onUndoMemory, onAllowAnyway, onOpenAudit, onOpenSteps, footers, footerSessionId, onFooterChange }: Props) {
const { t } = useTranslation();
// §33 grouping: a turn = the maximal run of assistant/tool/resolved-approval items between
// breakers (user, connector, notices, plan/dir requests…). Trailing assistant texts are the
@@ -617,6 +624,31 @@ export function Transcript({ items, running, streamingText, onRetry, onOpenConne
if (!running) emitUnasked();
const lastTurnIndex = blocks.reduce((acc, b, i) => ("turn" in b ? i : acc), -1);
+ // OB-5: an answer that ends its turn (no answer bubble follows it) carries the turn's footer.
+ const isAnswer = (b: (typeof blocks)[number] | undefined) =>
+ !!b && "item" in b && b.item.kind === "assistant" && !!b.item.text;
+ const answerEnds: number[] = [];
+ blocks.forEach((b, i) => {
+ if (isAnswer(b) && !isAnswer(blocks[i + 1])) answerEnds.push(i);
+ });
+ const footerFor = (bi: number, item: Extract<Item, { kind: "assistant" }>) => {
+ if (!footers || !footerSessionId || running && bi === answerEnds[answerEnds.length - 1]) return null;
+ const idx = answerEnds.indexOf(bi);
+ if (idx < 0) return null;
+ const f = turnForAnswer(footers.turns, item.ts, idx, item.mid);
+ if (!f) return null;
+ return (
+ <TurnFooterLine
+ sessionId={footerSessionId}
+ footer={f}
+ recording={footers.recording}
+ last={idx === answerEnds.length - 1}
+ defaultWhere={footers.where}
+ onChange={onFooterChange}
+ onOpenSteps={onOpenSteps ? () => onOpenSteps(item.ts, f.turn_id) : undefined}
+ />
+ );
+ };
return (
<div className="transcript">
{blocks.map((block, bi) => {
@@ -680,6 +712,7 @@ export function Transcript({ items, running, streamingText, onRetry, onOpenConne
{item.reasoning && <ThinkingBlock text={item.reasoning} />}
<Markdown text={item.text} />
<BubbleMeta text={item.text} ts={item.ts} align="left" onOpenSteps={onOpenSteps} />
+ {footerFor(bi, item)}
</div>
);
case "dirreq":
diff --git a/surfaces/gui/src/components/TurnFooter.test.tsx b/surfaces/gui/src/components/TurnFooter.test.tsx
new file mode 100644
index 00000000..13afd7e7
--- /dev/null
+++ b/surfaces/gui/src/components/TurnFooter.test.tsx
@@ -0,0 +1,63 @@
+// OB-5: the footer under an answer and the rating card (technical-design.md §8).
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+vi.mock("../api", () => ({
+ getSessionFooters: vi.fn(),
+ putTurnFeedback: vi.fn(async (_s: string, turnId: string, body: any) => ({
+ feedback: body.rating ? { turn_id: turnId, session_id: "s1", rating: body.rating, reasons: body.reasons || [], rated_at: 1, changed_at: null, content: { note: body.note || null } } : null,
+ where: { local: true, export: "langfuse", managed: false, with_note: !!body.note },
+ })),
+}));
+
+import { putTurnFeedback } from "../api";
+import { TurnFooterLine } from "./TurnFooter";
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+const footer = { turn_id: "t1", seq: 5, status: "completed", duration_ms: 14_000, total: 41_000, at_least: false,
+ warn: 1, auto_approved: 1, asked: 0, feedback: null };
+
+describe("TurnFooterLine", () => {
+ it("says this turn's tokens and hides parts that are 0 (M3-R6, M3-R7)", () => {
+ render(<TurnFooterLine sessionId="s1" footer={footer} last onOpenSteps={() => {}} />);
+ const text = screen.getByTestId("turn-footer").textContent || "";
+ expect(text).toContain("14s");
+ expect(text).toContain("41k tokens this turn");
+ expect(text).toContain("1 issue");
+ expect(text).toContain("1 auto-approved");
+ expect(text).not.toContain("asked you");
+ });
+
+ it("a 👎 opens the card; Send stores the reasons and the note and says where it went", async () => {
+ const changed = vi.fn();
+ render(<TurnFooterLine sessionId="s1" footer={footer} last onChange={changed} />);
+ fireEvent.click(screen.getByTestId("turn-footer-down"));
+ fireEvent.click(screen.getByTestId("rating-reason-did_unasked"));
+ fireEvent.change(screen.getByTestId("rating-note"), { target: { value: "ran a command I didn't want" } });
+ fireEvent.click(screen.getByTestId("rating-send"));
+ await waitFor(() => expect(putTurnFeedback).toHaveBeenCalled());
+ expect((putTurnFeedback as any).mock.calls[0]).toEqual(["s1", "t1", { rating: "down", reasons: ["did_unasked"], note: "ran a command I didn't want" }]);
+ await waitFor(() => expect(screen.getByTestId("turn-footer-where").textContent).toContain("Also sent to Langfuse"));
+ expect(screen.getByTestId("turn-footer-where").textContent).toContain("With your note.");
+ expect(changed).toHaveBeenCalled();
+ });
+
+ it("a 👍 is stored at once; a second 👍 clears it", async () => {
+ const { rerender } = render(<TurnFooterLine sessionId="s1" footer={footer} last />);
+ fireEvent.click(screen.getByTestId("turn-footer-up"));
+ await waitFor(() => expect((putTurnFeedback as any).mock.calls[0][2]).toEqual({ rating: "up", reasons: [], note: undefined }));
+ rerender(<TurnFooterLine sessionId="s1" footer={{ ...footer, feedback: { turn_id: "t1", session_id: "s1", rating: "up", reasons: [], rated_at: 1, changed_at: null } }} last />);
+ fireEvent.click(screen.getByTestId("turn-footer-up"));
+ await waitFor(() => expect((putTurnFeedback as any).mock.calls[1][2].rating).toBeNull());
+ });
+
+ it("with recording off, says so and still offers a rating", () => {
+ render(<TurnFooterLine sessionId="s1" footer={footer} recording={false} last />);
+ expect(screen.getByTestId("turn-footer").textContent).toContain("Recording is off on this machine");
+ expect(screen.getByTestId("turn-footer-down")).toBeTruthy();
+ });
+});
diff --git a/surfaces/gui/src/components/TurnFooter.tsx b/surfaces/gui/src/components/TurnFooter.tsx
new file mode 100644
index 00000000..ab42c80f
--- /dev/null
+++ b/surfaces/gui/src/components/TurnFooter.tsx
@@ -0,0 +1,171 @@
+// Observability Phase 3, OB-5: the quiet line under an answer, and its rating (technical-
+// design.md §8, UX-059 ob5). Time, this turn's tokens (the header pill is the whole session,
+// M3-R6), its warnings, what was auto-approved or asked (only when not 0, M3-R7), a Steps
+// link and 👍/👎. Always shown under the last turn, on hover for older ones (Q9). A 👎 opens a
+// card with the five reasons and a note; its last line says where the rating went.
+
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { getSessionFooters, putTurnFeedback } from "../api";
+import { formatTokens } from "../usage";
+import { formatDuration } from "./StepsPanel";
+import { footerParts, REASONS, whereKey, type FeedbackWhere, type TurnFeedback, type TurnFooter } from "../obs3";
+
+export interface FootersState {
+ turns: TurnFooter[];
+ recording: boolean;
+ where?: FeedbackWhere;
+}
+
+/** A session's footers, read again whenever `refreshKey` moves (a turn ended). */
+export function useSessionFooters(sessionId: string | null | undefined, refreshKey: unknown): [FootersState | null, (f: TurnFooter) => void] {
+ const [state, setState] = useState<FootersState | null>(null);
+ useEffect(() => {
+ let live = true;
+ if (!sessionId) {
+ setState(null);
+ return;
+ }
+ getSessionFooters(sessionId)
+ .then((r) => live && setState({ turns: r.turns || [], recording: r.recording !== false, where: r.where }))
+ .catch(() => live && setState(null));
+ return () => {
+ live = false;
+ };
+ }, [sessionId, refreshKey]);
+ const update = (f: TurnFooter) =>
+ setState((s) => (s ? { ...s, turns: s.turns.map((x) => (x.turn_id === f.turn_id ? f : x)) } : s));
+ return [state, update];
+}
+
+export function TurnFooterLine({
+ sessionId,
+ footer,
+ recording = true,
+ last,
+ onOpenSteps,
+ onChange,
+ defaultWhere,
+}: {
+ sessionId: string;
+ footer: TurnFooter;
+ recording?: boolean;
+ last: boolean;
+ defaultWhere?: FeedbackWhere;
+ onOpenSteps?: () => void;
+ onChange?: (f: TurnFooter) => void;
+}) {
+ const { t } = useTranslation();
+ const [card, setCard] = useState(false);
+ const [where, setWhere] = useState<FeedbackWhere | null>(null);
+ const rating = footer.feedback?.rating ?? null;
+
+ const rate = async (r: "up" | "down" | null, reasons: string[] = [], note?: string) => {
+ try {
+ const res = await putTurnFeedback(sessionId, footer.turn_id, { rating: r, reasons, note });
+ setWhere(res.where);
+ onChange?.({ ...footer, feedback: res.feedback });
+ return true;
+ } catch {
+ return false;
+ }
+ };
+
+ const parts = recording ? footerParts(footer) : [];
+ return (
+ <div className={"turnfoot-wrap" + (last ? " last" : "")} data-testid="turn-footer">
+ <div className="turnfoot">
+ {!recording ? (
+ <span className="text-faint">{t("p3.foot.recording_off")}</span>
+ ) : (
+ parts.map((p, i) => (
+ <span key={p.kind} className="turnfoot-part">
+ {i > 0 && <span className="sep">·</span>}
+ {p.kind === "time" && <span>{formatDuration(p.ms)}</span>}
+ {p.kind === "tokens" && <span data-testid="turn-footer-tokens">{t("p3.foot.tokens", { tokens: (p.at_least ? "≥ " : "") + formatTokens(p.total) })}</span>}
+ {p.kind === "issues" && <span className="steps-badge warn" data-testid="turn-footer-issues">{t("p3.foot.issues", { count: p.n })}</span>}
+ {p.kind === "auto_approved" && <span className="c-review">{t("p3.foot.auto_approved", { count: p.n })}</span>}
+ {p.kind === "asked" && <span>{t("p3.foot.asked", { count: p.n })}</span>}
+ </span>
+ ))
+ )}
+ {onOpenSteps && recording && (
+ <>
+ <span className="sep">·</span>
+ <button className="p3-link" data-testid="turn-footer-steps" onClick={onOpenSteps}>{t("steps.open")}</button>
+ </>
+ )}
+ <span className="sep">·</span>
+ <button className={"thumb" + (rating === "up" ? " sel" : "")} aria-pressed={rating === "up"} data-testid="turn-footer-up"
+ title={t("p3.fb.up")} onClick={() => { setCard(false); void rate(rating === "up" ? null : "up"); }}>👍</button>
+ <button className={"thumb" + (rating === "down" ? " sel" : "")} aria-pressed={rating === "down"} data-testid="turn-footer-down"
+ title={t("p3.fb.down")} onClick={() => { if (rating === "down" && !card) { void rate(null); return; } setCard(true); }}>👎</button>
+ {where && !card && <span className="text-faint ml-2" data-testid="turn-footer-where">{whereLine(where, t)}</span>}
+ </div>
+ {card && (
+ <RatingCard
+ initial={footer.feedback}
+ onSend={async (reasons, note) => {
+ const ok = await rate("down", reasons, note);
+ if (ok) setCard(false);
+ return ok;
+ }}
+ onSkip={async () => {
+ await rate("down");
+ setCard(false);
+ }}
+ where={where ?? defaultWhere}
+ />
+ )}
+ </div>
+ );
+}
+
+/** The machine's own answer says whether the note went too (`with_note`: a note was given
+ * and "Your messages and the AI's answers" is on, TD3-11). */
+export function whereLine(w: FeedbackWhere | null | undefined, t: (k: string, o?: any) => string): string {
+ const { key, withNote } = whereKey(w);
+ return t(key, { by: w?.by || "" }) + (withNote ? " " + t("p3.fb.with_note") : "");
+}
+
+export function RatingCard({
+ initial,
+ onSend,
+ onSkip,
+ where,
+}: {
+ initial?: TurnFeedback | null;
+ onSend: (reasons: string[], note?: string) => Promise<boolean>;
+ onSkip: () => void;
+ where?: FeedbackWhere | null;
+}) {
+ const { t } = useTranslation();
+ const [reasons, setReasons] = useState<string[]>(initial?.rating === "down" ? initial.reasons : []);
+ const [note, setNote] = useState(initial?.content?.note || "");
+ const [failed, setFailed] = useState(false);
+ const toggle = (r: string) => setReasons((cur) => (cur.includes(r) ? cur.filter((x) => x !== r) : [...cur, r]));
+ return (
+ <div className="p3-ratecard" data-testid="rating-card">
+ <b>{t("p3.fb.what_wrong")} <span className="text-faint font-normal">{t("p3.fb.optional")}</span></b>
+ <div className="flex gap-1.5 flex-wrap my-2">
+ {REASONS.map((r) => (
+ <button key={r} className={"p3-pill" + (reasons.includes(r) ? " on" : "")} aria-pressed={reasons.includes(r)}
+ data-testid={`rating-reason-${r}`} onClick={() => toggle(r)}>
+ {t(`p3.fb.reason.${r}`)}
+ </button>
+ ))}
+ </div>
+ <textarea className="p3-note" placeholder={t("p3.fb.note_placeholder")} value={note} rows={2}
+ data-testid="rating-note" onChange={(e) => setNote(e.target.value)} />
+ <div className="flex gap-2 mt-2 items-center">
+ <button className="btn primary" data-testid="rating-send" onClick={async () => setFailed(!(await onSend(reasons, note.trim() || undefined)))}>
+ {t("p3.fb.send")}
+ </button>
+ <button className="btn" data-testid="rating-skip" onClick={onSkip}>{t("p3.fb.skip")}</button>
+ <span className="text-faint ml-auto text-meta">
+ {failed ? t("p3.fb.failed") : whereLine(where, t)}
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/surfaces/gui/src/components/UsagePage.test.tsx b/surfaces/gui/src/components/UsagePage.test.tsx
new file mode 100644
index 00000000..c81d8b01
--- /dev/null
+++ b/surfaces/gui/src/components/UsagePage.test.tsx
@@ -0,0 +1,101 @@
+// OB-8: the Usage tab's numbers, from fixed rollup answers (technical-design.md §7).
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import i18n from "i18next";
+import { ApproverStripView, coworkerTable, UsageBody, type UsageData } from "./UsagePage";
+import type { UsageRollup } from "../api";
+
+afterEach(cleanup);
+
+const t = i18n.t.bind(i18n) as any;
+const group = (key: Record<string, any>, total: number, extra: Record<string, number> = {}) => ({
+ key, total, input_fresh: 0, cache_read: 0, cache_write: 0, output: 0, calls: 1, unreported: 0, failed: 0,
+ turns: 1, checked: 1, with_warn: 0, ...extra,
+});
+const rollup = (groups: any[], over: Partial<UsageRollup> = {}): UsageRollup =>
+ ({ groups, no_turn: { calls: 0, total: 0 }, not_checked: 0, kept_from: null, ...over }) as UsageRollup;
+
+function data(over: Partial<UsageData> = {}): UsageData {
+ return {
+ total: rollup([group({ all: "all" }, 848_910, { turns: 20, checked: 18, with_warn: 5, automation_turns: 2, median_active_ms: 14_000 })],
+ { not_checked: 2, no_turn: { calls: 2, total: 54 }, kept_from: Date.now(), names: { cowork: "Cowork" } }),
+ prev: null,
+ dayPurpose: rollup([]),
+ coworkers: rollup([group({ persona_id: "cowork", task_id: null }, 800_000, { checked: 10, with_warn: 3 }),
+ group({ persona_id: "cowork", task_id: "task-1" }, 48_910)]),
+ heavy: [
+ { turn_id: "t5", session_id: "s1", title: "Run the watch", seq: 5, session_deleted: false, persona_id: "cowork",
+ model_ids: ["model-x"], total: 146_000, at_least: false, active_ms: 22_000, status: "completed", found_open: false,
+ warn: 1, checks: ["tool_failed"], started_at: 0 },
+ { turn_id: "t2", session_id: "s1", title: "Run the watch", seq: 2, session_deleted: false, persona_id: "cowork",
+ model_ids: ["model-x"], total: 75_000, at_least: false, active_ms: null, status: "unknown", found_open: true,
+ warn: 0, checks: [], started_at: 0 },
+ { turn_id: "t9", session_id: "gone", title: null, seq: null, session_deleted: true, persona_id: "cowork",
+ model_ids: [], total: 1_000, at_least: true, active_ms: 1000, status: "completed", found_open: false,
+ warn: null, checks: [], started_at: 0 },
+ ],
+ approver: null,
+ machines: [
+ { id: null, name: "", total: 848_910, at_least: false, state: "live" },
+ { id: "m1", name: "build-box-1", total: 12_000, at_least: false, state: "cached", as_of: new Date(2026, 10, 4, 14, 2).getTime() },
+ { id: "m2", name: "laptop-2", total: null, at_least: false, state: "offline" },
+ ],
+ ...over,
+ };
+}
+
+describe("UsageBody", () => {
+ it("shows the tiles without a comparison when no earlier period is kept (V3-11)", () => {
+ render(<UsageBody data={data()} period="7d" t={t} />);
+ expect(screen.getByTestId("usage-tile-tokens").textContent).toContain("no earlier week kept to compare");
+ expect(screen.getByTestId("usage-tile-turns").textContent).toContain("2 automation turns");
+ expect(screen.getByTestId("usage-tile-issues").textContent).toContain("28%");
+ expect(screen.getByTestId("usage-tile-issues").textContent).toContain("2 not checked yet");
+ expect(screen.getByTestId("usage-tile-median").textContent).toContain("14s");
+ expect(screen.getByTestId("usage-no-turn").textContent).toContain("Not in a session: 2 calls · 54 tokens");
+ });
+
+ it("names each heaviest turn, says when it was found open, and gives a deleted session no link (M3-R2, M3-R3)", () => {
+ const open = vi.fn();
+ render(<UsageBody data={data()} period="7d" t={t} onOpenTurn={open} />);
+ const table = screen.getByTestId("usage-heaviest").textContent || "";
+ expect(table).toContain("turn 5");
+ expect(table).toContain("found open after a crash");
+ expect(table).toContain("deleted session");
+ expect(table).toContain("A tool failed");
+ const links = screen.getAllByTestId("usage-open-steps");
+ expect(links).toHaveLength(2);
+ fireEvent.click(links[0]);
+ expect(open).toHaveBeenCalledWith("s1", "t5");
+ });
+
+ it("lists machines, an offline one by its cached answer's time", () => {
+ render(<UsageBody data={data()} period="7d" t={t} />);
+ const m = screen.getByTestId("usage-machines").textContent || "";
+ expect(m).toContain("This machine");
+ expect(m).toContain("offline · as of 14:02");
+ expect(m).toContain("laptop-2");
+ });
+
+ it("names coworkers, with automations on their own row (M3-R1)", () => {
+ const rows = coworkerTable(data().coworkers.groups as any, { cowork: "Cowork" }, t);
+ expect(rows.map((r) => [r.name, r.automation, r.total])).toEqual([["Cowork", false, 800_000], ["Cowork", true, 48_910]]);
+ render(<UsageBody data={data()} period="7d" t={t} />);
+ expect(screen.getByTestId("usage-coworkers").textContent).toContain("(automation)");
+ });
+});
+
+describe("ApproverStripView", () => {
+ it("counts under 10 checks and says when shadow checks are in the tokens", () => {
+ const ap = { checks: 1, allowed: 1, asked: 0, blocked: 0, could_not_run: 0, median_ms: 1000, overridden: 0,
+ tokens: 3796, shadow_checks: 2, by_reviewer: [{ kind: "session_model", checks: 1, allowed: 1, asked: 0, blocked: 0, could_not_run: 0, median_ms: 1000 }], shown: true };
+ render(<ApproverStripView ap={ap} t={t} />);
+ const text = screen.getByTestId("usage-approver").textContent || "";
+ expect(text).toContain("allowed 1");
+ expect(text).not.toContain("%");
+ expect(text).toContain("session model");
+ expect(text).toContain("incl. 2 shadow checks");
+ expect(text).toContain("Auto-approve");
+ expect(text).not.toContain("Safety reviewer");
+ });
+});
diff --git a/surfaces/gui/src/components/UsagePage.tsx b/surfaces/gui/src/components/UsagePage.tsx
new file mode 100644
index 00000000..7d385afb
--- /dev/null
+++ b/surfaces/gui/src/components/UsagePage.tsx
@@ -0,0 +1,328 @@
+// Observability Phase 3, OB-8: Activity ▸ Usage (technical-design.md §7, UX-059 ob8). How much
+// the coworkers, models and machines used over Today, 7 or 30 days. Every number is a sum of
+// whole turns from the usage ledger, grouped by the turn's start on the viewer's own local days
+// (TD3-1, TD3-2), so the page agrees with the pills. Tokens only, never prices.
+
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ getApproverStrip,
+ getHeaviestTurns,
+ getMachines,
+ getUsageRollup,
+ type ApproverStrip,
+ type HeavyTurn,
+ type Machine,
+ type UsageRollup,
+} from "../api";
+import { formatTokens } from "../usage";
+import { formatDuration } from "./StepsPanel";
+import {
+ approverPart,
+ changePct,
+ comparable,
+ hhmm,
+ localDays,
+ previousDays,
+ purposeByDay,
+ SERIES,
+ type Period,
+ type RollupGroup,
+} from "../obs3";
+
+const CARD = "rounded-xl2 border border-line bg-panel";
+type T = (k: string, o?: any) => string;
+
+interface MachineRow {
+ id: string | null;
+ name: string;
+ total: number | null;
+ at_least: boolean;
+ state: "live" | "offline" | "cached";
+ as_of?: number;
+}
+
+export interface UsageData {
+ total: UsageRollup;
+ prev: UsageRollup | null;
+ dayPurpose: UsageRollup;
+ coworkers: UsageRollup;
+ heavy: HeavyTurn[];
+ approver: ApproverStrip | null;
+ machines: MachineRow[];
+}
+
+const sumAll = (r: UsageRollup | null | undefined): RollupGroup | null =>
+ r && r.groups.length ? r.groups[0] : null;
+
+/** Everything the page shows, for one period: one call per grouping, each to the machine
+ * that ran the work. Remote machines answer through the controller's proxy. */
+export async function loadUsage(period: Period, now = new Date()): Promise<UsageData> {
+ const days = localDays(period, now);
+ const from = days[0][1];
+ const to = days[days.length - 1][2];
+ const prevDays = previousDays(days);
+ const [total, prev, dayPurpose, coworkers, heavy, approver, fleet] = await Promise.all([
+ getUsageRollup({ from, to, group: "all" }),
+ getUsageRollup({ from: prevDays[0][1], to: prevDays[prevDays.length - 1][2], group: "all" }).catch(() => null),
+ getUsageRollup({ from, to, days, group: "day,purpose" }),
+ getUsageRollup({ from, to, group: "persona_id,task_id" }),
+ getHeaviestTurns(from, to).then((r) => r.turns).catch(() => [] as HeavyTurn[]),
+ getApproverStrip(from, to).catch(() => null),
+ getMachines().then((r) => r.machines || []).catch(() => [] as Machine[]),
+ ]);
+ const here = sumAll(total);
+ const machines: MachineRow[] = [
+ { id: null, name: "", total: here?.total ?? 0, at_least: (here?.unreported ?? 0) > 0, state: "live" },
+ ];
+ const remote = await Promise.all(
+ fleet.map(async (m): Promise<MachineRow> => {
+ try {
+ const r = await getUsageRollup({ from, to, group: "all" }, m.id);
+ const g = sumAll(r);
+ return {
+ id: m.id, name: m.name, total: g?.total ?? 0, at_least: (g?.unreported ?? 0) > 0,
+ state: r.cached ? "cached" : "live", as_of: r.cached?.as_of,
+ };
+ } catch {
+ return { id: m.id, name: m.name, total: null, at_least: false, state: "offline" };
+ }
+ }),
+ );
+ return { total, prev, dayPurpose, coworkers, heavy, approver, machines: [...machines, ...remote] };
+}
+
+export function UsagePage({ onOpenTurn }: { onOpenTurn?: (sessionId: string, turnId: string) => void }) {
+ const { t } = useTranslation();
+ const [period, setPeriod] = useState<Period>("7d");
+ const [data, setData] = useState<UsageData | null>(null);
+ const [error, setError] = useState(false);
+
+ useEffect(() => {
+ let live = true;
+ setError(false);
+ loadUsage(period)
+ .then((d) => live && setData(d))
+ .catch(() => live && setError(true));
+ return () => {
+ live = false;
+ };
+ }, [period]);
+
+ return (
+ <div data-testid="usage-page">
+ <div className="flex items-center gap-2 mb-4">
+ <div className="p3-seg" role="tablist">
+ {(["today", "7d", "30d"] as Period[]).map((p) => (
+ <button key={p} role="tab" aria-pressed={period === p} data-testid={`usage-period-${p}`} onClick={() => setPeriod(p)}>
+ {t(`p3.usage.period_${p}`)}
+ </button>
+ ))}
+ </div>
+ </div>
+ {error ? (
+ <div className={CARD + " p-4 text-ui text-muted"}>{t("p3.usage.load_error")}</div>
+ ) : !data ? (
+ <div className={CARD + " p-4 text-ui text-muted"}>{t("p3.usage.loading")}</div>
+ ) : (
+ <UsageBody data={data} period={period} t={t} onOpenTurn={onOpenTurn} />
+ )}
+ </div>
+ );
+}
+
+export function UsageBody({ data, period, t, onOpenTurn }: { data: UsageData; period: Period; t: T; onOpenTurn?: (sessionId: string, turnId: string) => void }) {
+ const days = useMemo(() => localDays(period), [period]);
+ const all = sumAll(data.total);
+ const prev = sumAll(data.prev);
+ const prevStart = previousDays(days)[0][1];
+ const canCompare = comparable(data.total.kept_from, prevStart);
+ const pct = canCompare && prev ? changePct(all?.total ?? 0, prev.total) : null;
+ const chart = purposeByDay(days, data.dayPurpose.groups);
+ const names = data.total.names || data.coworkers.names || {};
+ const turns = all?.turns ?? 0;
+ const checked = all?.checked ?? 0;
+ const withWarn = all?.with_warn ?? 0;
+ const notChecked = data.total.not_checked || 0;
+ const coworkerRows = coworkerTable(data.coworkers.groups, names, t);
+ const ap = data.approver;
+
+ return (
+ <>
+ <div className="p3-tiles">
+ <Tile label={t("p3.usage.tokens")} value={(all?.unreported ? "≥ " : "") + formatTokens(all?.total ?? 0)}
+ sub={!canCompare ? t(`p3.usage.no_compare_${period}`) : pct == null ? t("p3.usage.no_compare_none") :
+ t("p3.usage.vs_last", { sign: pct >= 0 ? "▲" : "▼", pct: Math.abs(pct) })} testid="usage-tile-tokens" />
+ <Tile label={t("p3.usage.turns")} value={String(turns)}
+ sub={t("p3.usage.automation_runs", { count: all?.automation_turns ?? 0 })} testid="usage-tile-turns" />
+ <Tile label={t("p3.usage.with_issues")} value={checked ? `${Math.round((withWarn / checked) * 100)}%` : "—"}
+ sub={t("p3.usage.with_issues_sub", { n: withWarn, of: checked }) + (notChecked ? " · " + t("p3.usage.not_checked", { count: notChecked }) : "")}
+ testid="usage-tile-issues" />
+ <Tile label={t("p3.usage.median_time")} value={formatDuration(all?.median_active_ms ?? null)}
+ sub={t("p3.usage.median_sub")} testid="usage-tile-median" />
+ </div>
+
+ <div className="p3-two">
+ <div className={CARD + " p3-card"}>
+ <b className="p3-h">{t("p3.usage.per_day")}</b>
+ <div className="p3-bars" data-testid="usage-bars">
+ {chart.rows.map((r) => (
+ <div key={r.label} className="p3-bar" title={`${r.label}: ${formatTokens(r.total)}`}>
+ {SERIES.map((s) =>
+ r.values[s] ? (
+ <i key={s} className={`p3-s-${s}`} style={{ height: `${Math.max(1, (r.values[s] / chart.max) * 100)}%` }}
+ title={`${t(`p3.series.${s}`)}: ${r.values[s].toLocaleString()}`} />
+ ) : null,
+ )}
+ </div>
+ ))}
+ </div>
+ {days.length > 1 && (
+ <div className="p3-xl">
+ {days.map(([label, start]) => (
+ <span key={label}>{days.length <= 7 ? new Date(start).toLocaleDateString(undefined, { weekday: "short", day: "2-digit" }) : new Date(start).getDate()}</span>
+ ))}
+ </div>
+ )}
+ <div className="p3-legend" data-testid="usage-legend">
+ {SERIES.filter((s) => chart.legend[s] > 0).map((s) => (
+ <span key={s}><i className={`p3-s-${s}`} />{t(`p3.series.${s}`)} {formatTokens(chart.legend[s])}</span>
+ ))}
+ </div>
+ </div>
+ <div className={CARD + " p3-card"}>
+ <b className="p3-h">{t("p3.usage.by_coworker")}</b>
+ <table className="p3-t" data-testid="usage-coworkers">
+ <thead><tr><th>{t("p3.usage.coworker")}</th><th className="n">{t("p3.usage.tokens")}</th><th className="n">{t("p3.usage.with_issues")}</th></tr></thead>
+ <tbody>
+ {coworkerRows.map((r) => (
+ <tr key={r.key}><td>{r.name}{r.automation && <span className="text-faint"> {t("p3.usage.automation")}</span>}</td>
+ <td className="n">{(r.atLeast ? "≥ " : "") + formatTokens(r.total)}</td>
+ <td className="n">{r.checked ? `${Math.round((r.withWarn / r.checked) * 100)}%` : "—"}</td></tr>
+ ))}
+ </tbody>
+ </table>
+ <b className="p3-h mt-3 block">{t("p3.usage.by_machine")}</b>
+ <table className="p3-t" data-testid="usage-machines">
+ <thead><tr><th>{t("p3.usage.machine")}</th><th className="n">{t("p3.usage.tokens")}</th><th></th></tr></thead>
+ <tbody>
+ {data.machines.map((m) => (
+ <tr key={m.id || "here"}>
+ <td>{m.id ? m.name : t("p3.usage.this_machine")}</td>
+ <td className="n">{m.total == null ? "—" : (m.at_least ? "≥ " : "") + formatTokens(m.total)}</td>
+ <td className="text-faint">
+ {m.state === "live" ? t("p3.usage.live") : m.state === "cached" && m.as_of ? t("p3.usage.offline_as_of", { time: hhmm(m.as_of) }) : t("p3.usage.offline")}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <div className={CARD + " p3-card mt-3"}>
+ <b className="p3-h">{t("p3.usage.heaviest")}</b>
+ {data.heavy.length === 0 ? (
+ <div className="text-meta text-faint mt-1">{t("p3.usage.no_turns")}</div>
+ ) : (
+ <table className="p3-t" data-testid="usage-heaviest">
+ <thead><tr><th>{t("p3.usage.session")}</th><th>{t("p3.usage.coworker")}</th><th>{t("p3.usage.model")}</th>
+ <th className="n">{t("p3.usage.tokens")}</th><th className="n">{t("p3.usage.active_time")}</th><th>{t("p3.usage.issues")}</th><th></th></tr></thead>
+ <tbody>
+ {data.heavy.map((h) => (
+ <tr key={h.turn_id}>
+ <td className="p3-trunc">{h.session_deleted ? <span className="text-faint">{t("p3.usage.deleted_session")}</span> : (h.title || h.session_id)}
+ {h.seq != null && <span className="text-faint"> · {t("p3.usage.turn_n", { n: h.seq })}</span>}</td>
+ <td>{(h.persona_id && names[h.persona_id]) || h.persona_id || "—"}</td>
+ <td className="font-mono">{h.model_ids.join(", ") || "—"}</td>
+ <td className="n">{(h.at_least ? "≥ " : "") + formatTokens(h.total)}</td>
+ <td className="n">{h.found_open ? <span className="text-faint">{t("p3.usage.found_open")}</span> : formatDuration(h.active_ms)}</td>
+ <td>{h.checks.map((c) => <span key={c} className="steps-badge warn mr-1">{t(`steps.issues.title.${c}`, { defaultValue: c })}</span>)}</td>
+ <td>{!h.session_deleted && onOpenTurn && (
+ <button className="p3-link" data-testid="usage-open-steps" onClick={() => onOpenTurn(h.session_id, h.turn_id)}>{t("steps.open")}</button>
+ )}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+
+ {ap && ap.shown && <ApproverStripView ap={ap} t={t} />}
+
+ {data.total.no_turn.calls > 0 && (
+ <div className="text-meta text-faint mt-2" data-testid="usage-no-turn">
+ {t("p3.usage.no_turn", { calls: data.total.no_turn.calls, tokens: data.total.no_turn.total.toLocaleString() })}
+ </div>
+ )}
+ {(data.total.deleted_session_turns ?? 0) > 0 && (
+ <div className="text-meta text-faint mt-1">{t("p3.usage.deleted_note", { count: data.total.deleted_session_turns })}</div>
+ )}
+ {data.total.kept_from != null && (
+ <div className="text-meta text-faint mt-1">{t("p3.usage.kept_note")}</div>
+ )}
+ </>
+ );
+}
+
+function Tile({ label, value, sub, testid }: { label: string; value: string; sub: string; testid?: string }) {
+ return (
+ <div className="p3-kpi" data-testid={testid}>
+ <span>{label}</span>
+ <b>{value}</b>
+ <em>{sub}</em>
+ </div>
+ );
+}
+
+/** By coworker, named from the installed coworkers or the kept versions (M3-R1); an
+ * automation's turns get their own row under their coworker, "(automation)". */
+export function coworkerTable(groups: RollupGroup[], names: Record<string, string>, t: T) {
+ const rows = new Map<string, { key: string; name: string; automation: boolean; total: number; atLeast: boolean; checked: number; withWarn: number }>();
+ for (const g of groups) {
+ const pid = g.key.persona_id as string | null;
+ const auto = g.key.task_id != null;
+ const key = `${pid ?? ""}|${auto ? "a" : ""}`;
+ const r = rows.get(key) || { key, name: pid ? names[pid] || pid : t("p3.usage.unknown_coworker"), automation: auto, total: 0, atLeast: false, checked: 0, withWarn: 0 };
+ r.total += g.total;
+ r.atLeast = r.atLeast || g.unreported > 0;
+ r.checked += g.checked;
+ r.withWarn += g.with_warn;
+ rows.set(key, r);
+ }
+ return [...rows.values()].sort((a, b) => b.total - a.total);
+}
+
+export function ApproverStripView({ ap, t }: { ap: ApproverStrip; t: T }) {
+ const lines = ap.by_reviewer.length ? ap.by_reviewer : [{ ...ap, kind: "" }];
+ return (
+ <div className={CARD + " p3-card mt-3 flex flex-col gap-1.5"} data-testid="usage-approver">
+ {lines.map((l) => {
+ const part = (n: number, key: string) => {
+ const p = approverPart(n, l.checks);
+ return t(`p3.ap.${key}_${p.share ? "share" : "count"}`, { n: p.value });
+ };
+ return (
+ <div key={l.kind} className="flex items-center gap-3 flex-wrap text-meta">
+ <b className="p3-h">{t("p3.ap.title")}</b>
+ <span className="text-muted">
+ {t("p3.ap.checks", { count: l.checks })}
+ {l.kind ? " · " + t(`p3.ap.kind.${l.kind}`, { defaultValue: l.kind }) : ""}
+ </span>
+ <span className="p3-chip ok">{part(l.allowed, "allowed")}</span>
+ <span className="p3-chip warn">{part(l.asked, "asked")}</span>
+ <span className="p3-chip err">{part(l.blocked, "blocked")}</span>
+ <span className="text-muted">
+ {t("p3.ap.could_not_run", { n: l.could_not_run })} · {t("p3.ap.overridden", { n: ap.overridden })} ·{" "}
+ {t("p3.ap.median", { time: formatDuration(l.median_ms) })}
+ </span>
+ </div>
+ );
+ })}
+ <div className="text-meta text-muted">
+ {t("p3.ap.tokens", { tokens: formatTokens(ap.tokens) })}
+ {ap.shadow_checks > 0 ? " · " + t("p3.ap.incl_shadow", { count: ap.shadow_checks }) : ""}
+ </div>
+ </div>
+ );
+}
diff --git a/surfaces/gui/src/itemsFromMessages.ts b/surfaces/gui/src/itemsFromMessages.ts
index c0de5b4e..4ad3b8c2 100644
--- a/surfaces/gui/src/itemsFromMessages.ts
+++ b/surfaces/gui/src/itemsFromMessages.ts
@@ -69,6 +69,7 @@ export function itemsFromMessages(messages: ConversationMessage[]): Item[] {
text: m.content || "",
...(typeof m.ts === "number" ? { ts: m.ts } : {}),
...(m.reasoning ? { reasoning: m.reasoning } : {}),
+ ...(typeof (m as any).mid === "string" ? { mid: (m as any).mid } : {}),
});
for (const tc of m.tool_calls || []) {
let args: any = {};
diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.json
index a33d6219..5a008180 100644
--- a/surfaces/gui/src/locales/en.json
+++ b/surfaces/gui/src/locales/en.json
@@ -3279,7 +3279,18 @@
"blocked_by_sandbox": "Blocked by the sandbox",
"sandbox_failed": "The sandbox could not start",
"ran_without_sandbox": "Ran without the sandbox",
- "waited_unwatched": "Waited while nobody was watching"
+ "waited_unwatched": "Waited while nobody was watching",
+ "wake_capped": "Team paused at the wake cap",
+ "watchdog_nudged": "The watchdog nudged the lead",
+ "lead_polling": "Lead polling",
+ "failed_in_a_row": "Failed runs in a row",
+ "scan_missing": "A promised scan did not run",
+ "scanner_failed": "A scanner failed",
+ "no_findings_without_scan": "“No findings” without a scan",
+ "finding_without_evidence": "A finding has no evidence step",
+ "self_verified": "A fix was verified by its own author",
+ "reviewed_before_prereq": "Reviewed before its prerequisite was done",
+ "same_approval_twice": "Same approval asked twice"
},
"summary": "{{total}} checks: {{fired}} found something · {{fine}} fine · {{na}} didn't apply",
"na": "Didn't apply · {{n}}",
@@ -3894,5 +3905,250 @@
"locked": "Locked",
"callout": "{{what}} from this machine are sent to {{by}}'s {{where}}. A small notice appears in each new session."
}
+ },
+ "p3": {
+ "usage": {
+ "tab_log": "Log",
+ "tab_usage": "Usage",
+ "sub": "Tokens your coworkers used, by day, coworker and machine. Waiting for you is never counted as work.",
+ "period_today": "Today",
+ "period_7d": "7 days",
+ "period_30d": "30 days",
+ "loading": "Loading…",
+ "load_error": "Usage could not be loaded from this machine.",
+ "tokens": "Tokens",
+ "turns": "Turns",
+ "with_issues": "Turns with issues",
+ "median_time": "Median turn time",
+ "vs_last": "{{sign}} {{pct}}% vs last period",
+ "no_compare_today": "no earlier day kept to compare",
+ "no_compare_7d": "no earlier week kept to compare",
+ "no_compare_30d": "no earlier 30 days kept to compare",
+ "no_compare_none": "nothing in the period before",
+ "automation_runs_one": "{{count}} automation turn",
+ "automation_runs_other": "{{count}} automation turns",
+ "with_issues_sub": "{{n}} of {{of}} checked",
+ "not_checked_one": "{{count}} not checked yet",
+ "not_checked_other": "{{count}} not checked yet",
+ "median_sub": "waiting for you not counted",
+ "per_day": "Tokens per day, by purpose",
+ "by_coworker": "By coworker",
+ "coworker": "Coworker",
+ "automation": "(automation)",
+ "unknown_coworker": "unknown coworker",
+ "by_machine": "By machine",
+ "machine": "Machine",
+ "this_machine": "This machine",
+ "live": "live",
+ "offline": "offline",
+ "offline_as_of": "offline · as of {{time}}",
+ "heaviest": "Heaviest turns",
+ "session": "Session",
+ "model": "Model",
+ "active_time": "Time without waiting",
+ "issues": "Issues",
+ "turn_n": "turn {{n}}",
+ "deleted_session": "deleted session",
+ "found_open": "unknown: found open after a crash",
+ "no_turns": "No turns in this period.",
+ "no_turn": "Not in a session: {{calls}} calls · {{tokens}} tokens (model calls made for other apps through this machine; in no total above).",
+ "deleted_note_one": "Includes {{count}} turn of a deleted session.",
+ "deleted_note_other": "Includes {{count}} turns of deleted sessions.",
+ "kept_note": "Token counts for the Usage page are kept 90 days, whatever “Keep for” says."
+ },
+ "series": {
+ "main": "Main work and helpers",
+ "summary": "Summaries",
+ "auto_approver": "Auto-approver",
+ "title": "Session titles",
+ "other": "Other"
+ },
+ "ap": {
+ "title": "Auto-approve",
+ "checks_one": "{{count}} check",
+ "checks_other": "{{count}} checks",
+ "kind": {
+ "session_model": "session model",
+ "openai_decisions": "decision model",
+ "typesafe_jev": "decision model"
+ },
+ "allowed_count": "allowed {{n}}",
+ "allowed_share": "allowed {{n}}%",
+ "asked_count": "asked you {{n}}",
+ "asked_share": "asked you {{n}}%",
+ "blocked_count": "blocked {{n}}",
+ "blocked_share": "blocked {{n}}%",
+ "could_not_run": "could not run {{n}}",
+ "overridden": "overridden {{n}}",
+ "median": "{{time}} median",
+ "tokens": "{{tokens}} tokens",
+ "incl_shadow_one": "incl. {{count}} shadow check",
+ "incl_shadow_other": "incl. {{count}} shadow checks"
+ },
+ "foot": {
+ "tokens": "{{tokens}} tokens this turn",
+ "issues_one": "{{count}} issue",
+ "issues_other": "{{count}} issues",
+ "auto_approved_one": "{{count}} auto-approved",
+ "auto_approved_other": "{{count}} auto-approved",
+ "asked_one": "{{count}} asked you",
+ "asked_other": "{{count}} asked you",
+ "recording_off": "Recording is off on this machine"
+ },
+ "fb": {
+ "up": "Good answer",
+ "down": "Something went wrong",
+ "what_wrong": "What went wrong?",
+ "optional": "(optional)",
+ "reason": {
+ "wrong_answer": "Wrong answer",
+ "too_slow": "Took too long",
+ "did_unasked": "Did something I didn't ask",
+ "did_not_finish": "Didn't finish",
+ "other": "Other"
+ },
+ "note_placeholder": "Add a note…",
+ "send": "Send",
+ "skip": "Skip",
+ "failed": "Could not save the rating.",
+ "where_local": "Saved on this machine.",
+ "where_langfuse": "Saved on this machine. Also sent to Langfuse (export is on).",
+ "where_otlp": "Saved on this machine. Also sent to your OpenTelemetry endpoint (export is on).",
+ "where_company": "Saved on this machine. Also sent to your company's Langfuse.",
+ "with_note": "With your note."
+ },
+ "doing": {
+ "title": "How it's been doing · last 30 days, on this machine",
+ "none": "No runs of this coworker in the last 30 days.",
+ "version": "Version",
+ "in_use": "In use",
+ "runs": "Runs",
+ "median_tokens": "Median tokens per run",
+ "with_issues": "Turns with issues",
+ "approvals": "Approvals per run",
+ "current": "current",
+ "unknown_version": "unknown version",
+ "before": "before {{date}}",
+ "automation_runs_one": "(incl. {{count}} automation)",
+ "automation_runs_other": "(incl. {{count}} automations)",
+ "too_few": "too few runs to compare",
+ "what_changed": "What changed in ⓕ{{fp}}",
+ "first_version": "the first version seen on this machine",
+ "instructions_edited": "instructions edited ({{lines}} lines)",
+ "instructions_added": "instructions added",
+ "instructions_removed": "instructions removed",
+ "file_added": "{{path}} added",
+ "file_removed": "{{path}} removed",
+ "file_edited": "{{path}} edited",
+ "skill_version": "skill {{skill}} {{from}} → {{to}}",
+ "skill_added": "skill {{skill}} added",
+ "skill_removed": "skill {{skill}} removed",
+ "skill_edited": "skill {{skill}} edited",
+ "no_file_change": "no file changed",
+ "model_unchanged": "model unchanged",
+ "model_changed": "model changed: {{from}} → {{to}}",
+ "models": "models: {{models}}",
+ "show_diff": "Show diff",
+ "hide_diff": "Hide diff",
+ "no_text_diff": "(no text difference)",
+ "note": "A run is the turns of one session under one version. Fewer than {{n}} runs: “too few runs” instead of a median."
+ },
+ "wake": {
+ "woke": "woke: {{reason}}",
+ "user": "You",
+ "answer": "Approval answered",
+ "assigned": "Assigned work",
+ "review": "Review",
+ "review_batch": "Review batch",
+ "blocker": "Blocker raised",
+ "prereq_done": "Prerequisite done",
+ "worker_waiting": "A worker is waiting",
+ "board": "Board change",
+ "mention": "Mentioned in chat",
+ "steer": "Steered by the lead",
+ "timer": "Timer (sleep_for)",
+ "wake_on": "Waited-for event",
+ "watchdog": "Watchdog (idle 10 min)",
+ "schedule": "Schedule",
+ "catch_up": "Catch-up run",
+ "manual": "Run now",
+ "channel": "Channel message",
+ "unknown": "Unknown"
+ },
+ "team": {
+ "by_wake": "Where it went · by wake reason",
+ "why": "Why it woke",
+ "wakes": "Wakes",
+ "cache_reads": "Cache reads",
+ "who": "Who",
+ "worker": "workers",
+ "total": "Team total",
+ "explained": "{{n}} of {{of}} turns have a known reason ({{pct}}%).",
+ "events": "Team events that used to be silent",
+ "issue": "issue",
+ "info": "info",
+ "events_note": "Each line opens the Steps of the turn involved."
+ },
+ "ev": {
+ "wake_capped": "Team paused at the wake cap (60 this hour) · this wake waited {{min}} min",
+ "wake_cap_reached": "The team hit its wake cap ({{count}} this hour); {{held}} deliveries held back",
+ "deferred": "A delivery to {{who}} was held back {{min}} min ({{by}})",
+ "by_busy": "the session was busy",
+ "by_stopped": "the session was stopped",
+ "by_batch": "the review window",
+ "by_cap": "the wake cap",
+ "watchdog_nudged": "The watchdog nudged the lead: items {{items}} idle 10 min",
+ "lead_polling": "Lead polling: woke on its timer {{count}} times with no board change",
+ "same_approval_twice": "Same approval asked twice: {{tool}} ({{first}}, then {{again}})",
+ "reviewed_before_prereq": "Item #{{item}} went to {{to}} before its prerequisite #{{pre}} was done"
+ },
+ "cov": {
+ "title": "Coverage for this task",
+ "ran": "{{scanner}} ran",
+ "failed": "{{scanner}} failed",
+ "exit": "exit {{code}}",
+ "exit_found": "exit {{code}} (found something)",
+ "no_exit": "no exit code",
+ "where": "{{actor}} turn {{turn}}, step {{step}}",
+ "open_step": "Open step",
+ "missing": "no {{area}} scan ran",
+ "promised": "Promised by the coworker's manifest: {{areas}}.",
+ "not_checked": "No recorded steps on this machine: coverage not checked."
+ },
+ "area": {
+ "code": "code",
+ "secrets": "secret",
+ "deps": "dependency",
+ "iac": "infrastructure"
+ },
+ "ev2": {
+ "title": "Evidence for finding #{{id}}",
+ "none": "No evidence step: this finding names no command behind it.",
+ "no_recorded_step": "No recorded step for its evidence.",
+ "found_by": "Found · turn {{turn}}, step {{step}}",
+ "fixed_by": "Fixed by {{who}}",
+ "verified_by": "Verified by {{who}}, not the fixer ✓",
+ "self_verified": "Verified by {{who}}, the worker that made the fix"
+ },
+ "runs": {
+ "failed_in_a_row_one": "Failed {{count}} run in a row.",
+ "failed_in_a_row_other": "Failed {{count}} runs in a row.",
+ "last_error": "Last error: {{error}}",
+ "unknown_error": "unknown",
+ "health": {
+ "ok": "ok",
+ "failed": "failed",
+ "skipped": "skipped",
+ "did_not_finish": "did not finish",
+ "unknown": "not recorded"
+ },
+ "run_said_ok": "(run said ok)",
+ "still_running": "(run still says running; its turn ended)",
+ "duration": "{{time}}",
+ "tokens": "{{tokens}} tokens",
+ "tokens_none": "— tokens",
+ "error": "error",
+ "not_recorded": "no recorded turn"
+ }
}
}
diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.json
index 1d0ab7b1..fd8533d6 100644
--- a/surfaces/gui/src/locales/zh.json
+++ b/surfaces/gui/src/locales/zh.json
@@ -3234,7 +3234,18 @@
"blocked_by_sandbox": "被沙盒拦截",
"sandbox_failed": "沙盒无法启动",
"ran_without_sandbox": "未在沙盒中运行",
- "waited_unwatched": "无人值守时等待"
+ "waited_unwatched": "无人值守时等待",
+ "wake_capped": "团队在唤醒上限处暂停",
+ "watchdog_nudged": "看门狗提醒了负责人",
+ "lead_polling": "负责人轮询",
+ "failed_in_a_row": "连续运行失败",
+ "scan_missing": "承诺的扫描没有运行",
+ "scanner_failed": "扫描器失败",
+ "no_findings_without_scan": "没扫描就说“没有发现”",
+ "finding_without_evidence": "发现没有证据步骤",
+ "self_verified": "修复由修复者本人验证",
+ "reviewed_before_prereq": "前置任务完成前就进入审查",
+ "same_approval_twice": "同一审批被问了两次"
},
"summary": "共 {{total}} 项检查:{{fired}} 项发现问题 · {{fine}} 项正常 · {{na}} 项不适用",
"na": "不适用 · {{n}}",
@@ -3837,5 +3848,240 @@
"locked": "已锁定",
"callout": "这台机器上的{{what}}会发送到 {{by}} 的 {{where}}。每个新会话都会显示一条简短提示。"
}
+ },
+ "p3": {
+ "usage": {
+ "tab_log": "日志",
+ "tab_usage": "用量",
+ "sub": "同事们用了多少令牌,按天、同事和机器分。等你回复的时间从不算作工作。",
+ "period_today": "今天",
+ "period_7d": "7 天",
+ "period_30d": "30 天",
+ "loading": "加载中…",
+ "load_error": "无法从这台机器读取用量。",
+ "tokens": "令牌",
+ "turns": "轮次",
+ "with_issues": "有问题的轮次",
+ "median_time": "轮次时长中位数",
+ "vs_last": "比上一周期 {{sign}} {{pct}}%",
+ "no_compare_today": "没有保留更早的一天可比较",
+ "no_compare_7d": "没有保留更早的一周可比较",
+ "no_compare_30d": "没有保留更早的 30 天可比较",
+ "no_compare_none": "上一周期没有内容",
+ "automation_runs_other": "{{count}} 个自动化轮次",
+ "with_issues_sub": "已检查 {{of}} 个中的 {{n}} 个",
+ "not_checked_other": "{{count}} 个尚未检查",
+ "median_sub": "不计等你的时间",
+ "per_day": "每天的令牌,按用途",
+ "by_coworker": "按同事",
+ "coworker": "同事",
+ "automation": "(自动化)",
+ "unknown_coworker": "未知同事",
+ "by_machine": "按机器",
+ "machine": "机器",
+ "this_machine": "这台机器",
+ "live": "在线",
+ "offline": "离线",
+ "offline_as_of": "离线 · 截至 {{time}}",
+ "heaviest": "最耗令牌的轮次",
+ "session": "会话",
+ "model": "模型",
+ "active_time": "不含等待的时长",
+ "issues": "问题",
+ "turn_n": "第 {{n}} 轮",
+ "deleted_session": "已删除的会话",
+ "found_open": "未知:崩溃后发现未结束",
+ "no_turns": "这一周期没有轮次。",
+ "no_turn": "不在会话中:{{calls}} 次调用 · {{tokens}} 令牌(通过这台机器为其他应用发起的模型调用,不计入上面的任何总数)。",
+ "deleted_note_other": "包含已删除会话的 {{count}} 个轮次。",
+ "kept_note": "用量页的令牌计数保留 90 天,不受“保留时长”设置影响。"
+ },
+ "series": {
+ "main": "主要工作和助手",
+ "summary": "摘要",
+ "auto_approver": "自动审批",
+ "title": "会话标题",
+ "other": "其他"
+ },
+ "ap": {
+ "title": "自动审批",
+ "checks_other": "{{count}} 次检查",
+ "kind": {
+ "session_model": "会话模型",
+ "openai_decisions": "决策模型",
+ "typesafe_jev": "决策模型"
+ },
+ "allowed_count": "允许 {{n}}",
+ "allowed_share": "允许 {{n}}%",
+ "asked_count": "询问你 {{n}}",
+ "asked_share": "询问你 {{n}}%",
+ "blocked_count": "阻止 {{n}}",
+ "blocked_share": "阻止 {{n}}%",
+ "could_not_run": "无法运行 {{n}}",
+ "overridden": "被你放行 {{n}}",
+ "median": "中位数 {{time}}",
+ "tokens": "{{tokens}} 令牌",
+ "incl_shadow_other": "含 {{count}} 次影子检查"
+ },
+ "foot": {
+ "tokens": "本轮 {{tokens}} 令牌",
+ "issues_other": "{{count}} 个问题",
+ "auto_approved_other": "{{count}} 个自动批准",
+ "asked_other": "询问你 {{count}} 次",
+ "recording_off": "这台机器已关闭记录"
+ },
+ "fb": {
+ "up": "回答不错",
+ "down": "有问题",
+ "what_wrong": "哪里出了问题?",
+ "optional": "(可选)",
+ "reason": {
+ "wrong_answer": "回答错误",
+ "too_slow": "太慢",
+ "did_unasked": "做了我没要求的事",
+ "did_not_finish": "没有完成",
+ "other": "其他"
+ },
+ "note_placeholder": "添加备注…",
+ "send": "发送",
+ "skip": "跳过",
+ "failed": "无法保存评价。",
+ "where_local": "已保存在这台机器上。",
+ "where_langfuse": "已保存在这台机器上。也已发送到 Langfuse(导出已开启)。",
+ "where_otlp": "已保存在这台机器上。也已发送到你的 OpenTelemetry 端点(导出已开启)。",
+ "where_company": "已保存在这台机器上。也已发送到你公司的 Langfuse。",
+ "with_note": "包括你的备注。"
+ },
+ "doing": {
+ "title": "表现如何 · 最近 30 天,在这台机器上",
+ "none": "最近 30 天这个同事没有运行。",
+ "version": "版本",
+ "in_use": "使用期间",
+ "runs": "运行次数",
+ "median_tokens": "每次运行令牌中位数",
+ "with_issues": "有问题的轮次",
+ "approvals": "每次运行的审批",
+ "current": "当前",
+ "unknown_version": "未知版本",
+ "before": "{{date}} 之前",
+ "automation_runs_other": "(含 {{count}} 个自动化)",
+ "too_few": "运行太少,无法比较",
+ "what_changed": "ⓕ{{fp}} 改了什么",
+ "first_version": "这台机器上看到的第一个版本",
+ "instructions_edited": "指令已修改({{lines}} 行)",
+ "instructions_added": "指令已添加",
+ "instructions_removed": "指令已删除",
+ "file_added": "{{path}} 已添加",
+ "file_removed": "{{path}} 已删除",
+ "file_edited": "{{path}} 已修改",
+ "skill_version": "技能 {{skill}} {{from}} → {{to}}",
+ "skill_added": "技能 {{skill}} 已添加",
+ "skill_removed": "技能 {{skill}} 已删除",
+ "skill_edited": "技能 {{skill}} 已修改",
+ "no_file_change": "没有文件改动",
+ "model_unchanged": "模型未变",
+ "model_changed": "模型已变:{{from}} → {{to}}",
+ "models": "模型:{{models}}",
+ "show_diff": "显示差异",
+ "hide_diff": "隐藏差异",
+ "no_text_diff": "(没有文本差异)",
+ "note": "一次运行指一个会话在同一版本下的所有轮次。少于 {{n}} 次运行时显示“运行太少”,不显示中位数。"
+ },
+ "wake": {
+ "woke": "唤醒原因:{{reason}}",
+ "user": "你",
+ "answer": "审批已回答",
+ "assigned": "分配的工作",
+ "review": "审查",
+ "review_batch": "批量审查",
+ "blocker": "出现阻碍",
+ "prereq_done": "前置任务完成",
+ "worker_waiting": "有成员在等待",
+ "board": "看板变化",
+ "mention": "在聊天中被提及",
+ "steer": "被负责人引导",
+ "timer": "定时器(sleep_for)",
+ "wake_on": "等待的事件",
+ "watchdog": "看门狗(空闲 10 分钟)",
+ "schedule": "计划",
+ "catch_up": "补运行",
+ "manual": "立即运行",
+ "channel": "频道消息",
+ "unknown": "未知"
+ },
+ "team": {
+ "by_wake": "令牌去向 · 按唤醒原因",
+ "why": "唤醒原因",
+ "wakes": "唤醒次数",
+ "cache_reads": "缓存读取",
+ "who": "谁",
+ "worker": "成员",
+ "total": "团队合计",
+ "explained": "{{of}} 个轮次中有 {{n}} 个原因已知({{pct}}%)。",
+ "events": "以前不显示的团队事件",
+ "issue": "问题",
+ "info": "信息",
+ "events_note": "每一行都会打开相关轮次的步骤。"
+ },
+ "ev": {
+ "wake_capped": "团队在唤醒上限处暂停(本小时 60 次)· 这次唤醒等了 {{min}} 分钟",
+ "wake_cap_reached": "团队达到了唤醒上限(本小时 {{count}} 次);{{held}} 次投递被推迟",
+ "deferred": "给 {{who}} 的投递被推迟了 {{min}} 分钟({{by}})",
+ "by_busy": "会话正忙",
+ "by_stopped": "会话已停止",
+ "by_batch": "审查等待窗口",
+ "by_cap": "唤醒上限",
+ "watchdog_nudged": "看门狗提醒了负责人:条目 {{items}} 空闲 10 分钟",
+ "lead_polling": "负责人轮询:按定时器醒来 {{count}} 次,看板没有变化",
+ "same_approval_twice": "同一审批被问了两次:{{tool}}({{first}},然后 {{again}})",
+ "reviewed_before_prereq": "条目 #{{item}} 在前置条目 #{{pre}} 完成前就进入了 {{to}}"
+ },
+ "cov": {
+ "title": "这个任务的覆盖情况",
+ "ran": "{{scanner}} 已运行",
+ "failed": "{{scanner}} 失败",
+ "exit": "退出码 {{code}}",
+ "exit_found": "退出码 {{code}}(发现了问题)",
+ "no_exit": "没有退出码",
+ "where": "{{actor}} 第 {{turn}} 轮,第 {{step}} 步",
+ "open_step": "打开步骤",
+ "missing": "没有运行{{area}}扫描",
+ "promised": "同事清单承诺的范围:{{areas}}。",
+ "not_checked": "这台机器上没有记录的步骤:未检查覆盖情况。"
+ },
+ "area": {
+ "code": "代码",
+ "secrets": "密钥",
+ "deps": "依赖",
+ "iac": "基础设施"
+ },
+ "ev2": {
+ "title": "发现 #{{id}} 的证据",
+ "none": "没有证据步骤:这个发现没有指明背后的命令。",
+ "no_recorded_step": "它的证据没有记录的步骤。",
+ "found_by": "发现于 · 第 {{turn}} 轮,第 {{step}} 步",
+ "fixed_by": "由 {{who}} 修复",
+ "verified_by": "由 {{who}} 验证,不是修复者 ✓",
+ "self_verified": "由 {{who}} 验证,也就是修复者本人"
+ },
+ "runs": {
+ "failed_in_a_row_other": "连续 {{count}} 次运行失败。",
+ "last_error": "最近的错误:{{error}}",
+ "unknown_error": "未知",
+ "health": {
+ "ok": "正常",
+ "failed": "失败",
+ "skipped": "已跳过",
+ "did_not_finish": "未完成",
+ "unknown": "未记录"
+ },
+ "run_said_ok": "(运行记录为正常)",
+ "still_running": "(运行仍显示进行中;它的轮次已结束)",
+ "duration": "{{time}}",
+ "tokens": "{{tokens}} 令牌",
+ "tokens_none": "— 令牌",
+ "error": "错误",
+ "not_recorded": "没有记录的轮次"
+ }
}
}
diff --git a/surfaces/gui/src/obs3.test.ts b/surfaces/gui/src/obs3.test.ts
new file mode 100644
index 00000000..7e02b18f
--- /dev/null
+++ b/surfaces/gui/src/obs3.test.ts
@@ -0,0 +1,126 @@
+// Phase 3 helpers: the viewer's day boundaries (DST included), the chart's series, the
+// share-vs-count rule, the footer's parts and how an answer finds its turn.
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ approverPart,
+ comparable,
+ footerParts,
+ healthTone,
+ localDays,
+ previousDays,
+ purposeByDay,
+ seriesOf,
+ turnForAnswer,
+ wakeKey,
+ whereKey,
+ type TurnFooter,
+} from "./obs3";
+
+// Node reads TZ again whenever it changes, so a test can view the days from London.
+const env = (globalThis as any).process.env as Record<string, string | undefined>;
+const TZ = env.TZ;
+afterEach(() => {
+ env.TZ = TZ;
+});
+
+describe("localDays", () => {
+ it("builds the viewer's local days from local midnights, 25 Oct 2026 being 25 hours in London", () => {
+ env.TZ = "Europe/London";
+ const days = localDays("30d", new Date(2026, 10, 4, 15, 0));
+ expect(days).toHaveLength(30);
+ expect(days[0][0]).toBe("2026-10-06");
+ expect(days[29][0]).toBe("2026-11-04");
+ const dst = days.find((d) => d[0] === "2026-10-25")!;
+ expect((dst[2] - dst[1]) / 3_600_000).toBe(25);
+ // contiguous: each day starts where the one before ended
+ for (let i = 1; i < days.length; i++) expect(days[i][1]).toBe(days[i - 1][2]);
+ // matches golden/phase3 vectors/days-europe-london.json for its first day
+ expect(days[0][1]).toBe(Date.UTC(2026, 9, 5, 23, 0));
+ });
+
+ it("today is one day; the previous period is the same length just before", () => {
+ env.TZ = "Asia/Kolkata";
+ const now = new Date(2026, 10, 4, 9, 30);
+ const today = localDays("today", now);
+ expect(today).toHaveLength(1);
+ expect(today[0][2] - today[0][1]).toBe(86_400_000);
+ const week = localDays("7d", now);
+ const prev = previousDays(week);
+ expect(prev).toHaveLength(7);
+ expect(prev[6][2]).toBe(week[0][1]);
+ });
+
+ it("compares with the last period only when the ledger reaches back over all of it (TD3-7)", () => {
+ expect(comparable(null, 1000)).toBe(false);
+ expect(comparable(1500, 1000)).toBe(false);
+ expect(comparable(1000, 1000)).toBe(true);
+ });
+});
+
+describe("tokens per day, by purpose", () => {
+ it("folds helpers into main work and adds a day's series up to its total", () => {
+ expect([seriesOf("main"), seriesOf("helper"), seriesOf("summary"), seriesOf("auto_approver"), seriesOf("title"), seriesOf("explore"), seriesOf(null)])
+ .toEqual(["main", "main", "summary", "auto_approver", "title", "other", "other"]);
+ const days: [string, number, number][] = [["d1", 0, 10], ["d2", 10, 20]];
+ const g = (day: string, purpose: string, total: number) => ({ key: { day, purpose }, total }) as any;
+ const out = purposeByDay(days, [g("d1", "main", 100), g("d1", "helper", 20), g("d1", "title", 3), g("d2", "auto_approver", 7), g("d9", "main", 999)]);
+ expect(out.rows[0].values).toMatchObject({ main: 120, title: 3 });
+ expect(out.rows[0].total).toBe(123);
+ expect(out.rows[1].total).toBe(7);
+ expect(out.legend).toEqual({ main: 120, summary: 0, auto_approver: 7, title: 3, other: 0 });
+ });
+});
+
+describe("the Auto-approve strip", () => {
+ it("shows counts under 10 checks and shares from 10 (M3-R5)", () => {
+ expect(approverPart(1, 1)).toEqual({ share: false, value: 1 });
+ expect(approverPart(9, 9)).toEqual({ share: false, value: 9 });
+ expect(approverPart(7, 10)).toEqual({ share: true, value: 70 });
+ });
+});
+
+const foot = (over: Partial<TurnFooter> = {}): TurnFooter => ({
+ turn_id: "t1", seq: 1, status: "completed", duration_ms: 14_000, total: 41_000, at_least: false, warn: 0,
+ auto_approved: 0, asked: 0, ...over,
+});
+
+describe("the turn footer", () => {
+ it("shows a part only when it is not 0 (M3-R7)", () => {
+ expect(footerParts(foot()).map((p) => p.kind)).toEqual(["time", "tokens"]);
+ expect(footerParts(foot({ warn: 1, auto_approved: 1 })).map((p) => p.kind)).toEqual(["time", "tokens", "issues", "auto_approved"]);
+ expect(footerParts(foot({ duration_ms: null, asked: 2 })).map((p) => p.kind)).toEqual(["tokens", "asked"]);
+ });
+
+ it("finds an answer's turn by its message, then its time, then its place", () => {
+ const fs = [foot({ turn_id: "a", last_message_id: "m1", started_at: 1000_000, duration_ms: 5000 }),
+ foot({ turn_id: "b", last_message_id: "m2", started_at: 1010_000, duration_ms: 5000 })];
+ expect(turnForAnswer(fs, undefined, 0, "m2")?.turn_id).toBe("b");
+ expect(turnForAnswer(fs, 1014, 0)?.turn_id).toBe("b");
+ expect(turnForAnswer(fs, 1004, 1)?.turn_id).toBe("a");
+ const noTimes = fs.map((f) => ({ ...f, started_at: undefined }));
+ expect(turnForAnswer(noTimes, 1004, 1)?.turn_id).toBe("b");
+ expect(turnForAnswer([], 1, 0)).toBeNull();
+ });
+
+ it("says where a rating went (§8.3)", () => {
+ expect(whereKey(null).key).toBe("p3.fb.where_local");
+ expect(whereKey({ local: true, export: null, managed: false, with_note: false }).key).toBe("p3.fb.where_local");
+ expect(whereKey({ local: true, export: "langfuse", managed: false, with_note: true })).toEqual({ key: "p3.fb.where_langfuse", withNote: true });
+ expect(whereKey({ local: true, export: "langfuse", managed: true, with_note: false }).key).toBe("p3.fb.where_company");
+ });
+});
+
+describe("wakes and health", () => {
+ it("names a gathered review wake a review batch", () => {
+ expect(wakeKey({ reason: "review", batched: 3 })).toBe("p3.wake.review_batch");
+ expect(wakeKey({ reason: "review", batched: null })).toBe("p3.wake.review");
+ expect(wakeKey({ reason: "timer" })).toBe("p3.wake.timer");
+ expect(wakeKey(null)).toBeNull();
+ });
+
+ it("colours a did-not-finish run as failed", () => {
+ expect(healthTone("did_not_finish")).toBe("err");
+ expect(healthTone("ok")).toBe("ok");
+ expect(healthTone("skipped")).toBe("muted");
+ });
+});
diff --git a/surfaces/gui/src/obs3.ts b/surfaces/gui/src/obs3.ts
new file mode 100644
index 00000000..46316c79
--- /dev/null
+++ b/surfaces/gui/src/obs3.ts
@@ -0,0 +1,231 @@
+// Observability Phase 3 ("learn across runs"): the pure helpers the Usage tab, the turn
+// footer, the coworker page, TeamView and the Scheduled view share. Kept out of the
+// components so the rules can be tested on their own (technical-design.md §7 to §12).
+// Tokens only: nothing here ever turns a count into money.
+
+/** One day as the viewer sees it: `[label, start, end)` in epoch ms (TD3-2). */
+export type DayBoundary = [string, number, number];
+export type Period = "today" | "7d" | "30d";
+
+const pad = (n: number) => String(n).padStart(2, "0");
+const isoLocal = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
+
+/** The viewer's local days of a period, oldest first, built from local midnights, so a DST
+ * day is simply 23 or 25 hours long. "Today" is one day; 7 and 30 days end today. */
+export function localDays(period: Period, now: Date = new Date()): DayBoundary[] {
+ const n = period === "today" ? 1 : period === "7d" ? 7 : 30;
+ const out: DayBoundary[] = [];
+ for (let i = n - 1; i >= 0; i--) {
+ const a = new Date(now.getFullYear(), now.getMonth(), now.getDate() - i);
+ const b = new Date(now.getFullYear(), now.getMonth(), now.getDate() - i + 1);
+ out.push([isoLocal(a), a.getTime(), b.getTime()]);
+ }
+ return out;
+}
+
+/** The same number of local days just before `days` (for "vs last period"). */
+export function previousDays(days: DayBoundary[]): DayBoundary[] {
+ if (!days.length) return [];
+ const first = new Date(days[0][1]);
+ const n = days.length;
+ const out: DayBoundary[] = [];
+ for (let i = n; i >= 1; i--) {
+ const a = new Date(first.getFullYear(), first.getMonth(), first.getDate() - i);
+ const b = new Date(first.getFullYear(), first.getMonth(), first.getDate() - i + 1);
+ out.push([isoLocal(a), a.getTime(), b.getTime()]);
+ }
+ return out;
+}
+
+/** "vs last period" only when the ledger reaches back over the whole earlier period (TD3-7,
+ * V3-11): never a "▲ 100%" from a period that was not kept. */
+export function comparable(keptFrom: number | null | undefined, prevStart: number): boolean {
+ return keptFrom != null && keptFrom <= prevStart;
+}
+
+export function changePct(now: number, before: number): number | null {
+ if (!before) return null;
+ return Math.round(((now - before) / before) * 100);
+}
+
+// -- tokens per day, by purpose (§7.2, M3-R4) --------------------------------------------------
+export const SERIES = ["main", "summary", "auto_approver", "title", "other"] as const;
+export type Series = (typeof SERIES)[number];
+
+/** The chart's five series: main work and helpers together, summaries, the auto-approver,
+ * session titles, and everything else, so a day's series add up to that day's total. */
+export function seriesOf(purpose: string | null | undefined): Series {
+ switch (purpose) {
+ case "main":
+ case "helper":
+ return "main";
+ case "summary":
+ return "summary";
+ case "auto_approver":
+ return "auto_approver";
+ case "title":
+ return "title";
+ default:
+ return "other";
+ }
+}
+
+export interface RollupGroup {
+ key: Record<string, any>;
+ total: number;
+ input_fresh: number;
+ cache_read: number;
+ cache_write: number;
+ output: number;
+ calls: number;
+ unreported: number;
+ failed: number;
+ over_limit?: number;
+ turns: number;
+ checked: number;
+ with_warn: number;
+ automation_turns?: number;
+ approvals?: number;
+ median_active_ms?: number | null;
+}
+
+/** `day,purpose` groups -> per day, per series, plus each series' total for the legend. */
+export function purposeByDay(days: DayBoundary[], groups: RollupGroup[]) {
+ const byDay = new Map<string, Record<Series, number>>();
+ for (const [label] of days) byDay.set(label, { main: 0, summary: 0, auto_approver: 0, title: 0, other: 0 });
+ const legend: Record<Series, number> = { main: 0, summary: 0, auto_approver: 0, title: 0, other: 0 };
+ for (const g of groups) {
+ const row = byDay.get(String(g.key.day));
+ if (!row) continue;
+ const s = seriesOf(g.key.purpose);
+ row[s] += g.total;
+ legend[s] += g.total;
+ }
+ const rows = days.map(([label]) => ({ label, values: byDay.get(label)!, total: SERIES.reduce((n, s) => n + byDay.get(label)![s], 0) }));
+ return { rows, legend, max: Math.max(1, ...rows.map((r) => r.total)) };
+}
+
+// -- the Auto-approve strip (§7.3, M3-R5) -----------------------------------------------------
+/** Under 10 checks a part is a count ("allowed 1"), from 10 a share ("allowed 72%"): "allowed
+ * 100%" of one check says nothing. */
+export function approverPart(n: number, checks: number): { share: boolean; value: number } {
+ if (checks >= 10) return { share: true, value: Math.round((n / checks) * 100) };
+ return { share: false, value: n };
+}
+
+// -- the turn footer (§8.2, M3-R6, M3-R7) -------------------------------------------------------
+export interface TurnFooter {
+ turn_id: string;
+ seq: number | null;
+ status: string;
+ first_message_id?: string | null;
+ last_message_id?: string | null;
+ started_at?: number;
+ duration_ms: number | null;
+ active_ms?: number | null;
+ total: number;
+ at_least: boolean;
+ warn: number | null;
+ auto_approved: number;
+ asked: number;
+ live_checks?: number;
+ wake?: { reason?: string; batched?: number | null } | null;
+ feedback?: TurnFeedback | null;
+}
+
+export interface TurnFeedback {
+ turn_id: string;
+ session_id: string;
+ rating: "up" | "down";
+ reasons: string[];
+ rated_at: number;
+ changed_at: number | null;
+ content?: { note: string | null };
+}
+
+export interface FeedbackWhere {
+ local: boolean;
+ export: string | null;
+ managed: boolean;
+ by?: string | null;
+ with_note: boolean;
+}
+
+export type FooterPart =
+ | { kind: "time"; ms: number }
+ | { kind: "tokens"; total: number; at_least: boolean }
+ | { kind: "issues"; n: number }
+ | { kind: "auto_approved"; n: number }
+ | { kind: "asked"; n: number };
+
+/** The footer's parts, each only when it says something: no "0 issues", no "0 asked you". */
+export function footerParts(f: TurnFooter): FooterPart[] {
+ const out: FooterPart[] = [];
+ if (f.duration_ms != null) out.push({ kind: "time", ms: f.duration_ms });
+ out.push({ kind: "tokens", total: f.total, at_least: f.at_least });
+ if (f.warn) out.push({ kind: "issues", n: f.warn });
+ if (f.auto_approved) out.push({ kind: "auto_approved", n: f.auto_approved });
+ if (f.asked) out.push({ kind: "asked", n: f.asked });
+ return out;
+}
+
+/** The turn an answer belongs to: the turn whose last message is the answer (`mid`); else by
+ * the answer's time (unix seconds), the first turn not yet over a second before it, as the
+ * Steps link picks it; else the answer's position among the answers. */
+export function turnForAnswer(footers: TurnFooter[], ts: number | undefined, answerIndex: number, mid?: string): TurnFooter | null {
+ if (!footers.length) return null;
+ if (mid) {
+ const byMid = footers.find((f) => f.last_message_id === mid);
+ if (byMid) return byMid;
+ }
+ if (ts != null && footers.every((f) => f.started_at != null)) {
+ const at = ts * 1000 - 1000;
+ const f = footers.find((x) => x.duration_ms == null || (x.started_at as number) + x.duration_ms >= at);
+ return f ?? footers[footers.length - 1];
+ }
+ return footers[Math.min(answerIndex, footers.length - 1)] ?? null;
+}
+
+export const REASONS = ["wrong_answer", "too_slow", "did_unasked", "did_not_finish", "other"] as const;
+
+/** The rating card's last line: where the rating went (§8.3). */
+export function whereKey(w: FeedbackWhere | null | undefined): { key: string; withNote: boolean } {
+ if (!w || !w.export) return { key: "p3.fb.where_local", withNote: false };
+ if (w.managed) return { key: "p3.fb.where_company", withNote: !!w.with_note };
+ return { key: w.export === "langfuse" ? "p3.fb.where_langfuse" : "p3.fb.where_otlp", withNote: !!w.with_note };
+}
+
+// -- wake reasons (OB-17) ----------------------------------------------------------------------
+/** The i18n key of a wake reason; a review wake that the 2 s window gathered is a "review batch". */
+export function wakeKey(wake: { reason?: string; batched?: number | null } | null | undefined): string | null {
+ const r = wake?.reason;
+ if (!r) return null;
+ if (r === "review" && wake?.batched) return "p3.wake.review_batch";
+ return `p3.wake.${r}`;
+}
+
+export function cacheShare(cacheRead: number, input: number): number | null {
+ return input > 0 ? Math.round((cacheRead / input) * 100) : null;
+}
+
+// -- coverage (OB-16) -----------------------------------------------------------------------------
+export const AREA_WORD: Record<string, string> = { code: "code", secrets: "secret", deps: "dependency", iac: "infrastructure" };
+
+// -- run health (OB-18) -----------------------------------------------------------------------------
+export type Health = "ok" | "failed" | "skipped" | "did_not_finish" | "unknown";
+export function healthTone(h: string | undefined): "ok" | "err" | "muted" {
+ if (h === "ok") return "ok";
+ if (h === "failed" || h === "did_not_finish") return "err";
+ return "muted";
+}
+
+/** Compact time-of-day for "as of 14:02". */
+export function hhmm(ms: number): string {
+ const d = new Date(ms);
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
+}
+
+/** "21 Oct" */
+export function shortDate(ms: number): string {
+ return new Date(ms).toLocaleDateString(undefined, { day: "2-digit", month: "short" });
+}
diff --git a/surfaces/gui/src/styles.css b/surfaces/gui/src/styles.css
index 645d9281..5e589a4a 100644
--- a/surfaces/gui/src/styles.css
+++ b/surfaces/gui/src/styles.css
@@ -2601,3 +2601,67 @@ html[data-theme="dark"] { --bar-model:#4c8dff; --bar-tool:#3fb8ad; --bar-wait:#3
.steps-fine-toggle{align-self:flex-start;background:none;border:0;padding:4px 0;color:var(--faint);font-size:12px;font-weight:600;cursor:pointer}
.steps-fine{font-size:12px;line-height:1.85;color:var(--muted)}
+
+/* -- Observability Phase 3 (UX-059 ob5, ob8, ob15 to ob18): Usage, footer, coworker history,
+ team wakes and events, coverage, run health. Colours are the app's tokens, so both themes
+ follow. ------------------------------------------------------------------------------------ */
+.p3-tabs { display:inline-flex; gap:2px; padding:2px; border:1px solid var(--line); border-radius:8px; background:var(--panel); }
+.p3-tabs button, .p3-seg button { padding:4px 12px; border-radius:6px; font-size:var(--fs-ui); color:var(--muted); background:none; border:0; cursor:pointer; }
+.p3-tabs button[aria-selected="true"], .p3-seg button[aria-pressed="true"] { background:var(--paper); color:var(--ink); box-shadow:0 0 0 1px var(--line); }
+.p3-seg { display:inline-flex; gap:2px; padding:2px; border:1px solid var(--line); border-radius:8px; background:var(--panel); }
+.p3-tiles { display:grid; grid-template-columns:repeat(4, minmax(0,1fr)); gap:10px; margin-bottom:12px; }
+@media (max-width: 760px) { .p3-tiles { grid-template-columns:repeat(2, minmax(0,1fr)); } .p3-two { grid-template-columns:1fr; } }
+.p3-kpi { border:1px solid var(--line); border-radius:12px; background:var(--panel); padding:10px 12px; display:flex; flex-direction:column; gap:2px; min-width:0; }
+.p3-kpi span { font-size:var(--fs-meta); color:var(--muted); }
+.p3-kpi b { font-size:22px; font-weight:600; color:var(--ink); font-variant-numeric:tabular-nums; }
+.p3-kpi em { font-style:normal; font-size:var(--fs-label); color:var(--faint); }
+.p3-two { display:grid; grid-template-columns:3fr 2fr; gap:12px; }
+.p3-card { padding:12px 14px; min-width:0; }
+.p3-h { font-weight:500; font-size:var(--fs-ui); color:var(--ink); }
+.p3-bars { display:flex; align-items:flex-end; gap:3px; height:120px; margin-top:10px; border-bottom:1px solid var(--line); }
+.p3-bar { flex:1; height:100%; display:flex; flex-direction:column-reverse; min-width:2px; }
+.p3-bar i { display:block; width:100%; }
+.p3-bar i:last-child { border-radius:3px 3px 0 0; }
+.p3-xl { display:flex; gap:3px; margin-top:3px; }
+.p3-xl span { flex:1; text-align:center; font-size:10px; color:var(--faint); white-space:nowrap; overflow:hidden; }
+.p3-legend { display:flex; flex-wrap:wrap; gap:4px 14px; margin-top:8px; font-size:var(--fs-meta); color:var(--muted); }
+.p3-legend i { display:inline-block; width:8px; height:8px; border-radius:2px; margin-right:5px; vertical-align:middle; }
+.p3-s-main { background:var(--accent); }
+.p3-s-summary { background:var(--bar-sum); }
+.p3-s-auto_approver { background:var(--bar-review); }
+.p3-s-title { background:var(--bar-tool); }
+.p3-s-other { background:var(--bar-ctx); }
+.p3-t { width:100%; border-collapse:collapse; font-size:var(--fs-meta); margin-top:6px; }
+.p3-t th { text-align:left; font-weight:400; color:var(--faint); padding:4px 6px; border-bottom:1px solid var(--line); }
+.p3-t td { padding:5px 6px; border-bottom:1px solid var(--line); color:var(--ink); vertical-align:top; }
+.p3-t tr:last-child td { border-bottom:0; }
+.p3-t .n { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
+.p3-trunc { max-width:260px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
+.p3-link { color:var(--accent); background:none; border:0; padding:0; cursor:pointer; font-size:inherit; }
+.p3-link:hover { text-decoration:underline; }
+.p3-chip { display:inline-block; font-size:var(--fs-label); line-height:1.5; border-radius:5px; padding:0 6px; background:var(--paper); color:var(--muted); }
+.p3-chip.ok { background:var(--ok-soft); color:var(--ok); }
+.p3-chip.warn { background:var(--warn-soft); color:var(--warn-ink); }
+.p3-chip.err { background:var(--danger-soft); color:var(--danger); }
+.p3-callout { border-radius:9px; padding:8px 12px; font-size:var(--fs-meta); margin:8px 0; }
+.p3-callout.err { background:var(--danger-soft); color:var(--danger); }
+.p3-event { display:flex; align-items:center; gap:8px; width:100%; background:none; border:0; padding:3px 0; font-size:var(--fs-meta); color:var(--ink); cursor:pointer; }
+.p3-event:disabled { cursor:default; }
+.p3-event:not(:disabled):hover span:nth-child(2) { text-decoration:underline; }
+.p3-diff { font-family:var(--mono); font-size:var(--fs-label); white-space:pre-wrap; background:var(--paper); border:1px solid var(--line); border-radius:6px; padding:6px 8px; max-height:260px; overflow:auto; color:var(--muted); }
+/* the turn footer: always under the last answer, on hover for older ones (Q9) */
+.turnfoot-wrap { margin-top:2px; }
+.turnfoot-wrap:not(.last) .turnfoot { opacity:0; transition:opacity .15s; }
+.group:hover .turnfoot-wrap .turnfoot, .turnfoot-wrap:focus-within .turnfoot { opacity:1; }
+.turnfoot { display:flex; align-items:center; flex-wrap:wrap; gap:4px; font-size:var(--fs-label); color:var(--faint); }
+.turnfoot .sep { margin:0 2px; color:var(--faint); }
+.turnfoot .c-review { color:var(--bar-review); }
+.turnfoot .thumb { background:none; border:0; padding:0 2px; cursor:pointer; filter:grayscale(1); opacity:.6; font-size:12px; }
+.turnfoot .thumb.sel, .turnfoot .thumb:hover { filter:none; opacity:1; }
+.p3-ratecard { margin-top:8px; max-width:520px; border:1px solid var(--line); border-radius:12px; background:var(--panel); padding:12px 14px; font-size:var(--fs-meta); color:var(--ink); }
+.p3-pill { border:1px solid var(--line); border-radius:999px; padding:2px 10px; background:var(--paper); color:var(--muted); cursor:pointer; font-size:var(--fs-meta); }
+.p3-pill.on { border-color:var(--accent); color:var(--accent); background:var(--accent-soft); }
+.p3-note { width:100%; border:1px solid var(--line); border-radius:8px; background:var(--paper); color:var(--ink); padding:6px 8px; font-family:var(--sans); font-size:var(--fs-meta); outline:none; resize:vertical; }
+.p3-note:focus { border-color:var(--accent); }
+.sched-run-health { display:flex; align-items:center; flex-wrap:wrap; gap:6px 10px; padding:0 2px 8px; font-size:var(--fs-meta); }
+.steps-turn-wake { margin-left:6px; font-size:var(--fs-meta); }
diff --git a/surfaces/gui/src/teamView.ts b/surfaces/gui/src/teamView.ts
index e64c5c96..5e1a6167 100644
--- a/surfaces/gui/src/teamView.ts
+++ b/surfaces/gui/src/teamView.ts
@@ -30,6 +30,8 @@ export interface TeamTask extends BoardItem {
timing?: Timing | null;
timing_partial?: boolean;
usage_partial?: boolean;
+ coverage?: TaskCoverage | null;
+ findings?: TaskFinding[];
}
export interface TeamWorker {
usage_partial?: boolean;
@@ -68,6 +70,77 @@ export interface TeamSummary {
median_answer_s?: number | null;
usage_points: { ts: number; role: string; tokens: number }[];
generated_at: number;
+ // OB-17 (Phase 3): why each team turn started, from the member sessions' recordings (their
+ // total equals their pills), and the team events that used to be silent. Absent on older engines.
+ wakes?: TeamWake[];
+ events?: TeamEvent[];
+ wake_explained?: { turns: number; explained: number };
+}
+
+export interface TeamWake {
+ reason: string;
+ wakes: number;
+ total: number;
+ cache_read: number;
+ input: number;
+ at_least?: boolean;
+ by_role: Record<string, { wakes: number; total: number }>;
+}
+
+export interface TeamEvent {
+ kind: "wake_capped" | "deferred" | "watchdog_nudged" | "lead_polling" | "same_approval_twice"
+ | "reviewed_before_prereq" | "wake_cap_reached" | string;
+ severity: "warn" | "info";
+ at: number | null;
+ who?: string;
+ session_id?: string;
+ turn_id?: string | null;
+ seq?: number | null;
+ deferred_ms?: number | null;
+ by?: string;
+ count?: number;
+ item_ids?: string[];
+ tool?: string;
+ first_by?: string;
+ again_by?: string;
+ item?: number;
+ prerequisite?: number;
+ to?: string;
+ hour?: string;
+ held?: string[];
+ board_seq?: number;
+}
+
+// OB-16 (Phase 3): a security task's coverage and its findings' evidence, when the engine
+// gives them on the summary's items. Absent: nothing is shown.
+export interface CoverageScan {
+ scanner: string;
+ area: string;
+ exit_code: number | null;
+ ok: boolean;
+ found_something?: boolean;
+ session_id?: string;
+ turn_id?: string;
+ turn_seq?: number | null;
+ step_seq?: number | null;
+ step_id?: string;
+ actor?: string;
+}
+export interface TaskCoverage {
+ promised: string[];
+ scans: CoverageScan[];
+ issues: { check: string; text: string; facts?: Record<string, any> }[];
+ fine?: { check: string; text: string }[];
+ not_checked?: boolean;
+}
+export interface TaskFinding {
+ id: number | string;
+ severity?: string;
+ title?: string;
+ evidence?: { session_id: string; call_id: string }[];
+ step_call_id?: string | null;
+ fixed_by?: string | null;
+ verified_by?: string | null;
}
export const tokenTotal = (u: TokenKinds) =>
u.input + u.output + u.cache_read + u.cache_write;
diff --git a/surfaces/gui/src/types.ts b/surfaces/gui/src/types.ts
index de6c52ca..c24bebbc 100644
--- a/surfaces/gui/src/types.ts
+++ b/surfaces/gui/src/types.ts
@@ -168,7 +168,8 @@ export type Item =
// registry — no per-connector special-casing.
| { kind: "connector"; source: MessageSource }
| { kind: "teamcreated"; teamId: string; workers: { actor: string; persona: string }[]; ts?: number }
- | { kind: "assistant"; text: string; ts?: number; reasoning?: string }
+ // `mid`: the message id (observability links a turn footer to its answer by it, OB-5).
+ | { kind: "assistant"; text: string; ts?: number; reasoning?: string; mid?: string }
// `hidden` = results the user's privacy filters removed before the agent saw them
// (from the tool message's `_display` sidecar; the agent-visible content has no trace).
// `standingRule` = the task-scoped rule that auto-allowed this call ("tool → target").
diff --git a/tests/test_observability_phase3_engine.py b/tests/test_observability_phase3_engine.py
index a0909bd8..103d74b8 100644
--- a/tests/test_observability_phase3_engine.py
+++ b/tests/test_observability_phase3_engine.py
@@ -339,3 +339,35 @@ def test_turns_recorded_before_the_ledger_are_filled_in(tmp_path):
[row] = store.usage_turns(0, 2**62)
assert row["total"] == 11 and store.turns_without_usage() == []
manager.observability.close()
+
+
+def test_a_wake_that_was_not_delivered_is_given_back_to_the_cap(tmp_path):
+ from coworker.teams.registry import TeamRegistry, TeamWorker
+
+ reg = TeamRegistry(tmp_path / "teams.json")
+ team = reg.create(space="sp", lead_session="lead-s", lead_actor="lead-1",
+ workers=[TeamWorker(actor="w", persona="appsec-worker", session_id="w-s")])
+ assert all(reg.count_wake(team.team_id, cap=2) for _ in range(2))
+ assert reg.count_wake(team.team_id, cap=2) is False
+ reg.refund_wake(team.team_id) # TD3-22: counted only once delivered
+ assert reg.count_wake(team.team_id, cap=2) is True
+
+
+def test_the_wake_cap_event_wakes_nobody_and_deferrals_are_recorded(tmp_path):
+ from coworker.teams.registry import TeamWorker
+
+ manager = SessionManager(workspace=tmp_path, provider=_Scripted([]))
+ team = manager.teams.create(space=str(tmp_path), lead_session="lead-s", lead_actor="lead-1",
+ workers=[TeamWorker(actor="w", persona="appsec-worker", session_id="w-s")])
+ manager._note_held("lead-s", "cap")
+ manager._note_wake_cap(team)
+ manager._note_wake_cap(team) # once per hour
+ caps = [e for e in manager.team_store.events(team.space) if e["kind"] == "wake_cap_reached"]
+ assert len(caps) == 1 and caps[0]["payload"]["held"] == ["lead-s"]
+ assert manager._actionable_team_events(team, caps, actor="lead-1", is_lead=True) == []
+ wake = manager._turn_wake("lead-s", source={"connector": "board"}, trigger="team_wake",
+ rows=[{"kind": "moved", "to": "review", "item": 3}])
+ assert wake["reason"] == "review" and wake["deferred"]["by"] == "cap" and wake["deferred"]["ms"] >= 0
+ assert wake["board_seq"] == caps[0]["seq"]
+ assert manager._team_stamp("w-s") == {"team_id": team.team_id, "role": "worker"}
+ manager.observability.close()