Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Inbox: notification words from the packs, guest rule its own tested function
milind-sonifc13b5d18c87
diff --cc server/drivers/agents-catalog-goldens/profiles.jsonindex 63895717d2,e2a255c1db..c41b96882b--- a/server/drivers/agents-catalog-goldens/profiles.json+++ b/server/drivers/agents-catalog-goldens/profiles.json@@@ -1,7 -1,7 +1,12 @@@{"default": {++<<<<<<< HEAD+ "bytes": 58681,+ "sha256": "18736e6dd4460703d877cb72ae962f2ab171fe53392969d8a641ce94385f8970",++=======+ "bytes": 58409,+ "sha256": "9562c453e4685c5ca69ede2fcb7138b2b455aa9a2fdbfa4478f06f5a718a0385",++>>>>>>> origin/main"tools": ["tool_result_read","list_room_targets",@@@ -51,8 -50,8 +56,13 @@@]},"voice": {++<<<<<<< HEAD+ "bytes": 59462,+ "sha256": "539d9dcbf4bfb9bde16929cb6e56f1e068d21ce5454571c06988ec33da3f7c26",++=======+ "bytes": 59190,+ "sha256": "eac49a92507f595d879017cfd47f08361be5f1a5078bd840c08eff1059b74e39",++>>>>>>> origin/main"tools": ["tool_result_read","list_room_targets",@@@ -103,8 -101,8 +113,13 @@@]},"shared": {++<<<<<<< HEAD+ "bytes": 60946,+ "sha256": "86af6b7a64c8df9cef99110fb76cf6a19644defcf0781c1d9beac6f3c8030608",++=======+ "bytes": 60674,+ "sha256": "ea942863af945881f8bd250611e8c5d3e575855af399d884381bec9fb1c063cd",++>>>>>>> origin/main"tools": ["tool_result_read","list_shared_computers",@@@ -156,8 -153,8 +171,13 @@@]},"shared+voice": {++<<<<<<< HEAD+ "bytes": 61727,+ "sha256": "8d2727d012131764e6d260955b94207eb0d8a96e103702c426e70f99942f2c0c",++=======+ "bytes": 61455,+ "sha256": "ba67957c0cd7f41b2d811efb95e9f301c9a2cd7429cd5649459b2f5ee6f13c59",++>>>>>>> origin/main"tools": ["tool_result_read","list_shared_computers",@@@ -210,8 -206,8 +230,13 @@@]},"skills": {++<<<<<<< HEAD+ "bytes": 61500,+ "sha256": "edcef7705d03ead50a63d4d352129863affe5f8be442c71da7b6aeb90d458aa7",++=======+ "bytes": 61228,+ "sha256": "44fb483dd17dc7a3207326a08b15a36830277f01e7dec6c5ac99b82c0ad55437",++>>>>>>> origin/main"tools": ["tool_result_read","list_room_targets",@@@ -263,8 -258,8 +288,13 @@@]},"skills+voice": {++<<<<<<< HEAD+ "bytes": 62281,+ "sha256": "7e74e94a770fdbe2d34a98684c0fd22f4382b08e504d6a1f0cae544f94dce30b",++=======+ "bytes": 62009,+ "sha256": "562d2e51f73b659a492f121fcc3823a9e017fefb451841d8678b17fdf7c9ce77",++>>>>>>> origin/main"tools": ["tool_result_read","list_room_targets",@@@ -317,8 -311,8 +347,13 @@@]},"skills+shared": {++<<<<<<< HEAD+ "bytes": 63765,+ "sha256": "a914ad1b1d104ef003616f4986436201c0fe4baffb7631f9849de412547169d5",++=======+ "bytes": 63493,+ "sha256": "050200414b4d840c2dc81783ec45240ef3630a47b9fc77cd64109351614f912d",++>>>>>>> origin/main"tools": ["tool_result_read","list_shared_computers",@@@ -372,8 -365,8 +407,13 @@@]},"skills+shared+voice": {++<<<<<<< HEAD+ "bytes": 64546,+ "sha256": "5b8b4a58100a280d351c780f32946a296337bfc03fe3c8fce2fa89b6638fb108",++=======+ "bytes": 64274,+ "sha256": "2b1428a64a26703de1ae9b6a1bc8ef3d872aca317f68efccff320ce8068befd9",++>>>>>>> origin/main"tools": ["tool_result_read","list_shared_computers",@@@ -800,8 -784,8 +840,13 @@@]},"skills+shared+voice+cloud-home": {++<<<<<<< HEAD+ "bytes": 64312,+ "sha256": "3e1e03c5865bd0ac5263294b6bc80b20c6828e0812f2dab5446270d6812dbe50",++=======+ "bytes": 64040,+ "sha256": "58dbe3d5123035455534cb47be9de9c8f200a56a69a35734c64600a53599c9f3",++>>>>>>> origin/main"tools": ["tool_result_read","list_shared_computers",@@@ -905,8 -887,8 +950,13 @@@]},"skills+shared+voice+escalations": {++<<<<<<< HEAD+ "bytes": 65376,+ "sha256": "0702cc5e81149e59ebcc5d9a331569616728f57c4f03eaf887ad8e7cde789e56",++=======+ "bytes": 65104,+ "sha256": "cf4ff32466e78a0d325ed21d69e6b718df04e52aa476d4df42bb706f8d74852b",++>>>>>>> origin/main"tools": ["tool_result_read","list_shared_computers",@@@ -962,8 -943,8 +1012,13 @@@]},"skills+shared+voice+escalations+x": {++<<<<<<< HEAD+ "bytes": 69215,+ "sha256": "b57f0c5771e4fa21a0dad22a346435a897e8a7e55fc3d9c80edbb0d725e57612",++=======+ "bytes": 68943,+ "sha256": "802eec8e0474ebeb267b97647389cf9b9faa3be22f837a16a0730a9737dc3dc5",++>>>>>>> origin/main"tools": ["tool_result_read","list_shared_computers",@@@ -1023,8 -1003,8 +1078,13 @@@]},"skills+shared+voice+escalations+x+team": {++<<<<<<< HEAD+ "bytes": 69215,+ "sha256": "b57f0c5771e4fa21a0dad22a346435a897e8a7e55fc3d9c80edbb0d725e57612",++=======+ "bytes": 69575,+ "sha256": "c62f12910c8534088d25b903ba6f70de139b39d90f722ecb3c1c0221f8974a99",++>>>>>>> origin/main"tools": ["tool_result_read","list_shared_computers",@@@ -1084,8 -1064,8 +1144,13 @@@]},"default+legacy-switches": {++<<<<<<< HEAD+ "bytes": 58681,+ "sha256": "18736e6dd4460703d877cb72ae962f2ab171fe53392969d8a641ce94385f8970",++=======+ "bytes": 58409,+ "sha256": "9562c453e4685c5ca69ede2fcb7138b2b455aa9a2fdbfa4478f06f5a718a0385",++>>>>>>> origin/main"tools": ["tool_result_read","list_room_targets",@@@ -1135,8 -1114,8 +1200,13 @@@]},"default+mausbot": {++<<<<<<< HEAD+ "bytes": 59332,+ "sha256": "783420d225c635f578dd2b2c5fa65f6bf8d7cabba428d0138e6a6e9281cc91eb",++=======+ "bytes": 59060,+ "sha256": "87d17f733fe82f6bfef7e0f1984111b8577756adad03ab176858e7dca428a5ec",++>>>>>>> origin/main"tools": ["tool_result_read","list_room_targets",@@@ -1188,8 -1166,8 +1258,13 @@@]},"skills+shared+voice+mausbot": {++<<<<<<< HEAD+ "bytes": 65197,+ "sha256": "7259ca545c161917bb1d24e76d31fb5bb77a860164364af284b077cca26d0757",++=======+ "bytes": 64925,+ "sha256": "9be4d6822fd7e63ccb8f8e6392aa7e303c1a16e3b911be2ea5b4edd9bd446358",++>>>>>>> origin/main"tools": ["tool_result_read","list_shared_computers",@@@ -1246,8 -1223,8 +1321,13 @@@]},"default+no-computer-pick": {++<<<<<<< HEAD+ "bytes": 57469,+ "sha256": "caa02a3430acc95e143615c847a35ba063ce7a33d7a928f8035edb8923dcc39f",++=======+ "bytes": 57197,+ "sha256": "ce30f32b2926cbe267fd259c2ed6e51365d6ffa95b08d98623e215378dfe7167",++>>>>>>> origin/main"tools": ["tool_result_read","list_room_targets",@@@ -1296,8 -1272,8 +1376,13 @@@]},"default+room": {++<<<<<<< HEAD+ "bytes": 50551,+ "sha256": "fc81781c8bb769cd843ed5378740654004337c73a886b2b202a0c8bf9d4690eb",++=======+ "bytes": 50279,+ "sha256": "81c95f17de75b178b06d88400c68d3e3a4e6e1b7cd74629b79b7b5002c1b3fb8",++>>>>>>> origin/main"tools": ["tool_result_read","list_room_targets",diff --cc server/host/place-inbox.test.tsindex 16cb6ca703,0000000000..b619aa36e4mode 100644,000000..100644--- a/server/host/place-inbox.test.ts+++ b/server/host/place-inbox.test.ts@@@ -1,242 -1,0 +1,262 @@@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import type { Notification } from "../../shared/notification.ts";+import type { OptionCardData } from "../../shared/wire.ts";+import type { RequestAuth } from "../request-auth.ts";- import { createPlaceInbox, PLACE_MESSAGES_HOURLY, type InboxViewer, type OpenCardRow, type PlaceInboxDeps } from "./place-inbox.ts";++import { createPlaceInbox, PLACE_MESSAGES_HOURLY, placeInboxViewer, type InboxViewer, type OpenCardRow, type PlaceInboxDeps } from "./place-inbox.ts";++const OWNER = { kind: "owner-session" } as unknown as RequestAuth;+const GUEST = { kind: "guest-session" } as unknown as RequestAuth;+const SHELL = { kind: "shell" } as unknown as RequestAuth;+const viewers = new Map<RequestAuth, InboxViewer>([[OWNER, { kind: "owner" }], [GUEST, { kind: "guest", key: "p_guest" }], [SHELL, { kind: "nobody" }]]);++const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++type Said = { id: string; at: number; role: string; peerAsk?: boolean; relayed?: boolean; via?: string; text?: string; inbox?: unknown };++function setup(over: Partial<PlaceInboxDeps> = {}, dataDir = mkdtempSync(join(tmpdir(), "place-inbox-"))) {+ dirs.push(dataDir);+ let clock = 1_000;+ let serial = 0;+ const said = new Map<string, Said[]>();+ const cards: OpenCardRow[] = [];+ const sent: Notification[] = [];+ const handed = new Map<string, string>();+ const guests = new Map<string, string>();+ const bots: Record<string, { id: string; name: string; threadId: string; color: string; notifications?: boolean }> = {+ eli: { id: "eli", name: "Eli", threadId: "eli-main", color: "blue" }, mira: { id: "mira", name: "Mira", threadId: "mira-main", color: "red" },+ };+ const titles: Record<string, string> = { "eli-main": "Eli", "eli-pricing": "Pricing work", "eli-launch": "Launch work", "guest-chat": "Guest chat" };+ const listeners: Array<(change: { type: string; threadId: string }) => void> = [];+ const store = {+ bot: (id: string) => bots[id],+ botByThread: (threadId: string) => (threadId.startsWith("eli") || threadId === "guest-chat" ? bots.eli : threadId.startsWith("mira") ? bots.mira : undefined),+ taskByThread: (_botId: string, threadId: string) => (titles[threadId] ? { threadId, title: titles[threadId] } : undefined),+ groupByThread: () => undefined,+ appendMessage: (threadId: string, line: Omit<Said, "id" | "at">) => {+ const posted = { ...line, id: `m${++serial}`, at: clock };+ said.set(threadId, [...(said.get(threadId) ?? []), posted]);+ return posted;+ },+ patchTask: () => undefined, patchGroup: () => undefined,+ messagesFor: (threadId: string) => said.get(threadId) ?? [],+ onChange: (listener: (change: { type: string; threadId: string }) => void) => { listeners.push(listener); return () => undefined; },+ };+ const inbox = createPlaceInbox({+ dataDir, store: store as unknown as PlaceInboxDeps["store"], openCards: () => cards,+ viewer: (auth) => viewers.get(auth)!,- sees: (auth, threadId) => auth === OWNER || threadId === "guest-chat",++ sees: () => true,+ mayAnswer: (auth) => auth === OWNER,+ guestOf: (threadId) => guests.get(threadId) ?? null, guestName: () => "Sam",+ handedBy: (threadId) => handed.get(threadId) ?? null,+ send: (one) => sent.push(one), now: () => clock, ...over,+ });+ const ask = (threadId: string, requestId: string, card: Partial<OptionCardData> = {}, at = clock) => {+ const row = { threadId, id: `card-${requestId}`, at, fromBotId: null, card: JSON.stringify({ requestId, title: "Ask", subtitle: `Ask ${requestId}`, options: ["Yes", "No"], requestType: "question", ...card }) };+ cards.push(row);+ return row;+ };+ return { inbox, store, said, cards, sent, handed, guests, bots, listeners, ask, dataDir, tick: (ms: number) => { clock += ms; } };+}+++describe("who is asking for the inbox", () => {++ const session = { kind: "session", session: { id: "s" } } as unknown as RequestAuth;++ const ownerShell = { kind: "loopback", trust: "owner" } as unknown as RequestAuth;++ const service = { kind: "loopback", trust: "service" } as unknown as RequestAuth;++ const cloud = (personal: boolean, owner: boolean) => ({ personal, owner: () => owner, personOf: () => "p_someone" });++++ it("on someone's Cloud: the owner's session is theirs, another is a guest, and loopback is a bot's shell", () => {++ expect(placeInboxViewer(session, cloud(true, true))).toEqual({ kind: "owner" });++ expect(placeInboxViewer(session, cloud(true, false))).toEqual({ kind: "guest", key: "p_someone" });++ expect(placeInboxViewer(ownerShell, cloud(true, false))).toEqual({ kind: "nobody" });++ expect(placeInboxViewer(service, cloud(true, false))).toEqual({ kind: "nobody" });++ });++++ it("anywhere else: the desktop's page and a paired device are the person's, and a local service nobody's", () => {++ expect(placeInboxViewer(ownerShell, cloud(false, false))).toEqual({ kind: "owner" });++ expect(placeInboxViewer(session, cloud(false, false))).toEqual({ kind: "owner" });++ expect(placeInboxViewer(service, cloud(false, false))).toEqual({ kind: "nobody" });++ });++});+++describe("the inbox of a place that is no team's", () => {+ it("lists what was already waiting, whenever it was asked, with no copy and no notification of its own", () => {+ const f = setup();+ f.ask("eli-main", "old", { tool: "Bash", requestType: "permission" }, 1);+ f.ask("mira-main", "new");+ const { rows, threadId, botId } = f.inbox.view(OWNER);+ expect({ threadId, botId }).toEqual({ threadId: null, botId: null });+ expect(rows.map((row) => [row.id, row.kind, row.tab, row.from.name, row.origin?.threadId, row.card?.requestId])).toEqual([+ ["card-new", "ask", "needs-you", "Mira", "mira-main", "new"],+ ["card-old", "ask", "needs-you", "Eli", "eli-main", "old"],+ ]);+ expect(f.inbox.count(OWNER)).toBe(2);+ expect(f.sent).toEqual([]);+ expect(f.said.size, "nothing was copied anywhere").toBe(0);+ });++ it("drops an ask as soon as its card leaves the open cards, however it was answered", () => {+ const f = setup();+ f.ask("eli-main", "q");+ expect(f.inbox.count(OWNER)).toBe(1);+ f.cards.length = 0;+ expect(f.inbox.count(OWNER)).toBe(0);+ expect(f.inbox.view(OWNER).rows).toEqual([]);+ });++ it("leaves out offers and receipts, and a card somebody already settled", () => {+ const f = setup();+ f.ask("eli-main", "offer", { quotaSwitch: {} as never });+ f.ask("eli-main", "sent", { outboundRequest: {} as never });+ f.ask("eli-main", "auto", { autoApplied: true });+ f.ask("eli-main", "answered", { answered: "allow" });+ expect(f.inbox.view(OWNER).rows).toEqual([]);+ });++ it("says who a bot was working for, and which conversation an item came from", () => {+ const f = setup();+ f.handed.set("eli-pricing", "mira");+ f.ask("eli-pricing", "a");+ f.ask("eli-launch", "b");+ const rows = f.inbox.view(OWNER).rows;+ const of = (id: string) => rows.find((row) => row.id === id)!;+ expect(of("card-a")).toMatchObject({ workingFor: { botId: "mira", name: "Mira" }, origin: { threadId: "eli-pricing", title: "Pricing work" } });+ expect(of("card-b").workingFor).toBeUndefined();+ expect(of("card-b").origin).toMatchObject({ threadId: "eli-launch", title: "Launch work" });+ });++ it("gets a bot's message to the person once: one line, one row, one notification, and their words settle it", () => {+ const f = setup();+ const sent = f.inbox.message("eli", "eli-pricing", "The report is ready.");+ expect(sent.status).toBe(200);+ expect(f.sent.map((one) => [one.kind, one.threadId, one.body])).toEqual([["mention", "eli-pricing", "The report is ready."]]);+ const [row] = f.inbox.view(OWNER).rows;+ expect(row).toMatchObject({ kind: "message", tab: "info", unread: true, replies: true, from: { name: "Eli" }, origin: { threadId: "eli-pricing", messageId: row!.id } });+ expect(f.said.get("eli-pricing")!.map((line) => line.id)).toEqual([row!.id]);+ expect(f.inbox.count(OWNER)).toBe(1);++ f.tick(10);+ f.store.appendMessage("eli-pricing", { role: "user", relayed: true });+ expect(f.inbox.view(OWNER).rows[0]!.tab, "a line relayed from another app isn't the person's answer").toBe("info");+ f.store.appendMessage("eli-pricing", { role: "user", via: "api" });+ expect(f.inbox.view(OWNER).rows[0]!.tab, "nor one through the API").toBe("info");+ f.store.appendMessage("eli-pricing", { role: "user", text: "Thanks" });+ expect(f.inbox.view(OWNER).rows[0]!.tab).toBe("done");+ expect(f.inbox.count(OWNER)).toBe(0);+ });++ it("stops a loop of messages from one conversation, and refuses a conversation that isn't the bot's", () => {+ const f = setup();+ for (let index = 0; index < PLACE_MESSAGES_HOURLY; index++) expect(f.inbox.message("eli", "eli-main", `m${index}`).status).toBe(200);+ expect(f.inbox.message("eli", "eli-main", "one more").status).toBe(429);+ expect(f.sent).toHaveLength(PLACE_MESSAGES_HOURLY);+ expect(f.inbox.message("eli", "somewhere-else", "hi").status).toBe(403);+ expect(f.inbox.message("nobody", "eli-main", "hi").status).toBe(403);+ });++ it("counts news until it is read, and a routine's report notifies only through the notification it came with", () => {+ const f = setup();+ const note: Notification = { kind: "done", botId: "eli", botName: "Eli", threadId: "eli-main", title: "Daily digest", body: "3 new leads" };+ expect(f.inbox.route(note, { routine: true })).toBe(note);+ expect(f.sent).toEqual([]);+ const [row] = f.inbox.view(OWNER).rows;+ expect(row).toMatchObject({ kind: "result", text: "3 new leads", tab: "info", unread: true });+ expect(row!.replies).toBeUndefined();+ expect(f.inbox.count(OWNER)).toBe(1);+ expect(f.inbox.markRead(OWNER, row!.id)).toBe(true);+ expect(f.inbox.count(OWNER)).toBe(0);+ expect(f.inbox.markDone(OWNER, row!.id)).toBe("done");+ expect(f.inbox.view(OWNER).rows[0]!.tab).toBe("done");+ });++ it("gives a line to nothing the person is sitting in front of: a chat's own finish and own failure stay out", () => {+ const f = setup();+ f.inbox.route({ kind: "done", botId: "eli", botName: "Eli", threadId: "eli-main", title: "Done", body: "" });+ f.inbox.route({ kind: "turn-failed", botId: "eli", botName: "Eli", threadId: "eli-main", title: "Failed", body: "" });+ f.inbox.route({ kind: "approval", botId: "eli", botName: "Eli", threadId: "eli-main", title: "Approve", body: "" }, { routine: true });+ expect(f.inbox.view(OWNER).rows, "an approval is its card, never a second line").toEqual([]);+ f.inbox.route({ kind: "routine-failed", botId: "eli", botName: "Eli", threadId: "eli-main", title: "Failed", body: "It broke" }, { routine: true });+ f.handed.set("eli-pricing", "mira");+ f.inbox.route({ kind: "turn-failed", botId: "eli", botName: "Eli", threadId: "eli-pricing", title: "Failed", body: "Handed work broke" });+ expect(f.inbox.view(OWNER).rows.map((row) => [row.kind, row.text])).toEqual(expect.arrayContaining([["notice", "It broke"], ["notice", "Handed work broke"]]));+ });++ it("reads an ask as seen without settling it: it still counts, and only its answer closes it", () => {+ const f = setup();+ f.ask("eli-main", "q");+ expect(f.inbox.view(OWNER).rows[0]!.unread).toBe(true);+ expect(f.inbox.markRead(OWNER, "card-q")).toBe(true);+ expect(f.inbox.view(OWNER).rows[0]!.unread).toBe(false);+ expect(f.inbox.count(OWNER)).toBe(1);+ expect(f.inbox.markDone(OWNER, "card-q")).toBe("an ask");+ expect(f.inbox.markRead(OWNER, "not-a-line")).toBe(false);+ expect(f.inbox.markDone(OWNER, "not-a-line")).toBe("unknown");+ });++ it("opening a conversation reads what waited there", () => {+ const f = setup();+ f.inbox.message("eli", "eli-main", "News");+ f.inbox.seen(OWNER, "eli-main");+ expect(f.inbox.view(OWNER).rows[0]!.unread).toBe(false);+ });++ it("forgets a deleted conversation's lines", () => {+ const f = setup();+ f.inbox.message("eli", "eli-main", "News");+ for (const listener of f.listeners) listener({ type: "thread.deleted", threadId: "eli-main" });+ expect(f.inbox.view(OWNER).rows).toEqual([]);+ });++ it("keeps its lines and what was seen across a restart", () => {+ const f = setup();+ f.ask("eli-main", "q");+ f.inbox.markRead(OWNER, "card-q");+ f.inbox.message("eli", "eli-main", "News");+ const again = setup({ openCards: () => f.cards, store: f.store as unknown as PlaceInboxDeps["store"], now: () => 2_000 }, f.dataDir);+ expect(again.inbox.view(OWNER).rows.map((row) => [row.kind, row.unread])).toEqual(expect.arrayContaining([["ask", false], ["message", true]]));+ });++ describe("on a Cloud with a guest", () => {+ function shared() {+ const f = setup();+ f.guests.set("guest-chat", "p_guest");+ f.ask("guest-chat", "theirs");+ f.ask("eli-main", "mine");+ f.inbox.message("eli", "guest-chat", "For the guest");+ f.inbox.message("eli", "eli-main", "For the owner");+ return f;+ }++ it("shows the owner a guest's ask labelled with who asked, since only they can answer it, and never the guest's news", () => {+ const f = shared();+ const rows = f.inbox.view(OWNER).rows;+ expect(rows.find((row) => row.id === "card-theirs")).toMatchObject({ askedBy: { name: "Sam" } });+ expect(rows.find((row) => row.id === "card-mine")!.askedBy).toBeUndefined();+ expect(rows.filter((row) => row.kind === "message").map((row) => row.text)).toEqual(["For the owner"]);+ });++ it("never notifies the owner about a guest's news", () => {+ const f = shared();+ expect(f.sent.map((one) => one.body)).toEqual(["For the owner"]);+ });++ it("shows a guest only their own news, none of the owner's, and no ask they can't answer", () => {+ const f = shared();+ expect(f.inbox.view(GUEST).rows.map((row) => row.text)).toEqual(["For the guest"]);+ expect(f.inbox.count(GUEST)).toBe(1);+ const ownerLine = f.inbox.view(OWNER).rows.find((row) => row.kind === "message")!.id;+ expect(f.inbox.markRead(GUEST, ownerLine), "not theirs to mark").toBe(false);+ expect(f.inbox.markDone(GUEST, ownerLine)).toBe("unknown");+ });++ it("gives nothing to a bot's shell on the Cloud", () => {+ const f = shared();+ expect(f.inbox.view(SHELL).rows).toEqual([]);+ expect(f.inbox.count(SHELL)).toBe(0);+ });+ });+});diff --cc server/host/place-inbox.tsindex 9b5984ece1,0000000000..99b4734a7fmode 100644,000000..100644--- a/server/host/place-inbox.ts+++ b/server/host/place-inbox.ts@@@ -1,252 -1,0 +1,260 @@@+// The inbox of a place that is no team's: this computer, or a Cloud of one person. There is one person here, so nothing is+// copied and nothing routed. An ask is the open card itself, read where it was asked, so one tap answers the one card+// however many surfaces show it, and whatever was waiting before this inbox existed is listed. What a bot sent the person+// is a line of its conversation, and a reply there is an ordinary line of theirs.+// Security: a guest's conversation stays out of the owner's lines, and the owner's stays out of a guest's. An ask is listed+// only for someone who may answer it, so a guest's questions reach the owner labelled with who asked, never as their own.+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { z } from "zod";++import { isPersistentQuestionCard } from "../../shared/ask-question.ts";+import type { InboxItem, InboxRow, InboxView } from "../../shared/inbox.ts";+import { liveCardKind } from "../../shared/live-approval.ts";+import type { Notification } from "../../shared/notification.ts";+import type { OptionCardData } from "../../shared/wire.ts";+import { ASK_NOTIFICATIONS } from "../ask-routing.ts";+import { writeFileAtomic } from "../atomic.ts";+import type { RequestAuth } from "../request-auth.ts";++import { conversationLanguage, serverLine } from "../server-lines.ts";+import type { Message, Store, StoreChange } from "../store.ts";+import { clip, oneLine } from "./text-clip.ts";++export const PLACE_INBOX_FILE = "place-inbox.json";+const MAX_LINES = 2_000;+const MAX_SEEN_ASKS = 2_000;+const KEEP_MS = 30 * 24 * 60 * 60_000;+const VIEW_ROWS = 200;+const ROW_TEXT_MAX = 4_000;+const NOTICE_TEXT_MAX = 2_000;+const HOUR_MS = 60 * 60_000;+/** Messages from one conversation in an hour: enough for real news, too few for a loop to bury the person. */+export const PLACE_MESSAGES_HOURLY = 10;++const id = z.string().min(1).max(512);+const lineSchema = z.object({+ id, botId: id, threadId: id, groupId: id.optional(), kind: z.enum(["message", "result", "notice"]),+ from: z.string().max(200), workingFor: z.object({ botId: id, name: z.string().max(200) }).optional(),+ /** The guest whose conversation this is: it is theirs, not the owner's. */+ guest: id.optional(),+ text: z.string().max(NOTICE_TEXT_MAX), at: z.number(), seen: z.boolean().optional(), done: z.boolean().optional(),+});+const fileSchema = z.object({ version: z.literal(1), lines: z.array(lineSchema).max(MAX_LINES), seenAsks: z.array(id).max(MAX_SEEN_ASKS) });+type Line = z.infer<typeof lineSchema>;++/** An open card as the messages table holds it. */+export interface OpenCardRow { threadId: string; id: string; at: number; card: string | null; fromBotId: string | null }++/** Who is asking for the inbox: its owner (on a server with members, a member), a guest on someone's Cloud, or nobody it+ * belongs to (a bot's shell on a Cloud, a local service). */+export type InboxViewer = { kind: "owner" } | { kind: "guest"; key: string } | { kind: "nobody" };+++/** Who is asking on this server. Security: on someone's Cloud loopback is a bot's shell, never its owner, and a session that++ * isn't the owner's is a guest; a local service is nobody's either. */++export function placeInboxViewer(auth: RequestAuth, cloud: { personal: boolean; owner(auth: RequestAuth): boolean; personOf(session: Extract<RequestAuth, { kind: "session" }>["session"]): string }): InboxViewer {++ if (cloud.personal && !cloud.owner(auth)) return auth.kind === "session" ? { kind: "guest", key: cloud.personOf(auth.session) } : { kind: "nobody" };++ return auth.kind === "loopback" && auth.trust === "service" ? { kind: "nobody" } : { kind: "owner" };++}+++export interface PlaceInboxDeps {+ dataDir: string;+ store: Pick<Store, "bot" | "botByThread" | "taskByThread" | "groupByThread" | "appendMessage" | "patchTask" | "patchGroup" | "messagesFor" | "onChange">;+ openCards(): OpenCardRow[];+ viewer(auth: RequestAuth): InboxViewer;+ sees(auth: RequestAuth, threadId: string): boolean;+ /** Whose answer counts on this card; decided where cards are answered, so a row never offers what the answer would refuse. */+ mayAnswer(auth: RequestAuth, threadId: string, requestId: string): boolean;+ /** The guest this conversation is for; null for the owner's own, and for work no guest asked for. */+ guestOf(threadId: string): string | null;+ /** The name the guest wrote under in this conversation. */+ guestName(threadId: string): string | undefined;+ /** The bot that handed this conversation's work on. */+ handedBy(threadId: string): string | null;+ /** Sends a notification as it is. */+ send(notification: Notification): void;+ now?: () => number;+}++/** Cards that wait on the person: not an offer to switch engines, a receipt, or anything settled. */+function waitsOnPerson(card: OptionCardData | null): card is OptionCardData {+ const kind = liveCardKind(card ?? undefined);+ if (!card || !kind || card.outboundRequest || card.quotaSwitch || card.teamMemoryRequest || card.autoApplied) return false;+ return kind === "review" || card.requestType === "permission" || Boolean(card.tool) || isPersistentQuestionCard(card);+}++export function createPlaceInbox(deps: PlaceInboxDeps) {+ const { store } = deps;+ const now = deps.now ?? Date.now;+ const file = join(deps.dataDir, PLACE_INBOX_FILE);+ let lines: Line[] = [];+ let seenAsks = new Set<string>();+ try {+ const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));+ if (parsed.success) { lines = parsed.data.lines; seenAsks = new Set(parsed.data.seenAsks); }+ else console.warn(`place inbox: ${file} is not an inbox file; starting fresh`);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.warn(`place inbox: ${file} is unreadable; starting fresh`);+ }+ const save = () => {+ lines = lines.filter((line) => now() - line.at < KEEP_MS).slice(-MAX_LINES);+ try {+ writeFileAtomic(file, `${JSON.stringify({ version: 1, lines, seenAsks: [...seenAsks].slice(-MAX_SEEN_ASKS) })}\n`, { mode: 0o600 });+ } catch (error) {+ console.warn(`place inbox: could not save ${file}: ${error instanceof Error ? error.message : String(error)}`);+ }+ };++ const workingFor = (threadId: string): { botId: string; name: string } | undefined => {+ const botId = deps.handedBy(threadId);+ const bot = botId ? store.bot(botId) : undefined;+ return bot ? { botId: bot.id, name: bot.name } : undefined;+ };++ const titleOf = (botId: string, threadId: string): string => store.groupByThread(threadId)?.name ?? store.taskByThread(botId, threadId)?.title ?? store.bot(botId)?.name ?? "";++ /** The person wrote in the conversation after a bot's message reached them: that is their answer. */+ function answeredThere(line: Line): boolean {+ if (line.kind !== "message") return false;+ const said = store.messagesFor(line.threadId);+ for (let index = said.length - 1; index >= 0 && said[index]!.at >= line.at; index--) {+ const one = said[index]!;+ if (one.role === "user" && !one.peerAsk && !one.relayed && one.via !== "api") return true;+ }+ return false;+ }++ const lineTab = (line: Line): InboxRow["tab"] => (line.done || answeredThere(line) ? "done" : "info");+ const lineFor = (auth: RequestAuth, line: Line): boolean => {+ const viewer = deps.viewer(auth);+ if (viewer.kind === "nobody" || !deps.sees(auth, line.threadId)) return false;+ return viewer.kind === "guest" ? line.guest === viewer.key : line.guest === undefined;+ };++ function askRows(auth: RequestAuth): InboxRow[] {+ if (deps.viewer(auth).kind === "nobody") return [];+ const rows = new Map<string, InboxRow>();+ for (const row of deps.openCards()) {+ let card: OptionCardData | null = null;+ try { card = row.card ? JSON.parse(row.card) as OptionCardData : null; } catch { continue; }+ if (!waitsOnPerson(card) || !deps.sees(auth, row.threadId) || !deps.mayAnswer(auth, row.threadId, card.requestId!)) continue;+ const bot = (row.fromBotId ? store.bot(row.fromBotId) : undefined) ?? store.botByThread(row.threadId);+ if (!bot) continue;+ const group = store.groupByThread(row.threadId);+ const guest = deps.guestOf(row.threadId);+ const handed = workingFor(row.threadId);+ rows.set(`${row.threadId}\u0000${card.requestId}`, {+ id: row.id, kind: "ask", tab: "needs-you", from: { name: bot.name, botId: bot.id },+ ...(handed ? { workingFor: handed } : {}), ...(guest ? { askedBy: { name: deps.guestName(row.threadId) ?? "" } } : {}),+ origin: { botId: bot.id, threadId: row.threadId, title: titleOf(bot.id, row.threadId), ...(group ? { groupId: group.id } : {}), messageId: row.id },+ text: clip(card.subtitle || card.title || "", ROW_TEXT_MAX), at: row.at, unread: !seenAsks.has(row.id), card,+ });+ }+ return [...rows.values()];+ }++ const lineRow = (line: Line): InboxRow => ({+ id: line.id, kind: line.kind, tab: lineTab(line), from: { name: line.from, botId: line.botId }, ...(line.workingFor ? { workingFor: line.workingFor } : {}),+ origin: { botId: line.botId, threadId: line.threadId, title: titleOf(line.botId, line.threadId), ...(line.groupId ? { groupId: line.groupId } : {}), messageId: line.id },+ text: clip(line.text, ROW_TEXT_MAX), at: line.at, unread: !line.seen, ...(line.kind === "message" ? { replies: true as const } : {}),+ });++ function view(auth: RequestAuth): InboxView {+ const rows = [...askRows(auth), ...lines.filter((line) => lineFor(auth, line)).map(lineRow)].sort((a, b) => b.at - a.at).slice(0, VIEW_ROWS);+ return { botId: null, threadId: null, rows, anchor: null };+ }++ function addLine(line: Line): Line {+ lines.push(line);+ save();+ return line;+ }++ const sent = new Map<string, number[]>();+ const recent = (threadId: string) => (sent.get(threadId) ?? []).filter((at) => now() - at < HOUR_MS);++ /** message_person with no team: one line in the conversation that sent it, one row, and one notification. */+ function message(botId: string, threadId: string, text: string): { status: number; text: string } {+ const bot = store.bot(botId);+ if (!bot) return { status: 403, text: "This conversation isn't one you speak in." };+ const group = store.groupByThread(threadId);+ if (bot.threadId !== threadId && !store.taskByThread(botId, threadId) && !group?.memberIds.includes(botId)) return { status: 403, text: "This conversation isn't one you speak in." };+ if (recent(threadId).length >= PLACE_MESSAGES_HOURLY) return { status: 429, text: `You have sent ${PLACE_MESSAGES_HOURLY} messages from this conversation in the last hour, the most allowed. Don't retry: put it in your reply.` };+ sent.set(threadId, [...recent(threadId), now()]);+ const handed = workingFor(threadId);+ const guest = deps.guestOf(threadId);+ const wire: InboxItem = { kind: "message", from: { name: bot.name, botId: bot.id }, replies: true };+ const posted = store.appendMessage(threadId, { role: "bot", kind: "text", text, inbox: wire, ...(group ? { from: { botId: bot.id, name: bot.name, color: bot.color } } : {}) });+ addLine({ id: posted.id, botId: bot.id, threadId, ...(group ? { groupId: group.id } : {}), kind: "message", from: bot.name.slice(0, 200), ...(handed ? { workingFor: handed } : {}),+ ...(guest ? { guest } : {}), text: clip(text, NOTICE_TEXT_MAX), at: now() });+ if (group) store.patchGroup(group.id, { unread: true });+ else store.patchTask(bot.id, threadId, { unread: true });+ if (!guest && bot.notifications !== false) {- deps.send({ kind: "mention", botId: bot.id, botName: bot.name, threadId, title: handed ? `${bot.name}, working for ${handed.name}` : `Message from ${bot.name}`, body: oneLine(text, 200),++ deps.send({ kind: "mention", botId: bot.id, botName: bot.name, threadId, title: handed ? serverLine(conversationLanguage(threadId), "server.notify.workingFor", { who: bot.name, other: handed.name }) : serverLine(conversationLanguage(threadId), "server.notify.message", { who: bot.name }), body: oneLine(text, 200),+ ...(group ? { groupId: group.id } : {}), ...(bot.avatarUrl ? { avatarUrl: bot.avatarUrl } : {}) });+ }+ return { status: 200, text: "It is in their Inbox and they were notified. Their answer comes back here, and you carry on from it." };+ }++ /** A routine's report or a failure of work nobody is watching gets a line; the notification about it goes out as it is. */+ function route(notification: Notification, how: { routine?: boolean } = {}): Notification {+ const { kind, botId, threadId } = notification;+ const result = kind === "done" && how.routine === true;+ const notice = ASK_NOTIFICATIONS.has(kind) && kind !== "approval" && kind !== "question" && (how.routine === true || deps.handedBy(threadId) !== null);+ const bot = result || notice ? store.bot(botId) : undefined;+ if (bot) {+ const handed = workingFor(threadId);+ const guest = deps.guestOf(threadId);+ addLine({ id: crypto.randomUUID(), botId: bot.id, threadId, ...(notification.groupId ? { groupId: notification.groupId } : {}), kind: result ? "result" : "notice", from: bot.name.slice(0, 200),+ ...(handed ? { workingFor: handed } : {}), ...(guest ? { guest } : {}), text: clip(notification.body || notification.title, NOTICE_TEXT_MAX), at: now() });+ }+ return notification;+ }++ const unsubscribe = store.onChange((change: StoreChange) => {+ if (change.type !== "thread.deleted") return;+ const before = lines.length;+ lines = lines.filter((line) => line.threadId !== change.threadId);+ if (lines.length !== before) save();+ });++ return {+ view,+ message,+ route,+ /** What waits on this viewer: every open ask, and news they have not read. */+ count(auth: RequestAuth): number {+ return view(auth).rows.filter((row) => row.tab === "needs-you" || (row.tab === "info" && row.unread)).length;+ },+ markRead(auth: RequestAuth, lineId: string): boolean {+ const line = lines.find((one) => one.id === lineId && lineFor(auth, one));+ if (line) {+ if (!line.seen) { line.seen = true; save(); }+ return true;+ }+ if (!askRows(auth).some((row) => row.id === lineId)) return false;+ if (!seenAsks.has(lineId)) { seenAsks.add(lineId); save(); }+ return true;+ },+ markDone(auth: RequestAuth, lineId: string): "done" | "unknown" | "an ask" {+ const line = lines.find((one) => one.id === lineId && lineFor(auth, one));+ if (line) {+ if (!line.done) { line.done = true; line.seen = true; save(); }+ return "done";+ }+ return askRows(auth).some((row) => row.id === lineId) ? "an ask" : "unknown";+ },+ /** The person opened this conversation: what waited there for them is read. */+ seen(auth: RequestAuth, threadId: string): void {+ let changed = false;+ for (const line of lines) if (line.threadId === threadId && !line.seen && lineFor(auth, line)) { line.seen = true; changed = true; }+ if (changed) save();+ },+ stop: unsubscribe,+ };+}++export type PlaceInbox = ReturnType<typeof createPlaceInbox>;++/** The name a guest wrote under last in a conversation. */+export const guestNameIn = (lines: readonly Pick<Message, "role" | "peerAsk" | "sender">[]): string | undefined =>+ lines.findLast((line) => line.role === "user" && !line.peerAsk && line.sender?.name)?.sender?.name;diff --cc server/index.tsindex a3a2a32c59,1c72b26ee0..2a1943124e--- a/server/index.ts+++ b/server/index.ts@@@ -626,7 -625,7 +625,7 @@@ import { createReactionRoutes } from ".import { createReactions, withReactionNotes, type Reactor } from "./reactions.ts";import { createPersonReplies } from "./person-replies.ts";import { personKey, relayedPersonKey } from "./person-key.ts";- import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { createPlaceInbox, guestNameIn } from "./host/place-inbox.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";-import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";++import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { createPlaceInbox, guestNameIn, placeInboxViewer } from "./host/place-inbox.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";import { createDevsReports } from "./host/devs-reports.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts";import { createThreadRoutes } from "./routes/threads.ts";@@@ -2862,7 -2853,7 +2853,7 @@@ const computerAsks = CLOUD_PERSONAL ? cconst { stopThreadForPerson, stopOnTypedCommand, restartForPerson, noteTeammatesLeftRunning } = createPersonStop({store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, clearUnattended,stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId)),- }); const teamMessages = createTeamMessages({ place: CLOUD_TEAM ? null : createPlaceInbox({ dataDir: DATA_DIR, store, openCards: openCardRows, send: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); }, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), mayAnswer: (auth, threadId, requestId) => cardAnswerRefusal(auth, threadId, requestId, "allow") === null, viewer: (auth) => (CLOUD_PERSONAL && !cloudOwnerSession(auth) ? (auth.kind === "session" ? { kind: "guest", key: personKey(auth.session) } : { kind: "nobody" }) : auth.kind === "loopback" && auth.trust === "service" ? { kind: "nobody" } : { kind: "owner" }), guestOf: (threadId) => { if (!CLOUD_PERSONAL || !cloudGuestDriven(threadId)) return null; const person = [...cloudThreadStarters(threadId), threadPersonKey(threadId)].find((one) => one && one !== CLOUD_OUTSIDE_KEY && !cloudOwnerPerson(one)); return person ?? null; }, guestName: (threadId) => guestNameIn(store.messagesFor(threadId)), handedBy: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.botId ?? store.botByThread(from.threadId)?.id ?? null : null; } }), team: CLOUD_TEAM, dataDir: DATA_DIR, store, people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(cfg, access)).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(cfg, payload as never, session, undefined, signal, access) }).busy } } });-}); const teamMessages = createTeamMessages({ team: CLOUD_TEAM, dataDir: DATA_DIR, store, people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(cfg, access)).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(cfg, payload as never, session, undefined, signal, access) }).busy } } });++}); const teamMessages = createTeamMessages({ place: CLOUD_TEAM ? null : createPlaceInbox({ dataDir: DATA_DIR, store, openCards: openCardRows, send: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); }, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), mayAnswer: (auth, threadId, requestId) => cardAnswerRefusal(auth, threadId, requestId, "allow") === null, viewer: (auth) => placeInboxViewer(auth, { personal: CLOUD_PERSONAL, owner: cloudOwnerSession, personOf: personKey }), guestOf: (threadId) => { if (!CLOUD_PERSONAL || !cloudGuestDriven(threadId)) return null; const person = [...cloudThreadStarters(threadId), threadPersonKey(threadId)].find((one) => one && one !== CLOUD_OUTSIDE_KEY && !cloudOwnerPerson(one)); return person ?? null; }, guestName: (threadId) => guestNameIn(store.messagesFor(threadId)), handedBy: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.botId ?? store.botByThread(from.threadId)?.id ?? null : null; } }), team: CLOUD_TEAM, dataDir: DATA_DIR, store, people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(cfg, access)).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(cfg, payload as never, session, undefined, signal, access) }).busy } } });const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,diff --cc server/place-inbox.e2e.test.tsindex 84d02cd637,0000000000..c0af6b2c9emode 100644,000000..100644--- a/server/place-inbox.e2e.test.ts+++ b/server/place-inbox.e2e.test.ts@@@ -1,220 -1,0 +1,220 @@@+// The Inbox with no team, end to end on both places a person's bots live (docs/team-cloud.md "Off a team"): this computer+// and My Cloud, each its own real server with a synthetic Claude CLI. A bot's approval and question are listed with the+// right count, answered through the row's own conversation, and the turn goes on; message_person arrives once and its+// reply reaches the bot. A guest's conversation left on a shared Cloud reaches the owner labelled, not as their own. It+// proves where things land, not a model's judgement.+import { randomBytes } from "node:crypto";+import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { launchCloudSendFixture, type CloudSendFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { markLeftBehind } from "./testing/cloud-left-behind.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const ENGINE = `const dir = process.env.FAKE_CLAUDE_FIXTURE_DIR;+process.env.FAKE_CLAUDE_ROOM_PLAN = dir + "/room-plan.json";`;+const TOKEN = `ops_fake-inbox-${randomBytes(8).toString("hex")}`;++type Card = { requestId?: string; tool?: string; answered?: string };+type Row = { id: string; kind: string; tab: string; unread: boolean; replies?: true; text: string; from: { name: string; botId?: string }; workingFor?: { name: string }; askedBy?: { name: string };+ origin?: { botId: string; threadId: string; title: string }; card?: Card };+type Note = { kind: string; botId: string; threadId: string; title: string; body: string };+type Bot = { id: string; name: string; threadId: string; busy?: boolean; activity?: string };+type Call = (method: string, path: string, body?: unknown) => Promise<{ status: number; body: any }>;++let fx: CloudSendFixture;++async function until(done: () => Promise<boolean> | boolean, what: string, timeoutMs = hostTimeout(60_000)): Promise<void> {+ const end = Date.now() + timeoutMs;+ while (!(await done())) {+ if (Date.now() > end) throw new Error(`Timed out waiting for ${what}`);+ await new Promise((resolve) => setTimeout(resolve, 150));+ }+}++function place(call: Call, home: () => string) {+ const plan: Record<string, { script: unknown[] }> = {};+ const file = () => join(home(), "room-plan.json");+ const script = (botId: string, ...entries: unknown[]) => {+ (plan[botId] ??= { script: [] }).script.push(...entries);+ writeFileSync(file(), JSON.stringify(plan));+ };+ const turns = (botId: string): Array<{ planKey?: string; threadId?: string; prompt: unknown }> => {+ const path = `${file()}.evidence.jsonl`;+ return existsSync(path) ? readFileSync(path, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)).filter((turn) => turn.botId === botId) : [];+ };+ const inbox = async () => (await call("GET", "/api/inbox")).body as { rows: Row[]; threadId: string | null };+ const count = async () => (await call("GET", "/api/inbox/count")).body.count as number;+ const listed = async () => (await inbox()).rows.filter((row) => row.tab !== "done");+ const notes = async () => ((await call("GET", "/api/notifications")).body.notifications ?? []) as Note[];+ const messages = async (threadId: string) => ((await call("GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages ?? []) as Array<{ id: string; role: string; kind: string; text?: string; at: number; card?: Card; inbox?: unknown }>;+ const bot = async (name: string) => {+ const created = await call("POST", "/api/bots", { name, modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ expect((await call("PATCH", `/api/bots/${created.body.bot.id}`, { approvalMode: "ask", applyToAllThreads: true })).status).toBe(200);+ return created.body.bot as Bot;+ };+ const thread = async (botId: string, title: string) => {+ const opened = await call("POST", `/api/bots/${botId}/tasks`, { title });+ expect(opened.status, JSON.stringify(opened.body)).toBe(201);+ return opened.body.task.threadId as string;+ };+ const say = async (botId: string, threadId: string, text: string, more: Record<string, unknown> = {}) => {+ const sent = await call("POST", `/api/bots/${botId}/messages`, { text, threadId, ...more });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ };+ return { script, turns, inbox, count, listed, notes, messages, bot, thread, say };+}++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: TOKEN, cloudEngine: ENGINE, desktopEngine: ENGINE });+ writeFileSync(join(fx.root, "desktop", "room-plan.json"), "{}");+ writeFileSync(join(fx.root, "cloud", "room-plan.json"), "{}");+}, hostTimeout(180_000));++afterAll(async () => { await fx?.close(); });++describe.each([+ ["this computer", "desktop"],+ ["My Cloud", "cloud"],+] as const)("on %s", (_name, role) => {+ const here = () => place(role === "desktop" ? fx.local : fx.onCloud, () => join(fx.root, role));++ it("starts with an inbox with nothing in it, not a missing one", async () => {+ const h = here();+ expect(await h.inbox()).toMatchObject({ rows: [], threadId: null });+ expect(await h.count()).toBe(0);+ });++ it("lists a bot's approval and question with the right count and their threads, and an answer from the inbox reaches the bot, whose turn goes on", async () => {+ const h = here();+ const eli = await h.bot(`Eli ${role}`);+ const pricing = await h.thread(eli.id, "Pricing work");+ const launch = await h.thread(eli.id, "Launch work");+ h.script(eli.id,+ { key: "P1", match: ["P1-GO"], timeoutMs: 120_000, approve: { tool: "Bash", input: { command: "echo hi" } }, reply: "P1: approved and ran", replyIfDenied: "P1: denied" },+ { key: "Q1", match: ["Q1-GO"], timeoutMs: 120_000, steps: [{ server: "ogb", tool: "ask_user", arguments: { question: "Which page?", choices: ["Home", "Pricing"] }, capture: { answer: "([\\s\\S]+)" } }], reply: "Q1: going with {{answer}}" });+ const before = (await h.notes()).length;+ await h.say(eli.id, pricing, "P1-GO");+ await h.say(eli.id, launch, "Q1-GO");++ await until(async () => (await h.listed()).length === 2, "the approval and the question in the inbox");+ expect(await h.count()).toBe(2);+ const rows = await h.listed();+ const approval = rows.find((row) => row.card?.tool)!;+ const question = rows.find((row) => !row.card?.tool)!;+ expect(approval).toMatchObject({ kind: "ask", tab: "needs-you", from: { name: eli.name }, origin: { threadId: pricing, title: "Pricing work" } });+ expect(question).toMatchObject({ kind: "ask", tab: "needs-you", from: { name: eli.name }, origin: { threadId: launch, title: "Launch work" } });+ expect((await h.inbox()).threadId, "nothing was copied into a conversation of its own").toBeNull();++ const notified = (await h.notes()).slice(0, (await h.notes()).length - before);+ expect(notified.filter((note) => note.threadId === pricing && note.kind === "approval"), "one notification per item").toHaveLength(1);+ expect(notified.filter((note) => note.threadId === launch && note.kind === "question"), "one notification per item").toHaveLength(1);++ const call = role === "desktop" ? fx.local : fx.onCloud;+ const allowed = await call("POST", `/api/threads/${approval.origin!.threadId}/respond`, { requestId: approval.card!.requestId, behavior: "allow" });+ expect(allowed.status, JSON.stringify(allowed.body)).toBe(200);+ await until(async () => (await h.messages(pricing)).some((line) => line.text === "P1: approved and ran"), "the approved turn to go on");+ expect(await h.count()).toBe(1);++ const answered = await call("POST", `/api/threads/${question.origin!.threadId}/respond`, { requestId: question.card!.requestId, behavior: "answer", message: "Pricing" });+ expect(answered.status, JSON.stringify(answered.body)).toBe(200);+ await until(async () => (await h.messages(launch)).some((line) => line.text === "Q1: going with Pricing"), "the answered turn to go on");+ expect(await h.count()).toBe(0);+ expect(await h.listed()).toEqual([]);++ const again = await call("POST", `/api/threads/${question.origin!.threadId}/respond`, { requestId: question.card!.requestId, behavior: "answer", message: "Home" });+ expect(again.status, "no answer is sent twice").toBeGreaterThanOrEqual(400);+ expect((await h.messages(launch)).some((line) => line.text?.includes("going with Home"))).toBe(false);+ }, hostTimeout(180_000));++ it("gets a bot's message_person to the person once, and their reply reaches the bot", async () => {+ const h = here();+ const eli = await h.bot(`Mel ${role}`);+ const work = await h.thread(eli.id, "Background work");+ h.script(eli.id,+ { key: "M1", match: ["M1-GO"], steps: [{ server: "agents", tool: "message_person", arguments: { message: "The report is ready." } }], reply: "M1: told them" },+ { key: "M2", match: ["Send it to Ada"], reply: "M2: sending it" });+ await h.say(eli.id, work, "M1-GO");+ await until(async () => (await h.messages(work)).some((line) => line.text === "M1: told them"), "the bot's turn");+ const line = (await h.listed()).find((row) => row.kind === "message")!;+ expect(line).toMatchObject({ tab: "info", unread: true, replies: true, text: "The report is ready.", from: { name: eli.name }, origin: { threadId: work, title: "Background work" } });+ expect(await h.count()).toBe(1);+ expect((await h.notes()).filter((note) => note.threadId === work && note.body === "The report is ready."), "one notification, not one for the chat and one for the inbox").toHaveLength(1);+ expect((await h.messages(work)).filter((one) => one.text === "The report is ready."), "one line").toHaveLength(1);++ await h.say(eli.id, work, "Send it to Ada", { replyToId: line.id });+ await until(() => h.turns(eli.id).some((turn) => turn.planKey === "M2"), "the reply to reach the bot");+ await until(async () => (await h.messages(work)).some((one) => one.text === "M2: sending it"), "the bot to carry on");+ expect(await h.count()).toBe(0);+ expect((await h.inbox()).rows.find((row) => row.id === line.id)!.tab).toBe("done");+ }, hostTimeout(120_000));++ it("says who a bot was working for, on a question from work another bot handed it", async () => {+ const h = here();+ const mira = await h.bot(`Mira ${role}`);+ const eli = await h.bot(`Ori ${role}`);+ h.script(mira.id,+ { key: "W1", match: ["W1-GO"], steps: [{ arguments: { bot_ids: [eli.id], message: "W1-BRIEF: pick the page." } }], reply: "W1: handed on" },+ { key: "W1-DONE", match: ["Your downstream room requests have settled.", "W1-GO"], reply: "W1-DONE" });+ h.script(eli.id, { key: "W1-E", match: ["W1-BRIEF"], timeoutMs: 120_000, steps: [{ server: "ogb", tool: "ask_user", arguments: { question: "Which page for Mira?", choices: ["Home", "Pricing"] }, capture: { answer: "([\\s\\S]+)" } }], reply: "W1-E: {{answer}}" });+ await h.say(mira.id, mira.threadId, "W1-GO");+ await until(async () => (await h.listed()).some((row) => row.from.name === eli.name && row.kind === "ask"), "the handed-on question in the inbox");+ const row = (await h.listed()).find((one) => one.from.name === eli.name && one.kind === "ask")!;+ expect(row.workingFor?.name).toBe(mira.name);+ expect(row.origin?.botId).toBe(eli.id);+ const call = role === "desktop" ? fx.local : fx.onCloud;+ expect((await call("POST", `/api/threads/${row.origin!.threadId}/respond`, { requestId: row.card!.requestId, behavior: "answer", message: "Home" })).status).toBe(200);+ await until(async () => (await h.messages(row.origin!.threadId)).some((line) => line.text === "W1-E: Home"), "the work to go on");+ expect((await h.listed()).some((one) => one.id === row.id)).toBe(false);+ }, hostTimeout(180_000));++ it("clears news once it is read, and keeps it listed until it is done", async () => {+ const h = here();+ const eli = await h.bot(`Nia ${role}`);+ h.script(eli.id, { key: "N1", match: ["N1-GO"], steps: [{ server: "agents", tool: "message_person", arguments: { message: "News for you." } }], reply: "N1: told them" });+ await h.say(eli.id, eli.threadId, "N1-GO");+ await until(async () => (await h.messages(eli.threadId)).some((line) => line.text === "N1: told them"), "the bot's turn");+ const call = role === "desktop" ? fx.local : fx.onCloud;+ const row = (await h.listed()).find((one) => one.text === "News for you.")!;+ expect(row.unread).toBe(true);+ expect((await call("POST", `/api/inbox/${row.id}/read`)).status).toBe(200);+ expect((await h.listed()).find((one) => one.id === row.id)).toMatchObject({ unread: false, tab: "info" });+ expect(await h.count()).toBe(0);+ expect((await call("POST", `/api/inbox/${row.id}/done`)).body.rows.find((one: Row) => one.id === row.id).tab).toBe("done");+ expect((await call("POST", "/api/inbox/not-a-line/read")).status).toBe(404);+ }, hostTimeout(120_000));+});++describe("on a Cloud someone else once used", () => {+ it("lets nobody connect as a guest, shows a bot's shell nothing, and labels a guest's ask to its owner while keeping a guest's news away", async () => {+ const h = place(fx.onCloud, () => join(fx.root, "cloud"));+ const refused = await fx.onCloud("POST", "/api/auth/pairing", { label: "Friend", scopes: ["client"] });+ expect(refused.status, "a personal Cloud takes the owner's own devices only").toBeGreaterThanOrEqual(400);++ const shell = await fetch(`${fx.cloudBase}/api/inbox`);- const seen = shell.ok ? (await shell.json() as { rows: Row[] }).rows : [];- expect(seen).toEqual([]);++ const seen = await shell.json().catch(() => null) as { rows?: Row[]; error?: string } | null;++ expect(shell.ok ? seen?.rows : [], `status ${shell.status}`).toEqual([]);++ const zed = await h.bot("Zed");+ const theirs = await h.thread(zed.id, "Sam's work");+ const owners = await h.thread(zed.id, "My work");+ h.script(zed.id,+ { key: "G1", match: ["G1-GO"], timeoutMs: 120_000, steps: [{ server: "agents", tool: "message_person", arguments: { message: "For the guest" } }, { server: "ogb", tool: "ask_user", arguments: { question: "Guest's question?", choices: ["A", "B"] }, capture: { answer: "([\\s\\S]+)" } }], reply: "G1: {{answer}}" },+ { key: "G2", match: ["G2-GO"], timeoutMs: 120_000, steps: [{ server: "ogb", tool: "ask_user", arguments: { question: "Owner's question?", choices: ["A", "B"] }, capture: { answer: "([\\s\\S]+)" } }], reply: "G2: {{answer}}" });++ markLeftBehind(join(fx.root, "cloud", ".openmausbot"), { threadIds: [theirs] });+ await fx.relaunch({ cloud: {} });+ await h.say(zed.id, theirs, "G1-GO");+ await h.say(zed.id, owners, "G2-GO");+ await until(async () => (await h.listed()).filter((row) => row.from.name === "Zed" && row.kind === "ask").length === 2, "both asks");+ const rows = await h.listed();+ const guests = rows.find((row) => row.origin?.threadId === theirs && row.kind === "ask")!;+ const own = rows.find((row) => row.origin?.threadId === owners && row.kind === "ask")!;+ expect(guests.askedBy, "a guest's ask says it isn't the owner's").toBeDefined();+ expect(own.askedBy).toBeUndefined();+ expect((await h.messages(theirs)).some((line) => line.text === "For the guest"), "the bot did send it").toBe(true);+ expect(rows.some((row) => row.text === "For the guest"), "a guest's news isn't the owner's").toBe(false);+ expect((await h.notes()).some((note) => note.body === "For the guest")).toBe(false);- }, hostTimeout(240_000));++ }, hostTimeout(420_000));+});diff --cc src/locales/de.jsonindex b05947c7ad,991686aa94..bb8fe667bb--- a/src/locales/de.json+++ b/src/locales/de.json@@@ -147,6 -147,6 +147,8 @@@"server.mcp.signIn.adminOnly": "Nur ein Admin dieser Installation kann sich bei {label} anmelden.","server.mcp.signIn.expired": "Das Anmeldefenster ist abgelaufen. Versuch es noch einmal.","server.mcp.signIn.failed": "Die Anmeldung wurde nicht abgeschlossen. Versuch es noch einmal.",++ "server.notify.message": "Nachricht von {who}",++ "server.notify.workingFor": "{who}, arbeitet für {other}","server.notify.approval": "{who} braucht eine Freigabe","server.notify.question": "{who} hat eine Frage","server.notify.signIn": "{who} braucht deine Anmeldung bei {site}",diff --cc src/locales/en.jsonindex d27c6039f5,f5d08c4ac7..50121610f8--- a/src/locales/en.json+++ b/src/locales/en.json@@@ -243,6 -243,6 +243,8 @@@"server.mcp.signIn.adminOnly": "Only an admin of this installation can sign in to {label}.","server.mcp.signIn.expired": "The sign-in window closed. Try again.","server.mcp.signIn.failed": "The sign-in didn't finish. Try again.",++ "server.notify.message": "Message from {who}",++ "server.notify.workingFor": "{who}, working for {other}","server.notify.approval": "{who} needs approval","server.notify.question": "{who} has a question","server.notify.signIn": "{who} needs you to sign in to {site}",