Python
feat(gui): show the changes auto-approve made without asking, at the end of a turn (OPE-238)
Devika Vermac3c813349b12
diff --git a/coworker/audit.py b/coworker/audit.pyindex 1b23a2b7..3c9770c5 100644--- a/coworker/audit.py+++ b/coworker/audit.py@@ -210,9 +210,15 @@ class AuditStore:session_id: Optional[str] = None,connector: Optional[str] = None,tool: Optional[str] = None,+ call_id: Optional[str] = None,) -> list[dict[str, Any]]:where = []params: list[Any] = []+ if call_id:+ # One tool call's rows (proposed, verdict, started, finished…): OPE-238 links+ # each "changed without asking" item here.+ where.append("call_id = ?")+ params.append(call_id)if session_id:where.append("session_id = ?")params.append(session_id)diff --git a/coworker/engine.py b/coworker/engine.pyindex 2597a592..de73b859 100644--- a/coworker/engine.py+++ b/coworker/engine.py@@ -16,6 +16,7 @@ import loggingfrom copy import deepcopyimport asyncio+import functoolsimport jsonimport timefrom dataclasses import dataclass, replace@@ -122,6 +123,57 @@ async def _deny_all(_request: PermissionRequest) -> ApprovalOutcome:return ApprovalOutcome.DENY+# OPE-238: the approval origins that mean "ran without asking": auto-approve let the+# action through with no card. A card the user answered, a standing rule or trust the+# user set up, and the bypass modes are the user's own choice and are not listed.+_UNASKED_ORIGINS = frozenset({"gate_tier", "reviewer"})+# Every turn ends with exactly one of these; the summary goes just before it, so the+# event that ends a turn stays the last one (the headless runner reads it that way).+_TURN_ENDINGS = frozenset({EventType.TURN_END, EventType.INTERRUPTED, EventType.ERROR})+++def _summarizes_turn(gen_fn: Callable[..., AsyncIterator[Event]]) -> Callable[..., AsyncIterator[Event]]:+ """Wrap a turn generator (run / retry / resume) so that, when any action ran without+ asking, one TURN_SUMMARY event lists them just before the turn ends.++ An index, not a copy: tool call id, tool name, origin, status and the reviewer's+ one-line reason. The arguments and results are already in the tool events and the+ audit log, which can be filtered by the same call id."""++ @functools.wraps(gen_fn)+ async def wrapper(self: "TurnEngine", *args: Any, **kwargs: Any) -> AsyncIterator[Event]:+ inner = gen_fn(self, *args, **kwargs)+ unasked: list[dict[str, Any]] = []+ try:+ async for event in inner:+ if event.type is EventType.TOOL_FINISHED:+ origin = event.data.get("approval_origin")+ if origin in _UNASKED_ORIGINS:+ unasked.append(+ {+ "tool_call_id": str(event.data.get("tool_call_id") or ""),+ "name": str(event.data.get("name") or ""),+ "origin": origin,+ "status": str(event.data.get("status") or ""),+ **(+ {"note": str(event.data["approval_note"])}+ if event.data.get("approval_note")+ else {}+ ),+ }+ )+ elif event.type in _TURN_ENDINGS and unasked:+ yield Event(EventType.TURN_SUMMARY, {"count": len(unasked), "actions": unasked})+ unasked = []+ yield event+ finally:+ # A surface that stops reading mid-turn closes this wrapper; close the turn+ # itself too, at once, so its own cleanup (run grants) runs as before.+ await inner.aclose()++ return wrapper++class TurnEngine:def __init__(self,@@ -398,6 +450,7 @@ class TurnEngine:self._steering.append((text, source, activity))# -- main loop --------------------------------------------------------------+ @_summarizes_turnasync def run(self,user_input: "str | list",@@ -532,6 +585,7 @@ class TurnEngine:notice.update({k: v for k, v in fields.items() if v is not None})self.messages.append(notice)+ @_summarizes_turnasync def retry(self) -> AsyncIterator[Event]:"""Re-run the model loop after a provider error — no new user message; the failedturn's input is already the tail of history. Guarded on the tail being an error@@ -570,6 +624,7 @@ class TurnEngine:info = workspace.describe()yield Event(EventType.SANDBOX_READY, {k: info.get(k) for k in ("provider", "enforcement", "reason", "sandbox") if info.get(k) is not None})+ @_summarizes_turnasync def resume(self) -> AsyncIterator[Event]:"""Continue a turn that was suspended at a prompt and persisted — durable resume after arestart (or engine eviction). Re-process the trailing assistant message's UNANSWEREDdiff --git a/coworker/events.py b/coworker/events.pyindex eff4f5d7..a929d011 100644--- a/coworker/events.py+++ b/coworker/events.py@@ -37,6 +37,9 @@ class EventType(str, Enum):TOOL_STARTED = "tool_started"TOOL_FINISHED = "tool_finished"ITERATION_END = "iteration_end"+ # OPE-238: the actions auto-approve let run with no card this turn (a gate tier or a+ # reviewer "allow"), emitted just before the event that ends the turn.+ TURN_SUMMARY = "turn_summary"TURN_END = "turn_end"ERROR = "error"INTERRUPTED = "interrupted"diff --git a/coworker/server/app.py b/coworker/server/app.pyindex 86b37651..2601c576 100644--- a/coworker/server/app.py+++ b/coworker/server/app.py@@ -2336,10 +2336,11 @@ def create_app(manager: SessionManager) -> FastAPI:session_id: str | None = None,connector: str | None = None,tool: str | None = None,+ call_id: str | None = None,) -> dict[str, Any]:return {"events": manager.list_audit(- limit=limit, session_id=session_id, connector=connector, tool=tool+ limit=limit, session_id=session_id, connector=connector, tool=tool, call_id=call_id)}diff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex 53d8c1be..9db225df 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -2548,9 +2548,10 @@ class SessionManager:session_id: Optional[str] = None,connector: Optional[str] = None,tool: Optional[str] = None,+ call_id: Optional[str] = None,) -> list[dict[str, Any]]:return self.audit_store.list(- limit=limit, session_id=session_id, connector=connector, tool=tool+ limit=limit, session_id=session_id, connector=connector, tool=tool, call_id=call_id)def browser_state(self) -> dict[str, Any]:diff --git a/docs/headless.md b/docs/headless.mdindex 397c9062..3b0e93ab 100644--- a/docs/headless.md+++ b/docs/headless.md@@ -172,6 +172,11 @@ record states it.| `provider_errors.log` | full cause chains of failed model calls, credentials redacted || `audit.db` | OpenWorker's audit log for the session |+A turn in which auto-approve let actions run with no approval card (a safe-change tier or a+reviewer "allow") ends with a `turn_summary` event in `events.jsonl`, just before the event+that ends the turn. It lists each action's tool call id, tool, origin and status; the audit+log can be filtered by the same call id (`/v1/audit?call_id=…`).+The trajectory and the exit code are the stable contract.A transient provider failure or an empty reply does not end the run: the runner waitsdiff --git a/surfaces/gui/src/App.tsx b/surfaces/gui/src/App.tsxindex 2fe6980f..34515aba 100644--- a/surfaces/gui/src/App.tsx+++ b/surfaces/gui/src/App.tsx@@ -370,6 +370,8 @@ export function App() {// composer's "No model connected" chip. Default true so we don't flash the chip before settings// load; corrected by loadSettings.const [modelReady, setModelReady] = useState(true);+ // OPE-238: Activity opened on one tool call's audit rows (unset = all activity).+ const [auditCallId, setAuditCallId] = useState<string | undefined>(undefined);const [surface, setSurface] = useState<"session" | "scheduled" | "audit" | "inbox" | "persona" | "settings">("session");@@ -1062,6 +1064,7 @@ export function App() {d.allow_anyway,d.approval_origin,d.approval_note,+ d.tool_call_id,),);// §8.4 breaker: the reviewer paused itself for the rest of the turn — say so@@ -2070,7 +2073,10 @@ export function App() {setSurface("scheduled");}}onOpenIntegrations={() => openSettings("connectors")}- onOpenAudit={() => setSurface("audit")}+ onOpenAudit={() => {+ setAuditCallId(undefined);+ setSurface("audit");+ }}onOpenInbox={() => setSurface("inbox")}scheduledActive={surface === "scheduled"}integrationsActive={surface === "settings" && settingsTab === "connectors"}@@ -2120,7 +2126,7 @@ export function App() {}}/>) : surface === "audit" ? (- <AuditView />+ <AuditView callId={auditCallId} />) : surface === "inbox" ? (<InboxView onOpenSession={openSessionFromInbox} />) : surface === "persona" ? (@@ -2315,6 +2321,11 @@ export function App() {onRetry={retry}onOpenConnectors={() => openSettings("connectors")}onAllowAnyway={allowAnyway}+ onOpenAudit={(callId) => {+ // OPE-238: an item of "changes made without asking" → its audit rows.+ setAuditCallId(callId);+ setSurface("audit");+ }}onUndoMemory={(id, previous) => void undoMemorySave(id, previous)}// §33 ref #3: sub-threshold streamed text renders INSIDE the live turn// group (header when collapsed, quiet line when expanded) — never as a@@ -2722,6 +2733,7 @@ function updateLastTool(allowAnyway?: boolean,approvalOrigin?: string,approvalNote?: string,+ callId?: string,): Item[] {const copy = [...items];for (let i = copy.length - 1; i >= 0; i--) {@@ -2737,6 +2749,7 @@ function updateLastTool(...(allowAnyway ? { allowAnyway } : {}),...(approvalOrigin ? { approvalOrigin } : {}),...(approvalNote ? { approvalNote } : {}),+ ...(callId ? { callId } : {}),};break;}diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.tsindex 45d4a481..c9c74913 100644--- a/surfaces/gui/src/api.ts+++ b/surfaces/gui/src/api.ts@@ -1109,6 +1109,7 @@ export interface AuditEvent {result_preview: string;reason: string;resource: string;+ call_id?: string;}export async function getAudit(params: {@@ -1116,8 +1117,11 @@ export async function getAudit(params: {session_id?: string;connector?: string;tool?: string;+ // OPE-238: one tool call's rows (the "changes made without asking" summary links here).+ call_id?: string;} = {}): Promise<AuditEvent[]> {const q = new URLSearchParams();+ if (params.call_id) q.set("call_id", params.call_id);if (params.limit) q.set("limit", String(params.limit));if (params.session_id) q.set("session_id", params.session_id);if (params.connector) q.set("connector", params.connector);diff --git a/surfaces/gui/src/components/AuditView.test.tsx b/surfaces/gui/src/components/AuditView.test.tsxnew file mode 100644index 00000000..dc04b25c--- /dev/null+++ b/surfaces/gui/src/components/AuditView.test.tsx@@ -0,0 +1,41 @@+// OPE-238: the "changes made without asking" summary opens Activity on one tool call's+// audit rows; the call filter is shown and can be cleared.+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { AuditView } from "./AuditView";++vi.mock("../api", () => ({+ getAudit: vi.fn(async () => []),+}));++import { getAudit } from "../api";++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("AuditView call filter", () => {+ it("loads only the given tool call's rows", async () => {+ render(<AuditView callId="call_9" />);+ await waitFor(() => expect(getAudit).toHaveBeenCalled());+ expect((getAudit as any).mock.calls[0][0]).toMatchObject({ call_id: "call_9" });+ expect(screen.getByTestId("audit-call-filter").textContent).toContain("call_9");+ });++ it("clearing the call filter loads everything again", async () => {+ render(<AuditView callId="call_9" />);+ await waitFor(() => expect(getAudit).toHaveBeenCalledTimes(1));+ fireEvent.click(screen.getByTestId("audit-call-filter-clear"));+ await waitFor(() => expect(getAudit).toHaveBeenCalledTimes(2));+ expect((getAudit as any).mock.calls[1][0].call_id).toBeUndefined();+ expect(screen.queryByTestId("audit-call-filter")).toBeNull();+ });++ it("without a call filter nothing changes", async () => {+ render(<AuditView />);+ await waitFor(() => expect(getAudit).toHaveBeenCalled());+ expect((getAudit as any).mock.calls[0][0].call_id).toBeUndefined();+ expect(screen.queryByTestId("audit-call-filter")).toBeNull();+ });+});diff --git a/surfaces/gui/src/components/AuditView.tsx b/surfaces/gui/src/components/AuditView.tsxindex 089d7155..f8d25d48 100644--- a/surfaces/gui/src/components/AuditView.tsx+++ b/surfaces/gui/src/components/AuditView.tsx@@ -10,26 +10,31 @@ const CARD = "rounded-xl2 border border-line bg-panel";const INPUT = "px-3 py-1.5 rounded-lg border border-line bg-paper text-ui text-ink outline-none focus:border-accent";const BTN_ACCENT = "text-ui px-3 py-1.5 rounded-lg bg-accent text-white shrink-0";-export function AuditView() {+// `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 } = {}) {const [events, setEvents] = useState<AuditEvent[]>([]);const [sessionFilter, setSessionFilter] = useState("");const [connectorFilter, setConnectorFilter] = useState("");const [toolFilter, setToolFilter] = useState("");+ const [callFilter, setCallFilter] = useState(callId || "");const { t } = useTranslation();- const refresh = () =>+ const refresh = (call = callFilter) =>getAudit({limit: 150,session_id: sessionFilter.trim() || undefined,connector: connectorFilter.trim() || undefined,tool: toolFilter.trim() || undefined,+ call_id: call || undefined,}).then(setEvents).catch(() => setEvents([]));useEffect(() => {- refresh();- }, []);+ setCallFilter(callId || "");+ refresh(callId || "");+ }, [callId]);return (<main className="flex-1 min-w-0 flex bg-paper">@@ -44,10 +49,25 @@ export function AuditView() {<input className={INPUT} placeholder={t("audit.placeholder_session")} value={sessionFilter} onChange={(e) => setSessionFilter(e.target.value)} /><input className={INPUT} placeholder={t("audit.placeholder_connector")} value={connectorFilter} onChange={(e) => setConnectorFilter(e.target.value)} /><input className={INPUT} placeholder={t("audit.placeholder_tool")} value={toolFilter} onChange={(e) => setToolFilter(e.target.value)} />- <button className={BTN_ACCENT} onClick={refresh}>+ <button className={BTN_ACCENT} onClick={() => refresh()}>{t("audit.filter")}</button></div>+ {callFilter && (+ <div className="flex items-center gap-2 mb-4 text-meta text-muted" data-testid="audit-call-filter">+ <span>{t("audit.call_filter", { id: callFilter })}</span>+ <button+ className="text-label text-faint hover:text-muted cursor-pointer"+ data-testid="audit-call-filter-clear"+ onClick={() => {+ setCallFilter("");+ refresh("");+ }}+ >+ {t("audit.call_filter_clear")}+ </button>+ </div>+ )}{events.length === 0 ? (<div className={CARD + " p-4 text-ui text-muted"}>{t("audit.no_events")}</div>diff --git a/surfaces/gui/src/components/Transcript.tsx b/surfaces/gui/src/components/Transcript.tsxindex 43758da2..70cf2d0f 100644--- a/surfaces/gui/src/components/Transcript.tsx+++ b/surfaces/gui/src/components/Transcript.tsx@@ -8,6 +8,7 @@ import { TeamUpdateLine, TeamCreatedLine, foldTeamUpdates } from "./TeamUpdateLiimport type { MessageSource } from "../api";import { ConnectorMessageCard } from "./ConnectorMessageCard";import { Icon } from "./Icon";+import { UnaskedSummary, unaskedTools } from "./UnaskedSummary";// 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@@ -478,6 +479,9 @@ interface Props {onUndoMemory?: (id: number, previous?: string) => void;// §8.4 "Allow anyway" on a reviewer-denied tool: one-shot exact-action override.onAllowAnyway?: (name: string, args: any) => void;+ // 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;}// The transcript index whose notice gets the Retry button: the tail error notice, looking@@ -537,13 +541,17 @@ function McpNotice({}-export function Transcript({ items, running, streamingText, onRetry, onOpenConnectors, onUndoMemory, onAllowAnyway }: Props) {+export function Transcript({ items, running, streamingText, onRetry, onOpenConnectors, onUndoMemory, onAllowAnyway, onOpenAudit }: 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// ANSWER and render as bubbles after the group; interior assistant texts are narration and// stay inside. A run with no activity at all is just bubbles (unchanged chat behavior).- const blocks: Array<{ turn: TurnItem[]; live?: boolean } | { item: Item; i: number; sources?: MessageSource[]; steps?: Item[] }> = [];+ const blocks: Array<+ | { turn: TurnItem[]; live?: boolean }+ | { unasked: ToolItem[] }+ | { item: Item; i: number; sources?: MessageSource[]; steps?: Item[] }+ > = [];let run: TurnItem[] = [];const flush = (live = false) => {if (!run.length) return;@@ -559,6 +567,11 @@ export function Transcript({ items, running, streamingText, onRetry, onOpenConneif (turn.some((it) => it.kind !== "assistant")) blocks.push({ turn, live });else turn.forEach((t) => blocks.push({ item: t, i: -1 }));answers.forEach((a) => blocks.push({ item: a, i: -1 }));+ // OPE-238: a finished turn ends with what ran without asking, after its answer.+ if (!live) {+ const unasked = unaskedTools(turn);+ if (unasked.length) blocks.push({ unasked });+ }};foldTeamUpdates(items).forEach(({ item, sources, steps }) => {const i = items.indexOf(item);@@ -583,6 +596,8 @@ export function Transcript({ items, running, streamingText, onRetry, onOpenConnereturn (<div className="transcript">{blocks.map((block, bi) => {+ if ("unasked" in block)+ return <UnaskedSummary tools={block.unasked} onOpenAudit={onOpenAudit} key={bi} />;if ("turn" in block)return (<TurnGroupdiff --git a/surfaces/gui/src/components/UnaskedSummary.test.tsx b/surfaces/gui/src/components/UnaskedSummary.test.tsxnew file mode 100644index 00000000..d9e8aec8--- /dev/null+++ b/surfaces/gui/src/components/UnaskedSummary.test.tsx@@ -0,0 +1,231 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";+import { Transcript } from "./Transcript";+import { exitCodeOf } from "./UnaskedSummary";+import type { Item } from "../types";++afterEach(cleanup);++// OPE-238: after a turn in which auto-approve let actions run with no card (a gate tier or+// a reviewer "allow"), the user sees every one of them, with diffs, without opening the+// audit log. Collapsed at rest; one click expands; each item links to its audit rows.+const TURN: Item[] = [+ { kind: "user", text: "tidy the notes and run the tests" },+ { kind: "tool", id: "t1", callId: "c1", name: "read_file", args: { path: "notes.md" }, status: "ok" },+ {+ kind: "tool",+ id: "t2",+ callId: "c2",+ name: "write_file",+ args: { path: "docs/summary.md", content: "# Summary\nThree tasks done." },+ status: "ok",+ approvalOrigin: "gate_tier",+ },+ {+ kind: "tool",+ id: "t3",+ callId: "c3",+ name: "replace_in_file",+ args: { path: "src/app.py", old: "DEBUG = True", new: "DEBUG = False" },+ status: "ok",+ approvalOrigin: "reviewer",+ approvalNote: "matches the request",+ },+ {+ kind: "tool",+ id: "t4",+ callId: "c4",+ name: "run_shell",+ args: { command: "pytest -q" },+ status: "ok",+ preview: '{"command": "pytest -q", "cwd": "/w", "exit_code": 0, "output": "5 passed"}',+ approvalOrigin: "reviewer",+ },+ // Approved by the user on a card: not "without asking".+ { kind: "approval", name: "run_shell", args: { command: "make deploy" }, reason: "", resolved: "once" },+ { kind: "tool", id: "t5", callId: "c5", name: "run_shell", args: { command: "make deploy" }, status: "ok", approvalOrigin: "user" },+ { kind: "assistant", text: "Done." },+];++function openSummary() {+ fireEvent.click(screen.getByTestId("unasked-summary-head"));+ return screen.getByTestId("unasked-summary-body");+}++describe("changes made without asking (OPE-238)", () => {+ it("is collapsed at rest and counts only the unasked actions", () => {+ render(<Transcript items={TURN} onApprove={vi.fn()} />);+ expect(screen.getByTestId("unasked-summary-head").textContent).toContain("3 changes made without asking");+ expect(screen.queryByTestId("unasked-summary-body")).toBeNull();+ expect(screen.queryByText("Three tasks done.")).toBeNull();+ });++ it("sits after the turn's answer", () => {+ const { container } = render(<Transcript items={TURN} onApprove={vi.fn()} />);+ const answer = screen.getByText("Done.");+ const summary = screen.getByTestId("unasked-summary");+ // DOCUMENT_POSITION_FOLLOWING: the summary comes after the answer bubble.+ expect(answer.compareDocumentPosition(summary) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(container.querySelectorAll("[data-testid=unasked-summary]").length).toBe(1);+ });++ it("expands to file changes with diffs and commands with their exit status, grouped by kind", () => {+ render(<Transcript items={TURN} onApprove={vi.fn()} />);+ const body = openSummary();++ const files = within(body).getByTestId("unasked-group-files");+ const commands = within(body).getByTestId("unasked-group-commands");+ expect(within(files).getAllByTestId("unasked-item").length).toBe(2);+ expect(within(commands).getAllByTestId("unasked-item").length).toBe(1);++ // write_file: the written content, as added lines.+ const added = Array.from(files.querySelectorAll(".diff-add")).map((n) => n.textContent);+ expect(added).toContain("+# Summary");+ expect(added).toContain("+Three tasks done.");+ // replace_in_file: old text removed, new text added.+ const removed = Array.from(files.querySelectorAll(".diff-del")).map((n) => n.textContent);+ expect(removed).toContain("-DEBUG = True");+ expect(added).toContain("+DEBUG = False");+ // The full path, not just the base name: the user is checking what changed where.+ expect(files.textContent).toContain("docs/summary.md");+ expect(files.textContent).toContain("src/app.py");++ // The command, with its exit status read from the result.+ expect(commands.textContent).toContain("pytest -q");+ expect(within(commands).getByTestId("unasked-exit").textContent).toBe("exit 0");++ // Who let each one through.+ expect(files.textContent).toContain("safe change, no card");+ expect(body.textContent).toContain("auto-approved");++ // The user-approved deploy is not listed.+ expect(body.textContent).not.toContain("make deploy");+ });++ it("collapses again on a second click", () => {+ render(<Transcript items={TURN} onApprove={vi.fn()} />);+ openSummary();+ fireEvent.click(screen.getByTestId("unasked-summary-head"));+ expect(screen.queryByTestId("unasked-summary-body")).toBeNull();+ });++ it("links each item to its audit rows by tool call", () => {+ const onOpenAudit = vi.fn();+ render(<Transcript items={TURN} onApprove={vi.fn()} onOpenAudit={onOpenAudit} />);+ const body = openSummary();+ const links = within(body).getAllByTestId("unasked-audit");+ expect(links.length).toBe(3);+ fireEvent.click(links[2]);+ expect(onOpenAudit).toHaveBeenCalledWith("c4");+ });++ it("shows no audit link where the app gives none", () => {+ render(<Transcript items={TURN} onApprove={vi.fn()} />);+ expect(within(openSummary()).queryByTestId("unasked-audit")).toBeNull();+ });++ it("a failed command shows its exit status as a failure", () => {+ const items: Item[] = [+ { kind: "user", text: "run the tests" },+ {+ kind: "tool",+ id: "t1",+ callId: "c1",+ name: "run_shell",+ args: { command: "pytest -q" },+ status: "ok",+ preview: '{"command": "pytest -q", "exit_code": 1, "output": "1 failed"}',+ approvalOrigin: "reviewer",+ },+ { kind: "assistant", text: "One test fails." },+ ];+ render(<Transcript items={items} onApprove={vi.fn()} />);+ const exit = within(openSummary()).getByTestId("unasked-exit");+ expect(exit.textContent).toBe("exit 1");+ expect(exit.className).toContain("text-danger");+ });++ it("a patch shows its own added and removed lines", () => {+ const patch = "*** Begin Patch\n*** Update File: a.txt\n@@\n-old line\n+new line\n*** End Patch";+ const items: Item[] = [+ { kind: "user", text: "fix a.txt" },+ { kind: "tool", id: "t1", callId: "c1", name: "apply_patch", args: { patch }, status: "ok", approvalOrigin: "reviewer" },+ { kind: "assistant", text: "Fixed." },+ ];+ const { container } = render(<Transcript items={items} onApprove={vi.fn()} />);+ expect(screen.getByTestId("unasked-summary-head").textContent).toContain("1 change made without asking");+ openSummary();+ expect(Array.from(container.querySelectorAll(".diff-del")).map((n) => n.textContent)).toContain("-old line");+ expect(Array.from(container.querySelectorAll(".diff-add")).map((n) => n.textContent)).toContain("+new line");+ });++ it("other actions the reviewer allowed are listed under their own heading", () => {+ const items: Item[] = [+ { kind: "user", text: "post the digest" },+ {+ kind: "tool",+ id: "t1",+ callId: "c1",+ name: "send_message",+ args: { target: "slack:T1/C9", text: "hi" },+ status: "ok",+ approvalOrigin: "reviewer",+ },+ { kind: "assistant", text: "Posted." },+ ];+ render(<Transcript items={items} onApprove={vi.fn()} />);+ const other = within(openSummary()).getByTestId("unasked-group-other");+ expect(other.textContent).toContain("Slack");+ });++ it("is not shown while the turn is still running", () => {+ const live = TURN.slice(0, -1); // no answer yet+ render(<Transcript items={live} onApprove={vi.fn()} running />);+ expect(screen.queryByTestId("unasked-summary")).toBeNull();+ });++ it("is not shown when every action was asked or allowed by the mode", () => {+ const items: Item[] = [+ { kind: "user", text: "read the notes" },+ { kind: "tool", id: "t1", callId: "c1", name: "read_file", args: { path: "notes.md" }, status: "ok" },+ { kind: "tool", id: "t2", callId: "c2", name: "run_shell", args: { command: "ls" }, status: "ok", approvalOrigin: "bypass" },+ { kind: "assistant", text: "Read." },+ ];+ render(<Transcript items={items} onApprove={vi.fn()} />);+ expect(screen.queryByTestId("unasked-summary")).toBeNull();+ });++ it("a denied call is never listed as a change", () => {+ const items: Item[] = [+ { kind: "user", text: "clean up" },+ { kind: "tool", id: "t1", callId: "c1", name: "run_shell", args: { command: "rm -rf build" }, status: "denied", approvalOrigin: "reviewer_denied" },+ { kind: "assistant", text: "Not allowed." },+ ];+ render(<Transcript items={items} onApprove={vi.fn()} />);+ expect(screen.queryByTestId("unasked-summary")).toBeNull();+ });++ it("each turn gets its own summary", () => {+ const items: Item[] = [+ ...TURN,+ { kind: "user", text: "again" },+ { kind: "tool", id: "t9", callId: "c9", name: "run_shell", args: { command: "ruff check" }, status: "ok", approvalOrigin: "reviewer" },+ { kind: "assistant", text: "Clean." },+ ];+ render(<Transcript items={items} onApprove={vi.fn()} />);+ const heads = screen.getAllByTestId("unasked-summary-head").map((h) => h.textContent);+ expect(heads.length).toBe(2);+ expect(heads[0]).toContain("3 changes");+ expect(heads[1]).toContain("1 change made");+ });+});++describe("exitCodeOf", () => {+ it("reads the exit code from a JSON result, a truncated one, or not at all", () => {+ expect(exitCodeOf('{"exit_code": 0}')).toBe(0);+ expect(exitCodeOf('{"command": "x", "cwd": "/w", "exit_code": 2, "output": "unterminated')).toBe(2);+ expect(exitCodeOf("ran: ls")).toBeNull();+ expect(exitCodeOf(undefined)).toBeNull();+ expect(exitCodeOf('{"exit_code": null}')).toBeNull();+ });+});diff --git a/surfaces/gui/src/components/UnaskedSummary.tsx b/surfaces/gui/src/components/UnaskedSummary.tsxnew file mode 100644index 00000000..41e2fa75--- /dev/null+++ b/surfaces/gui/src/components/UnaskedSummary.tsx@@ -0,0 +1,192 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import type { Item } from "../types";+import { humanizeTool } from "../humanize";+import { Icon } from "./Icon";++// OPE-238: "N changes made without asking". After a turn in which auto-approve let actions+// run with no approval card (a gate tier, OPE-233, or a reviewer "allow"), the user who was+// away sees every one of them here, with diffs, without opening the audit log. Collapsed at+// rest; one click expands. Built from the turn's tool items, whose approval origin is+// persisted on the tool message, so a reloaded session shows the same block.++type ToolItem = Extract<Item, { kind: "tool" }>;++// Mirrors `_UNASKED_ORIGINS` in coworker/engine.py.+const UNASKED_ORIGINS = new Set(["gate_tier", "reviewer"]);+const FILE_TOOLS = new Set(["write_file", "replace_in_file", "apply_patch", "apply_unified_diff"]);+const COMMAND_TOOLS = new Set(["run_shell"]);+// A whole-file write can be long: show its head, and say how much is left.+const MAX_DIFF_LINES = 200;++export function unaskedTools(items: Item[]): ToolItem[] {+ return items.filter(+ (it): it is ToolItem =>+ it.kind === "tool" && UNASKED_ORIGINS.has(it.approvalOrigin ?? "") && it.status !== "denied" && it.status !== "…",+ );+}++// A shell result is `{"command", "cwd", "exit_code", "output", …}`; the preview may be cut+// short, so read the field rather than parse the whole thing.+export function exitCodeOf(preview: string | undefined): number | null {+ if (!preview) return null;+ const m = /"exit_code"\s*:\s*(-?\d+)/.exec(preview);+ return m ? Number(m[1]) : null;+}++type DiffLine = { kind: "add" | "del" | "ctx" | "meta"; text: string };++function lines(text: unknown): string[] {+ const s = typeof text === "string" ? text : "";+ if (!s) return [];+ return s.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");+}++export function diffLines(name: string, args: any): DiffLine[] {+ const a = args && typeof args === "object" ? args : {};+ switch (name) {+ case "write_file":+ return lines(a.content).map((text) => ({ kind: "add", text }));+ case "replace_in_file":+ return [+ ...lines(a.old).map((text) => ({ kind: "del" as const, text })),+ ...lines(a.new).map((text) => ({ kind: "add" as const, text })),+ ];+ case "apply_patch":+ case "apply_unified_diff":+ return lines(name === "apply_patch" ? a.patch : a.diff).map((raw) => {+ if (raw.startsWith("***") || raw.startsWith("+++") || raw.startsWith("---") || raw.startsWith("@@"))+ return { kind: "meta", text: raw };+ if (raw.startsWith("+")) return { kind: "add", text: raw.slice(1) };+ if (raw.startsWith("-")) return { kind: "del", text: raw.slice(1) };+ return { kind: "ctx", text: raw.startsWith(" ") ? raw.slice(1) : raw };+ });+ default:+ return [];+ }+}++function Diff({ tool }: { tool: ToolItem }) {+ const { t } = useTranslation();+ const all = diffLines(tool.name, tool.args);+ if (!all.length) return null;+ const shown = all.slice(0, MAX_DIFF_LINES);+ return (+ <pre+ className="ml-5 mr-2 my-1 px-2.5 py-1.5 rounded-lg border border-line bg-paper font-mono text-meta leading-relaxed whitespace-pre-wrap break-words max-h-72 overflow-auto"+ data-testid="unasked-diff"+ >+ {shown.map((l, i) =>+ l.kind === "add" ? (+ <div className="diff-add text-ok" key={i}>{"+" + l.text}</div>+ ) : l.kind === "del" ? (+ <div className="diff-del text-danger" key={i}>{"-" + l.text}</div>+ ) : l.kind === "meta" ? (+ <div className="diff-meta text-faint" key={i}>{l.text}</div>+ ) : (+ <div className="diff-ctx text-muted" key={i}>{" " + l.text}</div>+ ),+ )}+ {all.length > shown.length && (+ <div className="text-faint">{t("transcript.unasked.more_lines", { count: all.length - shown.length })}</div>+ )}+ </pre>+ );+}++function UnaskedItem({ tool, onOpenAudit }: { tool: ToolItem; onOpenAudit?: (callId: string) => void }) {+ const { t } = useTranslation();+ const line = humanizeTool(tool.name, tool.args);+ const path = typeof tool.args?.path === "string" ? tool.args.path : "";+ const isCommand = COMMAND_TOOLS.has(tool.name);+ const exit = isCommand ? exitCodeOf(tool.preview) : null;+ const failed = tool.status !== "ok";+ return (+ <div data-testid="unasked-item" className="py-0.5">+ <div className="flex items-baseline gap-2 px-2">+ <span className={"w-3.5 text-center text-label shrink-0 " + (failed || (exit !== null && exit !== 0) ? "text-danger" : "text-ok")}>●</span>+ <span className="min-w-0 text-ui leading-relaxed">+ {isCommand ? (+ <code className="font-mono text-meta text-ink break-all">{String(tool.args?.command ?? "")}</code>+ ) : path ? (+ <>+ <span className="text-muted">{line.pre}</span>+ <span className="font-mono text-meta text-ink break-all">{path}</span>+ </>+ ) : (+ <>+ <span className="text-muted">{line.pre}</span>+ {line.obj && <span className="text-ink">{line.obj}</span>}+ {line.post && <span className="text-muted">{line.post}</span>}+ </>+ )}+ </span>+ {exit !== null ? (+ <span className={"text-label shrink-0 " + (exit === 0 ? "text-ok" : "text-danger")} data-testid="unasked-exit">+ {t("transcript.unasked.exit", { code: exit })}+ </span>+ ) : (+ failed && <span className="text-label text-danger shrink-0">{tool.status}</span>+ )}+ <span+ className="text-label text-faint shrink-0"+ title={+ tool.approvalOrigin === "gate_tier"+ ? t("transcript.approval.gate_tier_title")+ : tool.approvalNote || t("transcript.approval.reviewer_allowed_title")+ }+ >+ {tool.approvalOrigin === "gate_tier" ? t("transcript.approval.gate_tier") : t("transcript.approval.auto_approved")}+ </span>+ {onOpenAudit && tool.callId && (+ <button+ className="ml-auto shrink-0 text-label text-faint hover:text-muted cursor-pointer"+ data-testid="unasked-audit"+ onClick={() => onOpenAudit(tool.callId!)}+ >+ {t("transcript.unasked.audit")}+ </button>+ )}+ </div>+ <Diff tool={tool} />+ </div>+ );+}++export function UnaskedSummary({ tools, onOpenAudit }: { tools: ToolItem[]; onOpenAudit?: (callId: string) => void }) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);+ if (!tools.length) return null;+ const groups: Array<{ key: "files" | "commands" | "other"; items: ToolItem[] }> = [+ { key: "files" as const, items: tools.filter((x) => FILE_TOOLS.has(x.name)) },+ { key: "commands" as const, items: tools.filter((x) => COMMAND_TOOLS.has(x.name)) },+ { key: "other" as const, items: tools.filter((x) => !FILE_TOOLS.has(x.name) && !COMMAND_TOOLS.has(x.name)) },+ ].filter((g) => g.items.length);+ return (+ <details className="stepgroup unasked-summary" open={open} data-testid="unasked-summary">+ <summary+ className="stepgroup-head transcript-disclosure cursor-pointer select-none text-ui text-faint hover:text-muted"+ data-testid="unasked-summary-head"+ onClick={(e) => {+ e.preventDefault(); // drive open/closed from state, not the native toggle+ setOpen(!open);+ }}+ >+ <Icon name="chevronDown" size={12} />+ <span>{t("transcript.unasked.summary", { count: tools.length })}</span>+ </summary>+ {open && (+ <div className="ml-1.5 mt-1 pl-2 border-l-2 border-line flex flex-col gap-1.5" data-testid="unasked-summary-body">+ {groups.map((g) => (+ <div key={g.key} data-testid={`unasked-group-${g.key}`}>+ <div className="px-2 text-label text-faint uppercase tracking-wide">{t(`transcript.unasked.group_${g.key}`)}</div>+ {g.items.map((tool, i) => (+ <UnaskedItem tool={tool} onOpenAudit={onOpenAudit} key={tool.id || i} />+ ))}+ </div>+ ))}+ </div>+ )}+ </details>+ );+}diff --git a/surfaces/gui/src/itemsFromMessages.test.ts b/surfaces/gui/src/itemsFromMessages.test.tsindex 666d9aee..1e7d1172 100644--- a/surfaces/gui/src/itemsFromMessages.test.ts+++ b/surfaces/gui/src/itemsFromMessages.test.ts@@ -161,3 +161,27 @@ describe("itemsFromMessages mcp failure", () => {});});});++// OPE-238: a replayed tool item carries its tool call's id, so the "changes made without+// asking" summary can link it to its audit rows after a reload too.+describe("itemsFromMessages call ids", () => {+ it("puts the tool call id on the tool item", () => {+ const items = itemsFromMessages([+ { role: "user", content: "run the tests" },+ {+ role: "assistant",+ content: "",+ tool_calls: [{ id: "call_9", function: { name: "run_shell", arguments: '{"command": "pytest"}' } }],+ },+ {+ role: "tool",+ tool_call_id: "call_9",+ content: '{"exit_code": 0}',+ _display: { approval_origin: "reviewer" },+ },+ ] as any);+ const tool = items.find((i: any) => i.kind === "tool") as any;+ expect(tool.callId).toBe("call_9");+ expect(tool.approvalOrigin).toBe("reviewer");+ });+});diff --git a/surfaces/gui/src/itemsFromMessages.ts b/surfaces/gui/src/itemsFromMessages.tsindex e65cb453..6d095011 100644--- a/surfaces/gui/src/itemsFromMessages.ts+++ b/surfaces/gui/src/itemsFromMessages.ts@@ -72,6 +72,7 @@ export function itemsFromMessages(messages: ConversationMessage[]): Item[] {items.push({kind: "tool",id: tc.id,+ ...(tc.id ? { callId: tc.id } : {}),name: tc.function?.name,args,status: denied ? "denied" : "ok",diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex 8b26ec4a..b9fdc8fe 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -288,6 +288,17 @@"undone_forgotten": "Okay — forgotten.","undone_restored": "Okay — put back the way it was.","undo": "Undo"+ },+ "unasked": {+ "summary": "{{count}} changes made without asking",+ "summary_one": "{{count}} change made without asking",+ "group_files": "Files",+ "group_commands": "Commands",+ "group_other": "Other actions",+ "exit": "exit {{code}}",+ "audit": "audit log",+ "more_lines": "… {{count}} more lines",+ "more_lines_one": "… {{count}} more line"}},"rail": {@@ -924,7 +935,9 @@"fallback_tool": "tool","fallback_event": "event","session": "session",- "resource": "resource: {{value}}"+ "resource": "resource: {{value}}",+ "call_filter": "Showing one tool call: {{id}}",+ "call_filter_clear": "Show all"},"plan": {"proposed": "The agent proposed a plan",diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex 0edd2a84..851d6336 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -285,6 +285,15 @@"undone_forgotten": "好 —— 已忘记。","undone_restored": "好 —— 已恢复原样。","undo": "撤销"+ },+ "unasked": {+ "summary": "{{count}} 项未经询问的更改",+ "group_files": "文件",+ "group_commands": "命令",+ "group_other": "其他操作",+ "exit": "退出码 {{code}}",+ "audit": "审计日志",+ "more_lines": "… 还有 {{count}} 行"}},"rail": {@@ -912,7 +921,9 @@"fallback_tool": "工具","fallback_event": "事件","session": "会话",- "resource": "资源:{{value}}"+ "resource": "资源:{{value}}",+ "call_filter": "仅显示一次工具调用:{{id}}",+ "call_filter_clear": "显示全部"},"plan": {"proposed": "agent 提出了一个计划",diff --git a/surfaces/gui/src/types.ts b/surfaces/gui/src/types.tsindex 76f22a05..f3d53ace 100644--- a/surfaces/gui/src/types.ts+++ b/surfaces/gui/src/types.ts@@ -17,6 +17,7 @@ export type EventType =| "tool_started"| "tool_finished"| "iteration_end"+ | "turn_summary"| "turn_end"| "error"| "input_rejected"@@ -164,7 +165,8 @@ export type Item =// `approvalOrigin` = why the call ran without a card: "reviewer" (auto-approved by the// Auto-Approve reviewer; `approvalNote` carries its one-line reason) or "bypass"// (bypass-approvals mode). Rendered as a quiet debugging chip, deliberately subtle.- | { kind: "tool"; id: string; name: string; args: any; status: string; preview?: string; hidden?: number; standingRule?: string; reviewerReason?: string; allowAnyway?: boolean; approvalOrigin?: string; approvalNote?: string; approvalGrant?: string }+ // `callId` = the tool call's id (OPE-238: links the item to its audit rows).+ | { kind: "tool"; id: string; name: string; args: any; status: string; preview?: string; hidden?: number; standingRule?: string; reviewerReason?: string; allowAnyway?: boolean; approvalOrigin?: string; approvalNote?: string; approvalGrant?: string; callId?: string }| {kind: "approval";toolCallId?: string;diff --git a/tests/test_server.py b/tests/test_server.pyindex 1786ce8c..10862b94 100644--- a/tests/test_server.py+++ b/tests/test_server.py@@ -801,6 +801,13 @@ def test_ws_browser_tool_audit_round_trip(tmp_path):)assert any(r["tool"] == "browser_close" and r["stage"] == "finished" for r in rows)+ # OPE-238: one tool call's rows, by its id (the GUI's "changes made without asking"+ # summary links each item this way).+ call_id = next(r["call_id"] for r in rows if r["stage"] == "finished")+ one = client.get("/v1/audit", params={"call_id": call_id}).json()["events"]+ assert one and {r["call_id"] for r in one} == {call_id}+ assert client.get("/v1/audit", params={"call_id": "no-such-call"}).json()["events"] == []+def test_open_and_recent_workspaces(tmp_path):proj = tmp_path / "proj"diff --git a/tests/test_turn_summary.py b/tests/test_turn_summary.pynew file mode 100644index 00000000..e747a534--- /dev/null+++ b/tests/test_turn_summary.py@@ -0,0 +1,172 @@+"""OPE-238: at the end of a turn the engine says which actions ran without asking.++An action "ran without asking" when auto-approve let it through with no approval card:+a gate tier (OPE-233 inert writes) or a reviewer "allow". The engine emits one+`turn_summary` event listing them, just before the event that ends the turn, so the+event that ends a turn is still the last one. Actions the user approved on a card, or+that the mode allows outright, are not in it.++Each item names its tool call, and the audit log can be filtered by that call's id,+so a surface can link an item to its audit rows.+"""++from __future__ import annotations++import asyncio++from coworker.audit import AuditStore+from coworker.events import EventType+from coworker.providers import AssistantTurn+from test_auto_approve import _engine, _FakeReviewer, _run, _tool_turn+++def _summaries(events):+ return [ev for ev in events if ev.type == EventType.TURN_SUMMARY]+++def test_lists_gate_tier_and_reviewer_allowed_actions_before_turn_end(tmp_path):+ engine, rows, approvals = _engine(+ tmp_path,+ [+ _tool_turn(("write_file", {"path": "summary.txt", "content": "3 tasks done"})),+ _tool_turn(("run_shell", {"command": "pytest -q"})),+ _tool_turn(("write_file", {"path": "tool.py", "content": "print(1)"})),+ AssistantTurn(text="done", finish_reason="stop"),+ ],+ )+ engine.permissions.inert_writes = "on"+ engine.reviewer = _FakeReviewer({"run_shell": "allow", "write_file": "unsure"})+ events = _run(engine, "do the tasks")++ assert approvals == ["write_file"] # tool.py: the reviewer was unsure, the user approved+ summaries = _summaries(events)+ assert len(summaries) == 1+ # Right before the event that ends the turn.+ assert events[-1].type == EventType.TURN_END+ assert events[-2] is summaries[0]+ items = summaries[0].data["actions"]+ assert [(i["name"], i["origin"]) for i in items] == [+ ("write_file", "gate_tier"),+ ("run_shell", "reviewer"),+ ]+ assert all(i["status"] == "ok" for i in items)+ assert all(i["tool_call_id"] for i in items)+ assert items[1]["note"] == "scripted allow" # the reviewer's one-line reason rides along+ assert summaries[0].data["count"] == 2+++def test_no_event_when_everything_was_asked(tmp_path):+ engine, rows, approvals = _engine(+ tmp_path,+ [_tool_turn(("run_shell", {"command": "make deploy"})), AssistantTurn(text="done", finish_reason="stop")],+ )+ engine.reviewer = _FakeReviewer({"run_shell": "unsure"})+ events = _run(engine, "deploy")++ assert approvals == ["run_shell"]+ assert _summaries(events) == []+++def test_no_event_for_a_turn_without_tools(tmp_path):+ engine, _rows, _approvals = _engine(tmp_path, [AssistantTurn(text="hi", finish_reason="stop")])+ assert _summaries(_run(engine, "hello")) == []+++def test_a_reviewer_deny_is_not_listed(tmp_path):+ engine, _rows, _approvals = _engine(+ tmp_path,+ [_tool_turn(("run_shell", {"command": "rm -rf build"})), AssistantTurn(text="ok", finish_reason="stop")],+ )+ engine.reviewer = _FakeReviewer({"run_shell": "deny"})+ assert _summaries(_run(engine, "clean up")) == []+++def test_each_turn_gets_its_own_summary(tmp_path):+ engine, _rows, _approvals = _engine(+ tmp_path,+ [+ _tool_turn(("run_shell", {"command": "pytest -q"})),+ AssistantTurn(text="first", finish_reason="stop"),+ _tool_turn(("run_shell", {"command": "ruff check"})),+ _tool_turn(("run_shell", {"command": "mypy ."})),+ AssistantTurn(text="second", finish_reason="stop"),+ ],+ )+ engine.reviewer = _FakeReviewer({"run_shell": "allow"})+ first = _summaries(_run(engine, "run the tests"))+ second = _summaries(_run(engine, "lint and type-check"))+ assert [s.data["count"] for s in first] == [1]+ assert [s.data["count"] for s in second] == [2]+++def test_a_failed_action_is_listed_with_its_status(tmp_path):+ engine, _rows, _approvals = _engine(+ tmp_path,+ [_tool_turn(("run_shell", {"command": "pytest -q"})), AssistantTurn(text="done", finish_reason="stop")],+ )+ engine.reviewer = _FakeReviewer({"run_shell": "allow"})++ def run_shell(command: str) -> str:+ """Run a command.++ Args:+ command: the command line+ """+ raise RuntimeError("exit 1")++ engine.registry.register(run_shell, metadata=engine.registry.get("run_shell").metadata)+ items = _summaries(_run(engine, "run the tests"))[0].data["actions"]+ assert items[0]["name"] == "run_shell"+ assert items[0]["status"] != "ok"+++def test_the_summary_carries_no_arguments(tmp_path):+ # The tool events already carry what ran; the summary stays a short index of it.+ engine, _rows, _approvals = _engine(+ tmp_path,+ [_tool_turn(("run_shell", {"command": "echo SECRET_SHAPED"})), AssistantTurn(text="done", finish_reason="stop")],+ )+ engine.reviewer = _FakeReviewer({"run_shell": "allow"})+ summary = _summaries(_run(engine, "echo"))[0]+ assert "SECRET_SHAPED" not in repr(summary.data)+++def test_closing_the_turn_early_still_closes_the_inner_run(tmp_path):+ # A surface that stops reading mid-turn (a disconnect) must still end the run, so the+ # run grants are cleared as before.+ engine, _rows, _approvals = _engine(+ tmp_path,+ [_tool_turn(("run_shell", {"command": "pytest -q"})), AssistantTurn(text="done", finish_reason="stop")],+ )+ engine.reviewer = _FakeReviewer({"run_shell": "allow"})+ cleared: list[bool] = []+ original = engine.permissions.clear_run_allowances++ def spy():+ cleared.append(True)+ original()++ engine.permissions.clear_run_allowances = spy++ async def _go():+ gen = engine.run("run the tests")+ async for ev in gen:+ if ev.type == EventType.TOOL_FINISHED:+ break+ await gen.aclose()++ asyncio.run(_go())+ assert len(cleared) >= 2 # once at the start, once in the run's finally+++# -- the audit log can be filtered by tool call ------------------------------------------+++def test_audit_store_filters_by_call_id(tmp_path):+ store = AuditStore(tmp_path / "audit.db")+ for call_id, stage in (("a1", "started"), ("a1", "finished"), ("b2", "finished")):+ store.append({"session_id": "s", "tool": "run_shell", "stage": stage, "call_id": call_id, "arguments": {}})+ rows = store.list(call_id="a1")+ assert sorted(r["stage"] for r in rows) == ["finished", "started"]+ assert {r["call_id"] for r in rows} == {"a1"}+ assert len(store.list()) == 3