Python
Synchronize resolved team proposal cards across views
Rohit C Prasad4f9e79c751ff
diff --git a/coworker/engine.py b/coworker/engine.pyindex 5fe1d4a0..93a7f0c3 100644--- a/coworker/engine.py+++ b/coworker/engine.py@@ -1918,7 +1918,7 @@ class TurnEngine:else:yield Event(EventType.ITEMS_PROPOSED,- {"items": valid, "note": str(args.get("note", ""))},+ {"items": valid, "note": str(args.get("note", "")), "tool_call_id": tool_call.id},)self._audit(tool_call, stage="items_proposed")result = await self._wait_tool(tool_call,@@ -1941,6 +1941,7 @@ class TurnEngine:"name": tool_call.name,"status": status,"result_preview": _preview(result),+ "tool_call_id": tool_call.id,},)@@ -2006,6 +2007,7 @@ class TurnEngine:yield Event(EventType.TEAM_PROPOSED,{+ "tool_call_id": tool_call.id,"members": members,"enable_chat": bool(args.get("enable_chat", False)),"note": str(args.get("note", "")),@@ -2038,6 +2040,7 @@ class TurnEngine:"status": status,"result_preview": _preview(result),"display": {"team_created": created} if created else {},+ "tool_call_id": tool_call.id,},)diff --git a/surfaces/gui/e2e/fixtures.ts b/surfaces/gui/e2e/fixtures.tsindex 996c3dc7..ecafc674 100644--- a/surfaces/gui/e2e/fixtures.ts+++ b/surfaces/gui/e2e/fixtures.ts@@ -6,6 +6,15 @@ import { statePayload, type CardId } from "../src/gallery/states";// The app-wide /ws/events socket each page opened (UX-026 toast et al.) — specs// push server events through it via sendAppEvent below.const eventSockets = new WeakMap<Page, { send: (data: string) => void }>();+const sessionSockets = new WeakMap<Page, { send: (data: string) => void }>();++/** Simulate a session event caused by another viewer/API client. */+export async function sendSessionEvent(page: Page, obj: unknown): Promise<void> {+ for (let i = 0; i < 50 && !sessionSockets.get(page); i++) await page.waitForTimeout(100);+ const ws = sessionSockets.get(page);+ if (!ws) throw new Error("the app never opened its session socket");+ ws.send(JSON.stringify(obj));+}/** Push an app-wide event exactly as the server would over /ws/events. Waits for* the GUI to have connected its socket first. */@@ -681,6 +690,7 @@ export async function mockApi(page: import("@playwright/test").Page) {});await page.routeWebSocket(/\/ws\/session\//, (ws) => {+ sessionSockets.set(page, ws);const send = (type: string, data: Record<string, unknown> = {}) =>ws.send(JSON.stringify({ type, data }));const sendState = (type: string, card: CardId, id: string) => send(type, statePayload(card, id));diff --git a/surfaces/gui/e2e/gate-sync.spec.ts b/surfaces/gui/e2e/gate-sync.spec.tsnew file mode 100644index 00000000..f92b4ef3--- /dev/null+++ b/surfaces/gui/e2e/gate-sync.spec.ts@@ -0,0 +1,60 @@+import { expect } from "@playwright/test";+import { test, sendSessionEvent } from "./fixtures";++for (const gate of [+ { event: "team_proposed", name: "propose_team", card: "teamreq-card", payload: { members: [{ persona: "test-worker", name: "Sam" }] } },+ { event: "items_proposed", name: "propose_work_items", card: "itemsreq-card", payload: { items: [{ title: "Verify invoices", criteria: "Tests pass" }] } },+]) {+ for (const status of ["ok", "denied"]) {+ test(`${gate.name}: external ${status} clears the live card without reload`, async ({ page }) => {+ await page.goto("/");+ await sendSessionEvent(page, { type: gate.event, data: { ...gate.payload, tool_call_id: "proposal" } });+ await expect(page.getByTestId(gate.card)).toBeVisible();+ await sendSessionEvent(page, { type: "tool_finished", data: { name: gate.name, tool_call_id: "unrelated", status } });+ await expect(page.getByTestId(gate.card)).toBeVisible();+ await sendSessionEvent(page, { type: "tool_finished", data: { name: gate.name, tool_call_id: "proposal", status } });+ await expect(page.getByTestId(gate.card)).toHaveCount(0);+ await expect(page.getByPlaceholder(/Ask the coworker/)).toBeVisible();+ });+ }+ test(`${gate.name}: polling repairs a missed completion event`, async ({ page }) => {+ let resolved = false;+ await page.route(/\/v1\/inbox(?:\?|$)/, route => route.fulfill({+ json: { items: resolved ? [{ id: "inbox-proposal", tool_call_id: "proposal", state: "resolved", kind: "plan",+ resolution: '{"approved":true}', data: { gate: gate.name === "propose_team" ? "team" : "items" } }] : [] },+ }));+ await page.goto("/");+ await sendSessionEvent(page, { type: gate.event, data: { ...gate.payload, tool_call_id: "proposal" } });+ await expect(page.getByTestId(gate.card)).toBeVisible();+ resolved = true;+ await expect(page.getByTestId(gate.card)).toHaveCount(0, { timeout: 7000 });+ });+}++test("an older pending Inbox response cannot resurrect a completed staffing card", async ({ page }) => {+ let release: (() => void) | undefined;+ let hold = false;+ let intercepted = false;+ await page.route(/\/v1\/inbox(?:\?|$)/, async route => {+ if (hold) {+ intercepted = true;+ await new Promise<void>(resolve => { release = resolve; });+ await route.fulfill({ json: { items: [{ id: "old-inbox", tool_call_id: "proposal", state: "pending", kind: "plan",+ title: "Create this team?", data: { gate: "team", members: [{ persona: "test-worker", name: "Sam" }] } }] } });+ } else {+ await route.fulfill({ json: { items: [] } });+ }+ });+ await page.goto("/");+ await sendSessionEvent(page, { type: "team_proposed", data: { tool_call_id: "proposal", members: [{ persona: "test-worker", name: "Sam" }] } });+ await expect(page.getByTestId("teamreq-card")).toBeVisible();+ hold = true;+ await expect.poll(() => intercepted, { timeout: 6000 }).toBe(true);+ await sendSessionEvent(page, { type: "tool_finished", data: { name: "propose_team", tool_call_id: "proposal", status: "ok" } });+ await expect(page.getByTestId("teamreq-card")).toHaveCount(0);+ hold = false;+ release?.();+ await page.waitForTimeout(200);+ await expect(page.getByTestId("teamreq-card")).toHaveCount(0);+ await expect(page.getByRole("button", { name: "Create team", exact: true })).toHaveCount(0);+});diff --git a/surfaces/gui/src/App.tsx b/surfaces/gui/src/App.tsxindex 5bbd8aff..062a4a62 100644--- a/surfaces/gui/src/App.tsx+++ b/surfaces/gui/src/App.tsx@@ -84,6 +84,7 @@ import { SessionSetupRow } from "./components/SessionSetupRow";import { SendFolderDialog } from "./components/SendFolderDialog";import { Onboarding } from "./components/Onboarding";import { UpdateBanner } from "./components/UpdateBanner";+import { reconcileResolvedGates, retireFinishedGate } from "./gateReconciliation";import { ScheduledView } from "./components/ScheduledView";import { RightRail } from "./components/RightRail";import { SettingsView, type SetTab } from "./components/SettingsView";@@ -518,6 +519,11 @@ export function App() {// unattended session's blocking question/approval can be answered in context (resolving the// same item the Inbox shows; first responder wins).const [sessionInbox, setSessionInbox] = useState<InboxItem[]>([]);+ const finishedGateCalls = useRef(new Map<string, Set<string>>());+ const gateScope = `${machine || "local"}:${sessionId}`;+ const pendingInbox = useCallback((inbox: InboxItem[]) => inbox.filter(it =>+ it.state === "pending" && !(it.tool_call_id && finishedGateCalls.current.get(gateScope)?.has(it.tool_call_id)),+ ), [gateScope]);// Whether the active session is Unattended — when true, the agent's prompts route to the Inbox,// so we suppress the inline live cards (the Inbox / answer-in-context path shows them instead).// A ref too, because the WS event handler closes over stale state.@@ -536,7 +542,7 @@ export function App() {};const resolveSessionInbox = async (id: string, resolution: string) => {await resolveInboxItem(id, resolution);- getInbox(sessionId, "pending").then(setSessionInbox).catch(() => setSessionInbox([]));+ getInbox(sessionId, "pending").then(inbox => setSessionInbox(pendingInbox(inbox))).catch(() => {});refreshSessions(); // attention badge should drop right away};// MUST pick a folder before starting — requires_folder personas (git-bound Code, the@@ -971,6 +977,15 @@ export function App() {setItems((p) => [...p, questionItemFromPayload(d)]);break;case "tool_finished":+ if (d.tool_call_id && (d.name === "propose_team" || d.name === "propose_work_items")) {+ const calls = finishedGateCalls.current.get(gateScope) || new Set<string>();+ calls.add(d.tool_call_id);+ finishedGateCalls.current.set(gateScope, calls);+ }+ setItems(p => retireFinishedGate(p, d.name, d.tool_call_id));+ if (d.tool_call_id) {+ setSessionInbox(p => p.filter(it => it.tool_call_id !== d.tool_call_id));+ }if (d.superseded_worker_call) {// Retire exactly the decision whose worker prompt was answered// elsewhere. The tool result remains as the non-action audit receipt.@@ -1120,7 +1135,7 @@ export function App() {setUsage(usageFromMessages(m));}).catch(() => {});- getInbox(sessionId, "pending").then(setSessionInbox).catch(() => {});+ getInbox(sessionId, "pending").then(inbox => setSessionInbox(pendingInbox(inbox))).catch(() => {});return;}// Auto-send the pending message once the session connects ("Run now" prompts and@@ -1267,14 +1282,23 @@ export function App() {// change + after each turn, plus a slow poll so an unattended agent's new question surfaces.useEffect(() => {if (surface !== "session") return;+ let canceled = false;+ let request = 0;const load = () => {- getInbox(sessionId, "pending").then(setSessionInbox).catch(() => setSessionInbox([]));- getUnattended(sessionId).then(markUnattended).catch(() => markUnattended(false));+ const current = ++request;+ getInbox(sessionId).then(inbox => {+ if (canceled || current !== request) return;+ setSessionInbox(pendingInbox(inbox));+ setItems(items => reconcileResolvedGates(items, inbox));+ }).catch(() => {});+ getUnattended(sessionId).then(value => {+ if (!canceled && current === request) markUnattended(value);+ }).catch(() => {});};load();const t = setInterval(load, 4000);- return () => clearInterval(t);- }, [surface, sessionId, browserRefreshKey, markUnattended]);+ return () => { canceled = true; clearInterval(t); };+ }, [surface, sessionId, browserRefreshKey, markUnattended, pendingInbox]);const send = (text: string, attachments?: Attachment[], skill?: string) => {// UX-029: folder enforcement AT SEND. A code-family session with no folder has nodiff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.tsindex 6b53ee9c..e8851980 100644--- a/surfaces/gui/src/api.ts+++ b/surfaces/gui/src/api.ts@@ -1810,6 +1810,7 @@ export async function setSessionSkill(// -- Inbox + Unattended -------------------------------------------------------export interface InboxItem {id: string;+ tool_call_id?: string;session_id: string;kind: "approval" | "question" | "notification" | "directory" | "plan" | "tool" | "connector";title: string;diff --git a/surfaces/gui/src/cardPayloads.ts b/surfaces/gui/src/cardPayloads.tsindex 97d1d455..c36533b9 100644--- a/surfaces/gui/src/cardPayloads.ts+++ b/surfaces/gui/src/cardPayloads.ts@@ -46,6 +46,7 @@ export function planItemFromPayload(d: any): PlanItem {export function teamItemFromPayload(d: any): TeamRequestItem {return {kind: "teamreq",+ toolCallId: typeof d.tool_call_id === "string" ? d.tool_call_id : undefined,members: Array.isArray(d.members) ? d.members : [],enable_chat: !!d.enable_chat,note: d.note || "",@@ -71,7 +72,8 @@ export function connectorItemFromPayload(d: any): ConnectorRequestItem {/** `items_proposed`, or a parked `gate: "items"` item. */export function workItemsItemFromPayload(d: any): WorkItemsItem {- return { kind: "itemsreq", items: Array.isArray(d.items) ? d.items : [], note: d.note || "" };+ return { kind: "itemsreq", toolCallId: typeof d.tool_call_id === "string" ? d.tool_call_id : undefined,+ items: Array.isArray(d.items) ? d.items : [], note: d.note || "" };}/** `directory_requested`. */diff --git a/surfaces/gui/src/gateReconciliation.test.ts b/surfaces/gui/src/gateReconciliation.test.tsnew file mode 100644index 00000000..e53faa96--- /dev/null+++ b/surfaces/gui/src/gateReconciliation.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from "vitest";+import { teamItemFromPayload, workItemsItemFromPayload } from "./cardPayloads";+import { reconcileResolvedGates, retireFinishedGate } from "./gateReconciliation";+import type { InboxItem } from "./api";++describe("cross-surface gate reconciliation", () => {+ const old = teamItemFromPayload({ tool_call_id: "old", members: [] });+ const newer = teamItemFromPayload({ tool_call_id: "new", members: [] });+ const split = workItemsItemFromPayload({ tool_call_id: "split", items: [] });+ const legacy = teamItemFromPayload({ members: [] });++ it("retains server identity and retires only the exact completed proposal", () => {+ expect(old.toolCallId).toBe("old");+ expect(retireFinishedGate([old, newer, split, legacy], "propose_team", "old"))+ .toEqual([newer, split, legacy]);+ expect(retireFinishedGate([old, split], "propose_work_items", "split")).toEqual([old]);+ });+ it("does not guess for old servers, unrelated results, or unknown IDs", () => {+ const items = [old, newer, legacy];+ expect(retireFinishedGate(items, "propose_team")).toBe(items);+ expect(retireFinishedGate(items, "run_shell", "old")).toBe(items);+ expect(retireFinishedGate(items, "propose_team", "missing")).toEqual(items);+ });+ it.each([JSON.stringify({ approved: true }), JSON.stringify({ approved: false }), "interrupted"])(+ "reconciles a persisted resolution (%s) without dismissing a pending replacement", resolution => {+ const inbox = [+ { state: "resolved", tool_call_id: "old", resolution },+ { state: "pending", tool_call_id: "new" },+ ] as InboxItem[];+ expect(reconcileResolvedGates([old, newer, split, legacy], inbox)).toEqual([newer, split, legacy]);+ },+ );+ it("does not infer resolution from a missing Inbox row", () => {+ const items = [old, split, legacy];+ expect(reconcileResolvedGates(items, [])).toBe(items);+ expect(reconcileResolvedGates(items, [{ state: "resolved" }] as InboxItem[])).toBe(items);+ });+});diff --git a/surfaces/gui/src/gateReconciliation.ts b/surfaces/gui/src/gateReconciliation.tsnew file mode 100644index 00000000..09289fd5--- /dev/null+++ b/surfaces/gui/src/gateReconciliation.ts@@ -0,0 +1,20 @@+import type { InboxItem } from "./api";+import type { Item } from "./types";++/** Completion is authoritative, regardless of which surface supplied the answer.+ * 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));+}++/** Poll fallback for a missed socket event. Absence from the pending list is NOT+ * proof of resolution: a proposal event can arrive before the Inbox row exists. */+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")+ && item.toolCallId && resolved.has(item.toolCallId)));+}diff --git a/surfaces/gui/src/types.ts b/surfaces/gui/src/types.tsindex 081fa58d..762c9048 100644--- a/surfaces/gui/src/types.ts+++ b/surfaces/gui/src/types.ts@@ -217,6 +217,7 @@ export type Item =| {// The staffing gate (agent teams): a lead proposes its worker roster.kind: "teamreq";+ toolCallId?: string;// connectors = the LEAD'S SUGGESTION for this worker (arrives ticked on the card);// connector_reasons = why, per suggested connector.members: {@@ -261,6 +262,7 @@ export type Item =| {// The decomposition gate: a lead proposes work items; approval creates them.kind: "itemsreq";+ toolCallId?: string;items: { title: string; criteria: string; description?: string }[];note?: string;resolved?: "approved" | "rejected";diff --git a/tests/test_gate_sync.py b/tests/test_gate_sync.pynew file mode 100644index 00000000..eed3631e--- /dev/null+++ b/tests/test_gate_sync.py@@ -0,0 +1,50 @@+"""The same stable gate identity reaches every viewing socket on external resolution."""+import asyncio++import pytest++from test_engine import ScriptedProvider, _text_turn, _tool_turn+from test_team_live_gaps import manager++[email protected]("approved", [True, False])[email protected]("name,args,event_name", [+ ("propose_team", {"members": [{"persona": "test-worker", "name": "Sam"}]}, "team_proposed"),+ ("propose_work_items", {"items": [{"title": "Verify invoices", "criteria": "Tests pass"}]}, "items_proposed"),+])+def test_external_gate_answer_broadcasts_matching_completion_to_all_viewers(manager, approved, name, args, event_name):+ manager.provider = ScriptedProvider([_tool_turn(name, args, "proposal-id"), _text_turn("Finished")])+ engine = manager.get_engine("lead")+ views = [[], []]++ async def run():+ for view in views:+ async def receive(event, view=view):+ view.append(event)+ manager.register_session_client("lead", receive)++ async def ask(args, tool_call_id):+ item = manager.inbox.add_plan("lead", "Approve?", tool_call_id=tool_call_id)+ return {"approved": (await manager.inbox.wait(item.id)) == "allow"}++ if name == "propose_team":+ engine.team_approver = ask+ else:+ engine.items_approver = ask+ turn = asyncio.create_task(manager.deliver_to_session("lead", "Propose the work"))+ for _ in range(100):+ await asyncio.sleep(.01)+ pending = manager.inbox.pending("lead")+ if pending:+ break+ assert pending+ # The shared path used by REST/Inbox, not a foreground socket response.+ assert await manager.resolve_inbox(pending[0].id, "allow" if approved else "deny", by="second-viewer")+ await asyncio.wait_for(turn, 3)++ asyncio.run(run())+ for view in views:+ proposed = next(e for e in view if e["type"] == event_name)+ finished = next(e for e in view if e["type"] == "tool_finished" and e["data"]["name"] == name)+ assert proposed["data"]["tool_call_id"] == finished["data"]["tool_call_id"] == "proposal-id"+ assert finished["data"]["status"] == ("ok" if approved else "denied")