Python
Persist approval provenance and server-authored mode notices
Rohit C Prasad40990da5e24c
diff --git a/coworker/engine.py b/coworker/engine.pyindex 6d357779..96e4c461 100644--- a/coworker/engine.py+++ b/coworker/engine.py@@ -174,10 +174,12 @@ class TurnEngine:self.reviewer: Optional[Any] = Noneself._reviewer_denials = 0self._reviewer_verdicts: dict[str, Any] = {}- # (c) Why an executed call ran without a card, keyed by tool_call id: ("reviewer",- # reason) or ("bypass", ""). Consumed by _record_result into TOOL_FINISHED so the- # GUI can annotate quietly; user approvals already annotate via the resolved card.- self._approval_origins: dict[str, tuple[str, str]] = {}+ # (c) How each consequential call got cleared, keyed by tool_call id:+ # {"origin": "reviewer"|"bypass"|"user", "note": <reviewer reasoning>, "grant":+ # <user outcome>}. Consumed by _record_result into the TOOL_FINISHED event AND+ # into the tool message's `_display` sidecar, so the quiet provenance chips+ # survive reload (owner ruling 2026-08-24) — display-only, never provider-visible.+ self._approval_origins: dict[str, dict[str, str]] = {}# Shadow evaluation (spec Part 6 step 3): when True and a reviewer is attached, the# reviewer records what it WOULD have decided on each approval card while the human# still decides. Fire-and-forget — the card is never delayed, no decision is ever@@ -1123,7 +1125,7 @@ class TurnEngine:# (c) Bypass mode ran a consequential call no other rule allowed: annotate it.# "full access" is the exact reason string of permissions.py's bypass branch.if allowed and decision.reason == "full access":- self._approval_origins[tool_call.id] = ("bypass", "")+ self._approval_origins[tool_call.id] = {"origin": "bypass"}if not allowed and decision.needs_user and self._consume_allow_anyway(tool_call):# §8.4 "Allow anyway": the human already approved this exact action from the@@ -1133,6 +1135,7 @@ class TurnEngine:self._audit(tool_call, stage="auto_allowed", status="allowed", reason=reason)consulted_live = False+ unsure_note = "" # the reviewer's hesitation, when an unsure verdict raised the cardif (not allowedand decision.needs_user@@ -1159,7 +1162,9 @@ class TurnEngine:if verdict.verdict == "allow":allowed = Trueself._reviewer_denials = 0 # streak semantics: any non-deny resets- self._approval_origins[tool_call.id] = ("reviewer", verdict.reason)+ self._approval_origins[tool_call.id] = {+ "origin": "reviewer", "note": verdict.reason+ }reason = f"allowed by reviewer: {verdict.reason}"elif verdict.verdict == "deny":# §8.4 deny asymmetry — full reason to the USER (event + audit above),@@ -1184,9 +1189,12 @@ class TurnEngine:**({"reviewer_paused": _REVIEWER_PAUSED_TEXT} if tripped else {}),},)- self.messages.append(- _tool_error_message(tool_call, AGENT_DENY_MESSAGE)- )+ deny_msg = _tool_error_message(tool_call, AGENT_DENY_MESSAGE)+ deny_msg["_display"] = {+ "approval_origin": "reviewer_denied",+ "approval_note": verdict.reason,+ }+ self.messages.append(deny_msg)self._audit(tool_call,stage="finished",@@ -1198,6 +1206,7 @@ class TurnEngine:# "unsure" falls through to today's card — the human decides.if verdict.verdict == "unsure":self._reviewer_denials = 0 # streak semantics: any non-deny resets+ unsure_note = verdict.reasonif not allowed and decision.needs_user:# Shadow evaluation: record what the reviewer would have said about this card.@@ -1264,6 +1273,11 @@ class TurnEngine:False,"interrupted by user" if self._cancel.is_set() else "denied by user",)+ self._approval_origins[tool_call.id] = {+ "origin": "user",+ "grant": "deny",+ **({"note": unsure_note} if unsure_note else {}),+ }self._audit(tool_call,stage="approval_resolved",@@ -1286,6 +1300,11 @@ class TurnEngine:elif outcome is ApprovalOutcome.READONLY_SESSION:self.permissions.allow_readonly_for_session()allowed, reason = True, "approved by user"+ self._approval_origins[tool_call.id] = {+ "origin": "user",+ "grant": outcome.value,+ **({"note": unsure_note} if unsure_note else {}),+ }self._audit(tool_call,stage="approval_resolved",@@ -1298,7 +1317,15 @@ class TurnEngine:if not allowed:if spec is None:reason = f"unknown tool: {tool_call.name}"- self.messages.append(_tool_error_message(tool_call, reason))+ err_msg = _tool_error_message(tool_call, reason)+ origin = self._approval_origins.pop(tool_call.id, None)+ if origin:+ err_msg["_display"] = {+ "approval_origin": origin.get("origin", ""),+ **({"approval_note": origin["note"]} if origin.get("note") else {}),+ **({"approval_grant": origin["grant"]} if origin.get("grant") else {}),+ }+ self.messages.append(err_msg)yield Event(EventType.TOOL_FINISHED,{"name": tool_call.name, "status": "denied", "reason": reason},@@ -1343,6 +1370,17 @@ class TurnEngine:if isinstance(result, dict) and "_display" in result:display = result.get("_display") or Noneresult = {k: v for k, v in result.items() if k != "_display"}+ origin = self._approval_origins.pop(tool_call.id, None)+ if origin:+ # Provenance survives reload via the same display-only sidecar as the privacy+ # counts (owner ruling 2026-08-24) — `_outbound_messages` strips it, so no+ # provider ever sees it.+ display = {+ **(display or {}),+ "approval_origin": origin.get("origin", ""),+ **({"approval_note": origin["note"]} if origin.get("note") else {}),+ **({"approval_grant": origin["grant"]} if origin.get("grant") else {}),+ }message = _tool_result_message(tool_call, result)if display:message["_display"] = display@@ -1371,7 +1409,6 @@ class TurnEngine:)self._note_ingestion(tool_call, status)rule = self._standing_notes.pop(tool_call.id, "")- origin = self._approval_origins.pop(tool_call.id, None)return Event(EventType.TOOL_FINISHED,{@@ -1380,9 +1417,16 @@ class TurnEngine:"result_preview": _preview(result),**({"display": display} if display else {}),**({"standing_rule": rule} if rule else {}),- # (c) quiet provenance chip: "reviewer" (auto-approved) or "bypass"- **({"approval_origin": origin[0]} if origin else {}),- **({"approval_note": origin[1]} if origin and origin[1] else {}),+ # (c) quiet provenance chip — same fields the `_display` sidecar persists.+ **(+ {+ "approval_origin": origin.get("origin", ""),+ **({"approval_note": origin["note"]} if origin.get("note") else {}),+ **({"approval_grant": origin["grant"]} if origin.get("grant") else {}),+ }+ if origin+ else {}+ ),},)diff --git a/coworker/permissions.py b/coworker/permissions.pyindex e2e1cda8..9e822feb 100644--- a/coworker/permissions.py+++ b/coworker/permissions.py@@ -188,6 +188,28 @@ from .risk import ( # re-exported for back-compat (manager.py imports WRITE_TOO)+# The transcript's full Auto-Approve explainer (owner copy 2026-08-24). Persisted as a+# `mode_notice` message the FIRST time a session enters Auto-Approve — server-authored so+# it appears exactly once, in place, and survives reloads (the old client-side banner+# re-announced on every restart).+AUTO_APPROVE_NOTICE = (+ "Auto-approve uses a model to let routine actions through without asking; anything "+ "it isn't sure about still comes to you. It cuts interruptions but still carries "+ "some risk i.e. a command it allows still reaches anything you can. These are model "+ "judgments, and not guarantees."+)++# Human labels for the one-line persisted switch markers ("Ask for approval is on.").+MODE_LABELS = {+ "discuss": "Discuss",+ "plan": "Plan",+ "interactive": "Ask for approval",+ "auto": "Bypass approvals",+ "bypass-approvals": "Bypass approvals",+ "auto-approve": "Auto-approve",+}++class Mode(str, Enum):DISCUSS = "discuss" # read-only conversation: no edits, no planning workflowPLAN = (diff --git a/coworker/server/app.py b/coworker/server/app.pyindex e7ecadbe..97874547 100644--- a/coworker/server/app.py+++ b/coworker/server/app.py@@ -2504,6 +2504,24 @@ def create_app(manager: SessionManager) -> FastAPI:# This socket is now a live view of the session; background turns (channel delivery,# self-wake, durable resume) broadcast here too, not just locally driven run_turns.manager.register_session_client(session_id, ws.send_json)+ if engine.permissions.mode is Mode.AUTO_APPROVE and not any(+ m.get("kind") == "mode_notice" for m in engine.messages+ ):+ from coworker.permissions import AUTO_APPROVE_NOTICE++ engine._append_notice(+ "mode_notice", AUTO_APPROVE_NOTICE, title="Auto-approve is on."+ )+ manager.save(session_id, engine)+ await ws.send_json(+ {+ "type": "mode_notice",+ "data": {+ "title": "Auto-approve is on.",+ "text": AUTO_APPROVE_NOTICE,+ },+ }+ )inbound_times: deque[float] = deque()async def reject_input(reason: str) -> None:@@ -2619,6 +2637,42 @@ def create_app(manager: SessionManager) -> FastAPI:manager.audit_autonomy_change(session_id, "mode", previous.value, new_mode.value)+ # The transcript records which mode each exchange ran under+ # (owner ruling 2026-08-24): full explainer the first time a+ # session enters Auto-Approve, a one-line marker otherwise.+ # Server-authored + persisted, so reloads show it in place+ # exactly once instead of re-announcing on every restart.+ from coworker.permissions import (+ AUTO_APPROVE_NOTICE,+ MODE_LABELS,+ )++ if new_mode is Mode.AUTO_APPROVE and not any(+ m.get("kind") == "mode_notice"+ for m in engine.messages+ ):+ engine._append_notice(+ "mode_notice",+ AUTO_APPROVE_NOTICE,+ title="Auto-approve is on.",+ )+ notice_data = {+ "title": "Auto-approve is on.",+ "text": AUTO_APPROVE_NOTICE,+ }+ else:+ label = MODE_LABELS.get(+ new_mode.value, new_mode.value+ )+ engine._append_notice(+ "mode_switch", f"{label} is on."+ )+ notice_data = {"text": f"{label} is on."}+ manager.save(session_id, engine)+ await manager.broadcast_session(+ session_id,+ {"type": "mode_notice", "data": notice_data},+ )elif kind == "set_model":model = message.get("model")if model is not None and not isinstance(model, str):diff --git a/surfaces/gui/e2e/fixtures.ts b/surfaces/gui/e2e/fixtures.tsindex f293c848..9c2d444b 100644--- a/surfaces/gui/e2e/fixtures.ts+++ b/surfaces/gui/e2e/fixtures.ts@@ -1074,6 +1074,29 @@ export async function mockApi(page: import("@playwright/test").Page) {}send("interrupted", {});send("turn_done");+ } else if (msg.type === "set_mode") {+ // Mirrors the server: full explainer the FIRST time a session enters+ // Auto-Approve, a one-line marker for every later change.+ const anyWs = ws as any;+ if (msg.mode === "auto-approve" && !anyWs.__modeNoticeShown) {+ anyWs.__modeNoticeShown = true;+ send("mode_notice", {+ title: "Auto-approve is on.",+ text:+ "Auto-approve uses a model to let routine actions through without asking; " ++ "anything it isn't sure about still comes to you. It cuts interruptions but " ++ "still carries some risk i.e. a command it allows still reaches anything you " ++ "can. These are model judgments, and not guarantees.",+ });+ } else {+ const labels: Record<string, string> = {+ discuss: "Discuss",+ interactive: "Ask for approval",+ "bypass-approvals": "Bypass approvals",+ "auto-approve": "Auto-approve",+ };+ send("mode_notice", { text: `${labels[msg.mode] || msg.mode} is on.` });+ }} else if (msg.type === "set_model") {// Mid-session switch: the server applies it and broadcasts the persisted marker.// Like the real server, the FIRST bind (fresh session) is silent.diff --git a/surfaces/gui/e2e/reviewer-paused.spec.ts b/surfaces/gui/e2e/reviewer-paused.spec.tsindex 873b3c3a..efc038f4 100644--- a/surfaces/gui/e2e/reviewer-paused.spec.ts+++ b/surfaces/gui/e2e/reviewer-paused.spec.ts@@ -33,3 +33,29 @@ test("an unsure escalation shows the reviewer's hesitation on the card", async (await expect(note).toBeVisible();await expect(note).toContainText("reviewer wasn\u2019t sure: This runs a newly created script");});++test("mode notices: full explainer once, one-line markers after", async ({ page }) => {+ await page.goto("/");+ await page.getByText("Draft the launch note").first().click();++ const pickMode = async (label: string) => {+ await page.getByRole("button", { name: "Mode", exact: true }).click();+ await page.getByTestId("mode-menu").getByText(label, { exact: false }).first().click();+ };++ // First entry into Auto-approve: the full (new, shorter) explainer.+ await pickMode("Auto-approve");+ await expect(page.getByText("Auto-approve is on.")).toBeVisible();+ await expect(+ page.getByText(/uses a model to let routine actions through without asking/),+ ).toBeVisible();++ // Later switches: one-line markers only — the banner never repeats.+ await pickMode("Ask for approval");+ await expect(page.getByText("Ask for approval is on.")).toBeVisible();+ await pickMode("Auto-approve");+ await expect(page.getByText("Auto-approve is on.")).toHaveCount(2); // title + marker+ await expect(+ page.getByText(/uses a model to let routine actions through without asking/),+ ).toHaveCount(1);+});diff --git a/surfaces/gui/src/App.tsx b/surfaces/gui/src/App.tsxindex abf10e1c..6bebaea4 100644--- a/surfaces/gui/src/App.tsx+++ b/surfaces/gui/src/App.tsx@@ -59,7 +59,6 @@ import { Icon } from "./components/Icon";import { Sidebar } from "./components/Sidebar";import { ThinkingBlock, Transcript } from "./components/Transcript";import { Composer } from "./components/Composer";-import { modeNoticeStep, type ModeNoticeState } from "./modeNotice";import { Markdown } from "./components/Markdown";import { SearchModal } from "./components/SearchModal";import { SessionIntro } from "./components/SessionIntro";@@ -224,14 +223,11 @@ export function App() {// fresh state — the interrupted/error flush below needs the live buffer at event time.// Mode markers in the transcript: which session has already seen the full Auto-approve// explanation, and what mode the transcript last recorded (so a switch can be told apart- // from a re-render or a session change). See `modeNoticeStep`.- const modeNoticeState = useRef<ModeNoticeState>({ mark: null, bannerShownFor: "" });// Which session the current `mode` value is CONFIRMED for. On a session switch, `mode`// still holds the previous session's value until the server's `ready` event delivers the// real one — announcing anything in that window posts the old session's banner into the// new transcript (seen 2026-08-22: a fresh Ask-for-approval session opened with the// Auto-approve banner, then a stray "Ask for approval is on." marker when `ready` landed).- const [modeConfirmedFor, setModeConfirmedFor] = useState("");const streamingRef = useRef("");const setStreaming = (value: string | ((s: string) => string)) => {streamingRef.current = typeof value === "function" ? value(streamingRef.current) : value;@@ -695,9 +691,6 @@ export function App() {setConnected(true);if (d.model) setModel(d.model);if (d.mode) setMode(d.mode);- // Even when d.mode is absent (older servers), this is the best truth we'll get —- // unblock the mode-notice effect for this session either way.- setModeConfirmedFor(sessionId);if (d.command_trust?.required) setWorkspaceTrustRequest(d.command_trust);// Cowork: adopt the server-provisioned scratch dir (only when we don't already have one).if (d.workspace) setWorkspace((cur) => cur || d.workspace);@@ -891,6 +884,14 @@ export function App() {if (d.status === "max_iterations_exceeded")setItems((p) => [...p, { kind: "notice", tone: "warn", text: "Stopped: max iterations reached." }]);break;+ case "mode_notice":+ // Server-authored + persisted (owner ruling 2026-08-24): the Auto-Approve+ // explainer once per session ever, one-line markers for later switches.+ setItems((p) => [+ ...p,+ { kind: "notice", tone: "info", ...(d.title ? { title: d.title } : {}), text: d.text || "" },+ ]);+ break;case "model_changed":// Mid-session switch (server-applied): update the header fact and drop the// persisted marker into the live transcript (replay renders it from history).@@ -1039,13 +1040,6 @@ export function App() {setFollowing(true);}, [sessionId]);- useEffect(() => {- // The step is a no-op while `mode` still belongs to the previous session (until `ready`- // confirms it) — see modeNoticeStep for why acting on the stale value misfires.- const { item, state } = modeNoticeStep(modeNoticeState.current, mode, sessionId, modeConfirmedFor);- modeNoticeState.current = state;- if (item) setItems((p) => [...p, item]);- }, [mode, sessionId, modeConfirmedFor]);useEffect(() => {if (atBottomRef.current) scrollToBottom();}, [items, streaming]);diff --git a/surfaces/gui/src/components/Transcript.test.tsx b/surfaces/gui/src/components/Transcript.test.tsxindex dae63b02..44ec4c9a 100644--- a/surfaces/gui/src/components/Transcript.test.tsx+++ b/surfaces/gui/src/components/Transcript.test.tsx@@ -37,7 +37,7 @@ describe("TurnGroup (Transcript §33)", () => {expect(screen.getByTestId("turn-narration").textContent).toContain("Checking what merged");expect(screen.getByText("runbook.md")).toBeTruthy();expect(screen.getByText(/Sent a Slack message to/)).toBeTruthy();- expect(screen.getByText("✓ approved")).toBeTruthy();+ expect(screen.getByText("✓ user-approved")).toBeTruthy();expect(screen.queryByText("send_message approval")).toBeNull();// Raw stays one click away: the row's raw toggle reveals args + result verbatim.diff --git a/surfaces/gui/src/components/Transcript.tsx b/surfaces/gui/src/components/Transcript.tsxindex b4082586..68b75561 100644--- a/surfaces/gui/src/components/Transcript.tsx+++ b/surfaces/gui/src/components/Transcript.tsx@@ -155,7 +155,23 @@ function buildRows(items: TurnItem[]): TurnRow[] {return rows;}-function originChip(origin: string | undefined, note: string | undefined) {+function originChip(origin: string | undefined, note: string | undefined, grant?: string) {+ // Replayed user resolutions reuse the card-chip look (live sessions pair the card itself).+ if (origin === "user") {+ if (grant === "deny")+ return <span className="text-[11px] px-1.5 rounded-full bg-dangerSoft text-danger shrink-0">✕ declined</span>;+ return (+ <span+ className="text-[11px] px-1.5 rounded-full bg-okSoft text-ok shrink-0"+ title={+ `approved by you${grant ? ` · ${grant.replace(/_/g, " ")}` : ""}` ++ (note ? ` — reviewer wasn't sure: ${note}` : "")+ }+ >+ ✓ user-approved+ </span>+ );+ }if (origin !== "reviewer" && origin !== "bypass") return null;return (<span@@ -222,7 +238,7 @@ function StepRow({}/>{approval && approvalChip(approval.resolved)}- {!approval && originChip(tool.approvalOrigin, tool.approvalNote)}+ {!approval && originChip(tool.approvalOrigin, tool.approvalNote, tool.approvalGrant)}{!!tool.standingRule && (<spanclassName="text-[11px] px-1.5 rounded-full bg-tealSoft text-tealInk shrink-0"diff --git a/surfaces/gui/src/itemsFromMessages.ts b/surfaces/gui/src/itemsFromMessages.tsindex 691898c8..1917aa05 100644--- a/surfaces/gui/src/itemsFromMessages.ts+++ b/surfaces/gui/src/itemsFromMessages.ts@@ -16,12 +16,22 @@ export function itemsFromMessages(messages: ConversationMessage[]): Item[] {// `_display` sidecar on a tool message = user-facing metadata the agent never saw// (e.g. how many hits the privacy filters hid) — surfaces on the tool card.const hiddenCounts: Record<string, number> = {};+ // Approval provenance (owner ruling 2026-08-24): who cleared (or refused) the call —+ // "reviewer"/"bypass"/"user"/"reviewer_denied" — persisted in the same sidecar so the+ // quiet chips survive reload.+ const approvalMeta: Record<string, { origin: string; note?: string; grant?: string }> = {};for (const m of messages || []) {if (m.role === "tool" && m.tool_call_id) {results[m.tool_call_id] =typeof m.content === "string" ? m.content : JSON.stringify(m.content);const hidden = Number(m._display?.hidden_by_filters || 0);if (hidden > 0) hiddenCounts[m.tool_call_id] = hidden;+ if (m._display?.approval_origin)+ approvalMeta[m.tool_call_id] = {+ origin: String(m._display.approval_origin),+ ...(m._display.approval_note ? { note: String(m._display.approval_note) } : {}),+ ...(m._display.approval_grant ? { grant: String(m._display.approval_grant) } : {}),+ };}}for (const m of messages || []) {@@ -56,14 +66,24 @@ export function itemsFromMessages(messages: ConversationMessage[]): Item[] {}const preview = results[tc.id];const hidden = hiddenCounts[tc.id];+ const meta = approvalMeta[tc.id];+ // A denial (by the reviewer or the user) must not replay as a green step.+ const denied = meta && (meta.origin === "reviewer_denied" || meta.grant === "deny");items.push({kind: "tool",id: tc.id,name: tc.function?.name,args,- status: "ok",+ status: denied ? "denied" : "ok",preview,...(hidden ? { hidden } : {}),+ ...(meta ? { approvalOrigin: meta.origin } : {}),+ ...(meta?.note+ ? meta.origin === "reviewer_denied"+ ? { reviewerReason: meta.note }+ : { approvalNote: meta.note }+ : {}),+ ...(meta?.grant ? { approvalGrant: meta.grant } : {}),});}} else if (m.role === "notice") {@@ -92,6 +112,11 @@ export function itemsFromMessages(messages: ConversationMessage[]): Item[] {: m.kind === "reviewer_paused"? // §8.4 breaker: auto-approve paused itself for the rest of the turn.{ kind: "notice", tone: "info", text: m.text || "Auto-approve paused for the rest of this turn." }+ : m.kind === "mode_notice"+ ? // The once-per-session Auto-Approve explainer, in place forever.+ { kind: "notice", tone: "info", title: (m as any).title || "Auto-approve is on.", text: m.text || "" }+ : m.kind === "mode_switch"+ ? { kind: "notice", tone: "info", text: m.text || "" }: { kind: "notice", tone: "warn", text: "Error: " + (m.text || "unknown"), retriable: true },);}diff --git a/surfaces/gui/src/modeNotice.test.ts b/surfaces/gui/src/modeNotice.test.tsdeleted file mode 100644index a3cc2d31..00000000--- a/surfaces/gui/src/modeNotice.test.ts+++ /dev/null@@ -1,134 +0,0 @@-import { describe, expect, it } from "vitest";-import {- AUTO_APPROVE_NOTICE,- modeNotice,- modeNoticeStep,- type ModeMark,- type ModeNoticeState,-} from "./modeNotice";--// The transcript has to answer "which mode was this exchange under?" after the fact. The-// full explanation is a once-per-session thing; the markers are what make the log readable.-const S = "session-1";-const mark = (session: string, mode: string): ModeMark => ({ session, mode });--describe("modeNotice", () => {- it("explains Auto-Approve in full the first time a session is in it", () => {- const item = modeNotice("auto-approve", S, null, "");- expect(item).not.toBeNull();- expect(item).toMatchObject({ kind: "notice", tone: "info", title: "Auto-approve is on." });- // The prose, not just the heading — the block layout keys off `title`.- expect((item as { text: string }).text).toBe(AUTO_APPROVE_NOTICE);- });-- it("marks a switch away from Auto-Approve with one line", () => {- const item = modeNotice("discuss", S, mark(S, "auto-approve"), S);- expect(item).toMatchObject({ kind: "notice", tone: "info", text: "Discuss is on." });- expect(item).not.toHaveProperty("title"); // a marker, not the banner- });-- it("marks a switch BACK to Auto-Approve without repeating the explanation", () => {- // The reported behaviour: leaving and returning left no trace at all.- const item = modeNotice("auto-approve", S, mark(S, "discuss"), S);- expect(item).toMatchObject({ text: "Auto-approve is on." });- expect(item).not.toHaveProperty("title");- });-- it("uses the picker's own labels, so the transcript names what the user chose", () => {- expect(modeNotice("interactive", S, mark(S, "discuss"), S)).toMatchObject({- text: "Ask for approval is on.",- });- expect(modeNotice("auto", S, mark(S, "discuss"), S)).toMatchObject({- text: "Bypass approvals is on.",- });- });-- it("says nothing when the mode has not changed", () => {- expect(modeNotice("discuss", S, mark(S, "discuss"), "")).toBeNull();- expect(modeNotice("auto-approve", S, mark(S, "auto-approve"), S)).toBeNull();- });-- it("says nothing on the first render of a session that is not in Auto-Approve", () => {- // No previous mark means nothing to compare against — announcing the starting mode- // would put a marker at the top of every transcript.- expect(modeNotice("interactive", S, null, "")).toBeNull();- });-- it("treats switching sessions as a session change, not a mode change", () => {- // Opening another session that happens to be in a different mode must not read as a- // switch inside this one.- expect(modeNotice("discuss", "session-2", mark(S, "auto-approve"), S)).toBeNull();- });-- it("explains again in a new session, since the first banner scrolled away with the old one", () => {- const item = modeNotice("auto-approve", "session-2", mark(S, "auto-approve"), S);- expect(item).toMatchObject({ title: "Auto-approve is on." });- });-- it("stays silent while the mode is still the previous session's (unconfirmed)", () => {- // On a session switch the app's mode state is stale until the server's `ready` event.- // Acting on it posted the OLD session's banner into a fresh transcript.- const item = modeNotice("auto-approve", "session-2", mark(S, "auto-approve"), S);- // The pure function alone can't tell stale from restored — that's modeNoticeStep's job;- // this pins that the raw call WOULD banner here, so the step's gate is load-bearing.- expect(item).toMatchObject({ title: "Auto-approve is on." });- });-- it("never claims to detect prompt injection", () => {- // The copy is load-bearing: the reviewer cannot spot a normalized injection (OPE-114),- // so the banner must not imply it does. Guarded here because it is the exact overclaim- // the wording was written to avoid.- expect(AUTO_APPROVE_NOTICE.toLowerCase()).not.toContain("injection");- expect(AUTO_APPROVE_NOTICE).toContain("aren't sandboxed");- expect(AUTO_APPROVE_NOTICE).toContain("a false allow executes unchecked");- });-});--// The step function is what the app actually drives: it owns the ordering rules the pure-// function can't see — chiefly that a (mode, session) pair means nothing until the server's-// `ready` event has confirmed the mode belongs to that session.-describe("modeNoticeStep", () => {- const fresh: ModeNoticeState = { mark: null, bannerShownFor: "" };-- // The reported bug, replayed event for event: an Auto-approve session, then "New- // session" (defaulting to Ask for approval). The old code showed the banner from the- // stale mode, then a stray "Ask for approval is on." marker when `ready` landed.- it("a new non-auto session shows neither the banner nor a marker", () => {- // Session 1 is confirmed in auto-approve; the banner shows there.- let r = modeNoticeStep(fresh, "auto-approve", "s1", "s1");- expect(r.item).toMatchObject({ title: "Auto-approve is on." });- // New session: sessionId flips first, mode still stale, ready not yet in. Silence.- r = modeNoticeStep(r.state, "auto-approve", "s2", "s1");- expect(r.item).toBeNull();- // `ready` confirms s2 is in interactive. Still silence — nothing changed, s2-wise.- r = modeNoticeStep(r.state, "interactive", "s2", "s2");- expect(r.item).toBeNull();- });-- it("an unconfirmed pair records nothing — no fake 'switch' when the truth lands", () => {- // If the stale (auto-approve, s2) pair were recorded as s2's mode, ready's- // "interactive" would read as a mode change and print a marker at the transcript top.- let r = modeNoticeStep(fresh, "auto-approve", "s2", "s1");- expect(r.state).toEqual(fresh);- // And the banner must not be marked as "already shown" for s2 either — a session- // genuinely restored into auto-approve still deserves its banner (next test).- expect(r.state.bannerShownFor).toBe("");- });-- it("a session RESTORED into auto-approve still gets the banner once confirmed", () => {- // Switch from an auto-approve session to another auto-approve session: the mode- // VALUE never changes, only the confirmation. The banner must still re-fire.- let r = modeNoticeStep(fresh, "auto-approve", "s1", "s1");- r = modeNoticeStep(r.state, "auto-approve", "s3", "s1"); // stale window- expect(r.item).toBeNull();- r = modeNoticeStep(r.state, "auto-approve", "s3", "s3"); // ready confirms- expect(r.item).toMatchObject({ title: "Auto-approve is on." });- });-- it("an in-session switch still gets its one-line marker", () => {- let r = modeNoticeStep(fresh, "auto-approve", "s1", "s1");- r = modeNoticeStep(r.state, "interactive", "s1", "s1");- expect(r.item).toMatchObject({ text: "Ask for approval is on." });- expect(r.item).not.toHaveProperty("title");- });-});diff --git a/surfaces/gui/src/modeNotice.ts b/surfaces/gui/src/modeNotice.tsdeleted file mode 100644index 4bf7adb0..00000000--- a/surfaces/gui/src/modeNotice.ts+++ /dev/null@@ -1,87 +0,0 @@-// What the transcript records when the permission mode changes.-//-// Two different jobs, deliberately: the first time Auto-Approve is active in a session the-// user gets the full explanation, and every later switch gets a one-line marker. Without-// the marker a transcript is unreadable after the fact — nothing says which mode any given-// exchange ran under, and for a tool built on an auditable trail that matters more than the-// prose does.-import { modeLabel } from "./components/Composer";-import type { Item } from "./types";--// Spec §1.5. Says what the mode buys, what it can never override, and — deliberately-// unhedged — where it can be wrong. It reduces interruptions, not risk, and the closing-// line has to leave that clear.-export const AUTO_APPROVE_NOTICE = [- "Your session model classifies each action and lets the routine ones through without " +- "asking; anything it isn't sure about still comes to you — whatever the rules settle " +- "outright, it never sees.",- "It reduces interruptions from lower-risk actions, not the risk from what it can't tell: " +- "what a script will do, or whether an instruction came from you or from a web page or " +- "email. Shell commands aren't sandboxed — they reach anything you can. These are model " +- "judgments, not guarantees — a false allow executes unchecked.",-].join("\n\n");--/** The mode the transcript was last showing, per session. */-export type ModeMark = { session: string; mode: string } | null;--/**- * The item a mode change should append, or null when nothing should be said.- *- * Pure on purpose: the caller owns the refs, so this stays testable without rendering the- * app. `bannerShownFor` is the session that has already seen the full explanation.- */-export function modeNotice(- mode: string,- sessionId: string,- previous: ModeMark,- bannerShownFor: string,-): Item | null {- // First time this session is in Auto-Approve, however it got there — picked in the- // composer, applied by a plan approval, or restored with the session.- if (mode === "auto-approve" && bannerShownFor !== sessionId) {- return {- kind: "notice",- tone: "info",- title: "Auto-approve is on.",- text: AUTO_APPROVE_NOTICE,- };- }- // A later change WITHIN the same session: mark it, don't re-explain it. Switching- // sessions is not a mode change, so it says nothing — otherwise every session you opened- // would announce the mode it happened to be in.- if (previous && previous.session === sessionId && previous.mode !== mode) {- return { kind: "notice", tone: "info", text: `${modeLabel(mode)} is on.` };- }- return null;-}--/** What the caller carries between mode changes: the last recorded mark and which session- * has already seen the full banner. */-export type ModeNoticeState = { mark: ModeMark; bannerShownFor: string };--/**- * One observed (mode, session) pair → the item to append (or null) plus the next state.- *- * `modeConfirmedFor` is the session the current `mode` value is KNOWN to belong to — on a- * session switch, the app's mode state still holds the previous session's value until the- * server's `ready` event delivers the real one. Acting in that window posts the old- * session's banner into the new transcript, then a stray marker when the truth lands- * (seen 2026-08-22). So an unconfirmed pair is a no-op: nothing said, nothing recorded —- * recording the stale mode would also fake a "switch" once the real mode arrives.- */-export function modeNoticeStep(- state: ModeNoticeState,- mode: string,- sessionId: string,- modeConfirmedFor: string,-): { item: Item | null; state: ModeNoticeState } {- if (modeConfirmedFor !== sessionId) return { item: null, state };- const item = modeNotice(mode, sessionId, state.mark, state.bannerShownFor);- return {- item,- state: {- mark: { session: sessionId, mode },- bannerShownFor: mode === "auto-approve" ? sessionId : state.bannerShownFor,- },- };-}diff --git a/surfaces/gui/src/types.ts b/surfaces/gui/src/types.tsindex b773f2cf..475cfc5c 100644--- a/surfaces/gui/src/types.ts+++ b/surfaces/gui/src/types.ts@@ -21,6 +21,7 @@ export type EventType =| "input_rejected"| "interrupted"| "model_changed"+ | "mode_notice"| "memory_saved"| "compacting"| "compacted"@@ -137,7 +138,7 @@ 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 }+ | { 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 }| {kind: "approval";name: string;diff --git a/tests/test_auto_approve.py b/tests/test_auto_approve.pyindex 1a09be67..a2a35e82 100644--- a/tests/test_auto_approve.py+++ b/tests/test_auto_approve.py@@ -551,6 +551,11 @@ def test_reviewer_allow_runs_without_a_card(tmp_path):# (c) quiet provenance: the finish event says the reviewer allowed it, with its reason.assert finished[0].data["approval_origin"] == "reviewer"assert finished[0].data["approval_note"] == "scripted allow"+ # …and the same facts persist on the tool message's display sidecar, so the chip+ # survives reload (owner ruling 2026-08-24).+ tool_msgs = [m for m in engine.messages if m.get("role") == "tool"]+ assert tool_msgs[-1]["_display"]["approval_origin"] == "reviewer"+ assert tool_msgs[-1]["_display"]["approval_note"] == "scripted allow"verdict_rows = [r for r in rows if r.get("stage") == "reviewer_verdict"]assert verdict_rows[0]["status"] == "allow"@@ -591,6 +596,12 @@ def test_reviewer_unsure_falls_through_to_the_card(tmp_path):# The card answers "why am I being asked?" with the reviewer's own hesitation# (owner ask 2026-08-24) — only on unsure-raised cards, never invented elsewhere.assert cards[0].data["reviewer_unsure"] == "scripted unsure"+ # The user's resolution + the hesitation persist for reload (display sidecar).+ tool_msgs = [m for m in engine.messages if m.get("role") == "tool"]+ d = tool_msgs[-1]["_display"]+ assert d["approval_origin"] == "user"+ assert d["approval_grant"] == "once"+ assert d["approval_note"] == "scripted unsure"def test_five_straight_denials_route_the_rest_of_the_turn_to_the_human(tmp_path):diff --git a/tests/test_server.py b/tests/test_server.pyindex 1cc3cec1..acc18ac2 100644--- a/tests/test_server.py+++ b/tests/test_server.py@@ -1120,3 +1120,51 @@ def test_ws_ready_reports_live_turn(tmp_path):assert ws.receive_json()["data"]["running"] is Truefinally:manager.mark_idle("live1")+++def test_set_mode_persists_notice_once_then_markers(tmp_path):+ # Owner ruling 2026-08-24: the Auto-Approve explainer is server-authored and persisted+ # ONCE per session; later switches persist one-line markers. Restarts re-show nothing.+ manager = SessionManager(workspace=tmp_path, provider=ScriptedProvider([_text("hi")]))+ client = TestClient(create_app(manager))+ with client.websocket_connect("/ws/session/modes1") as ws:+ assert ws.receive_json()["type"] == "ready"+ ws.send_json({"type": "set_mode", "mode": "auto-approve"})+ ev = ws.receive_json()+ assert ev["type"] == "mode_notice"+ assert ev["data"]["title"] == "Auto-approve is on."+ assert "uses a model" in ev["data"]["text"]+ ws.send_json({"type": "set_mode", "mode": "interactive"})+ assert ws.receive_json()["data"] == {"text": "Ask for approval is on."}+ # Re-entering auto-approve: marker, never the banner again.+ ws.send_json({"type": "set_mode", "mode": "auto-approve"})+ assert ws.receive_json()["data"] == {"text": "Auto-approve is on."}++ engine = manager._engines["modes1"]+ kinds = [m.get("kind") for m in engine.messages if m.get("role") == "notice"]+ assert kinds.count("mode_notice") == 1+ assert kinds.count("mode_switch") == 2+++def test_connect_banners_a_session_already_in_auto_approve(tmp_path):+ from coworker.permissions import Mode++ manager = SessionManager(+ workspace=tmp_path,+ provider=ScriptedProvider([_text("hi")]),+ mode=Mode("auto-approve"),+ )+ client = TestClient(create_app(manager))+ with client.websocket_connect("/ws/session/modes2") as ws:+ assert ws.receive_json()["type"] == "ready"+ ev = ws.receive_json()+ assert ev["type"] == "mode_notice" and ev["data"]["title"] == "Auto-approve is on."+ # A reconnect stays quiet: the banner is persisted (asserted below), not re-announced —+ # a set_mode echo of the SAME mode also stays silent (previous is new_mode).+ with client.websocket_connect("/ws/session/modes2") as ws:+ assert ws.receive_json()["type"] == "ready"+ ws.send_json({"type": "set_mode", "mode": "interactive"})+ assert ws.receive_json()["data"] == {"text": "Ask for approval is on."}+ engine = manager._engines["modes2"]+ kinds = [m.get("kind") for m in engine.messages if m.get("role") == "notice"]+ assert kinds.count("mode_notice") == 1