Python
Reconcile ordinary approval cards by exact tool call identity
Rohit C Prasad81a01ff90140
diff --git a/coworker/engine.py b/coworker/engine.pyindex 5bd4ba16..676538c1 100644--- a/coworker/engine.py+++ b/coworker/engine.py@@ -1086,6 +1086,7 @@ class TurnEngine:allowed = Falseasync for item in self._authorize(tool_call):if isinstance(item, Event):+ item.data["tool_call_id"] = tool_call.idyield itemelse:allowed = item@@ -1159,7 +1160,7 @@ class TurnEngine:)return Event(EventType.TOOL_FINISHED,- {"name": tool_call.name, "status": "interrupted", "reason": "stopped"},+ {"name": tool_call.name, "tool_call_id": tool_call.id, "status": "interrupted", "reason": "stopped"},)def _parallel_safe(self, tool_call: ToolCall) -> bool:@@ -1926,6 +1927,7 @@ class TurnEngine:{"name": tool_call.name,"status": status,+ "tool_call_id": tool_call.id,"result_preview": _preview(result),**({"display": display} if display else {}),**({"standing_rule": rule} if rule else {}),diff --git a/surfaces/gui/e2e/worker-approval.spec.ts b/surfaces/gui/e2e/worker-approval.spec.tsindex 08b5410a..7cbed644 100644--- a/surfaces/gui/e2e/worker-approval.spec.ts+++ b/surfaces/gui/e2e/worker-approval.spec.ts@@ -1,6 +1,37 @@import { expect } from "@playwright/test";import { test, sendSessionEvent } from "./fixtures";+test("ordinary approval answered elsewhere retires on exact tool completion", async ({ page }) => {+ await page.goto("/");+ await sendSessionEvent(page, { type: "permission_required", data: {+ name: "github_clone", tool_call_id: "clone-old", arguments: { owner: "acme", repo: "billing-service" },+ } });+ await expect(page.getByRole("button", { name: "Allow once", exact: true })).toBeVisible();+ await sendSessionEvent(page, { type: "tool_finished", data: {+ name: "github_clone", tool_call_id: "unrelated", status: "ok",+ } });+ await expect(page.getByRole("button", { name: "Allow once", exact: true })).toBeVisible();+ await sendSessionEvent(page, { type: "tool_finished", data: {+ name: "github_clone", tool_call_id: "clone-old", status: "ok",+ } });+ await expect(page.getByRole("button", { name: "Allow once", exact: true })).toHaveCount(0);+});++test("ordinary approval answered elsewhere retires through poll when completion is missed", async ({ page }) => {+ let resolved = false;+ await page.route("**/v1/inbox?**", async route => {+ await route.fulfill({ json: { items: resolved ? [{ id: "clone-gate", kind: "approval", state: "resolved",+ tool_call_id: "clone-poll", resolution: "deny" }] : [] } });+ });+ await page.goto("/");+ await sendSessionEvent(page, { type: "permission_required", data: {+ name: "github_clone", tool_call_id: "clone-poll", arguments: { owner: "acme", repo: "billing-service" },+ } });+ await expect(page.getByRole("button", { name: "Allow once", exact: true })).toBeVisible();+ resolved = true;+ await expect(page.getByRole("button", { name: "Allow once", exact: true })).toHaveCount(0, { timeout: 10000 });+});+for (const suggestion of ["allow", "deny"]) {test(`overriding a lead ${suggestion} answers the exact worker request`, async ({ page }) => {const answers: Array<{ id: string; resolution: string }> = [];diff --git a/surfaces/gui/src/cardPayloads.ts b/surfaces/gui/src/cardPayloads.tsindex bbe0ddc0..e2c22ef5 100644--- a/surfaces/gui/src/cardPayloads.ts+++ b/surfaces/gui/src/cardPayloads.ts@@ -22,6 +22,7 @@ export type QuestionItem = Extract<Item, { kind: "question" }>;export function approvalItemFromPayload(d: any): ApprovalItem {return {kind: "approval",+ toolCallId: typeof d.tool_call_id === "string" ? d.tool_call_id : undefined,name: d.name,args: d.arguments,reason: d.reason,diff --git a/surfaces/gui/src/components/InboxItemCard.tsx b/surfaces/gui/src/components/InboxItemCard.tsxindex 5a2a28a4..82ef7aa8 100644--- a/surfaces/gui/src/components/InboxItemCard.tsx+++ b/surfaces/gui/src/components/InboxItemCard.tsx@@ -65,6 +65,7 @@ export function approvalItemFromParked(item: InboxItem): Extract<Item, { kind: "if (item.kind !== "approval" || !d?.tool) return null;return {kind: "approval",+ toolCallId: item.tool_call_id || undefined,name: String(d.tool),args: d.arguments ?? {},escalation: d.escalation,diff --git a/surfaces/gui/src/gateReconciliation.test.ts b/surfaces/gui/src/gateReconciliation.test.tsindex e53faa96..5a845a69 100644--- a/surfaces/gui/src/gateReconciliation.test.ts+++ b/surfaces/gui/src/gateReconciliation.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { teamItemFromPayload, workItemsItemFromPayload } from "./cardPayloads";+import { approvalItemFromPayload, teamItemFromPayload, workItemsItemFromPayload } from "./cardPayloads";import { reconcileResolvedGates, retireFinishedGate } from "./gateReconciliation";import type { InboxItem } from "./api";@@ -35,4 +35,21 @@ describe("cross-surface gate reconciliation", () => {expect(reconcileResolvedGates(items, [])).toBe(items);expect(reconcileResolvedGates(items, [{ state: "resolved" }] as InboxItem[])).toBe(items);});+ it("matches ordinary approvals by exact call ID, never tool name alone", () => {+ const a = approvalItemFromPayload({ name: "github_clone", tool_call_id: "clone-old" });+ const b = approvalItemFromPayload({ name: "github_clone", tool_call_id: "clone-new" });+ const unknown = approvalItemFromPayload({ name: "github_clone" });+ expect(retireFinishedGate([a, b, unknown], "github_clone", "clone-old")).toEqual([b, unknown]);+ expect(retireFinishedGate([a, b], "github_clone")).toEqual([a, b]);+ expect(retireFinishedGate([a], "run_shell", "clone-old")).toEqual([a]);+ });+ it.each(["allow", "deny", "interrupted"])("poll retires a resolved approval (%s) only", resolution => {+ const a = approvalItemFromPayload({ name: "run_shell", tool_call_id: "a" });+ const b = approvalItemFromPayload({ name: "run_shell", tool_call_id: "b" });+ expect(reconcileResolvedGates([a, b], [+ { state: "resolved", tool_call_id: "a", resolution },+ { state: "pending", tool_call_id: "b" },+ ] as InboxItem[])).toEqual([b]);+ expect(reconcileResolvedGates([b], [])).toEqual([b]);+ });});diff --git a/surfaces/gui/src/gateReconciliation.ts b/surfaces/gui/src/gateReconciliation.tsindex 09289fd5..b0a7a1a6 100644--- a/surfaces/gui/src/gateReconciliation.ts+++ b/surfaces/gui/src/gateReconciliation.ts@@ -5,8 +5,11 @@ import type { Item } from "./types";* Never match by title, roster or "last proposal": a newer gate can look identical. */export function retireFinishedGate(items: Item[], name: string, toolCallId?: string): Item[] {const kind = name === "propose_team" ? "teamreq" : name === "propose_work_items" ? "itemsreq" : null;- if (!kind || !toolCallId) return items;- return items.filter(item => !(item.kind === kind && item.toolCallId === toolCallId));+ if (!toolCallId) return items;+ const remaining = items.filter(item => !(((kind && item.kind === kind) ||+ (item.kind === "approval" && item.name === name)) &&+ "toolCallId" in item && item.toolCallId === toolCallId));+ return remaining.length === items.length ? items : remaining;}/** Poll fallback for a missed socket event. Absence from the pending list is NOT@@ -15,6 +18,6 @@ export function reconcileResolvedGates(items: Item[], inbox: InboxItem[]): Item[const resolved = new Set(inbox.filter(i => i.state === "resolved" && i.tool_call_id).map(i => i.tool_call_id));if (!resolved.size) return items;- return items.filter(item => !((item.kind === "teamreq" || item.kind === "itemsreq")+ return items.filter(item => !((item.kind === "teamreq" || item.kind === "itemsreq" || item.kind === "approval")&& item.toolCallId && resolved.has(item.toolCallId)));}diff --git a/surfaces/gui/src/types.ts b/surfaces/gui/src/types.tsindex e209f186..d57aa7f4 100644--- a/surfaces/gui/src/types.ts+++ b/surfaces/gui/src/types.ts@@ -161,6 +161,7 @@ export type Item =| { 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";+ toolCallId?: string;name: string;args: any;reason: string;diff --git a/tests/test_team_live_gaps.py b/tests/test_team_live_gaps.pyindex 36455dbe..75ce80e6 100644--- a/tests/test_team_live_gaps.py+++ b/tests/test_team_live_gaps.py@@ -252,6 +252,23 @@ def test_superseded_gate_never_executes_or_grants_permission(tmp_path):assert "already resolved" in finished[0].data["result_preview"][email protected]("answer", [ApprovalOutcome.ONCE, ApprovalOutcome.DENY, ApprovalOutcome.SUPERSEDED])+def test_ordinary_approval_and_completion_carry_the_same_exact_call_id(tmp_path, answer):+ async def approve(request):+ assert request.tool_call_id == "unique-write-call"+ return answer++ engine, _ = _engine(tmp_path, [+ _tool_turn("write_file", {"path": "result.txt", "content": "sample"}, call_id="unique-write-call"),+ _text_turn("Finished"),+ ], approver=approve)+ events = _collect(engine, "Write the sample file.")+ for kind in ("permission_required", "tool_finished"):+ event = next(e for e in events if e.type.value == kind)+ assert event.data["tool_call_id"] == "unique-write-call"+ assert (tmp_path / "result.txt").exists() == (answer is ApprovalOutcome.ONCE)++def test_background_delivery_enriches_actual_permission_event_and_retires_gate(manager, monkeypatch):