Multiplayer agent harness for work.
Send inbox loop-item changes only to the users who can see the loop (#2002)
Sina Matian7a0b6d987dd2
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex c0e2f53d1..33b3156ce 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -643,17 +643,34 @@ function runInboxFeed(): Promise<void> {return consumeCoreFeed("/v1/loop-items/events","loop_item",- (data) => {- const ev = data as { owner?: string; loopId?: string; itemId?: string; op?: string };- if (!ev.owner || !ev.loopId || !ev.itemId) return;- for (const clients of deliveryClients.values()) for (const res of clients) sseEvent(res, "inbox_resync", {});- },- () => {- for (const conns of deliveryClients.values()) for (const res of conns) sseEvent(res, "inbox_resync", {});- },+ (data) => void forwardInboxItem(data as { loopId?: string; itemId?: string; op?: string }),+ resyncInbox,);}+function resyncInbox(): void {+ for (const conns of deliveryClients.values()) for (const res of conns) sseEvent(res, "inbox_resync", {});+}++async function forwardInboxItem(ev: { loopId?: string; itemId?: string; op?: string }): Promise<void> {+ if (!ev.loopId || !ev.itemId || !deliveryClients.size) return;+ const r = await coreFetch(+ "POST",+ "/v1/inbox/viewers",+ JSON.stringify({ loopId: ev.loopId, candidates: [...deliveryClients.keys()] }),+ ).catch(() => null);+ if (r?.status === 404) return;+ let viewers: string[] | undefined;+ try {+ viewers = r?.status === 200 ? (JSON.parse(r.text) as { viewers?: string[] }).viewers : undefined;+ } catch {+ viewers = undefined;+ }+ if (!viewers) return resyncInbox();+ const frame = { loopId: ev.loopId, itemId: ev.itemId, op: ev.op ?? "" };+ for (const user of viewers) for (const res of deliveryClients.get(user) ?? []) sseEvent(res, "inbox_item", frame);+}+async function coreFetch(method: HttpMethod,pathWithQuery: string,diff --git a/plugins/web-ui/src/inbox.ts b/plugins/web-ui/src/inbox.tsindex b07c8a0b6..815f19e2e 100644--- a/plugins/web-ui/src/inbox.ts+++ b/plugins/web-ui/src/inbox.ts@@ -34,7 +34,7 @@ import { embeddedComposer } from "./embedded-composer";import type { ComposerSubmission } from "./composer";import { api, ApiError, putUiState } from "./core-bridge";import { onInboxItemEvent, onInboxResync } from "./conversations";-import { createInboxEventCoalescer, type InboxItemRef } from "./inbox-coalesce";+import { createInboxEventCoalescer } from "./inbox-coalesce";import { charForName, ensureEmojiIndex } from "./emoji-picker";import type { DensityTier } from "./density";import { deepLinkPath, UI_BASE } from "./deep-link";@@ -797,11 +797,15 @@ let realtimeWired = false;const enqueueRealtimeEvent = createInboxEventCoalescer(250,- (batch) => void applyRealtimeBatch(batch),+ () => void refreshWhenVisible(),(fn, ms) => void window.setTimeout(fn, ms),);-async function applyRealtimeBatch(_batch: InboxItemRef[]): Promise<void> {+async function refreshWhenVisible(): Promise<void> {+ if (document.visibilityState !== "visible" || !anySurfaceVisible()) {+ resyncMissedWhileHidden = true;+ return;+ }await refreshInbox({ silent: true });}@@ -815,16 +819,12 @@ function ensureRealtime(): void {realtimeWired = true;onInboxItemEvent((event) => {if (!can("inbox")) return;- if (!inboxState.selected.some((loop) => loop.id === event.loopId)) return;+ if (inboxState.loaded && !inboxState.selected.some((loop) => loop.id === event.loopId)) return;enqueueRealtimeEvent({ loopId: event.loopId, itemId: event.itemId });});onInboxResync(() => {if (!can("inbox")) return;- if (document.visibilityState !== "visible" || !anySurfaceVisible()) {- resyncMissedWhileHidden = true;- return;- }- void refreshInbox({ silent: true });+ void refreshWhenVisible();});document.addEventListener("visibilitychange", () => {if (document.visibilityState !== "visible" || !anySurfaceVisible()) return;diff --git a/plugins/web-ui/test/inbox-feed-resync.test.ts b/plugins/web-ui/test/inbox-feed-resync.test.tsindex 7395951d4..4925f2a1c 100644--- a/plugins/web-ui/test/inbox-feed-resync.test.ts+++ b/plugins/web-ui/test/inbox-feed-resync.test.ts@@ -7,14 +7,25 @@ const coreBridge = readFileSync(new URL("../src/core-bridge.ts", import.meta.urlconst conversations = readFileSync(new URL("../src/conversations.ts", import.meta.url), "utf8");const inbox = readFileSync(new URL("../src/inbox.ts", import.meta.url), "utf8");-test("the BFF's inbox feed announces reconnects, mirroring the session-state feed", () => {+test("the BFF sends each loop-item change only to its viewers and resyncs everyone only on reconnect", () => {const feed = server.match(/function runInboxFeed\(\): Promise<void> \{[\s\S]*?\n\}/)?.[0] ?? "";assert.match(feed, /consumeCoreFeed\(\s*"\/v1\/loop-items\/events",\s*"loop_item",/);+ assert.match(feed, /forwardInboxItem\([\s\S]*?\),\s*resyncInbox,/);+ const forward = server.match(/async function forwardInboxItem\([\s\S]*?\n\}/)?.[0] ?? "";assert.match(- feed,- /sseEvent\(res, "inbox_resync", \{\}\)/,- "a re-established core feed tells every browser to refetch the inbox",+ forward,+ /"\/v1\/inbox\/viewers",\s*JSON\.stringify\(\{ loopId: ev\.loopId, candidates: \[\.\.\.deliveryClients\.keys\(\)\] \}\)/,);+ assert.match(+ forward,+ /for \(const user of viewers\) for \(const res of deliveryClients\.get\(user\) \?\? \[\]\) sseEvent\(res, "inbox_item", frame\);/,+ );+ assert.match(+ forward,+ /if \(!viewers\) return resyncInbox\(\);/,+ "an unanswerable viewer lookup falls back to a resync, so nobody misses a change",+ );+ assert.doesNotMatch(forward, /inbox_resync/);});test("the BFF treats a core-side resync frame like a dropped feed", () => {@@ -22,9 +33,9 @@ test("the BFF treats a core-side resync frame like a dropped feed", () => {assert.match(consume, /event: \$\{eventName\}_resync`\)\) \{\s*onReconnect\?\.\(\);\s*continue;/);});-test("a resync while the inbox is hidden marks it stale, and the next staleness-gated refresh consumes the mark", () => {- const wired = inbox.match(/onInboxResync\(\(\) => \{[\s\S]*?\n {2}\}\);/)?.[0] ?? "";- assert.match(wired, /resyncMissedWhileHidden = true;\s*return;/);+test("a resync or item event while the inbox is hidden marks it stale, and the next staleness-gated refresh consumes the mark", () => {+ const gate = inbox.match(/async function refreshWhenVisible[\s\S]*?\n\}/)?.[0] ?? "";+ assert.match(gate, /resyncMissedWhileHidden = true;\s*return;\s*\}\s*await refreshInbox\(\{ silent: true \}\);/);const refresh = inbox.match(/export async function refreshInbox[\s\S]*?\n\}/)?.[0] ?? "";assert.match(refresh,@@ -48,14 +59,17 @@ test("the browser handles inbox_resync frames and treats its own reconnect the stest("a resync lands as a silent inbox refresh", () => {assert.match(conversations, /\(\) => inboxResyncHandler\?\.\(\)/);const wired = inbox.match(/onInboxResync\(\(\) => \{[\s\S]*?\}\);/)?.[0] ?? "";- assert.match(wired, /refreshInbox\(\{ silent: true \}\)/);+ assert.match(wired, /void refreshWhenVisible\(\);/);});test("realtime inbox events flow through the coalescer, so a burst refetches every touched item", () => {assert.match(inbox, /enqueueRealtimeEvent\(\{ loopId: event\.loopId, itemId: event\.itemId \}\);/);- assert.match(inbox, /createInboxEventCoalescer\(/);- const flush = inbox.match(/async function applyRealtimeBatch[\s\S]*?\n\}/)?.[0] ?? "";- assert.match(flush, /await refreshInbox\(\{ silent: true \}\)/);+ assert.match(+ inbox,+ /if \(inboxState\.loaded && !inboxState\.selected\.some\(\(loop\) => loop\.id === event\.loopId\)\) return;/,+ "an event that lands before the first load finishes still queues a follow-up refresh",+ );+ assert.match(inbox, /createInboxEventCoalescer\(\s*250,\s*\(\) => void refreshWhenVisible\(\),/);});test("a refresh requested while one is in flight re-runs instead of being dropped", () => {diff --git a/src/api/routes/inbox.ts b/src/api/routes/inbox.tsindex 104b2d139..e3fff2c67 100644--- a/src/api/routes/inbox.ts+++ b/src/api/routes/inbox.ts@@ -1,4 +1,5 @@import { migrateInbox } from "../../loops/inbox-migration.ts";+import { canonicalPerson } from "../../directory/person.ts";import { scopeId, type Loop } from "../../types.ts";import { ensureDefaultInboxLoops, findInboxLoop } from "../../loops/inbox-loop.ts";import {@@ -200,8 +201,29 @@ async function access(ctx: ApiCtx): Promise<void> {});}+async function viewers(ctx: ApiCtx): Promise<void> {+ if (ctx.capability || ctx.actor) return sendJson(ctx.res, 403, { error: "forbidden" });+ const body = isObj(ctx.body) ? ctx.body : {};+ const loop = typeof body.loopId === "string" ? await loopDeps(ctx)?.store.get(body.loopId) : undefined;+ if (!loop) return sendJson(ctx.res, 404, { error: "not_found" });+ const candidates = Array.isArray(body.candidates)+ ? [...new Set(body.candidates.filter((value): value is string => typeof value === "string"))]+ : [];+ const identity = ctx.deps.identity;+ await identity?.refresh();+ const allowed = await Promise.all(+ candidates.map(+ async (id) =>+ (!identity || identity.classify(id).type === "internal") &&+ canAdministerLoop(ctx, loop, { actorId: canonicalPerson(id), liveHuman: false }),+ ),+ );+ sendJson(ctx.res, 200, { viewers: candidates.filter((_, i) => allowed[i]) });+}+export const inboxRoutes: ReadonlyArray<Route<ApiCtx>> = [{ method: "GET", path: "/v1/inbox", auth: "source", handle: inbox },+ { method: "POST", path: "/v1/inbox/viewers", auth: "source", handle: viewers },{ method: "GET", path: "/v1/inbox/access", auth: "source", handle: access },{ method: "PUT", path: "/v1/inbox", auth: "source", handle: inbox },];diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.tsindex 861c3541e..2fd8d08ca 100644--- a/src/api/user-scoped-routes.ts+++ b/src/api/user-scoped-routes.ts@@ -134,6 +134,7 @@ const SYSTEM: Rule[] = [pat("POST", "/v1/runs/:id/delivery-state"),pat("POST", "/v1/deliveries/:id/ack"),pat("POST", "/v1/deliveries/ack-by-key"),+ pat("POST", "/v1/inbox/viewers"),pat("POST", "/v1/directory"),pat("POST", "/v1/principals/:id/deactivate"),pat("POST", "/v1/principals/:id/reactivate"),diff --git a/test/inbox-selection.test.ts b/test/inbox-selection.test.tsindex a9819c249..b26c4eb6f 100644--- a/test/inbox-selection.test.ts+++ b/test/inbox-selection.test.ts@@ -14,6 +14,7 @@ import type { PersistedUiState } from "../src/surfaces/ui-state.ts";import type { ApiCtx } from "../src/api/routes/route.ts";import { ensureDefaultInboxLoops, ensureInboxLoop } from "../src/loops/inbox-loop.ts";import { migrateInbox } from "../src/loops/inbox-migration.ts";+import { installPrincipalLinks } from "../src/directory/person.ts";function world(enabled = true, sourceRefresh?: ApiCtx["deps"]["inboxSourceRefresh"]) {const deps = {@@ -602,3 +603,57 @@ test("email classification is projected only by the flagged inbox endpoint", asyassert.equal((await disabled.call("GET", null, `filter=${filter}`)).status, 403);}});++test("inbox viewers are exactly the active candidates who can administer the loop, including shared group scopes and aliases", async (t) => {+ const store = createLoopStore();+ const base = { createdBy: "alice", playbook: "triage", successCondition: "done" };+ const { loop: personal } = await store.create({+ ...base,+ owner: "alice",+ ownerScopeId: "personal:alice",+ name: "Mine",+ });+ const { loop: group } = await store.create({ ...base, owner: "alice", ownerScopeId: "group:core", name: "Team" });+ const members = new Set(["alice", "bob", "carol"]);+ const route = inboxRoutes.find((r) => "path" in r && r.path === "/v1/inbox/viewers")!;+ const ask = async (body: unknown, capability: unknown = null) => {+ let status = 0;+ let data: any;+ await route.handle({+ method: "POST",+ body,+ url: new URL("http://local/v1/inbox/viewers"),+ capability,+ deps: {+ loops: { store },+ identity: {+ refresh: async () => {},+ classify: (id: string) => ({ id, type: id === "carol" ? "deactivated" : "internal" }),+ },+ },+ app: {+ samePerson: async (a: string, b: string) => a === b,+ membershipControlsScope: async (scope: string) => scope.startsWith("group:"),+ managesScope: async (who: string, scope: string) => scope === "group:core" && members.has(who),+ },+ res: {+ writeHead: (value: number) => {+ status = value;+ },+ end: (value: string) => {+ data = JSON.parse(value);+ },+ },+ } as unknown as ApiCtx);+ return { status, data };+ };+ const candidates = ["alice", "bob-slack", "carol", "mallory"];+ installPrincipalLinks({ canonical: (key) => (key === "bob-slack" ? "bob" : undefined), aliases: () => [] });+ t.after(() => installPrincipalLinks(null));+ assert.deepEqual((await ask({ loopId: personal.id, candidates })).data.viewers, ["alice"]);+ assert.deepEqual((await ask({ loopId: group.id, candidates })).data.viewers, ["alice", "bob-slack"]);+ members.delete("alice");+ assert.deepEqual((await ask({ loopId: group.id, candidates })).data.viewers, ["bob-slack"]);+ assert.equal((await ask({ loopId: "missing", candidates })).status, 404);+ assert.equal((await ask({ loopId: group.id, candidates }, { actorId: "mallory" })).status, 403);+});