Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(team): an inbox item stays listed only while it really waits, and its count shows on the inbox (#3724)
Milind Sonibaa8425f30a5
diff --git a/apps/docs/content/docs/features/chat-and-teams.mdx b/apps/docs/content/docs/features/chat-and-teams.mdxindex 6882bbd8b4..8b0279389a 100644--- a/apps/docs/content/docs/features/chat-and-teams.mdx+++ b/apps/docs/content/docs/features/chat-and-teams.mdx@@ -88,7 +88,9 @@ On a team's Cloud, everything for you arrives in one place: your chat with your- Questions and approvals for you (from the bots that report to you), with the same Approve and Deny buttons as in the chat they came from. Answering here answers there.- Work handed between bots that waits on you, failures, and your routines' results.-**Answering is replying.** Use **Reply** on a line, or just tell your Chief ("tell Philipp Friday works"). The answer goes back where the line came from: to the bot that asked, which carries on, or to the teammate's own inbox. Only your answer goes, nothing else from your chat.+**Answering is replying.** Use **Reply** on a line, give it a 👍 or 👎, or just tell your Chief ("tell Philipp Friday works"). The answer goes back where the line came from: to the bot that asked, which carries on, or to the teammate's own inbox. Only your answer goes, nothing else from your chat.++**What waits on you is counted.** Your own row under People shows how many questions and approvals wait on you in your inbox, and the same number is added to the count on the app's icon and in the browser tab. It drops as soon as you settle one, wherever you do it: in your inbox, in the chat it came from, or on your phone. A message you answer in the chat it came from leaves **Needs you** too.**Your assistant answers simple facts for you.** When a teammate asks something your shared facts answer, your Chief answers by itself and says it was "Marco's assistant". It only knows when you are busy (from your own Google Calendar, when you connected it: times only, never what the meetings are), the shared notes of your bots, and how their work stands. It never decides, approves, promises or agrees to anything for you, never sends anything outside the team, and never reads your private chats or About you: those questions wait for you. You see every question and every answer it gave in your inbox, and replying corrects it.diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex 44c45421b5..ad1a351f93 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -346,7 +346,17 @@ anyone's inbox. A member without any bot of their own gets the notification wherturn for it; the line records the answer and a "Told Philipp" chip follows it. A bot that asked carries on: itsconversation gets a line from the inbox's bot, "Marco replied to your message ("…"): …" (`relay.kind: "reply"`), whichstarts its turn or waits behind the running one. Writing to the Chief in the inbox instead ("tell Philipp yes") works-too: its turns there are told what waits on the person, and `message_person` to a line's sender answers that line.+too: its turns there are told what waits on the person, and `message_person` to a line's sender answers that line. A 👍+or 👎 on a line answers it the same way, with that emoji.++**What waits on the person** is read from where it was asked, each time. An ask waits while the card that asked is open+in its conversation: once it is answered there, from the inbox's copy (either respond route), by a reaction or on a+call, or closed (an approval whose turn ended or was stopped, a question the person closed), it no longer waits, and the+copy follows the card. A question its turn left open still waits for a late answer; once its conversation is deleted,+the copy is closed. A line that wants an answer waits until the person answers it, from the inbox or with a line of+their own in the conversation it came from. The inbox's task carries the asks that wait (`WireTask.openAsks`, sent again+whenever one is asked or settled), which the app shows on the person's own row under People and adds to its unread+count: the browser tab's title and the app's icon.**The representative.** When a message asks something a fact the person already shares with the team answers, theirinbox's bot answers it for them (`server/host/representative.ts`); the answer goes back like a reply, as "Marco's@@ -376,9 +386,9 @@ sidebar lists the team's people with their pictures: your own row opens your inbthe composer on screen. Each person is tagged by their whole name, and by their first name when no other teammate sharesit (`shared/person-mention.ts`). A bot's turn is told the team's people (names and admin roles; not the person it talkswith), that `message_person` reaches their inbox, and that a tag already did. Needs you lists the inbox's messages the-person has not opened (`kind: "message"`); the app opens the inbox on the person's first arrival of the day when-something waits there. The state is ids, names and short excerpts, in `person-inbox.json`; a member who leaves takes-their inbox with them.+person has not opened and that still wait (`kind: "message"`); the app opens the inbox on the person's first arrival of+the day when something waits there. The state is ids, names and short excerpts, in `person-inbox.json`; a member who+leaves takes their inbox with them.On a My Cloud and on a desktop there are no team people: the @ list shows bots, `@you` and the profile name tag the oneperson as before, and `message_person` and the inbox do not exist.diff --git a/server/cloud-team-inbox.e2e.test.ts b/server/cloud-team-inbox.e2e.test.tsindex 9ef06f8246..d37bc66ce4 100644--- a/server/cloud-team-inbox.e2e.test.ts+++ b/server/cloud-team-inbox.e2e.test.ts@@ -3,7 +3,9 @@// cards through the permission socket, and Marco's own Google Calendar on the fake connected-apps service. A bot's "tell// Marco", an @Marco and an approval routed to Marco land in his inbox, his chat with his Chief, with one notification// each; his answer reaches the bot that asked, which carries on; his assistant answers when he is free, labelled, and-// leaves decisions and his private chats alone. It proves where things land and what is read, not a model's judgement.+// leaves decisions and his private chats alone. The asks waiting on him are counted on his inbox, live, and each stops+// waiting however he answers it: in the bot's own chat, through either respond route, or with a 👍. It proves where+// things land and what is read, not a model's judgement.import { randomBytes, randomUUID } from "node:crypto";import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { connect, type Socket } from "node:net";@@ -34,8 +36,9 @@ const TOKEN = `ops_fake-team-${randomBytes(8).toString("hex")}`;type Row = { id: string; role: string; kind: string; text?: string; card?: { requestId?: string; answered?: string }; replyToId?: string;relay?: { kind: string; email: string; name: string }; peerAsk?: { botId: string; name: string };inbox?: { kind: string; from: { name: string; email?: string; botId?: string }; via?: { name: string }; origin?: { botId: string; threadId: string; title: string }; replies?: true; answers?: Array<{ by: string; text: string }> } };-type Bot = { id: string; name: string; threadId: string; mainThreadId?: string; busy?: boolean; activity?: string; tasks?: Array<{ threadId: string; title: string; inbox?: true; private?: true }> };-type Frame = { kind: string; notification?: { kind: string; botId: string; threadId: string; title: string; body: string; forPerson?: string } };+type Task = { threadId: string; title: string; inbox?: true; private?: true; openAsks?: number };+type Bot = { id: string; name: string; threadId: string; mainThreadId?: string; busy?: boolean; activity?: string; tasks?: Task[] };+type Frame = { kind: string; bot?: Bot; notification?: { kind: string; botId: string; threadId: string; title: string; body: string; forPerson?: string } };let fx: CloudSendFixture, team: CloudTeamFixture, broker: BrokerFake;let philipp = "", marco = "";@@ -62,6 +65,11 @@ const bots = async (token: string) => (await team.as(token, "GET", "/api/bots"))const idle = async () => (await bots(philipp)).every((bot) => !bot.busy && bot.activity !== "working");const notifiedIn = (frames: Frame[], threadId: string) => frames.filter((frame) => frame.kind === "notify" && frame.notification?.threadId === threadId);const inboxLines = async () => (await messages(marco, inbox)).rows.filter((row) => row.inbox);+const inboxTask = async () => (await bots(marco)).find((bot) => bot.id === chief.id)!.tasks!.find((task) => task.inbox)!;+/** Marco's inbox task in each frame about his Chief that reached his live stream. */+const inboxFrames = (frames: Frame[]) => frames.filter((frame) => frame.kind === "bot" && frame.bot?.id === chief.id).map((frame) => frame.bot!.tasks?.find((task) => task.inbox));+const needsYou = async (token: string) => (await team.as(token, "GET", "/api/needs-you")).body.items as Array<{ kind: string; botId?: string; text?: string }>;+const chiefTurns = async () => (await messages(marco, inbox)).rows.filter((row) => row.role === "bot" && row.kind === "text" && !row.inbox);async function until(done: () => Promise<boolean> | boolean, timeoutMs = 60_000): Promise<void> {const end = Date.now() + timeoutMs;@@ -115,7 +123,11 @@ async function passFromScout(message: string) {expect(answer.status, await answer.clone().text()).toBe(200);}/** Philipp's message holds Reporter's turn in its main chat while it asks Marco's approval through its permission socket. */-async function approvalFromReporter(command: string) {+const approvalFromReporter = (command: string) => askedOfMarco((id) => ({ t: "ask", id, tool: "Bash", input: { command } }));+/** Philipp's message holds Reporter's turn in its main chat while it asks Marco a card through its permission socket. Every+ * other turn has ended first, so the turn that writes the dump next is this one. */+async function askedOfMarco(ask: (requestId: string) => Record<string, unknown>) {+ await until(idle);writeFileSync(file("hang-mode"), "");rmSync(file("release"), { force: true });rmSync(file("dump.json"), { force: true });@@ -130,7 +142,7 @@ async function approvalFromReporter(command: string) {socket.on("error", () => {});await new Promise<void>((resolve, reject) => { socket.once("connect", resolve); socket.once("error", reject); });const requestId = randomUUID();- socket.write(`${JSON.stringify({ t: "ask", id: requestId, tool: "Bash", input: { command } })}\n`);+ socket.write(`${JSON.stringify(ask(requestId))}\n`);await expect.poll(async () => (await messages(philipp, reporter.threadId)).rows.some((row) => row.card?.requestId === requestId), { timeout: 10_000 }).toBe(true);return requestId;}@@ -282,7 +294,67 @@ it("never lets the assistant decide or approve for Marco, and never shows it hisexpect(prompt).not.toContain("Globex");}, hostTimeout(180_000));+it("counts the asks waiting on Marco on his inbox, live, and drops one as soon as he answers it in the bot's own chat", async () => {+ expect((await inboxTask()).openAsks, "what came before is answered or only news").toBeUndefined();+ const before = marcos.length;+ const requestId = await approvalFromReporter("rm -rf ./dist");+ await until(async () => (await inboxTask()).openAsks === 1);+ await until(() => inboxFrames(marcos.slice(before)).some((task) => task?.openAsks === 1));+ const answered = await team.as(marco, "POST", `/api/threads/${reporter.threadId}/respond`, { requestId, behavior: "deny" });+ expect(answered.status, JSON.stringify(answered.body)).toBe(200);+ await until(async () => (await inboxTask()).openAsks === undefined);+ await until(() => { const seen = inboxFrames(marcos.slice(before)); return seen.length > 1 && seen.at(-1)!.openAsks === undefined; });+ expect((await inboxLines()).find((row) => row.card?.requestId === requestId)!.card!.answered, "the copy in his inbox follows").toBeTruthy();+ expect((await needsYou(marco)).filter((item) => item.botId === reporter.id)).toEqual([]);+ writeFileSync(file("release"), "");+ await until(idle);+}, hostTimeout(120_000));++it("brings an answer given through the inbox bot's own respond route to the bot that asked, after its turn ended too", async () => {+ const requestId = await askedOfMarco((id) => ({ t: "ask", kind: "question", id, tool: "AskUserQuestion",+ input: { questions: [{ question: "Which chart goes first?", options: [{ label: "Revenue" }, { label: "Costs" }] }] } }));+ await until(async () => (await inboxTask()).openAsks === 1);+ writeFileSync(file("release"), "");+ await until(idle);+ expect((await inboxTask()).openAsks, "a question nobody answered still waits once its turn is over").toBe(1);+ const answered = await team.as(marco, "POST", `/api/bots/${chief.id}/respond`, { threadId: inbox, requestId, behavior: "answer", message: "Revenue" });+ expect(answered.status, JSON.stringify(answered.body)).toBe(200);+ const asked = async () => (await messages(philipp, reporter.threadId)).rows.find((row) => row.card?.requestId === requestId)!;+ await until(async () => { const card = await asked(); return (await messages(philipp, reporter.threadId)).rows.some((row) => row.role === "user" && row.text === "Revenue" && row.replyToId === card.id); });+ expect((await asked()).card!.answered, "Reporter got the answer where it asked").toBe("answer");+ await until(async () => (await inboxTask()).openAsks === undefined);+ expect(await chiefTurns(), "Marco's Chief took no turn").toEqual([]);+ await until(idle);+}, hostTimeout(120_000));++it("takes Marco's 👍 on a line in his inbox back to the bot that asked, which carries on", async () => {+ await passFromScout("Can you send me the slides by Friday?");+ const line = (await inboxLines()).findLast((row) => row.text === "Can you send me the slides by Friday?")!;+ script(null, "Great, the slides are on their way.");+ const reacted = await team.as(marco, "POST", `/api/threads/${inbox}/messages/${line.id}/reactions`, { emoji: "👍" });+ expect(reacted.status, JSON.stringify(reacted.body)).toBe(200);+ await until(async () => (await messages(philipp, philippThread)).rows.some((row) => row.role === "bot" && row.text === "Great, the slides are on their way."));+ expect((await messages(philipp, philippThread)).rows.findLast((row) => row.relay?.kind === "reply"))+ .toMatchObject({ text: 'Marco replied to your message ("Can you send me the slides by Friday?"): 👍', relay: { email: MARCO.email } });+ expect((await inboxLines()).find((row) => row.id === line.id)!.inbox!.answers).toEqual([expect.objectContaining({ by: "person", text: "👍" })]);+ expect(await chiefTurns(), "Marco's Chief took no turn").toEqual([]);+ await until(idle);+}, hostTimeout(120_000));++it("lets a tag Marco answered in the chat it came from leave his Needs you", async () => {+ const main = scout.mainThreadId ?? scout.threadId;+ const tag = "@Marco can you confirm the Q4 numbers?";+ script(null, tag);+ await turn(philipp, scout, main, "Ask Marco to confirm the Q4 numbers.");+ const listed = async () => (await needsYou(marco)).some((item) => item.kind === "message" && item.text === tag);+ await until(listed);+ script(null, "Thanks Marco, the numbers stand.");+ await turn(marco, scout, main, "Confirmed, they are right.");+ expect(await listed()).toBe(false);+}, hostTimeout(120_000));+it("opens Marco's inbox on his first arrival of the day, and forgets it once he leaves", async () => {+ await passFromScout("Can you book the meeting room for Friday?");const arrived = await team.as(marco, "POST", "/api/presence/active", { source: "desktop" });expect(arrived.body.open, JSON.stringify(arrived.body)).toEqual({ botId: chief.id, threadId: inbox });expect((await team.as(marco, "POST", "/api/presence/active", { source: "desktop" })).body.open).toBeUndefined();@@ -296,7 +368,7 @@ it("opens Marco's inbox on his first arrival of the day, and forgets it once heit("has none of it on a My Cloud: no inbox, no person route", async () => {const solo = (await fx.onCloud("POST", "/api/bots", { name: "Solo" })).body.bot as Bot;- expect(solo.tasks?.some((task) => task.inbox) ?? false).toBe(false);+ expect(solo.tasks?.some((task) => task.inbox || task.openAsks !== undefined) ?? false).toBe(false);expect(((await fx.onCloud("GET", "/api/needs-you")).body.items as Array<{ kind: string }>).filter((item) => item.kind === "message")).toEqual([]);expect((await fx.onCloud("GET", "/api/notifications")).body.notifications.filter((entry: { forPerson?: string }) => entry.forPerson)).toEqual([]);}, hostTimeout(60_000));diff --git a/server/host/person-inbox.test.ts b/server/host/person-inbox.test.tsindex 1ab6e91283..93c964550d 100644--- a/server/host/person-inbox.test.ts+++ b/server/host/person-inbox.test.ts@@ -3,7 +3,7 @@ import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import type { Notification } from "../../shared/notification.ts";-import { key, MARCO, PHILIPP, teamInbox } from "../testing/team-inbox-fixture.ts";+import { key, MARCO, PHILIPP, session, teamInbox } from "../testing/team-inbox-fixture.ts";import { PERSON_INBOX_FILE } from "./person-inbox.ts";const fixtures: Array<ReturnType<typeof teamInbox>> = [];@@ -73,6 +73,88 @@ describe("asks routed to a person", () => {});});+describe("what still waits on the person", () => {+ const question = (requestId: string) => ({ title: "Your bot has a question", subtitle: "Which landing page?", options: ["Home", "Pricing"], requestId, requestType: "question" as const });+ const asked = (f: ReturnType<typeof fixture>, threadId: string, requestId: string, made: ReturnType<typeof card | typeof question> = card(requestId)) => {+ if (!f.bots.find((bot) => bot.id === "reporter")!.tasks.some((task) => task.threadId === threadId)) f.bots.find((bot) => bot.id === "reporter")!.tasks.push({ threadId, title: threadId });+ const line = f.store.appendMessage(threadId, { role: "bot", kind: "options", text: made.title, card: made });+ f.team.route(ask("reporter", "Reporter", threadId, made.requestType === "question" ? "question" : "approval"));+ return line;+ };++ it("counts an ask only while the card that asked is open where it was asked, whoever closes it there", () => {+ const f = fixture();+ const counted: number[] = [];+ const patchTask = f.store.patchTask;+ f.store.patchTask = (botId, threadId, patch) => { if (patch.unread) counted.push(f.team.inbox.openAsks(threadId)); return patchTask(botId, threadId, patch); };+ const approval = asked(f, "rep-shared", "req-1");+ const choice = asked(f, "rep-weekly", "req-2", question("req-2"));+ const inbox = f.inboxOf(MARCO).threadId;+ expect(counted, "the inbox goes out to Marco with each new ask already counted").toEqual([1, 2]);+ expect(f.team.inbox.openAsks(inbox)).toBe(2);+ expect(f.team.inbox.wire(inbox)).toEqual({ inbox: true, openAsks: 2 });+ f.store.patchMessage("rep-shared", approval.id, { card: { ...card("req-1"), answered: "allow" } });+ expect(f.team.inbox.openAsks(inbox), "approved where it was asked").toBe(1);+ expect(f.changed).toEqual([inbox]);+ f.store.patchMessage("rep-weekly", choice.id, { card: { ...question("req-2"), dismissed: true } });+ expect(f.team.inbox.openAsks(inbox), "closed without an answer").toBe(0);+ expect(f.team.inbox.wire(inbox)).toEqual({ inbox: true });+ expect(f.lines(inbox).map((row) => row.card)).toEqual([expect.objectContaining({ answered: "allow" }), expect.objectContaining({ dismissed: true })]);+ expect(f.team.inbox.wire("rep-shared"), "only the inbox says it is one").toEqual({});+ });++ it("never counts what is only news: a message, a routine's report or a failure", () => {+ const f = fixture();+ f.team.pass("scout", "philipp-private", "Marco", "Can you review the deck?");+ f.team.route({ kind: "done", botId: "scout", botName: "Scout", threadId: "marco-private", title: "Scout finished", body: "Daily digest: 3 new leads." }, { routine: true });+ f.team.route({ kind: "routine-failed", botId: "reporter", botName: "Reporter", threadId: "rep-main", title: "Reporter's routine failed", body: "Timed out" });+ const inbox = f.inboxOf(MARCO).threadId;+ expect(f.lines(inbox)).toHaveLength(3);+ expect(f.team.inbox.openAsks(inbox)).toBe(0);+ });++ it("keeps what is still open after a restart, and nothing that was settled", () => {+ const f = fixture();+ const settled = asked(f, "rep-shared", "req-1");+ asked(f, "rep-weekly", "req-2");+ f.store.patchMessage("rep-shared", settled.id, { card: { ...card("req-1"), answered: "deny", dismissed: true } });+ f.restart();+ const inbox = f.inboxOf(MARCO).threadId;+ expect(f.team.inbox.openAsks(inbox)).toBe(1);+ f.store.patchMessage("rep-weekly", f.lines("rep-weekly")[0]!.id, { card: { ...card("req-2"), answered: "allow" } });+ expect(f.team.inbox.openAsks(inbox), "the copy still follows the card after the restart").toBe(0);+ expect(f.lines(inbox)[1]!.card).toMatchObject({ answered: "allow" });+ });++ it("closes the copy of an ask whose conversation is gone, so nothing in the inbox waits on a card no one can answer", () => {+ const f = fixture();+ asked(f, "rep-shared", "req-1");+ const inbox = f.inboxOf(MARCO).threadId;+ f.deleteThread("rep-shared");+ expect(f.lines(inbox)[0]!.card).toMatchObject({ answered: "unavailable", dismissed: true });+ expect(f.team.inbox.openAsks(inbox)).toBe(0);+ expect(f.changed).toEqual([inbox]);+ });++ it("lets a message answered where it came from leave Needs you and what the Chief is told waits, through a restart", () => {+ const f = fixture();+ const reply = f.store.appendMessage("scout-main", { role: "bot", kind: "text", text: "@Marco can you confirm the Q4 numbers?", turnId: "t1" });+ f.store.patchMessage("scout-main", reply.id, { turnSucceeded: true });+ const inbox = f.inboxOf(MARCO).threadId;+ expect(f.team.needsYou(session(MARCO.email))).toEqual([expect.objectContaining({ kind: "message", from: "Scout", threadId: inbox })]);+ expect(f.team.prompt("marcos-chief", inbox, true)).toContain('Waiting on "Marco"\'s answer');+ f.said("scout-main", "Philipp here, I'll leave it to Marco.", PHILIPP);+ expect(f.team.needsYou(session(MARCO.email)), "someone else's line answers nothing for Marco").toHaveLength(1);+ f.said("scout-main", "Confirmed, the numbers are right.", MARCO);+ expect(f.team.needsYou(session(MARCO.email))).toEqual([]);+ expect(f.team.inbox.waiting(inbox)).toEqual([]);+ expect(f.team.prompt("marcos-chief", inbox, true)).not.toContain("Waiting on");+ f.restart();+ expect(f.team.needsYou(session(MARCO.email))).toEqual([]);+ expect(f.team.inbox.waiting(inbox)).toEqual([]);+ });+});+describe("the inbox itself", () => {it("becomes the chat the person's brief was in, and moves when they crown another Chief", () => {const f = fixture();diff --git a/server/host/person-inbox.ts b/server/host/person-inbox.tsindex f4459be585..759e7ff334 100644--- a/server/host/person-inbox.ts+++ b/server/host/person-inbox.ts@@ -12,7 +12,9 @@ import { z } from "zod";import { botOwner } from "../../shared/bot-owner.ts";import type { InboxItem } from "../../shared/inbox.ts";+import { liveCardKind } from "../../shared/live-approval.ts";import type { Notification } from "../../shared/notification.ts";+import type { WireTask } from "../../shared/wire.ts";import { ASK_NOTIFICATIONS } from "../ask-routing.ts";import { writeFileAtomic } from "../atomic.ts";import { audienceMember, type Audience } from "../audience.ts";@@ -106,6 +108,8 @@ export interface PersonInboxDeps {notes(botId: string): string;/** Gives a member who has neither a Chief nor a MausBot yet the MausBot every member gets. */ensureOwnBot?(email: string): void;+ /** What waits on this inbox's person may have changed: its bot goes out to them again. */+ changed?(threadId: string): void;now?: () => number;}@@ -190,6 +194,36 @@ export function createPersonInbox(deps: PersonInboxDeps) {const line = (item: Item) => store.messagesFor(item.threadId).find((message) => message.id === item.id);+ /** The card that asked, in the conversation it was asked in; undefined once that conversation is gone. */+ const asking = (item: Item) => item.requestId && item.origin+ ? store.messagesFor(item.origin.threadId).findLast((message) => message.card?.requestId === item.requestId && !message.inbox)+ : undefined;+ /** An ask waits on its person while the card that asked is open where it was asked, however it is answered or closed. */+ const askOpen = (item: Item) => item.kind === "ask" && liveCardKind(asking(item)?.card) !== null;++ /** The person wrote in the conversation a message came from after it reached them: they answered it there. */+ function answeredThere(item: Item): boolean {+ if (item.kind !== "message" || !item.origin) return false;+ const lines = store.messagesFor(item.origin.threadId);+ for (let index = lines.length - 1; index >= 0 && lines[index]!.at > item.at; index--) {+ const said = lines[index]!;+ if (said.role === "user" && !said.peerAsk && said.sender?.id === item.person) return true;+ }+ return false;+ }++ /** Nothing waits on the person any more: an ask's card is closed where it was asked, or a message was answered here or there. */+ const settled = (item: Item) => item.kind === "ask" && item.requestId ? !askOpen(item) : Boolean(item.answered) || answeredThere(item);++ /** How many asks in this inbox wait on its person: questions, approvals and work handed on, open here and where they+ * were asked. */+ function openAsks(threadId: string): number {+ const asks = items.filter((item) => item.threadId === threadId && item.kind === "ask" && item.requestId);+ if (!asks.length) return 0;+ const copies = new Map(store.messagesFor(threadId).map((message) => [message.id, message]));+ return asks.filter((item) => liveCardKind(copies.get(item.id)?.card) !== null && askOpen(item)).length;+ }+function notifyItem(item: Item, title: string, kind: Notification["kind"], body: string): void {const bot = store.bot(item.botId);if (!bot || bot.notifications === false) return;@@ -225,7 +259,6 @@ export function createPersonInbox(deps: PersonInboxDeps) {const posted = store.appendMessage(at.threadId, delivery.card? { role: "bot", kind: "options", text: delivery.text, card: { ...delivery.card }, inbox: wire }: { role: "bot", kind: "text", text: delivery.text, inbox: wire });- store.patchTask(at.bot.id, at.threadId, { unread: true });const item: Item = {id: posted.id, person: to, botId: at.bot.id, threadId: at.threadId, kind: delivery.kind, from: delivery.from.name.slice(0, 200),...(delivery.from.email ? { fromEmail: delivery.from.email } : {}), ...(delivery.from.botId ? { fromBot: delivery.from.botId } : {}),@@ -235,6 +268,7 @@ export function createPersonInbox(deps: PersonInboxDeps) {};items.push(item);save();+ store.patchTask(at.bot.id, at.threadId, { unread: true });if (delivery.representable && deps.representative) void represent(item, delivery, at.bot);else if (!delivery.quiet) notifyItem(item, delivery.title, delivery.notify, delivery.text);return item;@@ -333,15 +367,22 @@ export function createPersonInbox(deps: PersonInboxDeps) {return items.find((item) => item.threadId === threadId && item.requestId === requestId && item.origin)?.origin?.threadId ?? threadId;}+ /** A copy follows the card it was copied from; once that card's conversation is gone, nothing can answer the copy. */+ function follow(item: Item, card: NonNullable<Message["card"]> | null): void {+ const copy = line(item);+ if (!copy?.card) return;+ const next = card ?? (liveCardKind(copy.card) ? { ...copy.card, answered: "unavailable", dismissed: true } : copy.card);+ if (JSON.stringify(copy.card) === JSON.stringify(next)) return;+ store.patchMessage(item.threadId, item.id, { card: { ...next } });+ if (Boolean(liveCardKind(copy.card)) !== Boolean(liveCardKind(next))) deps.changed?.(item.threadId);+ }+const unsubscribe = team ? store.onChange((change: StoreChange) => {if (change.type === "message.patch" && change.message.card?.requestId && !change.message.inbox) {const card = change.message.card;- for (const item of items) {- if (item.requestId !== card.requestId || item.origin?.threadId !== change.threadId) continue;- const copy = line(item);- if (copy?.card && JSON.stringify(copy.card) !== JSON.stringify(card)) store.patchMessage(item.threadId, item.id, { card: { ...card } });- }+ for (const item of items) if (item.requestId === card.requestId && item.origin?.threadId === change.threadId) follow(item, card);} else if (change.type === "thread.deleted") {+ for (const item of items) if (item.requestId && item.origin?.threadId === change.threadId) follow(item, null);const before = items.length;items = items.filter((item) => item.threadId !== change.threadId);for (const [key, at] of Object.entries(homes)) if (at.threadId === change.threadId) delete homes[key];@@ -373,11 +414,18 @@ export function createPersonInbox(deps: PersonInboxDeps) {},/** The lines in this inbox that wait on its person's answer, oldest first. */waiting(threadId: string): Item[] {- return items.filter((item) => item.threadId === threadId && item.to !== undefined && !item.answered);+ return items.filter((item) => item.threadId === threadId && item.to !== undefined && !settled(item));+ },+ openAsks,+ /** A task's wire when it is a person's inbox: that it is, and how many asks wait on them there. */+ wire(threadId: string): Pick<WireTask, "inbox" | "openAsks"> {+ if (!personOf(threadId)) return {};+ const open = openAsks(threadId);+ return { inbox: true, ...(open ? { openAsks: open } : {}) };},- /** What arrived in this person's inbox that they have not opened yet, newest first. */+ /** What arrived in this person's inbox that they have not opened yet and still waits on them, newest first. */unseen(person: string): Item[] {- return items.filter((item) => item.person === person && !item.seen && !item.answered).sort((a, b) => b.at - a.at);+ return items.filter((item) => item.person === person && !item.seen && !settled(item)).sort((a, b) => b.at - a.at);},/** The person opened or wrote in this conversation: what waited there for them is seen. */seen(person: string, threadId: string): void {diff --git a/server/host/team-messages.test.ts b/server/host/team-messages.test.tsindex d8f2be090b..02bf6a8e1b 100644--- a/server/host/team-messages.test.ts+++ b/server/host/team-messages.test.ts@@ -64,6 +64,23 @@ describe("message_person", () => {expect(f.notified).toEqual([]);});+ it("takes a 👍 on a line of the inbox as the answer: back to the bot that asked, which carries on, and the line is answered", async () => {+ const f = fixture();+ f.team.pass("scout", "philipp-private", "Marco", "Can you review the deck?");+ f.team.route({ kind: "done", botId: "scout", botName: "Scout", threadId: "marco-private", title: "Scout finished", body: "Daily digest." }, { routine: true });+ const inbox = f.inboxOf(MARCO).threadId;+ const [item, report] = f.lines(inbox);+ const sender = { name: "Marco", id: key(MARCO.email) };+ await expect(f.team.reactedIn(session(MARCO.email), inbox, item!.id, "👍", { sendId: "reaction-1", sender })).resolves.toEqual({ queued: false });+ expect(f.continued).toEqual([expect.objectContaining({ botId: "scout", threadId: "philipp-private", text: 'Marco replied to your message ("Can you review the deck?"): 👍' })]);+ expect(f.lines(inbox).find((row) => row.sendId === "reaction-1")).toMatchObject({ role: "user", text: "👍", reaction: "👍", replyToId: item!.id });+ expect(f.team.inbox.waiting(inbox)).toEqual([]);+ await expect(f.team.reactedIn(session(MARCO.email), inbox, item!.id, "👍", { sendId: "reaction-1", sender }), "the same reaction again").resolves.toEqual({ queued: false, repeated: true });+ expect(f.continued).toHaveLength(1);+ expect(f.team.reactedIn(session(MARCO.email), inbox, report!.id, "👍", { sendId: "reaction-2", sender }), "a report waits on nothing: the inbox's bot gets it").toBeNull();+ expect(f.team.reactedIn(session(PHILIPP.email), inbox, item!.id, "👍", { sendId: "reaction-3", sender }), "only its own person answers from it").toBeNull();+ });+it("lets the person's Chief pass their answer back from the inbox, to whoever sent it", () => {const f = fixture();f.team.pass("reporter", "rep-main", "Marco", "Which chart goes first?");diff --git a/server/host/team-messages.ts b/server/host/team-messages.tsindex 0f042688ff..60409e9eab 100644--- a/server/host/team-messages.ts+++ b/server/host/team-messages.ts@@ -54,7 +54,7 @@ export interface TeamMessagesDeps {sees(person: { email: string; role: TeamRole }): { bot(botId: string): boolean; thread(threadId: string): boolean };notify(notification: Notification): void;/** What the inbox needs from the server: whose asks are whose, hand-offs, a bot carrying on, the assistant's reads. */- inbox: Pick<PersonInboxDeps, "askedPerson" | "handedFrom" | "continueTurn"> & Partial<Pick<PersonInboxDeps, "notes" | "ensureOwnBot">> & {+ inbox: Pick<PersonInboxDeps, "askedPerson" | "handedFrom" | "continueTurn"> & Partial<Pick<PersonInboxDeps, "notes" | "ensureOwnBot" | "changed">> & {representative?: Omit<RepresentativeDeps, "timeZone"> & Partial<Pick<RepresentativeDeps, "timeZone">>;};now?: () => number;@@ -267,6 +267,23 @@ export function createTeamMessages(deps: TeamMessagesDeps) {const arrivedOn = new Map<string, string>();const sessionPerson = (auth: RequestAuth) => (auth.kind === "session" && auth.session.email ? byKey(keyOf(auth.session.email)) : undefined);+ /** A reply this inbox's own person wrote to one of its lines: it goes back where the line came from, and this inbox's+ * bot takes no turn. Null for any other line, which is sent as usual. */+ function replyIn(auth: RequestAuth, threadId: string, replyToId: string, text: string, line: { sendId?: string; sender?: ResolvedSender; reaction?: string }): { status: number; message?: Message; error?: string } | null {+ const me = sessionPerson(auth);+ if (!team || !me || inbox.personOf(threadId) !== me.key) return null;+ const item = inbox.replyable(threadId, replyToId);+ if (!item) return null;+ const again = line.sendId ? store.messagesFor(threadId).find((message) => message.sendId === line.sendId) : undefined;+ if (again) return { status: 202, message: again };+ if (recent(threadId).length >= MESSAGE_PERSON_HOURLY) return { status: 429, error: tooMany().text };+ const posted = store.appendMessage(threadId, { role: "user", kind: "text", text, replyToId, ...(line.sendId ? { sendId: line.sendId } : {}),+ ...(line.sender ? { sender: line.sender } : {}), ...(line.reaction ? { reaction: line.reaction } : {}) });+ const back = answerFromInbox(threadId, null, item, text);+ if (back.status !== 200) store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `Not passed to ${item.from}`, ok: false, output: back.text } });+ return { status: 202, message: posted };+ }+function inboxPrompt(threadId: string, own: string | null): string {if (!own || inbox.personOf(threadId) !== own) return "";const person = byKey(own);@@ -305,20 +322,15 @@ export function createTeamMessages(deps: TeamMessagesDeps) {const text = people + inboxPrompt(threadId, own);return text ? `${text}\n` : "";},- /** A reply this inbox's own person wrote to one of its lines: it goes back where the line came from, and this- * inbox's bot takes no turn. Null for any other line, which is sent as usual. */- replyIn(auth: RequestAuth, threadId: string, replyToId: string, text: string, line: { sendId?: string; sender?: ResolvedSender }): { status: number; message?: Message; error?: string } | null {- const me = sessionPerson(auth);- if (!team || !me || inbox.personOf(threadId) !== me.key) return null;- const item = inbox.replyable(threadId, replyToId);- if (!item) return null;- const again = line.sendId ? store.messagesFor(threadId).find((message) => message.sendId === line.sendId) : undefined;- if (again) return { status: 202, message: again };- if (recent(threadId).length >= MESSAGE_PERSON_HOURLY) return { status: 429, error: tooMany().text };- const posted = store.appendMessage(threadId, { role: "user", kind: "text", text, replyToId, ...(line.sendId ? { sendId: line.sendId } : {}), ...(line.sender ? { sender: line.sender } : {}) });- const back = answerFromInbox(threadId, null, item, text);- if (back.status !== 200) store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `Not passed to ${item.from}`, ok: false, output: back.text } });- return { status: 202, message: posted };+ replyIn,+ /** A 👍 or 👎 this inbox's own person gives one of its lines: their answer, back where the line came from, as a+ * reply would be. Null for any other line, which the reaction reaches as usual. */+ reactedIn(auth: RequestAuth, threadId: string, messageId: string, emoji: string, line: { sendId: string; sender?: ResolvedSender }): Promise<{ queued: false; repeated?: true }> | null {+ const repeated = store.messagesFor(threadId).some((message) => message.sendId === line.sendId);+ const passed = replyIn(auth, threadId, messageId, emoji, { ...line, reaction: emoji });+ if (!passed) return null;+ if (passed.status >= 400) return Promise.reject(Object.assign(new Error(passed.error ?? "That answer can't be passed back."), { status: passed.status }));+ return Promise.resolve(repeated ? { queued: false, repeated: true } : { queued: false });},/** This person's Needs you lines: the messages in their inbox they have not opened, newest first. */needsYou(auth: RequestAuth): NeedsYouItem[] {diff --git a/server/index.ts b/server/index.tsindex 7161a045fd..039ec36f1e 100644--- a/server/index.ts+++ b/server/index.ts@@ -2913,7 +2913,7 @@ const { cloudLendingTurn, cloudLendingRefusalNotice, cloudLendingRefusal, cloudTconst { stopThreadForPerson, stopOnTypedCommand, 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({ 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, 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 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)), 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 });const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,defaults: () => [cfg.defaultModelSelection, cfg.newBotDefaults?.profile.modelSelection], engineName: id => registry.get(id)?.displayName ?? id,@@ -2998,7 +2998,7 @@ const wireTask = (task: TaskRecord, botModel: ModelSelection, awaiting = threads// Snoozes heal on read against the server clock; the 0 sentinel ("until new activity") survives reads.const { snoozedUntil, ...base } = toWireTask(task, botModel);const keepWarm = cacheKeepWarmStatus(task.threadId);- const coordinated = { ...base, waitingForTeammates: awaiting.has(task.threadId) && !task.busy, ...(keepWarm ? { cacheKeepWarm: keepWarm } : {}), ...(teamHost.ownTurn(task.threadId) ? { private: true as const } : {}), ...(teamMessages.inbox.personOf(task.threadId) ? { inbox: true as const } : {}) };+ const coordinated = { ...base, waitingForTeammates: awaiting.has(task.threadId) && !task.busy, ...(keepWarm ? { cacheKeepWarm: keepWarm } : {}), ...(teamHost.ownTurn(task.threadId) ? { private: true as const } : {}), ...teamMessages.inbox.wire(task.threadId) };const asleep = snoozedUntil === 0 || (snoozedUntil !== undefined && snoozedUntil > Date.now());return asleep ? { ...coordinated, snoozedUntil } : coordinated;};@@ -12521,7 +12521,7 @@ const chatApps = createChatApps({ store, dataDir: DATA_DIR });const chatAppsMcp = createChatAppsMcp({ store, apps: chatApps, dataDir: DATA_DIR, storedServers: () => cfg.mcpServers ?? {}, mountedServers: engineMcpServers, personMcp: teamConnections.personMcp, oauth: mcpOAuth });ROUTES.push(createChatAppRoutes({ store, apps: chatApps, threadRefusal: cloudThreadRefusal, mcpRpc: chatAppsMcp.rpc }));const { react } = createReactions({- store, reply: (input) => personReplies.deliver({ ...input, about: "message" }),+ store, reply: (input) => teamMessages.reactedIn(input.auth, input.threadId, input.target.id, input.answer, { sendId: input.sendId, sender: messageSender(input.auth) }) ?? personReplies.deliver({ ...input, about: "message" }),answerCard: (input) => respondToCard({ ...input, via: "reaction" }), withdraw: personReplies.withdraw,});const publishedPages = createPublishedPages({ dataDir: DATA_DIR, cloudHome: CLOUD_HOME, patch: (threadId, messageId, text, publishedPage) => void store.patchMessage(threadId, messageId, { text, publishedPage }), apps: { chat: chatApps, store } }); ROUTES.push(createReactionRoutes({ react, reactorFor, cloudGuestSendRefusal }), publishedPages.routes);diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.tsindex 0a51acd6ed..c7c32fcf44 100644--- a/server/routes/bot-messages.ts+++ b/server/routes/bot-messages.ts@@ -167,7 +167,8 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler/** widget -> sendId of a press on its way in: a second tap before acceptance must not send a second answer. */const pressesInFlight = new Map<string, string | undefined>();const appMessageRate = new AppMessageRate();- return async ({ req, res, path, method, auth, json, readBody }) => {+ const route: RouteHandler = async (ctx) => {+ const { req, res, path, method, auth, json, readBody } = ctx;let m: RegExpMatchArray | null = null;const requirePinnedClientThread = pinnedClientThread(auth, req);const routines = deps.routines();@@ -499,7 +500,11 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerif (m && method === "POST") {const body = await readBody(req);const selected = requestedTaskBot(m[1], body.threadId);- const bot = botForThread(selected.id, answeredIn(selected.threadId, String(body.requestId)))!;+ const answering = answeredIn(selected.threadId, String(body.requestId));+ if (answering !== selected.threadId && !store.taskByThread(selected.id, answering)) {+ return route({ ...ctx, path: `/api/threads/${selected.threadId}/respond`, readBody: async () => body });+ }+ const bot = botForThread(selected.id, answering)!;const behavior = requestBehavior(body.behavior);const reviewedSha256 = typeof body.reviewedSha256 === "string" ? body.reviewedSha256 : undefined;if (!behavior) return json(res, 400, { error: "behavior must be allow, deny, or answer" });@@ -749,4 +754,5 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler}return PASS;};+ return route;}diff --git a/server/testing/team-inbox-fixture.ts b/server/testing/team-inbox-fixture.tsindex e4085207ec..d75e185b34 100644--- a/server/testing/team-inbox-fixture.ts+++ b/server/testing/team-inbox-fixture.ts@@ -43,7 +43,8 @@ export function teamInbox(options: { team?: boolean; representative?: TeamMessag].filter((bot) => !(options.noChiefFor ?? []).includes(bot.reportsTo ?? "") || !bot.chiefOfStaff) as Bot[];const groups = [{ id: "room", name: "Launch", threadId: "room-thread", memberIds: ["scout"] }];const roomPeople = new Set([key(PHILIPP.email), key(MARCO.email)]);- let made = 0, ids = 0;+ let made = 0, ids = 0, clock = 0;+ const tick = () => (clock = Math.max(Date.now(), clock + 1));const unread: string[] = [];const store = {bots,@@ -58,7 +59,7 @@ export function teamInbox(options: { team?: boolean; representative?: TeamMessagreturn task;},appendMessage: (threadId: string, message: Omit<Message, "id" | "at">) => {- const full = { id: `m${++ids}`, at: Date.now(), ...message } as Message;+ const full = { id: `m${++ids}`, at: tick(), ...message } as Message;threads.set(threadId, [...(threads.get(threadId) ?? []), full]);emit({ type: "message", threadId, message: full });return full;@@ -85,9 +86,11 @@ export function teamInbox(options: { team?: boolean; representative?: TeamMessagconst notified: Notification[] = [];const continued: Array<{ botId: string; threadId: string; text: string; from: { botId: string; name: string }; relay: Message["relay"] }> = [];const audienceOf = (threadId: string): Audience => audiences.get(threadId) ?? (starters.has(threadId) ? memberAudience(starters.get(threadId)!) : "team");- const team = createTeamMessages({+ const changed: string[] = [];+ const make = () => createTeamMessages({team: options.team === false ? null : { id: "team-acme", name: "Acme" },dataDir,+ now: tick,store: store as never,people: { everyone: () => people.map(({ email, role, leftAt }) => ({ email, role, firstSeenAt: 1, lastSeenAt: 1, ...(leftAt ? { leftAt } : {}) })) },personName: (person) => people.find((one) => key(one.email) === person)?.name,@@ -111,17 +114,23 @@ export function teamInbox(options: { team?: boolean; representative?: TeamMessagreturn owner ? key(owner) : null;},continueTurn: (botId, threadId, text, from, relay) => { continued.push({ botId, threadId, text, from, relay }); },+ changed: (threadId) => { changed.push(threadId); },handedFrom: (threadId) => options.handed?.[threadId] ?? null,notes: (botId) => ({ reporter: "The Q4 report draft is due on Nov 3.", scout: "Philipp's notes.", "marcos-mausbot": "Notes only Marco sees." })[botId] ?? "",...(options.representative ? { representative: options.representative } : {}),},});+ let team = make();const lines = (threadId: string) => threads.get(threadId) ?? [];const said = (threadId: string, text: string, who: { email: string; name: string }, extra: Partial<Message> = {}) =>store.appendMessage(threadId, { role: "user", kind: "text", text, sender: { name: who.name, id: key(who.email) }, ...extra });const inboxOf = (who: { email: string }) => team.inbox.home(key(who.email))!;return {- team, store, lines, notified, continued, unread, said, bots, audiences, starters, dataDir, inboxOf,+ get team() { return team; },+ store, lines, notified, continued, changed, unread, said, bots, audiences, starters, dataDir, inboxOf,+ /** The server starts again: the inbox reads back what it kept, over the same conversations. */+ restart: () => { team.stop(); team = make(); },+ deleteThread: (threadId: string) => { threads.delete(threadId); emit({ type: "thread.deleted", threadId }); },close: () => { team.stop(); rmSync(dataDir, { recursive: true, force: true }); },};}diff --git a/shared/wire.ts b/shared/wire.tsindex ac700111db..0371de4298 100644--- a/shared/wire.ts+++ b/shared/wire.ts@@ -148,6 +148,8 @@ export interface WireTask {private?: true;/** On a team's server: this person's inbox, the conversation with their Chief where everything for them arrives. */inbox?: true;+ /** On a person's inbox: how many asks (questions, approvals, work handed on) still wait where they were asked; absent: none. */+ openAsks?: number;/** Set by close_thread; absent while the thread is open. */closedBy?: TaskClosedBy;archivedAt?: number;diff --git a/src/App.tsx b/src/App.tsxindex 2e89e9bc80..273129f1ae 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -52,7 +52,7 @@ import { CommandPalette } from "@/components/CommandPalette";import { setLocale, t } from "@/lib/i18n";import { shouldOpenKeyboardShortcuts } from "@/lib/keyboard-shortcuts";import { effectiveLanguage, useLanguageChoice } from "@/lib/language-preference";-import { botShowsUnread, showBrowserUnread } from "@/lib/bot-unread";+import { botUnreadCount, showBrowserUnread } from "@/lib/bot-unread";import { phonePairingSettingsAction, takePhonePairingRequest } from "@/lib/phone-pairing"; import { takeConnectRequest } from "@/lib/connect-link";import { useExternalChatLinks } from "@/hooks/use-external-chat-links";import { useUsageSnapshot } from "@/hooks/use-usage-snapshot";@@ -73,7 +73,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {const { capabilities } = useDesktopCapabilities();const captionChrome = useCaptionChrome();const unreadCount =- state.bots.filter((bot) => !bot.hidden && botShowsUnread(bot)).length ++ state.bots.filter((bot) => !bot.hidden).reduce((sum, bot) => sum + botUnreadCount(bot), 0) +state.groups.filter((group) => group.unread).length;const remoteClient = window.ogb?.remoteClient?.active === true;const twoSidePanelsFit = useMediaQuery(TWO_SIDE_PANELS_FIT, true);diff --git a/src/components/SidebarPeople.test.ts b/src/components/SidebarPeople.test.tsindex a2febc19b4..43e5b1c8ae 100644--- a/src/components/SidebarPeople.test.ts+++ b/src/components/SidebarPeople.test.ts@@ -3,7 +3,7 @@ import { renderToStaticMarkup } from "react-dom/server";import { afterEach, describe, expect, it, vi } from "vitest";import { initialState, StoreContext, type AppState, type Bot, type Message } from "@/state/store";-import { setTeamPeople, type TeamPeople } from "@/state/team-people";+import { needsYouVersion, setTeamPeople, type TeamPeople } from "@/state/team-people";import { InboxAnswers, InboxCaption, RelayLabel } from "./InboxLine";import { inboxBotOf, SidebarPeople } from "./SidebarPeople";@@ -39,6 +39,25 @@ describe("the team's people in the sidebar", () => {expect(render(createElement(SidebarPeople, { compact: false }))).toBe("");});+ it("counts the asks waiting on you on your inbox row, and shows no count when none wait", () => {+ setTeamPeople(asMarco);+ const inbox = (openAsks?: number) => bot({ id: "mc", name: "Marco's Chief", chiefOfStaff: true, reportsTo: MARCO.email,+ tasks: [{ threadId: "inbox", title: "Inbox", createdAt: 1, inbox: true, ...(openAsks ? { openAsks } : {}) }] });+ const waiting = render(createElement(SidebarPeople, { compact: false }), { bots: [inbox(2)] });+ expect(waiting).toMatch(/aria-label="Your inbox: waiting on you, 2"[^>]*data-person="[email protected]"/);+ expect(waiting).toMatch(/data-inbox-waiting="2"[^>]*>2<\/span>/);+ expect(render(createElement(SidebarPeople, { compact: true }), { bots: [inbox(2)] }), "on the rail too").toContain('data-inbox-waiting="2"');+ const none = render(createElement(SidebarPeople, { compact: false }), { bots: [inbox()] });+ expect(none).toContain('aria-label="Your inbox: everything sent to you"');+ expect(none).not.toContain("data-inbox-waiting");+ });++ it("refreshes Needs you as soon as an ask in the inbox is answered or closed", () => {+ const tasks = (openAsks?: number) => [bot({ id: "mc", tasks: [{ threadId: "inbox", title: "Inbox", createdAt: 1, inbox: true, ...(openAsks ? { openAsks } : {}) }] })];+ expect(needsYouVersion(tasks(1), [], [])).not.toBe(needsYouVersion(tasks(), [], []));+ expect(needsYouVersion(tasks(2), [], [])).toBe(needsYouVersion(tasks(2), [], []));+ });+it("finds the person's inbox with their own Chief, else their own MausBot", () => {const mausbot = bot({ id: "mm", name: "MausBot", defaultBot: { person: MARCO.email } });const chief = bot({ id: "mc", name: "Marco's Chief", chiefOfStaff: true, reportsTo: MARCO.email });diff --git a/src/components/SidebarPeople.tsx b/src/components/SidebarPeople.tsxindex f5ac228b3b..3fcfe45b05 100644--- a/src/components/SidebarPeople.tsx+++ b/src/components/SidebarPeople.tsx@@ -1,6 +1,8 @@// On a Team Cloud: the team's people, with their pictures. Your own row opens your inbox, your chat with your Chief, where-// everything sent to you arrives. Anyone else's puts @their name in the composer, which reaches their inbox once sent.+// everything sent to you arrives, and counts the asks waiting on you there. Anyone else's puts @their name in the+// composer, which reaches their inbox once sent.import { botOwner } from "../../shared/bot-owner";+import { openAsksOf } from "@/lib/bot-unread";import { cn } from "@/lib/cn";import { leadComposerDraft } from "@/lib/drafts";import { t } from "@/lib/i18n";@@ -36,6 +38,7 @@ export function SidebarPeople({ compact }: { compact: boolean }) {const people = [...team.people].sort((a, b) => Number(Boolean(b.you)) - Number(Boolean(a.you)) || a.name.localeCompare(b.name));const inbox = inboxBotOf(state.bots, me?.email);const inboxThread = inbox?.tasks?.find((task) => task.inbox)?.threadId;+ const waiting = inbox ? openAsksOf(inbox) : 0;const open = (person: TeamPerson) => {if (person.you) {if (inbox) openBot(dispatch, inbox, showThreads);@@ -55,13 +58,18 @@ export function SidebarPeople({ compact }: { compact: boolean }) {{!compact && <div className="px-2 pb-0.5 pt-1 text-[11px] font-medium text-ink-tertiary">{t("sidebar.people.title")}</div>}<ul className={cn("flex", compact ? "flex-col items-center gap-1" : "flex-col")}>{people.map((person) => {- const label = person.you ? t("sidebar.people.yourInbox") : t("sidebar.people.mention", { name: person.name });+ const label = !person.you ? t("sidebar.people.mention", { name: person.name })+ : waiting ? t("sidebar.people.yourInboxWaiting", { count: waiting }) : t("sidebar.people.yourInbox");return (<li key={person.email}><button type="button" onClick={() => open(person)} aria-label={label} title={label} data-person={person.email}- className={cn("flex w-full min-w-0 items-center gap-2 rounded-lg text-left text-[13px] text-ink hover:bg-raised/60", compact ? "p-1" : "px-2 py-1")}>+ className={cn("relative flex w-full min-w-0 items-center gap-2 rounded-lg text-left text-[13px] text-ink hover:bg-raised/60", compact ? "p-1" : "px-2 py-1")}><PersonFace person={person} size={compact ? 22 : 18} />{!compact && <span className="min-w-0 flex-1 truncate">{person.you ? t("sidebar.people.you", { name: person.name }) : person.name}</span>}+ {person.you && waiting > 0 && (+ <span aria-hidden="true" data-inbox-waiting={waiting}+ className={cn("rounded-full bg-warning px-1.5 text-[11px] font-semibold tabular-nums text-panel", compact && "absolute -right-0.5 -top-0.5 px-1 text-[10px]")}>{waiting}</span>+ )}</button></li>);diff --git a/src/lib/bot-unread.test.ts b/src/lib/bot-unread.test.tsindex 26c605704e..f79edba37e 100644--- a/src/lib/bot-unread.test.ts+++ b/src/lib/bot-unread.test.ts@@ -1,6 +1,21 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { showBrowserUnread, titleWithUnread } from "./bot-unread";+import { botUnreadCount, showBrowserUnread, titleWithUnread } from "./bot-unread";++describe("what one bot adds to the unread count", () => {+ it("adds one while it shows unread, and nothing once read, as it always did", () => {+ expect(botUnreadCount({ tasks: [{ unread: true }, { unread: true }] })).toBe(1);+ expect(botUnreadCount({ unread: true })).toBe(1);+ expect(botUnreadCount({ tasks: [{ unread: false }] })).toBe(0);+ });++ it("adds each ask waiting on the person in their inbox, read or not, and drops them as they are settled", () => {+ expect(botUnreadCount({ tasks: [{ unread: true, openAsks: 3 }] })).toBe(3);+ expect(botUnreadCount({ tasks: [{ unread: false, openAsks: 2 }] })).toBe(2);+ expect(botUnreadCount({ tasks: [{ unread: true, openAsks: 1 }] })).toBe(1);+ expect(botUnreadCount({ tasks: [{ unread: false }] }), "all settled").toBe(0);+ });+});describe("browser unread indicator", () => {afterEach(() => vi.unstubAllGlobals());diff --git a/src/lib/bot-unread.ts b/src/lib/bot-unread.tsindex 11a47cbdb9..97f2345f8f 100644--- a/src/lib/bot-unread.ts+++ b/src/lib/bot-unread.ts@@ -1,11 +1,23 @@-export function botShowsUnread(bot: {+type UnreadBot = {unread?: boolean;- tasks?: ReadonlyArray<{ unread?: boolean; routineRunId?: string; archivedAt?: number }> | null;-}): boolean {+ tasks?: ReadonlyArray<{ unread?: boolean; routineRunId?: string; archivedAt?: number; openAsks?: number }> | null;+};++export function botShowsUnread(bot: UnreadBot): boolean {if (!bot.tasks?.length) return Boolean(bot.unread);return bot.tasks.some((task) => Boolean(task.unread) && !task.routineRunId && task.archivedAt === undefined);}+/** The asks waiting on the person in a bot's conversations: on a team, the ones in their inbox. */+export function openAsksOf(bot: Pick<UnreadBot, "tasks">): number {+ return (bot.tasks ?? []).reduce((sum, task) => sum + (task.openAsks ?? 0), 0);+}++/** What one bot adds to the unread count: one while it shows unread, or each ask waiting in it when they are more. */+export function botUnreadCount(bot: UnreadBot): number {+ return Math.max(botShowsUnread(bot) ? 1 : 0, openAsksOf(bot));+}+const SHOWN_COUNT = /^\(\d+\) /;/** Puts the count in front of the page's own title, in place of a count shown before. */diff --git a/src/locales/de.json b/src/locales/de.jsonindex cbca973e8d..6df9a9e269 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -524,6 +524,7 @@"sidebar.people.title": "Personen","sidebar.people.you": "{name} (du)","sidebar.people.yourInbox": "Dein Posteingang: alles, was an dich geht",+ "sidebar.people.yourInboxWaiting": "Dein Posteingang: wartet auf dich, {count}","sidebar.people.mention": "{name} schreiben","orgChart.mode.departments": "Abteilungen","orgChart.mode.people": "Wer berichtet an wen",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 93f419122f..a92586c257 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -1663,6 +1663,7 @@"sidebar.people.title": "People","sidebar.people.you": "{name} (you)","sidebar.people.yourInbox": "Your inbox: everything sent to you",+ "sidebar.people.yourInboxWaiting": "Your inbox: waiting on you, {count}","sidebar.people.mention": "Write to {name}","orgChart.mode.departments": "Departments","orgChart.mode.people": "Who reports to whom",diff --git a/src/locales/es.json b/src/locales/es.jsonindex f5850113fa..989e4bba5a 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -1419,6 +1419,7 @@"sidebar.people.title": "Personas","sidebar.people.you": "{name} (tú)","sidebar.people.yourInbox": "Tu bandeja de entrada: todo lo que te envían",+ "sidebar.people.yourInboxWaiting": "Tu bandeja de entrada: te esperan, {count}","sidebar.people.mention": "Escribir a {name}","orgChart.mode.departments": "Departamentos","orgChart.mode.people": "Quién reporta a quién",diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex c29acfc456..b594b861cc 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -443,6 +443,7 @@"sidebar.people.title": "Personnes","sidebar.people.you": "{name} (vous)","sidebar.people.yourInbox": "Votre boîte de réception : tout ce qu'on vous envoie",+ "sidebar.people.yourInboxWaiting": "Votre boîte de réception : en attente de vous, {count}","sidebar.people.mention": "Écrire à {name}","orgChart.mode.departments": "Départements","orgChart.mode.people": "Qui rend compte à qui",diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex d3e1cecc3e..51ecd8c8e8 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -443,6 +443,7 @@"sidebar.people.title": "लोग","sidebar.people.you": "{name} (आप)","sidebar.people.yourInbox": "आपका इनबॉक्स: आपको भेजा गया सब कुछ",+ "sidebar.people.yourInboxWaiting": "आपका इनबॉक्स: आपके इंतज़ार में, {count}","sidebar.people.mention": "{name} को लिखें","orgChart.mode.departments": "विभाग","orgChart.mode.people": "कौन किसे रिपोर्ट करता है",diff --git a/src/locales/it.json b/src/locales/it.jsonindex 2ebbe5756f..628cf9e38b 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -6201,6 +6201,7 @@"sidebar.people.title": "Persone","sidebar.people.you": "{name} (tu)","sidebar.people.yourInbox": "La tua posta in arrivo: tutto ciò che ti viene inviato",+ "sidebar.people.yourInboxWaiting": "La tua posta in arrivo: in attesa di te, {count}","sidebar.people.mention": "Scrivi a {name}","approval.yourComputer.browserSite": "Devo usare il tuo {app}, dove hai effettuato l'accesso a {site}. Consenti una volta?","approval.yourComputer.browser": "Devo usare il tuo {app}, dove hai effettuato l'accesso. Consenti una volta?",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 0c5499d007..d472ebe799 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -1611,6 +1611,7 @@"sidebar.people.title": "メンバー","sidebar.people.you": "{name}(あなた)","sidebar.people.yourInbox": "あなたの受信箱:あなた宛てのものがすべて届きます",+ "sidebar.people.yourInboxWaiting": "あなたの受信箱:あなたの対応待ち、{count} 件","sidebar.people.mention": "{name}さんに書く","orgChart.mode.departments": "部署","orgChart.mode.people": "報告関係",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex 2810628f36..c49bdca5dd 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -6324,6 +6324,7 @@"sidebar.people.title": "Osoby","sidebar.people.you": "{name} (ty)","sidebar.people.yourInbox": "Twoja skrzynka: wszystko, co do ciebie trafia",+ "sidebar.people.yourInboxWaiting": "Twoja skrzynka: czeka na ciebie, {count}","sidebar.people.mention": "Napisz do: {name}","helperIntro.watch": "Pilnuję też Twojego dnia i wysyłam Ci krótkie podsumowanie.","approval.yourComputer.browserSite": "Muszę użyć aplikacji {app}, w której jesteś zalogowany na {site}. Zezwolić raz?",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 67494e0881..52d28dc1ea 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -1481,6 +1481,7 @@"sidebar.people.title": "Pessoas","sidebar.people.you": "{name} (você)","sidebar.people.yourInbox": "Sua caixa de entrada: tudo o que é enviado para você",+ "sidebar.people.yourInboxWaiting": "Sua caixa de entrada: esperando por você, {count}","sidebar.people.mention": "Escrever para {name}","orgChart.mode.departments": "Departamentos","orgChart.mode.people": "Quem responde a quem",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex bb87ad25cd..c4b490f5ec 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -1610,6 +1610,7 @@"sidebar.people.title": "Люди","sidebar.people.you": "{name} (вы)","sidebar.people.yourInbox": "Ваши входящие: всё, что вам отправили",+ "sidebar.people.yourInboxWaiting": "Ваши входящие: ждут вас, {count}","sidebar.people.mention": "Написать: {name}","orgChart.mode.departments": "Отделы","orgChart.mode.people": "Кому кто подчиняется",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex 01bba3176b..f617ac65d3 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -1175,6 +1175,7 @@"sidebar.people.title": "Kişiler","sidebar.people.you": "{name} (sen)","sidebar.people.yourInbox": "Gelen kutun: sana gönderilen her şey",+ "sidebar.people.yourInboxWaiting": "Gelen kutun: seni bekliyor, {count}","sidebar.people.mention": "{name} kişisine yaz","orgChart.mode.departments": "Departmanlar","orgChart.mode.people": "Kim kime rapor veriyor",diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex 0b54de0fa7..c391dbb093 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -559,6 +559,7 @@"sidebar.people.title": "Люди","sidebar.people.you": "{name} (ви)","sidebar.people.yourInbox": "Ваші вхідні: усе, що вам надіслали",+ "sidebar.people.yourInboxWaiting": "Ваші вхідні: чекає на вас, {count}","sidebar.people.mention": "Написати: {name}","orgChart.mode.departments": "Відділи","orgChart.mode.people": "Хто кому звітує",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex c468e906b7..3742cd03ce 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -1175,6 +1175,7 @@"sidebar.people.title": "Mọi người","sidebar.people.you": "{name} (bạn)","sidebar.people.yourInbox": "Hộp thư của bạn: mọi thứ gửi cho bạn",+ "sidebar.people.yourInboxWaiting": "Hộp thư của bạn: đang chờ bạn, {count}","sidebar.people.mention": "Viết cho {name}","orgChart.mode.departments": "Phòng ban","orgChart.mode.people": "Ai báo cáo cho ai",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex c258f1fe37..25fc04ff1d 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -1008,6 +1008,7 @@"sidebar.people.title": "成員","sidebar.people.you": "{name}(你)","sidebar.people.yourInbox": "你的收件匣:寄給你的一切都在這裡",+ "sidebar.people.yourInboxWaiting": "你的收件匣:待你處理,{count}","sidebar.people.mention": "寫給 {name}","orgChart.mode.departments": "部門","orgChart.mode.people": "回報關係",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex d1fd7039a9..4b45b3645a 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -701,6 +701,7 @@"sidebar.people.title": "成员","sidebar.people.you": "{name}(你)","sidebar.people.yourInbox": "你的收件箱:发给你的一切都在这里",+ "sidebar.people.yourInboxWaiting": "你的收件箱:待你处理,{count}","sidebar.people.mention": "写给 {name}","orgChart.mode.departments": "部门","orgChart.mode.people": "汇报关系",diff --git a/src/state/store.tsx b/src/state/store.tsxindex e1df48c938..ea75c8de77 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -233,7 +233,7 @@ export interface ModelSelection {variant?: string;}-export interface Task extends Pick<WireTask, "private" | "setupRequest" | "inbox"> {+export interface Task extends Pick<WireTask, "private" | "setupRequest" | "inbox" | "openAsks"> {waitingForTeammates?: boolean;threadId: string;routineRunId?: string;diff --git a/src/state/team-people.ts b/src/state/team-people.tsindex 6864b5ff14..53bd5bbf07 100644--- a/src/state/team-people.ts+++ b/src/state/team-people.ts@@ -6,6 +6,7 @@ import { mentionablePeople } from "../../shared/person-mention";import type { NeedsYouItem } from "../../shared/today";import { api } from "./api";import { teamOfConfig } from "./team-chats";+import { openAsksOf } from "@/lib/bot-unread";import { readSessionState } from "@/lib/session";/** `pictureUrl`: their picture, served to the team's members only; absent when they have none. */@@ -95,11 +96,11 @@ export function refreshNeedsYou(): void {}, 800);}-type VersionedBot = { id: string; reportsTo?: string; activity?: string; tasks?: ReadonlyArray<{ activity?: string; unread?: boolean }> };+type VersionedBot = { id: string; reportsTo?: string; activity?: string; tasks?: ReadonlyArray<{ activity?: string; unread?: boolean; openAsks?: number }> };/** Changes whenever something may have reached or left this person's Needs you: an owner, a bot's work, a conversation- * read or not, a notification. */+ * read or not, an ask in their inbox answered or closed, a notification. */export function needsYouVersion(bots: readonly VersionedBot[], groups: ReadonlyArray<{ unread?: boolean }>, notifications: ReadonlyArray<{ read: boolean }>): string {- const bot = (one: VersionedBot) => `${one.id}:${one.reportsTo ?? ""}:${one.activity ?? ""}:${(one.tasks ?? []).filter((task) => task.activity === "waiting-on-you").length}:${(one.tasks ?? []).filter((task) => task.unread).length}`;+ const bot = (one: VersionedBot) => `${one.id}:${one.reportsTo ?? ""}:${one.activity ?? ""}:${(one.tasks ?? []).filter((task) => task.activity === "waiting-on-you").length}:${(one.tasks ?? []).filter((task) => task.unread).length}:${openAsksOf(one)}`;return `${bots.map(bot).join("|")}|${groups.filter((group) => group.unread).length}|${notifications.length}:${notifications.filter((entry) => !entry.read).length}`;}