Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

feat(team): the inbox as a list in the right panel, and one live card in the inbox chat (#3735)

Milind Soni3ff8778788c4
diff --git a/apps/docs/content/docs/features/chat-and-teams.mdx b/apps/docs/content/docs/features/chat-and-teams.mdx
index 8b0279389a..575e0f2ea5 100644
--- a/apps/docs/content/docs/features/chat-and-teams.mdx
+++ b/apps/docs/content/docs/features/chat-and-teams.mdx
@@ -90,6 +90,8 @@ On a team's Cloud, everything for you arrives in one place: your chat with your
**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.
+**Your inbox at a glance.** In your chat with your Chief, one card keeps what needs you in view: how many things need you and how many are just for your information, the newest few with their answer buttons right there, and **Open inbox**. The whole inbox opens on the right, in three tabs: **Needs you** (questions and approvals), **For your info** (reports, mentions and messages) and **Done**. Click a line to read it in full and answer or reply; mark news done when you need nothing more from it. On a phone it opens as a sheet.
+
**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/screenshots/inbox-card-dark.png b/docs/screenshots/inbox-card-dark.png
new file mode 100644
index 0000000000..495a0cb779
Binary files /dev/null and b/docs/screenshots/inbox-card-dark.png differ
diff --git a/docs/screenshots/inbox-card-light.png b/docs/screenshots/inbox-card-light.png
new file mode 100644
index 0000000000..1dc386b245
Binary files /dev/null and b/docs/screenshots/inbox-card-light.png differ
diff --git a/docs/screenshots/inbox-panel-dark.png b/docs/screenshots/inbox-panel-dark.png
new file mode 100644
index 0000000000..9b4260b7ed
Binary files /dev/null and b/docs/screenshots/inbox-panel-dark.png differ
diff --git a/docs/screenshots/inbox-panel-light.png b/docs/screenshots/inbox-panel-light.png
new file mode 100644
index 0000000000..fa5ee2ee28
Binary files /dev/null and b/docs/screenshots/inbox-panel-light.png differ
diff --git a/docs/screenshots/inbox-phone-dark.png b/docs/screenshots/inbox-phone-dark.png
new file mode 100644
index 0000000000..7a2cf8a463
Binary files /dev/null and b/docs/screenshots/inbox-phone-dark.png differ
diff --git a/docs/screenshots/inbox-reading-light.png b/docs/screenshots/inbox-reading-light.png
new file mode 100644
index 0000000000..a8c2e5c2b8
Binary files /dev/null and b/docs/screenshots/inbox-reading-light.png differ
diff --git a/docs/team-cloud.md b/docs/team-cloud.md
index ad1a351f93..cfe9eb178f 100644
--- a/docs/team-cloud.md
+++ b/docs/team-cloud.md
@@ -358,6 +358,17 @@ their own in the conversation it came from. The inbox's task carries the asks th
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 inbox's list and its card.** `GET /api/inbox` lists the session's own person's inbox (`InboxView`,
+`shared/inbox.ts`), newest first, each line in one tab: **Needs you** while it waits on them (an ask, by the rule above;
+their count is the badge), **For your info** for news until they answer it or mark it done, and **Done** once it is
+settled or marked done. `POST /api/inbox/<line>/done` marks news done (an open ask refuses, 409: only its answer settles
+it) and `POST /api/inbox/<line>/read` marks one line read; each answers with the list as it is now. The app shows the
+list in the right panel, opened from the card, the badge or the person's own row under People: dense rows with each
+line's quick answers, a reading view with the reply, and a sheet at phone width. Answering from a row answers the copy's
+card or replies to the line, through the same routes as in the chat. In the inbox conversation one card sits under the
+newest line that needed the person (`InboxView.anchor`) and updates in place. The inbox's task carries
+`inboxChangedAt`, which moves whenever the list changes; a client showing the list reads it again then.
+
**The representative.** When a message asks something a fact the person already shares with the team answers, their
inbox's bot answers it for them (`server/host/representative.ts`); the answer goes back like a reply, as "Marco's
assistant answered …" (`relay.kind: "assistant"`), and the line shows the question, the answer and that a reply corrects
diff --git a/server/cloud-team-inbox.e2e.test.ts b/server/cloud-team-inbox.e2e.test.ts
index d37bc66ce4..adfbbc4cde 100644
--- a/server/cloud-team-inbox.e2e.test.ts
+++ b/server/cloud-team-inbox.e2e.test.ts
@@ -36,7 +36,7 @@ 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 Task = { threadId: string; title: string; inbox?: true; private?: true; openAsks?: number };
+type Task = { threadId: string; title: string; inbox?: true; private?: true; openAsks?: number; inboxChangedAt?: 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 } };
@@ -353,6 +353,36 @@ it("lets a tag Marco answered in the chat it came from leave his Needs you", asy
expect(await listed()).toBe(false);
}, hostTimeout(120_000));
+it("lists Marco's inbox by tab, settles an ask answered from its row, and keeps news until he marks it done", async () => {
+ type Listed = { id: string; kind: string; tab: string; text: string; card?: { requestId?: string } };
+ const listed = async () => (await team.as(marco, "GET", "/api/inbox")).body as { botId: string; threadId: string; rows: Listed[] };
+ const before = marcos.length;
+ const requestId = await approvalFromReporter("rm -rf ./tmp");
+ await until(async () => (await listed()).rows.some((row) => row.card?.requestId === requestId));
+ const view = await listed();
+ expect(view).toMatchObject({ botId: chief.id, threadId: inbox });
+ expect(view.rows.find((row) => row.card?.requestId === requestId)).toMatchObject({ kind: "ask", tab: "needs-you" });
+ expect(view.rows.filter((row) => row.tab === "needs-you").map((row) => row.card?.requestId), "only what waits on him needs him").toEqual([requestId]);
+ expect(view.rows.find((row) => row.text === "Can you approve the travel budget for me?")).toMatchObject({ kind: "message", tab: "info" });
+ expect(view.rows.find((row) => row.text === "The launch moved to Friday."), "answered from the inbox").toMatchObject({ tab: "done" });
+ const ask = view.rows.find((row) => row.card?.requestId === requestId)!;
+ expect((await team.as(marco, "POST", `/api/inbox/${ask.id}/done`)).status, "an ask is settled by its answer").toBe(409);
+
+ const answered = await team.as(marco, "POST", `/api/threads/${inbox}/respond`, { requestId, behavior: "allow" });
+ expect(answered.status, JSON.stringify(answered.body)).toBe(200);
+ await until(async () => (await listed()).rows.find((row) => row.id === ask.id)?.tab === "done");
+ expect((await inboxTask()).openAsks).toBeUndefined();
+ await until(() => inboxFrames(marcos.slice(before)).some((task, index, all) => index > 0 && (task?.inboxChangedAt ?? 0) > (all[0]?.inboxChangedAt ?? 0)));
+
+ const news = view.rows.find((row) => row.text === "Can you approve the travel budget for me?")!;
+ const marked = await team.as(marco, "POST", `/api/inbox/${news.id}/done`);
+ expect(marked.status, JSON.stringify(marked.body)).toBe(200);
+ expect((marked.body as { rows: Listed[] }).rows.find((row) => row.id === news.id)).toMatchObject({ tab: "done" });
+ expect((await team.as(philipp, "POST", `/api/inbox/${news.id}/done`)).status, "only his own").toBe(404);
+ writeFileSync(file("release"), "");
+ await until(idle);
+}, 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" });
diff --git a/server/host/person-inbox.test.ts b/server/host/person-inbox.test.ts
index 93c964550d..e6f10a3104 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, session, teamInbox } from "../testing/team-inbox-fixture.ts";
+import { ADA, 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>> = [];
@@ -92,13 +92,13 @@ describe("what still waits on the person", () => {
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 });
+ expect(f.team.inbox.wire(inbox)).toEqual({ inbox: true, openAsks: 2, inboxChangedAt: expect.any(Number) });
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.team.inbox.wire(inbox)).toEqual({ inbox: true, inboxChangedAt: expect.any(Number) });
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({});
});
@@ -155,6 +155,76 @@ describe("what still waits on the person", () => {
});
});
+describe("the inbox as its panel lists it", () => {
+ const approve = (requestId: string) => ({ title: "Approval needed", subtitle: "rm -rf ./build", options: ["Allow", "Deny"], requestId, tool: "Bash", requestType: "permission" as const });
+ const askOf = (f: ReturnType<typeof fixture>, threadId: string, made: ReturnType<typeof approve>) => {
+ const reporter = f.bots.find((bot) => bot.id === "reporter")!;
+ if (!reporter.tasks.some((task) => task.threadId === threadId)) reporter.tasks.push({ threadId, title: threadId });
+ const asked = f.store.appendMessage(threadId, { role: "bot", kind: "options", text: made.title, card: made });
+ f.team.route(ask("reporter", "Reporter", threadId));
+ return asked;
+ };
+ const tabs = (f: ReturnType<typeof fixture>) => Object.fromEntries((f.team.inbox.view(key(MARCO.email))?.rows ?? []).map((row) => [row.text, row.tab]));
+
+ it("puts an open ask under Needs you, news under For your info, and what is settled or done under Done", () => {
+ const f = fixture();
+ f.team.pass("scout", "philipp-private", "Marco", "Can you review the deck?");
+ f.team.pass("reporter", "rep-main", "Marco", "The Q4 draft is ready.");
+ f.team.route({ kind: "done", botId: "scout", botName: "Scout", threadId: "marco-private", title: "Scout finished", body: "Daily digest: 3 new leads." }, { routine: true });
+ const approval = askOf(f, "rep-shared", approve("req-1"));
+ askOf(f, "rep-weekly", approve("req-2"));
+ const inbox = f.inboxOf(MARCO).threadId;
+ const view = f.team.inbox.view(key(MARCO.email))!;
+ expect(view).toMatchObject({ botId: "marcos-chief", threadId: inbox });
+ expect(view.rows.map((row) => row.at)).toEqual(view.rows.map((row) => row.at).sort((a, b) => b - a));
+ expect(view.rows[0]).toMatchObject({ kind: "ask", tab: "needs-you", unread: true, card: { requestId: "req-2", tool: "Bash" }, from: { name: "Reporter" } });
+ expect(view.anchor, "the card in the chat sits under the newest ask").toBe(view.rows[0]!.id);
+ expect(tabs(f)).toEqual({
+ "Can you review the deck?": "info", "The Q4 draft is ready.": "info", "Daily digest: 3 new leads.": "info",
+ "Run: rm -rf ./build": "needs-you",
+ });
+ expect(view.rows.filter((row) => row.tab === "needs-you")).toHaveLength(2);
+
+ f.store.patchMessage("rep-shared", approval.id, { card: { ...approve("req-1"), answered: "allow" } });
+ const deck = view.rows.find((row) => row.text === "Can you review the deck?")!;
+ f.team.replyIn(session(MARCO.email), inbox, deck.id, "Tonight.", {});
+ const report = view.rows.find((row) => row.text === "Daily digest: 3 new leads.")!;
+ expect(f.team.inbox.markDone(key(MARCO.email), report.id)).toBe("done");
+ expect(f.team.inbox.markDone(key(MARCO.email), view.rows[0]!.id), "an open ask is settled by answering it").toBe("an ask");
+ expect(f.team.inbox.markDone(key(PHILIPP.email), report.id), "only its own person").toBe("unknown");
+ const after = f.team.inbox.view(key(MARCO.email))!.rows;
+ expect(after.filter((row) => row.tab === "needs-you").map((row) => row.card?.requestId)).toEqual(["req-2"]);
+ expect(after.filter((row) => row.tab === "info").map((row) => row.text)).toEqual(["The Q4 draft is ready."]);
+ expect(after.filter((row) => row.tab === "done")).toHaveLength(3);
+ expect(f.team.inbox.openAsks(inbox), "the badge counts what Needs you lists").toBe(1);
+ });
+
+ it("marks one line read, and tells the person's client each time what it lists changes", () => {
+ const f = fixture();
+ f.team.pass("scout", "philipp-private", "Marco", "Can you review the deck?");
+ const reply = f.store.appendMessage("scout-main", { role: "bot", kind: "text", text: "@Marco can you confirm the numbers?", turnId: "t1" });
+ f.store.patchMessage("scout-main", reply.id, { turnSucceeded: true });
+ const inbox = f.inboxOf(MARCO).threadId;
+ const [deck, tag] = f.team.inbox.view(key(MARCO.email))!.rows.slice().reverse();
+ const stamps = () => f.team.inbox.wire(inbox).inboxChangedAt ?? 0;
+ const before = stamps();
+ expect(f.team.inbox.markRead(key(MARCO.email), deck!.id)).toBe(true);
+ expect(f.team.inbox.view(key(MARCO.email))!.rows.find((row) => row.id === deck!.id)!.unread).toBe(false);
+ expect(f.team.inbox.view(key(MARCO.email))!.rows.find((row) => row.id === tag!.id)!.unread).toBe(true);
+ expect(stamps()).toBeGreaterThan(before);
+ f.changed.length = 0;
+ f.said("scout-main", "Confirmed.", MARCO);
+ expect(f.changed, "answered where it came from").toEqual([inbox]);
+ expect(tabs(f)["@Marco can you confirm the numbers?"]).toBe("done");
+ f.changed.length = 0;
+ f.team.inbox.markDone(key(MARCO.email), deck!.id);
+ f.team.inbox.markRead(key(MARCO.email), deck!.id);
+ expect(f.changed, "a second mark changes nothing").toEqual([inbox]);
+ expect(f.team.inbox.view(key(PHILIPP.email))?.rows ?? [], "Philipp's inbox holds nothing of Marco's").toEqual([]);
+ expect(f.team.inbox.view(key(ADA.email)), "no Chief, no MausBot: no inbox").toBeNull();
+ });
+});
+
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.ts
index 759e7ff334..826b06e250 100644
--- a/server/host/person-inbox.ts
+++ b/server/host/person-inbox.ts
@@ -11,10 +11,9 @@ import { join } from "node:path";
import { z } from "zod";
import { botOwner } from "../../shared/bot-owner.ts";
-import type { InboxItem } from "../../shared/inbox.ts";
+import type { InboxItem, InboxRow, InboxTab, InboxTask, InboxView } 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";
@@ -32,6 +31,8 @@ const BRIEF_TITLE = "Brief";
const MAX_ITEMS = 2_000;
const KEEP_MS = 30 * 24 * 60 * 60_000;
const NOTE_MAX = 2_000;
+const VIEW_ROWS = 200;
+const ROW_TEXT_MAX = 4_000;
/** Questions one person's assistant may answer in an hour; past it they wait for the person. */
export const ASSISTANT_HOURLY = 20;
const HOUR_MS = 60 * 60_000;
@@ -53,6 +54,8 @@ const itemSchema = z.object({
at: z.number(),
answered: z.boolean().optional(),
seen: z.boolean().optional(),
+ /** The person marked it done: news they need nothing more from. */
+ done: z.boolean().optional(),
});
const fileSchema = z.object({ version: z.literal(1), homes: z.record(person, z.object({ botId: id, threadId: id })), items: z.array(itemSchema).max(MAX_ITEMS) });
@@ -198,8 +201,9 @@ export function createPersonInbox(deps: PersonInboxDeps) {
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;
+ /** An ask waits on its person while its copy here and the card that asked are open, however either is answered or
+ * closed. */
+ const askWaits = (item: Item, copy = line(item)) => item.kind === "ask" && liveCardKind(copy?.card) !== null && 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 {
@@ -213,7 +217,18 @@ export function createPersonInbox(deps: PersonInboxDeps) {
}
/** 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);
+ const settled = (item: Item) => item.kind === "ask" && item.requestId ? !askWaits(item) : Boolean(item.answered) || answeredThere(item);
+
+ /** When what each inbox lists last changed, so a client showing it reads it again; `touch` also sends its bot out. */
+ const changedAt = new Map<string, number>();
+ const mark = (threadId: string) => { changedAt.set(threadId, Math.max(now(), (changedAt.get(threadId) ?? 0) + 1)); };
+ const touch = (threadId: string) => { mark(threadId); deps.changed?.(threadId); };
+
+ /** The tab a line is listed in: an ask by its card where it was asked, anything else by its answer or the person's done. */
+ function tabOf(item: Item, copy?: Message): InboxTab {
+ if (item.kind === "ask" && item.requestId) return askWaits(item, copy) ? "needs-you" : "done";
+ return item.done || settled(item) ? "done" : "info";
+ }
/** How many asks in this inbox wait on its person: questions, approvals and work handed on, open here and where they
* were asked. */
@@ -221,7 +236,7 @@ export function createPersonInbox(deps: PersonInboxDeps) {
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;
+ return asks.filter((item) => askWaits(item, copies.get(item.id))).length;
}
function notifyItem(item: Item, title: string, kind: Notification["kind"], body: string): void {
@@ -268,6 +283,7 @@ export function createPersonInbox(deps: PersonInboxDeps) {
};
items.push(item);
save();
+ mark(at.threadId);
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);
@@ -329,6 +345,7 @@ export function createPersonInbox(deps: PersonInboxDeps) {
const posted = line(item);
if (posted?.inbox) store.patchMessage(item.threadId, item.id, { inbox: { ...posted.inbox, answers: [...(posted.inbox.answers ?? []), { by, text: oneLine(text, 600), at: now() }] } });
save();
+ touch(item.threadId);
return passed;
}
@@ -374,7 +391,7 @@ export function createPersonInbox(deps: PersonInboxDeps) {
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);
+ if (Boolean(liveCardKind(copy.card)) !== Boolean(liveCardKind(next))) touch(item.threadId);
}
const unsubscribe = team ? store.onChange((change: StoreChange) => {
@@ -417,11 +434,53 @@ export function createPersonInbox(deps: PersonInboxDeps) {
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"> {
+ /** A task's wire when it is a person's inbox: that it is, how many asks wait on them there, and when its list changed. */
+ wire(threadId: string): InboxTask {
if (!personOf(threadId)) return {};
- const open = openAsks(threadId);
- return { inbox: true, ...(open ? { openAsks: open } : {}) };
+ const open = openAsks(threadId), at = changedAt.get(threadId);
+ return { inbox: true, ...(open ? { openAsks: open } : {}), ...(at ? { inboxChangedAt: at } : {}) };
+ },
+ /** This person's inbox as it lists its lines; null for someone without one. */
+ view(person: string): InboxView | null {
+ const at = homes[person];
+ if (!at || personOf(at.threadId) !== person) {
+ const bot = team && deps.person(person) ? representativeOf(person) : null;
+ return bot ? { botId: bot.id, threadId: null, rows: [], anchor: null } : null;
+ }
+ const lines = new Map(store.messagesFor(at.threadId).map((message) => [message.id, message]));
+ const own = items.filter((item) => item.person === person && item.threadId === at.threadId && lines.has(item.id)).sort((a, b) => b.at - a.at);
+ const rows = own.slice(0, VIEW_ROWS).map((item): InboxRow => {
+ const posted = lines.get(item.id)!;
+ return {
+ id: item.id, kind: item.kind, tab: tabOf(item, posted), from: posted.inbox?.from ?? { name: item.from }, ...(posted.inbox?.via ? { via: posted.inbox.via } : {}),
+ ...(posted.inbox?.origin ? { origin: posted.inbox.origin } : {}), text: clip(posted.text ?? item.text, ROW_TEXT_MAX), at: item.at, unread: !item.seen,
+ ...(posted.inbox?.replies ? { replies: true as const } : {}), ...(posted.inbox?.answers?.length ? { answers: posted.inbox.answers } : {}),
+ ...(item.kind === "ask" && posted.card ? { card: posted.card } : {}),
+ };
+ });
+ const anchor = own.find((item) => item.kind === "ask") ?? own[0];
+ return { botId: at.botId, threadId: at.threadId, rows, anchor: anchor?.id ?? null };
+ },
+ /** The person is done with a line of news; an ask is done only once its card is answered or closed where it was asked. */
+ markDone(person: string, id: string): "done" | "unknown" | "an ask" {
+ const item = items.find((one) => one.person === person && one.id === id);
+ if (!item) return "unknown";
+ if (item.kind === "ask" && item.requestId) return "an ask";
+ if (!item.done) { item.done = true; item.seen = true; save(); touch(item.threadId); }
+ return "done";
+ },
+ /** The person read a line. */
+ markRead(person: string, id: string): boolean {
+ const item = items.find((one) => one.person === person && one.id === id);
+ if (!item) return false;
+ if (!item.seen) { item.seen = true; save(); touch(item.threadId); }
+ return true;
+ },
+ /** The person wrote in a conversation: their inbox's list changes when a message from there waited on them. */
+ wrote(person: string, threadId: string): void {
+ const inboxes = new Set(items.filter((item) => item.person === person && item.kind === "message" && item.origin?.threadId === threadId && !item.answered && !item.done)
+ .map((item) => item.threadId));
+ for (const inbox of inboxes) touch(inbox);
},
/** What arrived in this person's inbox that they have not opened yet and still waits on them, newest first. */
unseen(person: string): Item[] {
@@ -431,7 +490,7 @@ export function createPersonInbox(deps: PersonInboxDeps) {
seen(person: string, threadId: string): void {
let changed = false;
for (const item of items) if (item.person === person && item.threadId === threadId && !item.seen) { item.seen = true; changed = true; }
- if (changed) save();
+ if (changed) { save(); touch(threadId); }
},
/** The person left: their inbox and what waited in it are forgotten. */
forget(person: string): void {
diff --git a/server/host/team-messages.ts b/server/host/team-messages.ts
index 60409e9eab..ed8a03c6ff 100644
--- a/server/host/team-messages.ts
+++ b/server/host/team-messages.ts
@@ -8,6 +8,7 @@ import { z } from "zod";
import { nameFromEmail, ownerEmail } from "../../shared/bot-owner.ts";
import type { Notification } from "../../shared/notification.ts";
import { mentionablePeople, teammateMentions } from "../../shared/person-mention.ts";
+import type { InboxView } from "../../shared/inbox.ts";
import type { NeedsYouItem } from "../../shared/today.ts";
import type { ResolvedSender } from "../../shared/wire.ts";
import { audienceMember, type Audience } from "../audience.ts";
@@ -21,7 +22,7 @@ import type { BotRecord, GroupRecord, Message, Store, StoreChange } from "../sto
import type { TeamPeople } from "../team-people.ts";
import { currentTimeZone } from "../time-zone.ts";
import { loadMemory } from "../workspace.ts";
-import { createPersonInbox, type Delivery, type Item, type Passed, type PersonInboxDeps } from "./person-inbox.ts";
+import { createPersonInbox, type Delivery, type Item, type Passed, type PersonInbox, type PersonInboxDeps } from "./person-inbox.ts";
import { createRepresentative, type RepresentativeDeps } from "./representative.ts";
import { oneLine } from "./text-clip.ts";
@@ -210,7 +211,7 @@ export function createTeamMessages(deps: TeamMessagesDeps) {
/** A teammate's line tags @Bob: their words reach Bob's inbox, wherever they wrote them; Bob's answer reaches theirs. */
function personWrote(threadId: string, line: Message) {
const writer = byKey(line.sender?.id);
- if (writer) inbox.seen(writer.key, threadId);
+ if (writer) { inbox.seen(writer.key, threadId); inbox.wrote(writer.key, threadId); }
const at = owner(threadId);
if (!at || !line.text) return;
const writerName = writer?.name ?? line.sender?.name ?? "Someone";
@@ -332,6 +333,21 @@ export function createTeamMessages(deps: TeamMessagesDeps) {
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 });
},
+ /** The session's person's inbox as its panel lists it; null off a team or for someone without one. */
+ view(auth: RequestAuth): InboxView | null {
+ const me = sessionPerson(auth);
+ return team && me ? inbox.view(me.key) : null;
+ },
+ /** The session's person is done with a line of news in their inbox. */
+ markDone(auth: RequestAuth, id: string): ReturnType<PersonInbox["markDone"]> {
+ const me = sessionPerson(auth);
+ return team && me ? inbox.markDone(me.key, id) : "unknown";
+ },
+ /** The session's person read a line of their inbox. */
+ markRead(auth: RequestAuth, id: string): boolean {
+ const me = sessionPerson(auth);
+ return Boolean(team && me && inbox.markRead(me.key, id));
+ },
/** This person's Needs you lines: the messages in their inbox they have not opened, newest first. */
needsYou(auth: RequestAuth): NeedsYouItem[] {
const me = sessionPerson(auth);
diff --git a/server/index.ts b/server/index.ts
index 039ec36f1e..a069d4faca 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -628,7 +628,7 @@ import { createStatusRoutes } from "./routes/status.ts";
import { findAntigravityLeftovers, removeAntigravityLeftovers } from "./drivers/antigravity-temp.ts";
import { createLiveRoutes } from "./routes/live.ts";
import { createNotificationRoutes } from "./routes/notifications.ts";
-import { createTodayRoutes } from "./routes/today.ts"; import { createSidebarSectionRoutes } from "./routes/sidebar-sections.ts";
+import { createTodayRoutes } from "./routes/today.ts"; import { createInboxRoutes } from "./routes/inbox.ts"; import { createSidebarSectionRoutes } from "./routes/sidebar-sections.ts";
import { createToolTimingRoute, createUsageRoutes } from "./routes/usage.ts";
import { createBotMessageRoutes } from "./routes/bot-messages.ts";
import { clearInternalTurn, isInternalTurn, markInternalTurn } from "./internal-turns.ts"; import { createFirstReplyRescue } from "./first-reply-rescue.ts";
@@ -12601,7 +12601,7 @@ ROUTES.push(createBotMemoryRoutes({
broadcast({ kind: "config", ...configStatus() });
},
}));
-const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin") ? { person: actorKey(auth), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager }, connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }));
+const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin") ? { person: actorKey(auth), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager }, connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: teamMessages.arrived } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => publicUrl() ?? (auth.kind === "session" ? requestOrigin(req) : null) }),
createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: settleSignIn, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: { error: memberLoginRefusal(CLOUD_TEAM) } }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId) }));
diff --git a/server/request-auth.ts b/server/request-auth.ts
index 346be447c2..8d11a0cec2 100644
--- a/server/request-auth.ts
+++ b/server/request-auth.ts
@@ -396,6 +396,9 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg
{ methods: ["POST"], path: /^\/api\/presence\/active$/ },
// what a bot asks of this person: their own questions and approvals only
{ methods: ["GET"], path: /^\/api\/needs-you$/ },
+ // a Team Cloud person's own inbox: its lines, and one of them read or done; the handler serves the session's own alone
+ { methods: ["GET"], path: /^\/api\/inbox$/ },
+ { methods: ["POST"], path: /^\/api\/inbox\/[\w-]+\/(?:read|done)$/ },
// who a Team Cloud bot can report to, and handing over a bot the member owns: the handler checks who may
{ methods: ["GET"], path: /^\/api\/team\/people$/ },
// a teammate's picture: the handler serves it to the team's own members only
diff --git a/server/routes/inbox.test.ts b/server/routes/inbox.test.ts
new file mode 100644
index 0000000000..4268bc6b3d
--- /dev/null
+++ b/server/routes/inbox.test.ts
@@ -0,0 +1,58 @@
+import type { IncomingMessage, ServerResponse } from "node:http";
+import { afterEach, expect, it } from "vitest";
+
+import { requiredScope, type RequestAuth } from "../request-auth.ts";
+import { MARCO, PHILIPP, session, teamInbox } from "../testing/team-inbox-fixture.ts";
+import { createInboxRoutes } from "./inbox.ts";
+import { PASS, type RouteContext } from "./table.ts";
+
+const fixtures: Array<ReturnType<typeof teamInbox>> = [];
+afterEach(() => { for (const made of fixtures.splice(0)) made.close(); });
+
+function setup(options: Parameters<typeof teamInbox>[0] = {}) {
+ const f = teamInbox(options);
+ fixtures.push(f);
+ const route = createInboxRoutes(f.team);
+ const call = async (method: string, path: string, auth: RequestAuth = session(MARCO.email)) => {
+ const sent: { status?: number; body?: any } = {};
+ const out = await route({
+ req: {} as IncomingMessage, res: {} as ServerResponse, url: new URL(path, "http://127.0.0.1"), path, method, auth,
+ readBody: (async () => ({})) as RouteContext["readBody"],
+ json: ((_res: ServerResponse, status: number, body: unknown) => { sent.status = status; sent.body = body; }) as RouteContext["json"],
+ });
+ return { out, ...sent };
+ };
+ return { f, call };
+}
+
+it("answers each member with their own inbox, which a client session may read and mark", async () => {
+ const { f, call } = setup();
+ f.team.pass("scout", "philipp-private", "Marco", "The launch moved to Friday.");
+ const mine = await call("GET", "/api/inbox");
+ expect(mine).toMatchObject({ status: 200, body: { botId: "marcos-chief", rows: [{ text: "The launch moved to Friday.", tab: "info", unread: true }] } });
+ const line = mine.body.rows[0].id as string;
+ expect((await call("POST", `/api/inbox/${line}/read`)).body.rows[0]).toMatchObject({ unread: false, tab: "info" });
+ expect((await call("POST", `/api/inbox/${line}/done`)).body.rows[0]).toMatchObject({ tab: "done" });
+ expect(await call("POST", `/api/inbox/${line}/done`, session(PHILIPP.email)), "someone else's line").toMatchObject({ status: 404 });
+ expect((await call("GET", "/api/inbox", session(PHILIPP.email))).body.rows).toEqual([]);
+ expect(await call("DELETE", "/api/inbox")).toMatchObject({ status: 405 });
+ expect((await call("GET", "/api/needs-you")).out).toBe(PASS);
+ for (const [method, path] of [["GET", "/api/inbox"], ["POST", `/api/inbox/${line}/read`], ["POST", `/api/inbox/${line}/done`]] as const) {
+ expect(requiredScope(method, path), `${method} ${path}`).toBe("client");
+ }
+});
+
+it("refuses to mark an open ask done, which only its answer settles", async () => {
+ const { f, call } = setup();
+ f.bots.find((bot) => bot.id === "reporter")!.tasks.push({ threadId: "rep-shared", title: "Weekly numbers" });
+ f.store.appendMessage("rep-shared", { role: "bot", kind: "options", text: "Run a command?", card: { title: "Run a command?", subtitle: "rm -rf ./build", options: ["Allow", "Deny"], requestId: "req-1", tool: "Bash", requestType: "permission" } });
+ f.team.route({ kind: "approval", botId: "reporter", botName: "Reporter", threadId: "rep-shared", title: "Reporter needs approval", body: "Run: rm -rf ./build" });
+ const [ask] = (await call("GET", "/api/inbox")).body.rows;
+ expect(ask).toMatchObject({ tab: "needs-you", card: { requestId: "req-1" } });
+ expect(await call("POST", `/api/inbox/${ask.id}/done`)).toMatchObject({ status: 409 });
+});
+
+it("has no inbox off a team", async () => {
+ const { call } = setup({ team: false });
+ expect(await call("GET", "/api/inbox")).toMatchObject({ status: 404 });
+});
diff --git a/server/routes/inbox.ts b/server/routes/inbox.ts
new file mode 100644
index 0000000000..6955d6a3db
--- /dev/null
+++ b/server/routes/inbox.ts
@@ -0,0 +1,30 @@
+import type { InboxView } from "../../shared/inbox.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import { PASS, type RouteHandler } from "./table.ts";
+
+export interface InboxRouteDeps {
+ /** The session's person's inbox; null off a team or for someone without one. */
+ view(auth: RequestAuth): InboxView | null;
+ markDone(auth: RequestAuth, id: string): "done" | "unknown" | "an ask";
+ markRead(auth: RequestAuth, id: string): boolean;
+}
+
+/** GET /api/inbox: the session's person's inbox as its panel lists it. POST /api/inbox/<line>/read and /done: one of its
+ * lines read, or news they need nothing more from; each answers with the inbox as it lists them now. */
+export function createInboxRoutes(deps: InboxRouteDeps): RouteHandler {
+ return async ({ res, path, method, auth, json }) => {
+ if (path === "/api/inbox") {
+ if (method !== "GET") return json(res, 405, { error: "method not allowed" });
+ const view = deps.view(auth);
+ return view ? json(res, 200, view) : json(res, 404, { error: "There is no inbox here." });
+ }
+ const m = /^\/api\/inbox\/([\w-]+)\/(read|done)$/.exec(path);
+ if (!m) return PASS;
+ if (method !== "POST") return json(res, 405, { error: "method not allowed" });
+ const marked = m[2] === "read" ? (deps.markRead(auth, m[1]!) ? "done" : "unknown") : deps.markDone(auth, m[1]!);
+ if (marked === "unknown") return json(res, 404, { error: "That line is not in your inbox." });
+ if (marked === "an ask") return json(res, 409, { error: "This waits on your answer: answer it, or close it, where it asks." });
+ const view = deps.view(auth);
+ return view ? json(res, 200, view) : json(res, 404, { error: "There is no inbox here." });
+ };
+}
diff --git a/shared/inbox.ts b/shared/inbox.ts
index 99a17dcc5b..ff55055af8 100644
--- a/shared/inbox.ts
+++ b/shared/inbox.ts
@@ -1,3 +1,5 @@
+import type { OptionCardData } from "./wire.ts";
+
/** On a Team Cloud, a line in a person's inbox: their own conversation with their own Chief of Staff (their own MausBot
* when they crowned none), where everything addressed to them arrives. It says who it is from and where it came from,
* so clients can label it and open that conversation. Replying to the line answers it: the answer goes back where it
@@ -19,3 +21,46 @@ export interface InboxItem {
/** How it was answered: the person's own words, or their assistant's, which answers facts only. */
answers?: Array<{ by: "person" | "assistant"; text: string; at: number }>;
}
+
+/** A task's fields on a team's server when it is a person's inbox, sent to that person alone. */
+export interface InboxTask {
+ /** This person's inbox, the conversation with their Chief where everything for them arrives. */
+ inbox?: true;
+ /** The asks waiting on them there (questions, approvals, work handed on), each open where it was asked; absent when
+ * none. */
+ openAsks?: number;
+ /** When what the inbox lists last changed; a client that shows the list reads it again when this moves. */
+ inboxChangedAt?: number;
+}
+
+/** Where a line of the inbox is listed: "needs-you" while it waits on the person (an ask whose card is open where it was
+ * asked), "info" for news until they answer it or mark it done, "done" once it is settled or marked done. */
+export type InboxTab = "needs-you" | "info" | "done";
+
+/** One line of a person's inbox as their inbox lists it, newest first. `kind` names its source; a new source adds a kind
+ * of its own with what its row needs. */
+export interface InboxRow {
+ /** The line's id in the inbox conversation. */
+ id: string;
+ kind: InboxItem["kind"];
+ tab: InboxTab;
+ from: InboxItem["from"];
+ via?: InboxItem["via"];
+ origin?: InboxItem["origin"];
+ text: string;
+ at: number;
+ unread: boolean;
+ replies?: true;
+ answers?: InboxItem["answers"];
+ /** An ask's card as the inbox holds it: answering it answers the card where it was asked. */
+ card?: OptionCardData;
+}
+
+/** A person's inbox: where its lines live (none yet before the first arrives), and the line the inbox's card in that
+ * conversation sits under (the newest that needed them, else the newest). */
+export interface InboxView {
+ botId: string;
+ threadId: string | null;
+ rows: InboxRow[];
+ anchor: string | null;
+}
diff --git a/shared/wire.ts b/shared/wire.ts
index 0371de4298..090082a8eb 100644
--- a/shared/wire.ts
+++ b/shared/wire.ts
@@ -29,7 +29,7 @@ import type { NotificationLogEntry } from "./notification.ts";
import type { Routine, RoutineRun } from "./routines.ts";
import type { WebhookAttempt, WebhookTrigger } from "./webhooks.ts";
import type { PublishedPageCard } from "./published-page.ts";
-import type { InboxItem } from "./inbox.ts";
+import type { InboxItem, InboxTask } from "./inbox.ts";
import type { LiveCallRecord, LiveCallState } from "./live-call-wire.ts";
export type { LiveCallRecord, LiveCallState, LiveCallStatus, LiveClient, LiveEndReason, LiveKeySource, LiveSettings } from "./live-call-wire.ts";
@@ -129,7 +129,7 @@ export interface BotMovedTo {
/** One task = one conversation with its own context, thread and provider
* session. */
-export interface WireTask {
+export interface WireTask extends InboxTask {
/** Outstanding handoffs, not an active provider turn. */
waitingForTeammates?: boolean;
threadId: string;
@@ -146,10 +146,6 @@ export interface WireTask {
openedBy?: TaskOpenedBy;
/** On a team's server: one person's conversation, seen by them alone (never by another member or an admin). */
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.tsx
index 273129f1ae..1bf0102fe2 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -33,6 +33,8 @@ import { CloudSendStrip } from "@/components/CloudSendStrip";
import { HomeLine } from "@/components/HomeLine";
import { useTeamChats } from "@/state/team-chats";
import { needsYouVersion, useTeamPeopleLoader } from "@/state/team-people";
+import { inboxVersion, useInboxLoader, useInboxPanel } from "@/state/inbox";
+import { InboxPanel } from "@/components/inbox/InboxPanel";
import { CloudAddDialog } from "@/components/CloudAddDialog";
import { PlacesRail } from "@/components/PlacesRail";
import { CloudHowTo } from "@/components/CloudHowTo";
@@ -67,6 +69,9 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
const { state, dispatch } = useStore();
useTeamChats(state.config);
useTeamPeopleLoader(state.config, needsYouVersion(state.bots, state.groups, state.notifications));
+ const inbox = inboxVersion(state.bots);
+ useInboxLoader(inbox);
+ const inboxShown = useInboxPanel().open && inbox !== null;
// A Switch AI pick lands once its stopped turn's chat is idle, wherever the person is by then.
useAiSwitchKeeper({ bots: state.bots, dispatch });
const showThreads = useShowThreads();
@@ -137,7 +142,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
const notificationFeed = useNotificationFeed() && !remoteClient;
const advanced = useAdvancedMode();
const roomPanelOpen = useRoomPanelShown({ group, state, simple: !advanced && !remoteClient });
- const sidePanelOpen = (Boolean(bot) && (state.settingsOpen || state.computerOpen || state.inspectorOpen || state.activityOpen)) || roomPanelOpen || (notificationFeed && state.notificationsOpen);
+ const sidePanelOpen = (Boolean(bot) && (state.settingsOpen || state.computerOpen || state.inspectorOpen || state.activityOpen)) || roomPanelOpen || (notificationFeed && state.notificationsOpen) || inboxShown;
const collapseSidebar = sidePanelOpen && !sidebarAndPanelFit;
const calendarFocus = state.activeView === "routines" && state.routinesFocus.view === "calendar";
@@ -386,6 +391,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
)}
{!remoteClient && state.inspectorOpen && bot && <InspectorPanel key={bot.threadId} bot={bot} />}
{!remoteClient && state.activityOpen && bot && <ActivityPanel key={`activity:${bot.id}`} bot={bot} />}
+ {inboxShown && <InboxPanel />}
{notificationFeed && !calendarFocus && state.notificationsOpen && <NotificationsPanel />}
{notificationFeed && !calendarFocus && <NotificationRail />}
{state.appSettingsOpen && <SettingsModal />}
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index ed132677e2..2b66469628 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -84,7 +84,7 @@ import { ReplyQuote } from "./ReplyQuote";
import { ConnectorCard } from "./ConnectorCard";
import { SecretRequestCard } from "./SecretRequestCard";
import { SignInRequestCard } from "./SignInRequestCard";
-import { AutomationCaption, RoutineRunRow } from "./RoutineRunCard"; import { InboxAnswers, InboxCaption, RelayLabel } from "./InboxLine";
+import { AutomationCaption, RoutineRunRow } from "./RoutineRunCard"; import { InboxAnswers, InboxCaption, RelayLabel } from "./InboxLine"; import { InboxCardSlot } from "./inbox/InboxCard";
import { CallRecordRow } from "./CallRecordRow";
import { AttachmentGallery, collectMessageFiles, replyAttachmentGroup, splitMessageAttachments } from "./AttachmentGallery";
import { ScreenFrame } from "./ScreenFrame";
@@ -813,7 +813,7 @@ const MessagesList = memo(function MessagesList({
{newDay && <DaySeparator at={m.at} today={today} simple={simple} />}
{divider}
{m.automation && <AutomationCaption message={m} line={m.automation} botId={botId} />}{m.inbox && <InboxCaption message={m} />}
- {row}{m.inbox?.answers && <InboxAnswers message={m} />}{m.setupOffer && <SetupOffer botId={botId} threadId={threadId} message={m} transcript={transcript} />}
+ {row}{m.inbox?.answers && <InboxAnswers message={m} />}{m.inbox && <InboxCardSlot threadId={threadId} messageId={m.id} />}{m.setupOffer && <SetupOffer botId={botId} threadId={threadId} message={m} transcript={transcript} />}
</div>
);
})}
diff --git a/src/components/InboxLine.tsx b/src/components/InboxLine.tsx
index db0937cc7c..404e81980f 100644
--- a/src/components/InboxLine.tsx
+++ b/src/components/InboxLine.tsx
@@ -9,11 +9,12 @@ import { PersonFace } from "./TeamOwner";
const face = (person: { name: string; email: string }): TeamPerson => ({ email: person.email, name: person.name, role: "member" });
-function Sender({ from }: { from: NonNullable<Message["inbox"]>["from"] }) {
+/** The face of who a line is from: a teammate's picture, or the bot's avatar. */
+export function InboxSender({ from, size = 16 }: { from: NonNullable<Message["inbox"]>["from"]; size?: number }) {
const { state } = useStore();
- if (from.email) return <PersonFace person={face({ name: from.name, email: from.email })} size={16} />;
+ if (from.email) return <PersonFace person={face({ name: from.name, email: from.email })} size={size} />;
const bot = state.bots.find((one) => one.id === from.botId);
- return <BotAvatar bot={bot ?? { name: from.name, color: "blue" }} state="happy" size={16} motion="none" motionKey={0} animated={false} />;
+ return <BotAvatar bot={bot ?? { name: from.name, color: "blue" }} state="happy" size={size} motion="none" motionKey={0} animated={false} />;
}
/** Above an inbox line: from whom, through which bot, and the conversation it came from. */
@@ -26,7 +27,7 @@ export function InboxCaption({ message }: { message: Message }) {
const origin = item.origin;
return (
<div data-inbox-line={item.kind} className="-mb-2 flex min-w-0 items-center gap-1.5 pl-0.5 text-[11px] text-ink-tertiary">
- <Sender from={item.from} />
+ <InboxSender from={item.from} />
<span className="truncate font-medium text-ink-secondary">{who}</span>
{item.via && <span className="shrink-0">· {t("inbox.via", { name: item.via.name })}</span>}
{origin && (
diff --git a/src/components/SidebarPeople.tsx b/src/components/SidebarPeople.tsx
index 3fcfe45b05..061722d3e3 100644
--- a/src/components/SidebarPeople.tsx
+++ b/src/components/SidebarPeople.tsx
@@ -1,6 +1,6 @@
-// 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, and counts the asks waiting on you there. Anyone else's puts @their name in the
-// composer, which reaches their inbox once sent.
+// 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, with the inbox's list beside it, 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";
@@ -8,6 +8,7 @@ import { leadComposerDraft } from "@/lib/drafts";
import { t } from "@/lib/i18n";
import { useShowThreads } from "@/lib/thread-preferences";
import { openBot, openThread, useStore, type AppState, type Bot } from "@/state/store";
+import { openInbox } from "@/state/inbox";
import { useTeamPeople, type TeamPerson } from "@/state/team-people";
import { PersonFace } from "./TeamOwner";
@@ -42,6 +43,7 @@ export function SidebarPeople({ compact }: { compact: boolean }) {
const open = (person: TeamPerson) => {
if (person.you) {
if (inbox) openBot(dispatch, inbox, showThreads);
+ if (inboxThread) openInbox({ tab: waiting ? "needs-you" : undefined });
return;
}
const tag = `@${person.name} `;
diff --git a/src/components/inbox/InboxCard.tsx b/src/components/inbox/InboxCard.tsx
new file mode 100644
index 0000000000..67c64c68a3
--- /dev/null
+++ b/src/components/inbox/InboxCard.tsx
@@ -0,0 +1,83 @@
+// On a Team Cloud, in the person's inbox chat: one card that keeps what waits on them in view. It sits under the newest
+// line that needed them and updates in place: how many need them and how many are news, the newest few that need them
+// with their answers right there, and the way into the whole inbox. With nothing open it shrinks to one line.
+import { useEffect, useState } from "react";
+import { Check, CornerUpLeft, Inbox, X } from "lucide-react";
+import type { InboxRow, InboxView } from "../../../shared/inbox";
+import { t } from "@/lib/i18n";
+import { openInbox, readInboxRow, useInboxView } from "@/state/inbox";
+import { INBOX_PRIMARY, INBOX_SECONDARY } from "./InboxReading";
+import { InboxRowItem } from "./InboxRow";
+import { askOf, CARD_ROWS, choiceResponse, choicesOf, rowsIn, tabCounts } from "./inbox-view";
+import { useInboxActions } from "./use-inbox-actions";
+
+/** Most choices a question shows as buttons on the card; one with more opens in the inbox. */
+const CARD_CHOICES = 3;
+
+/** The card goes under one line of the inbox conversation only: the line the inbox says it sits under. */
+export function InboxCardSlot({ threadId, messageId }: { threadId: string; messageId: string }) {
+ const view = useInboxView();
+ if (!view || view.threadId !== threadId || view.anchor !== messageId) return null;
+ return <InboxCard view={view} />;
+}
+
+function Answers({ row, view }: { row: InboxRow; view: InboxView }) {
+ const { answer } = useInboxActions(view);
+ const ask = askOf(row);
+ const choices = choicesOf(row);
+ const reading = () => { readInboxRow(row); openInbox({ reading: row.id }); };
+ if (ask === "approval") {
+ return (
+ <>
+ <button type="button" data-inbox-action="allow" onClick={() => answer(row, { behavior: "allow" })} className={INBOX_PRIMARY}><Check size={14} aria-hidden="true" />{t("approval.action.allowOnce")}</button>
+ <button type="button" data-inbox-action="deny" onClick={() => answer(row, { behavior: "deny" })} className={INBOX_SECONDARY}><X size={14} aria-hidden="true" />{t("approval.action.deny")}</button>
+ </>
+ );
+ }
+ return (
+ <>
+ {choices.length > 0 && choices.length <= CARD_CHOICES && choices.map((choice) => (
+ <button key={choice} type="button" data-inbox-choice={choice} onClick={() => answer(row, choiceResponse(row, choice))} className={INBOX_SECONDARY}>{choice}</button>
+ ))}
+ <button type="button" data-inbox-action="reply" onClick={reading} className={INBOX_SECONDARY}><CornerUpLeft size={14} aria-hidden="true" />{t("chat.reply")}</button>
+ </>
+ );
+}
+
+export function InboxCard({ view }: { view: InboxView }) {
+ const { run } = useInboxActions(view);
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ const timer = setInterval(() => setNow(Date.now()), 60_000);
+ return () => clearInterval(timer);
+ }, []);
+ const counts = tabCounts(view);
+ const rows = rowsIn(view, "needs-you").slice(0, CARD_ROWS);
+ const openRow = (row: InboxRow) => { readInboxRow(row); openInbox({ reading: row.id }); };
+ const openAll = () => openInbox({ tab: counts["needs-you"] ? "needs-you" : "info" });
+ if (!rows.length) {
+ return (
+ <section data-inbox-card="caught-up" aria-label={t("inbox.card.caughtUp")} className="my-1 flex w-full max-w-[min(38rem,100%)] items-center gap-2 rounded-xl border border-hairline/40 bg-panel px-3 py-1.5 text-[13px] text-ink-secondary">
+ <Check size={14} aria-hidden="true" className="shrink-0 text-success" />
+ <span className="min-w-0 flex-1 truncate">{t("inbox.card.caughtUp")}{counts.info > 0 && ` · ${t("inbox.card.forInfo", { count: counts.info })}`}</span>
+ <button type="button" onClick={openAll} className="shrink-0 text-[12px] font-medium text-accent hover:underline">{t("inbox.card.open")}</button>
+ </section>
+ );
+ }
+ return (
+ <section data-inbox-card="open" aria-label={t("inbox.card.summary", { needs: counts["needs-you"], info: counts.info })}
+ className="my-1 w-full max-w-[min(38rem,100%)] overflow-hidden rounded-2xl border border-hairline/50 bg-panel">
+ <header className="flex items-center gap-2 border-b border-hairline/40 px-3 py-2">
+ <Inbox size={15} aria-hidden="true" className="shrink-0 text-warning" />
+ <span className="min-w-0 flex-1 truncate text-[13px] font-medium text-ink">{t("inbox.card.summary", { needs: counts["needs-you"], info: counts.info })}</span>
+ <button type="button" onClick={openAll} className="shrink-0 text-[12px] font-medium text-accent hover:underline">{t("inbox.card.open")}</button>
+ </header>
+ {rows.map((row) => (
+ <div key={row.id} className="border-b border-hairline/20 last:border-b-0">
+ <InboxRowItem row={row} now={now} onOpen={openRow} onAction={run} inCard />
+ <div className="flex flex-wrap items-center gap-1.5 px-2.5 pb-2 pl-[2.375rem]"><Answers row={row} view={view} /></div>
+ </div>
+ ))}
+ </section>
+ );
+}
diff --git a/src/components/inbox/InboxPanel.dom.test.ts b/src/components/inbox/InboxPanel.dom.test.ts
new file mode 100644
index 0000000000..2ab4fcd718
--- /dev/null
+++ b/src/components/inbox/InboxPanel.dom.test.ts
@@ -0,0 +1,150 @@
+// @vitest-environment happy-dom
+import { act, createElement, type ReactElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const server = vi.hoisted(() => ({ calls: [] as Array<{ path: string; method: string; body?: unknown }>, view: null as null | { rows: Array<{ id: string; tab: string }> } }));
+vi.mock("../../state/api", () => ({
+ api: vi.fn(async (path: string, init?: RequestInit) => {
+ server.calls.push({ path, method: init?.method ?? "GET", ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}) });
+ const done = /^\/api\/inbox\/([\w-]+)\/done$/.exec(path);
+ if (done && server.view) server.view = { ...server.view, rows: server.view.rows.map((row) => (row.id === done[1] ? { ...row, tab: "done", unread: false } : row)) };
+ return server.view;
+ }),
+}));
+
+import { initialState, StoreContext, type AppState } from "@/state/store";
+import { closeInbox, currentInboxPanel, inboxVersion, openInbox, setInboxView, useInboxLoader } from "@/state/inbox";
+import { approvalRow, inboxView, messageRow, questionRow, reportRow, settledRow } from "@/testing/inbox-fixture";
+import type { InboxView } from "../../../shared/inbox";
+import { InboxCardSlot } from "./InboxCard";
+import { InboxPanel } from "./InboxPanel";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: Root;
+const dispatch = vi.fn();
+const mount = (child: ReactElement) => act(async () => {
+ root.render(createElement(StoreContext.Provider,
+ { value: { state: { ...initialState } as AppState, dispatch, flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn() } as never }, child));
+});
+const settle = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
+const click = (selector: string) => act(async () => { document.querySelector<HTMLElement>(selector)!.click(); });
+const shown = (view: InboxView) => { server.view = view; setInboxView(view); };
+
+beforeEach(() => {
+ root = createRoot(document.body.appendChild(document.createElement("div")));
+ server.calls.length = 0;
+ dispatch.mockClear();
+ shown(inboxView());
+});
+afterEach(() => {
+ act(() => root.unmount());
+ closeInbox();
+ setInboxView(null);
+ document.body.innerHTML = "";
+ vi.unstubAllGlobals();
+});
+
+describe("the inbox panel", () => {
+ it("opens on Needs you with its count, lists each tab's own lines, and reads one in full", async () => {
+ openInbox({ tab: "needs-you" });
+ await mount(createElement(InboxPanel));
+ const tab = (name: string) => document.querySelector<HTMLElement>(`[data-inbox-tab="${name}"]`)!;
+ expect(tab("needs-you").getAttribute("aria-selected")).toBe("true");
+ expect(tab("needs-you").getAttribute("aria-label")).toBe("Needs you, 2");
+ const listed = () => [...document.querySelectorAll<HTMLElement>("[data-inbox-row]")].map((row) => row.dataset.inboxRow);
+ expect(listed()).toEqual([approvalRow.id, questionRow.id]);
+ expect(document.querySelector(`[data-inbox-row="${approvalRow.id}"]`)!.hasAttribute("data-unread")).toBe(true);
+ await click('[data-inbox-tab="info"]');
+ expect(listed()).toEqual([messageRow.id, reportRow.id]);
+ await click('[data-inbox-tab="done"]');
+ expect(listed()).toEqual([settledRow.id]);
+ await click('[data-inbox-tab="info"]');
+ await click(`[data-inbox-row="${messageRow.id}"] button`);
+ expect(document.querySelector(`[data-inbox-reading="${messageRow.id}"]`)?.textContent).toContain("The launch moved to Friday.");
+ expect(server.calls).toContainEqual({ path: `/api/inbox/${messageRow.id}/read`, method: "POST" });
+ expect(document.querySelector("textarea"), "a message that waits on an answer takes a reply").not.toBeNull();
+ await click('[aria-label="Back to the list"]');
+ expect(listed()).toEqual([messageRow.id, reportRow.id]);
+ });
+
+ it("answers an ask from its row through the copy's own card, as the chat's buttons do, and marks news done", async () => {
+ openInbox({ tab: "needs-you" });
+ await mount(createElement(InboxPanel));
+ await click(`[data-inbox-row="${approvalRow.id}"] [data-inbox-action="allow"]`);
+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "decideRequest", threadId: "inbox", requestId: "req-approval", behavior: "allow" }));
+ await click(`[data-inbox-row="${questionRow.id}"] [data-inbox-action="close"]`);
+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "decideRequest", threadId: "inbox", requestId: "req-question", behavior: "answer" }));
+ await click('[data-inbox-tab="info"]');
+ await click(`[data-inbox-row="${reportRow.id}"] [data-inbox-action="done"]`);
+ expect(server.calls).toContainEqual({ path: `/api/inbox/${reportRow.id}/done`, method: "POST" });
+ expect(document.querySelector(`[data-inbox-row="${reportRow.id}"]`), "it leaves the tab at once").toBeNull();
+ });
+
+ it("is a sheet at phone width", async () => {
+ vi.stubGlobal("matchMedia", (query: string) => ({ matches: query.includes("max-width"), addEventListener() {}, removeEventListener() {} }));
+ openInbox();
+ await mount(createElement(InboxPanel));
+ expect(document.querySelector('[data-inbox-panel="sheet"]')).not.toBeNull();
+ expect(document.querySelector('[data-inbox-panel="side"]')).toBeNull();
+ });
+});
+
+describe("the inbox's card in the chat", () => {
+ const lines = (ids: string[]) => createElement("div", null, ...ids.map((id) => createElement(InboxCardSlot, { key: id, threadId: "inbox", messageId: id })));
+
+ it("sits once, under the newest line that needed the person, and opens the inbox", async () => {
+ await mount(lines([settledRow.id, reportRow.id, messageRow.id, questionRow.id, approvalRow.id]));
+ expect(document.querySelectorAll("[data-inbox-card]")).toHaveLength(1);
+ expect(document.querySelector('[data-inbox-card="open"]')!.getAttribute("aria-label")).toBe("2 need you · 2 for your info");
+ expect([...document.querySelectorAll("[data-inbox-card] [data-inbox-row]")].map((row) => (row as HTMLElement).dataset.inboxRow)).toEqual([approvalRow.id, questionRow.id]);
+ await click('[data-inbox-card] [data-inbox-choice="Pricing"]');
+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "decideRequest", threadId: "inbox", requestId: "req-question", behavior: "answer", message: "Pricing" }));
+ await click('[data-inbox-card] header button');
+ expect(currentInboxPanel()).toMatchObject({ open: true, tab: "needs-you" });
+ await mount(createElement(InboxCardSlot, { threadId: "elsewhere", messageId: approvalRow.id }));
+ expect(document.querySelector("[data-inbox-card]"), "never in another conversation").toBeNull();
+ });
+
+ it("shrinks to one line when nothing waits, and moves under a new ask once it lands", async () => {
+ const caughtUp = inboxView([messageRow, reportRow, { ...settledRow }]);
+ shown({ ...caughtUp, anchor: settledRow.id });
+ await mount(lines([settledRow.id, reportRow.id, messageRow.id]));
+ expect(document.querySelector('[data-inbox-card="caught-up"]')?.textContent).toContain("All caught up · 2 for your info");
+ const later = { ...approvalRow, id: "line-later" };
+ await act(async () => { shown({ ...inboxView([later, messageRow, reportRow, settledRow]), anchor: later.id }); });
+ await mount(lines([settledRow.id, reportRow.id, messageRow.id, later.id]));
+ const cards = document.querySelectorAll("[data-inbox-card]");
+ expect(cards).toHaveLength(1);
+ expect(cards[0]!.getAttribute("data-inbox-card")).toBe("open");
+ });
+});
+
+describe("keeping the list live", () => {
+ function Loader({ version }: { version: string | null }) {
+ useInboxLoader(version);
+ return null;
+ }
+
+ it("reads the list again whenever the person's inbox task says it changed, and never off a team", async () => {
+ const task = (inboxChangedAt?: number, openAsks?: number) => [{ id: "marcos-chief", tasks: [{ threadId: "inbox", inbox: true as const, ...(inboxChangedAt ? { inboxChangedAt } : {}), ...(openAsks ? { openAsks } : {}) }] }];
+ expect(inboxVersion([{ id: "solo", tasks: [{ threadId: "t1" }] }]), "nothing is anyone's inbox off a team").toBeNull();
+ const first = inboxVersion(task(5, 2));
+ expect(inboxVersion(task(6, 2))).not.toBe(first);
+ expect(inboxVersion(task(5, 1))).not.toBe(first);
+ await mount(createElement(Loader, { version: first }));
+ await settle();
+ const reads = () => server.calls.filter((call) => call.path === "/api/inbox").length;
+ expect(reads()).toBe(1);
+ await mount(createElement(Loader, { version: first }));
+ await settle();
+ expect(reads(), "the same version reads nothing").toBe(1);
+ await mount(createElement(Loader, { version: inboxVersion(task(6, 1)) }));
+ await settle();
+ expect(reads()).toBe(2);
+ await mount(createElement(Loader, { version: null }));
+ await settle();
+ expect(reads()).toBe(2);
+ });
+});
diff --git a/src/components/inbox/InboxPanel.tsx b/src/components/inbox/InboxPanel.tsx
new file mode 100644
index 0000000000..b8055582f2
--- /dev/null
+++ b/src/components/inbox/InboxPanel.tsx
@@ -0,0 +1,90 @@
+// On a Team Cloud: the person's whole inbox in the right panel, one tab per kind of line (what needs them, news, done),
+// each line a dense row that reads in full in the panel. At phone width it is a sheet over the chat.
+import { useEffect, useState, type KeyboardEvent } from "react";
+import { createPortal } from "react-dom";
+import { X } from "lucide-react";
+import type { InboxRow, InboxTab } from "../../../shared/inbox";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import type { LocaleKey } from "@/locales";
+import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";
+import { closeInbox, readInboxLine, readInboxRow, showInboxTab, useInboxPanel, useInboxView } from "@/state/inbox";
+import { InboxReading } from "./InboxReading";
+import { InboxRowItem } from "./InboxRow";
+import { INBOX_TABS, rowsIn, tabCounts } from "./inbox-view";
+import { useInboxActions } from "./use-inbox-actions";
+
+const TAB_LABEL: Record<InboxTab, LocaleKey> = { "needs-you": "needsYou.title", info: "inbox.tab.info", done: "inbox.tab.done" };
+const EMPTY: Record<InboxTab, LocaleKey> = { "needs-you": "inbox.empty.needsYou", info: "inbox.empty.info", done: "inbox.empty.done" };
+
+export function InboxPanel() {
+ const view = useInboxView();
+ const panel = useInboxPanel();
+ const phone = useMediaQuery(PHONE_LAYOUT);
+ const { run } = useInboxActions(view);
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ const timer = setInterval(() => setNow(Date.now()), 30_000);
+ return () => clearInterval(timer);
+ }, []);
+ const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {
+ if (event.key !== "Escape" || event.defaultPrevented) return;
+ event.preventDefault();
+ if (panel.reading) readInboxLine(null);
+ else closeInbox();
+ };
+ const counts = tabCounts(view);
+ const reading = panel.reading ? view?.rows.find((row) => row.id === panel.reading) : undefined;
+ const open = (row: InboxRow) => { readInboxRow(row); readInboxLine(row.id); };
+ const rows = rowsIn(view, panel.tab);
+ const body = (
+ <>
+ <div className="flex items-center gap-1.5 border-b border-hairline/40 px-3.5 py-2.5">
+ <h2 className="flex-1 text-[14px] font-semibold text-ink">{t("inbox.panel.title")}</h2>
+ <button type="button" onClick={closeInbox} aria-label={t("common.close")} title={t("common.close")}
+ className="flex size-[26px] shrink-0 items-center justify-center rounded-md text-ink-secondary hover:bg-raised hover:text-ink">
+ <X size={14} />
+ </button>
+ </div>
+ {reading && view ? <InboxReading view={view} row={reading} now={now} /> : (
+ <>
+ <div role="tablist" aria-label={t("inbox.panel.title")} className="flex shrink-0 gap-1 border-b border-hairline/40 px-2">
+ {INBOX_TABS.map((tab) => (
+ <button key={tab} type="button" role="tab" aria-selected={panel.tab === tab} data-inbox-tab={tab} onClick={() => showInboxTab(tab)}
+ aria-label={tab === "needs-you" ? t("needsYou.count", { count: counts[tab] }) : t(TAB_LABEL[tab])}
+ className={cn("-mb-px flex items-center gap-1.5 border-b-2 px-2.5 py-2 text-[13px] font-medium",
+ panel.tab === tab ? "border-accent text-ink" : "border-transparent text-ink-secondary hover:text-ink")}>
+ {t(TAB_LABEL[tab])}
+ {tab !== "done" && counts[tab] > 0 && (
+ <span aria-hidden="true" className={cn("rounded-full px-1.5 text-[11px] font-semibold tabular-nums", tab === "needs-you" ? "bg-warning text-panel" : "bg-raised text-ink-secondary")}>{counts[tab]}</span>
+ )}
+ </button>
+ ))}
+ </div>
+ <div role="tabpanel" aria-label={t(TAB_LABEL[panel.tab])} className="min-h-0 flex-1 overflow-y-auto">
+ {rows.length === 0
+ ? <p className="px-4 py-8 text-center text-[13px] text-ink-secondary">{t(EMPTY[panel.tab])}</p>
+ : rows.map((row) => <InboxRowItem key={row.id} row={row} now={now} onOpen={open} onAction={run} />)}
+ </div>
+ </>
+ )}
+ </>
+ );
+ if (phone) {
+ return createPortal(
+ <div className="fixed inset-0 z-50 flex flex-col justify-end bg-black/40" onMouseDown={(event) => { if (event.target === event.currentTarget) closeInbox(); }}>
+ <section role="dialog" aria-modal="true" aria-label={t("inbox.panel.title")} data-inbox-panel="sheet" onKeyDown={onKeyDown}
+ className="animate-pop-in flex max-h-[85dvh] min-h-[50dvh] flex-col overflow-hidden rounded-t-2xl border-t border-hairline/50 bg-panel pb-[env(safe-area-inset-bottom)]">
+ {body}
+ </section>
+ </div>,
+ document.body,
+ );
+ }
+ return (
+ <aside aria-label={t("inbox.panel.title")} data-inbox-panel="side" onKeyDown={onKeyDown}
+ className="animate-panel-in flex h-full w-[380px] max-w-full shrink-0 flex-col border-l border-hairline/40 bg-panel max-md:absolute max-md:inset-y-0 max-md:right-0 max-md:z-30">
+ {body}
+ </aside>
+ );
+}
diff --git a/src/components/inbox/InboxReading.tsx b/src/components/inbox/InboxReading.tsx
new file mode 100644
index 0000000000..f0143338db
--- /dev/null
+++ b/src/components/inbox/InboxReading.tsx
@@ -0,0 +1,115 @@
+// One line of the inbox read in full inside the panel: who it is from, what about, when and where it came from, all of
+// it, then its answer: the ask's own buttons, the question's choices or a reply, and the way back to the list.
+import { useState } from "react";
+import { ArrowLeft, Check, ExternalLink, Send, X } from "lucide-react";
+import type { InboxRow, InboxView } from "../../../shared/inbox";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import type { Message } from "@/state/store";
+import { readInboxLine, replyToInboxRow } from "@/state/inbox";
+import { InboxSender } from "../InboxLine";
+import { QuestionCard } from "../QuestionCard";
+import { threadUpdatedLabel } from "../SidebarThreadRow";
+import { askOf, choiceResponse, choicesOf, closeResponse, subjectOf } from "./inbox-view";
+import { useInboxActions } from "./use-inbox-actions";
+
+export const INBOX_BUTTON = "inline-flex h-7 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent";
+export const INBOX_PRIMARY = `${INBOX_BUTTON} bg-accent text-accent-ink hover:bg-accent/90`;
+export const INBOX_SECONDARY = `${INBOX_BUTTON} bg-raised text-ink hover:bg-inset`;
+
+/** The line as the chat shows it, so a question answers here with the very card it asks with in the chat. */
+const asMessage = (row: InboxRow): Message => ({ id: row.id, role: "bot", kind: "options", text: row.text, at: row.at, card: row.card } as Message);
+
+function settledLabel(row: InboxRow): string {
+ if (row.kind !== "ask") return t("common.done");
+ const answered = row.card?.answered;
+ if (answered === "allow") return t("approval.status.allowed");
+ if (answered === "deny") return t("approval.status.denied");
+ return answered === "answer" && !row.card?.dismissed ? t("question.status.answered") : t("question.status.closed");
+}
+
+export function InboxReading({ view, row, now }: { view: InboxView; row: InboxRow; now: number }) {
+ const { answer, openInChat, run } = useInboxActions(view);
+ const [reply, setReply] = useState("");
+ const [sending, setSending] = useState(false);
+ const ask = askOf(row);
+ const choices = choicesOf(row);
+ const send = async (text: string) => {
+ if (!text.trim() || sending) return;
+ setSending(true);
+ try {
+ if (ask === "question") answer(row, { behavior: "answer", message: text.trim() });
+ else await replyToInboxRow(view, row, text.trim());
+ setReply("");
+ } finally {
+ setSending(false);
+ }
+ };
+ const canReply = ask === "question" ? !row.card?.questionRequest : row.tab === "info" && row.replies === true;
+ return (
+ <article data-inbox-reading={row.id} aria-label={`${row.from.name} · ${subjectOf(row)}`} className="flex min-h-0 flex-1 flex-col">
+ <header className="flex items-start gap-2 border-b border-hairline/40 px-3 py-2.5">
+ <button type="button" onClick={() => readInboxLine(null)} aria-label={t("inbox.action.back")} title={t("inbox.action.back")}
+ className="flex size-7 shrink-0 items-center justify-center rounded-md text-ink-secondary hover:bg-raised hover:text-ink">
+ <ArrowLeft size={15} aria-hidden="true" />
+ </button>
+ <span className="mt-0.5 shrink-0" aria-hidden="true"><InboxSender from={row.from} size={28} /></span>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-baseline gap-2">
+ <span className="min-w-0 truncate text-[14px] font-semibold text-ink">{row.from.name}</span>
+ <span className="ml-auto shrink-0 text-[11px] tabular-nums text-ink-tertiary">{threadUpdatedLabel(row.at, now)}</span>
+ </div>
+ <div className="truncate text-[13px] text-ink">{subjectOf(row)}</div>
+ {(row.origin || row.via) && (
+ <div className="truncate text-[12px] text-ink-tertiary">
+ {row.via && t("inbox.via", { name: row.via.name })}{row.via && row.origin && " · "}{row.origin && t("inbox.in", { title: row.origin.title })}
+ </div>
+ )}
+ </div>
+ </header>
+ <div className="min-h-0 flex-1 space-y-3 overflow-y-auto px-4 py-3">
+ <p className="whitespace-pre-wrap break-words text-[14px] leading-6 text-ink">{row.text}</p>
+ {row.card?.subtitle && row.card.subtitle !== row.text && <p className="whitespace-pre-wrap break-words rounded-lg bg-inset px-3 py-2 font-mono text-[12px] text-ink-secondary">{row.card.subtitle}</p>}
+ {row.answers?.map((given) => (
+ <p key={given.at} className="rounded-lg border border-hairline/40 px-3 py-2 text-[13px] text-ink-secondary">
+ <span className="block text-[11px] font-medium text-ink-tertiary">{t(given.by === "assistant" ? "inbox.assistantAnswered" : "inbox.youReplied")}</span>
+ <span className="whitespace-pre-wrap break-words">{given.text}</span>
+ </p>
+ ))}
+ {row.tab === "done" && <p className="flex items-center gap-1.5 text-[13px] text-ink-secondary"><Check size={14} aria-hidden="true" />{settledLabel(row)}</p>}
+ {ask === "question" && row.card?.questionRequest && view.threadId && <QuestionCard threadId={view.threadId} bot={{ name: row.from.name }} message={asMessage(row)} />}
+ {ask === "review" && <p className="text-[13px] text-ink-secondary">{t("inbox.reviewInChat")}</p>}
+ </div>
+ <footer className="space-y-2 border-t border-hairline/40 px-3 py-2.5">
+ {(ask === "approval" || choices.length > 0) && (
+ <div className="flex flex-wrap items-center gap-1.5">
+ {ask === "approval" ? (
+ <>
+ <button type="button" data-inbox-action="allow" onClick={() => answer(row, { behavior: "allow" })} className={INBOX_PRIMARY}><Check size={14} aria-hidden="true" />{t("approval.action.allowOnce")}</button>
+ <button type="button" data-inbox-action="deny" onClick={() => answer(row, { behavior: "deny" })} className={INBOX_SECONDARY}><X size={14} aria-hidden="true" />{t("approval.action.deny")}</button>
+ </>
+ ) : !row.card?.questionRequest && choices.map((choice) => (
+ <button key={choice} type="button" data-inbox-choice={choice} onClick={() => answer(row, choiceResponse(row, choice))} className={INBOX_SECONDARY}>{choice}</button>
+ ))}
+ </div>
+ )}
+ {canReply && (
+ <form className="flex items-end gap-1.5" onSubmit={(event) => { event.preventDefault(); void send(reply); }}>
+ <textarea value={reply} onChange={(event) => setReply(event.target.value)} rows={2} aria-label={t("inbox.reply.placeholder")} placeholder={t("inbox.reply.placeholder")}
+ onKeyDown={(event) => { if (event.key === "Enter" && !event.shiftKey) { event.preventDefault(); void send(reply); } }}
+ className="min-h-[2.5rem] flex-1 resize-none rounded-xl border border-hairline/50 bg-panel px-3 py-2 text-[13px] text-ink placeholder:text-ink-tertiary focus:border-accent/60 focus:outline-none" />
+ <button type="submit" disabled={!reply.trim() || sending} aria-label={t("chat.send")} title={t("chat.send")}
+ className={cn("flex size-9 shrink-0 items-center justify-center rounded-full bg-accent text-accent-ink", (!reply.trim() || sending) && "opacity-50")}>
+ <Send size={15} aria-hidden="true" />
+ </button>
+ </form>
+ )}
+ <div className="flex flex-wrap items-center gap-1.5">
+ {ask === "question" && <button type="button" data-inbox-action="close" onClick={() => answer(row, closeResponse(row))} className={INBOX_SECONDARY}>{t("common.done")}</button>}
+ {row.tab === "info" && <button type="button" data-inbox-action="done" onClick={() => { run(row, "done"); readInboxLine(null); }} className={INBOX_SECONDARY}><Check size={14} aria-hidden="true" />{t("common.done")}</button>}
+ <button type="button" data-inbox-action="open" onClick={() => openInChat(row)} className={INBOX_SECONDARY}><ExternalLink size={14} aria-hidden="true" />{t("inbox.action.openInChat")}</button>
+ </div>
+ </footer>
+ </article>
+ );
+}
diff --git a/src/components/inbox/InboxRow.tsx b/src/components/inbox/InboxRow.tsx
new file mode 100644
index 0000000000..4906022a3a
--- /dev/null
+++ b/src/components/inbox/InboxRow.tsx
@@ -0,0 +1,60 @@
+// One line of the person's inbox as a dense row: the sender's face and name, the subject, a muted snippet and the time.
+// An unread row is bold on a stronger ground. On hover or keyboard focus the time gives way to the row's quick actions.
+import { Check, CornerUpLeft, ExternalLink, X, type LucideIcon } from "lucide-react";
+import type { InboxRow } from "../../../shared/inbox";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import type { LocaleKey } from "@/locales";
+import { InboxSender } from "../InboxLine";
+import { threadUpdatedLabel } from "../SidebarThreadRow";
+import { quickActions, subjectOf, type QuickAction } from "./inbox-view";
+
+const ACTION_LOOK: Record<QuickAction, { Icon: LucideIcon; label: LocaleKey }> = {
+ allow: { Icon: Check, label: "approval.action.allowOnce" },
+ deny: { Icon: X, label: "approval.action.deny" },
+ reply: { Icon: CornerUpLeft, label: "chat.reply" },
+ close: { Icon: Check, label: "common.done" },
+ done: { Icon: Check, label: "common.done" },
+ open: { Icon: ExternalLink, label: "inbox.action.openInChat" },
+};
+
+const ROW_ACTION = "flex size-7 shrink-0 items-center justify-center rounded-md text-ink-secondary hover:bg-inset hover:text-ink focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent";
+
+export function InboxRowItem({ row, now, onOpen, onAction, inCard = false }: {
+ row: InboxRow;
+ now: number;
+ onOpen(row: InboxRow): void;
+ onAction(row: InboxRow, action: QuickAction): void;
+ /** On the inbox's card in the chat, which is wider than the panel and draws its own dividers. */
+ inCard?: boolean;
+}) {
+ const subject = subjectOf(row);
+ const actions = quickActions(row);
+ return (
+ <div data-inbox-row={row.id} data-tab={row.tab} data-unread={row.unread ? "" : undefined}
+ className={cn("group relative flex min-w-0 items-center gap-2 border-b border-hairline/20 pr-1.5 focus-within:bg-raised/70 hover:bg-raised/70",
+ row.unread ? "bg-raised/45" : "bg-transparent", inCard && "border-b-0")}>
+ <button type="button" onClick={() => onOpen(row)} title={`${row.from.name} · ${subject}`}
+ className={cn("flex min-w-0 flex-1 items-center gap-2 py-1.5 pl-2.5 text-left text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent/60",
+ row.unread ? "font-semibold text-ink" : "font-normal text-ink-secondary")}>
+ <span className="shrink-0" aria-hidden="true"><InboxSender from={row.from} size={20} /></span>
+ <span className={cn("shrink-0 truncate", inCard ? "w-[7.5rem]" : "w-[5.5rem] sm:w-[6.5rem]")}>{row.from.name}</span>
+ <span className="flex min-w-0 flex-1 items-baseline gap-1.5">
+ <span className="max-w-[45%] shrink-0 truncate">{subject}</span>
+ <span className="min-w-0 truncate font-normal text-ink-tertiary">{row.text}</span>
+ </span>
+ <span className="shrink-0 text-[11px] font-normal tabular-nums text-ink-tertiary group-focus-within:invisible group-hover:invisible">{threadUpdatedLabel(row.at, now)}</span>
+ </button>
+ <span className="absolute right-1.5 top-1/2 hidden -translate-y-1/2 items-center gap-0.5 rounded-md bg-raised group-focus-within:flex group-hover:flex">
+ {actions.map((action) => {
+ const { Icon, label } = ACTION_LOOK[action];
+ return (
+ <button key={action} type="button" data-inbox-action={action} aria-label={t(label)} title={t(label)} onClick={() => onAction(row, action)} className={ROW_ACTION}>
+ <Icon size={14} aria-hidden="true" />
+ </button>
+ );
+ })}
+ </span>
+ </div>
+ );
+}
diff --git a/src/components/inbox/inbox-view.test.ts b/src/components/inbox/inbox-view.test.ts
new file mode 100644
index 0000000000..caa21cf878
--- /dev/null
+++ b/src/components/inbox/inbox-view.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+
+import { approvalRow, inboxView, messageRow, questionRow, reportRow, settledRow } from "@/testing/inbox-fixture";
+import { askOf, choiceResponse, choicesOf, closeResponse, quickActions, rowsIn, subjectOf, tabCounts } from "./inbox-view";
+
+describe("the inbox's tabs", () => {
+ it("lists each line in the one tab the server put it in, newest first, and counts them", () => {
+ const view = inboxView();
+ expect(rowsIn(view, "needs-you").map((row) => row.id)).toEqual([approvalRow.id, questionRow.id]);
+ expect(rowsIn(view, "info").map((row) => row.id)).toEqual([messageRow.id, reportRow.id]);
+ expect(rowsIn(view, "done").map((row) => row.id)).toEqual([settledRow.id]);
+ expect(tabCounts(view)).toEqual({ "needs-you": 2, info: 2, done: 1 });
+ expect(tabCounts(null)).toEqual({ "needs-you": 0, info: 0, done: 0 });
+ });
+
+ it("answers only an ask that is still open: news and a settled ask offer no answer", () => {
+ expect([approvalRow, questionRow, messageRow, reportRow, settledRow].map(askOf)).toEqual(["approval", "question", null, null, null]);
+ });
+});
+
+describe("a row's actions", () => {
+ it("offers an approval's own answer first, a question's reply and close, news its done, anything else its chat", () => {
+ expect(quickActions(approvalRow)).toEqual(["allow", "deny", "reply"]);
+ expect(quickActions(questionRow)).toEqual(["reply", "close"]);
+ expect(quickActions(messageRow)).toEqual(["done", "open"]);
+ expect(quickActions(reportRow)).toEqual(["done", "open"]);
+ expect(quickActions(settledRow)).toEqual(["open"]);
+ });
+
+ it("names each line's subject plainly, or by the conversation a message came from", () => {
+ expect([approvalRow, questionRow, reportRow].map(subjectOf)).toEqual(["Approval", "Question", "Routine report"]);
+ expect(subjectOf(messageRow)).toBe("Message");
+ expect(subjectOf({ ...messageRow, origin: { botId: "scout", threadId: "scout-main", title: "Launch" } })).toBe("Launch");
+ });
+
+ it("taps a question's choice as its answer, in the card's own format, and closes it without one", () => {
+ expect(choicesOf(questionRow)).toEqual(["Home", "Pricing"]);
+ expect(choiceResponse(questionRow, "Home")).toEqual({ behavior: "answer", message: "Home" });
+ const asked = { ...questionRow, card: { ...questionRow.card!, questionRequest: { version: 1 as const, questions: [{ question: "Which page?", options: [{ label: "Home" }, { label: "Pricing" }] }] } } };
+ expect(choicesOf(asked)).toEqual(["Home", "Pricing"]);
+ expect(choiceResponse(asked, "Pricing").message).toContain("Pricing");
+ expect(closeResponse(questionRow)).toMatchObject({ behavior: "answer", dismiss: true });
+ expect(closeResponse(approvalRow), "an approval closes as a deny").toMatchObject({ behavior: "deny" });
+ expect(choicesOf(approvalRow)).toEqual([]);
+ });
+});
diff --git a/src/components/inbox/inbox-view.ts b/src/components/inbox/inbox-view.ts
new file mode 100644
index 0000000000..be8d49f7ce
--- /dev/null
+++ b/src/components/inbox/inbox-view.ts
@@ -0,0 +1,58 @@
+import { formatQuestionAnswers, questionChoices } from "../../../shared/ask-question";
+import type { InboxRow, InboxTab, InboxView } from "../../../shared/inbox";
+import { liveCardKind } from "../../../shared/live-approval";
+import { t } from "@/lib/i18n";
+import { dismissResponse, type CardResponse } from "@/lib/card-answer";
+
+export const INBOX_TABS: readonly InboxTab[] = ["needs-you", "info", "done"];
+/** The Needs you lines the inbox's card in the chat shows, the newest first. */
+export const CARD_ROWS = 3;
+
+export const rowsIn = (view: InboxView | null, tab: InboxTab): InboxRow[] => (view?.rows ?? []).filter((row) => row.tab === tab);
+
+export function tabCounts(view: InboxView | null): Record<InboxTab, number> {
+ const counts: Record<InboxTab, number> = { "needs-you": 0, info: 0, done: 0 };
+ for (const row of view?.rows ?? []) counts[row.tab] += 1;
+ return counts;
+}
+
+/** What an ask asks: an approval, a question, or something to review where it was asked; null for anything else or an
+ * ask already settled. */
+export const askOf = (row: InboxRow) => (row.kind === "ask" && row.tab === "needs-you" ? liveCardKind(row.card) : null);
+
+/** The subject a row shows after its sender: what kind of line it is, or the conversation a message came from. */
+export function subjectOf(row: InboxRow): string {
+ if (row.kind === "ask") return row.card?.tool ? t("inbox.subject.approval") : row.card?.requestType === "question" || row.card?.questionRequest ? t("inbox.subject.question") : row.card?.title || t("inbox.subject.approval");
+ if (row.kind === "result") return t("inbox.subject.result");
+ if (row.kind === "notice") return t("inbox.subject.notice");
+ return row.origin?.title ?? t("inbox.subject.message");
+}
+
+/** The choices a question offers as buttons, when one tap answers it: a single question, one pick. */
+export const choicesOf = (row: InboxRow): string[] => {
+ const card = row.card;
+ if (askOf(row) !== "question" || !card) return [];
+ if (card.questionRequest) return questionChoices(card.questionRequest.questions) ?? [];
+ return card.options;
+};
+
+/** What a tap on one of a question's choices sends. */
+export function choiceResponse(row: InboxRow, label: string): CardResponse {
+ const questions = row.card?.questionRequest?.questions;
+ return { behavior: "answer", message: questions ? formatQuestionAnswers(questions, [[label]]) : label };
+}
+
+/** What closing a question without an answer sends; an approval closes as a deny. */
+export const closeResponse = (row: InboxRow): CardResponse => dismissResponse(row.card ?? {});
+
+export type QuickAction = "allow" | "deny" | "reply" | "close" | "done" | "open";
+
+/** The actions a row offers on hover or focus, the ask's own answer first. */
+export function quickActions(row: InboxRow): QuickAction[] {
+ const ask = askOf(row);
+ if (ask === "approval") return ["allow", "deny", "reply"];
+ if (ask === "question") return ["reply", "close"];
+ if (ask === "review") return ["open"];
+ if (row.tab === "info") return ["done", "open"];
+ return ["open"];
+}
diff --git a/src/components/inbox/use-inbox-actions.ts b/src/components/inbox/use-inbox-actions.ts
new file mode 100644
index 0000000000..bb4e00b1b8
--- /dev/null
+++ b/src/components/inbox/use-inbox-actions.ts
@@ -0,0 +1,40 @@
+import { useCallback } from "react";
+import type { InboxRow, InboxView } from "../../../shared/inbox";
+import { useShowThreads } from "@/lib/thread-preferences";
+import { openThread, useStore } from "@/state/store";
+import { doneInboxRow, openInbox, readInboxRow, refreshInbox } from "@/state/inbox";
+import type { CardResponse } from "@/lib/card-answer";
+import { closeResponse, type QuickAction } from "./inbox-view";
+
+/** What a row's buttons do. An ask is answered through its copy's card here, which answers the card where it was asked,
+ * as its buttons in the chat do; a line of news is done, or opened where it came from. */
+export function useInboxActions(view: InboxView | null) {
+ const { state, dispatch } = useStore();
+ const showThreads = useShowThreads();
+
+ const answer = useCallback((row: InboxRow, response: CardResponse) => {
+ if (!view?.threadId || !row.card?.requestId) return;
+ readInboxRow(row);
+ dispatch({ type: "decideRequest", threadId: view.threadId, requestId: row.card.requestId, behavior: response.behavior, ...(response.message ? { message: response.message } : {}),
+ onError: () => { void refreshInbox(); } });
+ }, [view, dispatch]);
+
+ const openInChat = useCallback((row: InboxRow) => {
+ readInboxRow(row);
+ const target = row.origin ? { botId: row.origin.botId, threadId: row.origin.threadId, messageId: row.origin.messageId }
+ : view?.threadId ? { botId: view.botId, threadId: view.threadId, messageId: row.id } : null;
+ if (!target) return;
+ openThread(dispatch, { botId: target.botId, threadId: target.threadId }, state, showThreads);
+ if (target.messageId) dispatch({ type: "focusMessage", threadId: target.threadId, messageId: target.messageId });
+ }, [view, state, dispatch, showThreads]);
+
+ const run = useCallback((row: InboxRow, action: QuickAction) => {
+ if (action === "allow" || action === "deny") answer(row, { behavior: action });
+ else if (action === "close") answer(row, closeResponse(row));
+ else if (action === "done") doneInboxRow(row);
+ else if (action === "open") openInChat(row);
+ else { readInboxRow(row); openInbox({ reading: row.id }); }
+ }, [answer, openInChat]);
+
+ return { run, answer, openInChat };
+}
diff --git a/src/locales/de.json b/src/locales/de.json
index 6df9a9e269..65b3b2c403 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -525,6 +525,26 @@
"sidebar.people.you": "{name} (du)",
"sidebar.people.yourInbox": "Dein Posteingang: alles, was an dich geht",
"sidebar.people.yourInboxWaiting": "Dein Posteingang: wartet auf dich, {count}",
+ "inbox.panel.title": "Posteingang",
+ "inbox.tab.info": "Zur Info",
+ "inbox.tab.done": "Erledigt",
+ "inbox.card.summary": "{needs} brauchen dich · {info} zur Info",
+ "inbox.card.forInfo": "{count} zur Info",
+ "inbox.card.caughtUp": "Alles erledigt",
+ "inbox.card.open": "Posteingang öffnen",
+ "inbox.action.openInChat": "Im Chat öffnen",
+ "inbox.action.back": "Zurück zur Liste",
+ "inbox.reply.placeholder": "Deine Antwort",
+ "inbox.empty.needsYou": "Nichts wartet auf dich.",
+ "inbox.empty.info": "Keine Neuigkeiten für dich.",
+ "inbox.empty.done": "Hier ist noch nichts erledigt.",
+ "inbox.subject.approval": "Freigabe",
+ "inbox.subject.question": "Frage",
+ "inbox.subject.message": "Nachricht",
+ "inbox.subject.result": "Routinebericht",
+ "inbox.subject.notice": "Bitte ansehen",
+ "inbox.reviewInChat": "Sieh dir das im Chat an, aus dem es kommt, um es zu beantworten.",
+ "inbox.youReplied": "Du hast geantwortet",
"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.json
index a92586c257..3849329310 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -1664,6 +1664,26 @@
"sidebar.people.you": "{name} (you)",
"sidebar.people.yourInbox": "Your inbox: everything sent to you",
"sidebar.people.yourInboxWaiting": "Your inbox: waiting on you, {count}",
+ "inbox.panel.title": "Inbox",
+ "inbox.tab.info": "For your info",
+ "inbox.tab.done": "Done",
+ "inbox.card.summary": "{needs} need you · {info} for your info",
+ "inbox.card.forInfo": "{count} for your info",
+ "inbox.card.caughtUp": "All caught up",
+ "inbox.card.open": "Open inbox",
+ "inbox.action.openInChat": "Open in chat",
+ "inbox.action.back": "Back to the list",
+ "inbox.reply.placeholder": "Write your answer",
+ "inbox.empty.needsYou": "Nothing waits on you.",
+ "inbox.empty.info": "No news for you.",
+ "inbox.empty.done": "Nothing done here yet.",
+ "inbox.subject.approval": "Approval",
+ "inbox.subject.question": "Question",
+ "inbox.subject.message": "Message",
+ "inbox.subject.result": "Routine report",
+ "inbox.subject.notice": "Needs a look",
+ "inbox.reviewInChat": "Look at this in the chat it came from to answer it.",
+ "inbox.youReplied": "You replied",
"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.json
index 989e4bba5a..5174e76c29 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -1420,6 +1420,26 @@
"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}",
+ "inbox.panel.title": "Bandeja de entrada",
+ "inbox.tab.info": "Para tu información",
+ "inbox.tab.done": "Hecho",
+ "inbox.card.summary": "{needs} te necesitan · {info} para tu información",
+ "inbox.card.forInfo": "{count} para tu información",
+ "inbox.card.caughtUp": "Todo al día",
+ "inbox.card.open": "Abrir la bandeja",
+ "inbox.action.openInChat": "Abrir en el chat",
+ "inbox.action.back": "Volver a la lista",
+ "inbox.reply.placeholder": "Escribe tu respuesta",
+ "inbox.empty.needsYou": "Nada te espera.",
+ "inbox.empty.info": "No hay novedades para ti.",
+ "inbox.empty.done": "Aún no hay nada hecho aquí.",
+ "inbox.subject.approval": "Aprobación",
+ "inbox.subject.question": "Pregunta",
+ "inbox.subject.message": "Mensaje",
+ "inbox.subject.result": "Informe de rutina",
+ "inbox.subject.notice": "Requiere atención",
+ "inbox.reviewInChat": "Revísalo en el chat de donde viene para responder.",
+ "inbox.youReplied": "Respondiste",
"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.json
index b594b861cc..64f1e2801c 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -444,6 +444,26 @@
"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}",
+ "inbox.panel.title": "Boîte de réception",
+ "inbox.tab.info": "Pour info",
+ "inbox.tab.done": "Terminé",
+ "inbox.card.summary": "{needs} vous attendent · {info} pour info",
+ "inbox.card.forInfo": "{count} pour info",
+ "inbox.card.caughtUp": "Tout est à jour",
+ "inbox.card.open": "Ouvrir la boîte de réception",
+ "inbox.action.openInChat": "Ouvrir dans le chat",
+ "inbox.action.back": "Retour à la liste",
+ "inbox.reply.placeholder": "Écrivez votre réponse",
+ "inbox.empty.needsYou": "Rien ne vous attend.",
+ "inbox.empty.info": "Pas de nouvelles pour vous.",
+ "inbox.empty.done": "Rien de terminé ici pour l'instant.",
+ "inbox.subject.approval": "Approbation",
+ "inbox.subject.question": "Question",
+ "inbox.subject.message": "Message",
+ "inbox.subject.result": "Rapport de routine",
+ "inbox.subject.notice": "À regarder",
+ "inbox.reviewInChat": "Regardez-le dans le chat d'où il vient pour y répondre.",
+ "inbox.youReplied": "Vous avez répondu",
"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.json
index 51ecd8c8e8..80e1fe32f4 100644
--- a/src/locales/hi.json
+++ b/src/locales/hi.json
@@ -444,6 +444,26 @@
"sidebar.people.you": "{name} (आप)",
"sidebar.people.yourInbox": "आपका इनबॉक्स: आपको भेजा गया सब कुछ",
"sidebar.people.yourInboxWaiting": "आपका इनबॉक्स: आपके इंतज़ार में, {count}",
+ "inbox.panel.title": "इनबॉक्स",
+ "inbox.tab.info": "आपकी जानकारी के लिए",
+ "inbox.tab.done": "हो गया",
+ "inbox.card.summary": "{needs} को आपकी ज़रूरत है · {info} आपकी जानकारी के लिए",
+ "inbox.card.forInfo": "{count} आपकी जानकारी के लिए",
+ "inbox.card.caughtUp": "सब निपट गया",
+ "inbox.card.open": "इनबॉक्स खोलें",
+ "inbox.action.openInChat": "चैट में खोलें",
+ "inbox.action.back": "सूची पर वापस",
+ "inbox.reply.placeholder": "अपना जवाब लिखें",
+ "inbox.empty.needsYou": "आपके लिए कुछ भी इंतज़ार में नहीं है।",
+ "inbox.empty.info": "आपके लिए कोई खबर नहीं।",
+ "inbox.empty.done": "यहाँ अभी कुछ पूरा नहीं हुआ।",
+ "inbox.subject.approval": "मंज़ूरी",
+ "inbox.subject.question": "सवाल",
+ "inbox.subject.message": "संदेश",
+ "inbox.subject.result": "रूटीन रिपोर्ट",
+ "inbox.subject.notice": "देखने की ज़रूरत",
+ "inbox.reviewInChat": "जवाब देने के लिए इसे उस चैट में देखें जहाँ से यह आया है।",
+ "inbox.youReplied": "आपने जवाब दिया",
"sidebar.people.mention": "{name} को लिखें",
"orgChart.mode.departments": "विभाग",
"orgChart.mode.people": "कौन किसे रिपोर्ट करता है",
diff --git a/src/locales/it.json b/src/locales/it.json
index 628cf9e38b..d2621d04e8 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -6202,6 +6202,26 @@
"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}",
+ "inbox.panel.title": "Posta in arrivo",
+ "inbox.tab.info": "Per tua informazione",
+ "inbox.tab.done": "Fatto",
+ "inbox.card.summary": "{needs} hanno bisogno di te · {info} per tua informazione",
+ "inbox.card.forInfo": "{count} per tua informazione",
+ "inbox.card.caughtUp": "Tutto in pari",
+ "inbox.card.open": "Apri la posta in arrivo",
+ "inbox.action.openInChat": "Apri nella chat",
+ "inbox.action.back": "Torna all'elenco",
+ "inbox.reply.placeholder": "Scrivi la tua risposta",
+ "inbox.empty.needsYou": "Niente ti aspetta.",
+ "inbox.empty.info": "Nessuna novità per te.",
+ "inbox.empty.done": "Qui non c'è ancora niente di fatto.",
+ "inbox.subject.approval": "Approvazione",
+ "inbox.subject.question": "Domanda",
+ "inbox.subject.message": "Messaggio",
+ "inbox.subject.result": "Resoconto della routine",
+ "inbox.subject.notice": "Da guardare",
+ "inbox.reviewInChat": "Guardalo nella chat da cui arriva per rispondere.",
+ "inbox.youReplied": "Hai risposto",
"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.json
index d472ebe799..4bee4cc8b9 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -1612,6 +1612,26 @@
"sidebar.people.you": "{name}(あなた)",
"sidebar.people.yourInbox": "あなたの受信箱:あなた宛てのものがすべて届きます",
"sidebar.people.yourInboxWaiting": "あなたの受信箱:あなたの対応待ち、{count} 件",
+ "inbox.panel.title": "受信箱",
+ "inbox.tab.info": "お知らせ",
+ "inbox.tab.done": "完了",
+ "inbox.card.summary": "{needs} 件があなたの対応待ち · {info} 件のお知らせ",
+ "inbox.card.forInfo": "{count} 件のお知らせ",
+ "inbox.card.caughtUp": "すべて対応済み",
+ "inbox.card.open": "受信箱を開く",
+ "inbox.action.openInChat": "チャットで開く",
+ "inbox.action.back": "一覧に戻る",
+ "inbox.reply.placeholder": "返信を書く",
+ "inbox.empty.needsYou": "あなたの対応待ちはありません。",
+ "inbox.empty.info": "お知らせはありません。",
+ "inbox.empty.done": "完了したものはまだありません。",
+ "inbox.subject.approval": "承認",
+ "inbox.subject.question": "質問",
+ "inbox.subject.message": "メッセージ",
+ "inbox.subject.result": "ルーティンの報告",
+ "inbox.subject.notice": "確認が必要",
+ "inbox.reviewInChat": "返答するには、元のチャットで確認してください。",
+ "inbox.youReplied": "あなたの返信",
"sidebar.people.mention": "{name}さんに書く",
"orgChart.mode.departments": "部署",
"orgChart.mode.people": "報告関係",
diff --git a/src/locales/pl.json b/src/locales/pl.json
index c49bdca5dd..1bf44b89d6 100644
--- a/src/locales/pl.json
+++ b/src/locales/pl.json
@@ -6325,6 +6325,26 @@
"sidebar.people.you": "{name} (ty)",
"sidebar.people.yourInbox": "Twoja skrzynka: wszystko, co do ciebie trafia",
"sidebar.people.yourInboxWaiting": "Twoja skrzynka: czeka na ciebie, {count}",
+ "inbox.panel.title": "Skrzynka",
+ "inbox.tab.info": "Do wiadomości",
+ "inbox.tab.done": "Zrobione",
+ "inbox.card.summary": "{needs} czeka na ciebie · {info} do wiadomości",
+ "inbox.card.forInfo": "{count} do wiadomości",
+ "inbox.card.caughtUp": "Wszystko załatwione",
+ "inbox.card.open": "Otwórz skrzynkę",
+ "inbox.action.openInChat": "Otwórz w czacie",
+ "inbox.action.back": "Wróć do listy",
+ "inbox.reply.placeholder": "Napisz odpowiedź",
+ "inbox.empty.needsYou": "Nic na ciebie nie czeka.",
+ "inbox.empty.info": "Brak wiadomości dla ciebie.",
+ "inbox.empty.done": "Nic tu jeszcze nie jest zrobione.",
+ "inbox.subject.approval": "Zgoda",
+ "inbox.subject.question": "Pytanie",
+ "inbox.subject.message": "Wiadomość",
+ "inbox.subject.result": "Raport z rutyny",
+ "inbox.subject.notice": "Do sprawdzenia",
+ "inbox.reviewInChat": "Aby odpowiedzieć, zajrzyj do czatu, z którego to przyszło.",
+ "inbox.youReplied": "Twoja odpowiedź",
"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.json
index 52d28dc1ea..cb804ce9a8 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -1482,6 +1482,26 @@
"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}",
+ "inbox.panel.title": "Caixa de entrada",
+ "inbox.tab.info": "Para sua informação",
+ "inbox.tab.done": "Concluído",
+ "inbox.card.summary": "{needs} precisam de você · {info} para sua informação",
+ "inbox.card.forInfo": "{count} para sua informação",
+ "inbox.card.caughtUp": "Tudo em dia",
+ "inbox.card.open": "Abrir a caixa de entrada",
+ "inbox.action.openInChat": "Abrir no chat",
+ "inbox.action.back": "Voltar para a lista",
+ "inbox.reply.placeholder": "Escreva sua resposta",
+ "inbox.empty.needsYou": "Nada espera por você.",
+ "inbox.empty.info": "Nenhuma novidade para você.",
+ "inbox.empty.done": "Nada concluído aqui ainda.",
+ "inbox.subject.approval": "Aprovação",
+ "inbox.subject.question": "Pergunta",
+ "inbox.subject.message": "Mensagem",
+ "inbox.subject.result": "Relatório da rotina",
+ "inbox.subject.notice": "Precisa de atenção",
+ "inbox.reviewInChat": "Veja no chat de onde veio para responder.",
+ "inbox.youReplied": "Você respondeu",
"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.json
index c4b490f5ec..049d454961 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -1611,6 +1611,26 @@
"sidebar.people.you": "{name} (вы)",
"sidebar.people.yourInbox": "Ваши входящие: всё, что вам отправили",
"sidebar.people.yourInboxWaiting": "Ваши входящие: ждут вас, {count}",
+ "inbox.panel.title": "Входящие",
+ "inbox.tab.info": "К сведению",
+ "inbox.tab.done": "Готово",
+ "inbox.card.summary": "Ждут вас: {needs} · к сведению: {info}",
+ "inbox.card.forInfo": "К сведению: {count}",
+ "inbox.card.caughtUp": "Всё разобрано",
+ "inbox.card.open": "Открыть входящие",
+ "inbox.action.openInChat": "Открыть в чате",
+ "inbox.action.back": "Назад к списку",
+ "inbox.reply.placeholder": "Напишите ответ",
+ "inbox.empty.needsYou": "Ничего не ждёт вас.",
+ "inbox.empty.info": "Новостей для вас нет.",
+ "inbox.empty.done": "Здесь пока ничего не сделано.",
+ "inbox.subject.approval": "Одобрение",
+ "inbox.subject.question": "Вопрос",
+ "inbox.subject.message": "Сообщение",
+ "inbox.subject.result": "Отчёт рутины",
+ "inbox.subject.notice": "Нужно посмотреть",
+ "inbox.reviewInChat": "Чтобы ответить, посмотрите в чате, откуда это пришло.",
+ "inbox.youReplied": "Ваш ответ",
"sidebar.people.mention": "Написать: {name}",
"orgChart.mode.departments": "Отделы",
"orgChart.mode.people": "Кому кто подчиняется",
diff --git a/src/locales/tr.json b/src/locales/tr.json
index f617ac65d3..f02a4dc65f 100644
--- a/src/locales/tr.json
+++ b/src/locales/tr.json
@@ -1176,6 +1176,26 @@
"sidebar.people.you": "{name} (sen)",
"sidebar.people.yourInbox": "Gelen kutun: sana gönderilen her şey",
"sidebar.people.yourInboxWaiting": "Gelen kutun: seni bekliyor, {count}",
+ "inbox.panel.title": "Gelen kutusu",
+ "inbox.tab.info": "Bilginize",
+ "inbox.tab.done": "Bitti",
+ "inbox.card.summary": "{needs} seni bekliyor · {info} bilginize",
+ "inbox.card.forInfo": "{count} bilginize",
+ "inbox.card.caughtUp": "Her şey tamam",
+ "inbox.card.open": "Gelen kutusunu aç",
+ "inbox.action.openInChat": "Sohbette aç",
+ "inbox.action.back": "Listeye dön",
+ "inbox.reply.placeholder": "Yanıtını yaz",
+ "inbox.empty.needsYou": "Seni bekleyen bir şey yok.",
+ "inbox.empty.info": "Senin için haber yok.",
+ "inbox.empty.done": "Burada henüz biten bir şey yok.",
+ "inbox.subject.approval": "Onay",
+ "inbox.subject.question": "Soru",
+ "inbox.subject.message": "Mesaj",
+ "inbox.subject.result": "Rutin raporu",
+ "inbox.subject.notice": "Bakılması gerek",
+ "inbox.reviewInChat": "Yanıtlamak için geldiği sohbette bak.",
+ "inbox.youReplied": "Yanıtın",
"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.json
index c391dbb093..bacd155168 100644
--- a/src/locales/uk.json
+++ b/src/locales/uk.json
@@ -560,6 +560,26 @@
"sidebar.people.you": "{name} (ви)",
"sidebar.people.yourInbox": "Ваші вхідні: усе, що вам надіслали",
"sidebar.people.yourInboxWaiting": "Ваші вхідні: чекає на вас, {count}",
+ "inbox.panel.title": "Вхідні",
+ "inbox.tab.info": "До відома",
+ "inbox.tab.done": "Готово",
+ "inbox.card.summary": "Чекають на вас: {needs} · до відома: {info}",
+ "inbox.card.forInfo": "До відома: {count}",
+ "inbox.card.caughtUp": "Усе розібрано",
+ "inbox.card.open": "Відкрити вхідні",
+ "inbox.action.openInChat": "Відкрити в чаті",
+ "inbox.action.back": "Назад до списку",
+ "inbox.reply.placeholder": "Напишіть відповідь",
+ "inbox.empty.needsYou": "Ніщо на вас не чекає.",
+ "inbox.empty.info": "Новин для вас немає.",
+ "inbox.empty.done": "Тут поки нічого не зроблено.",
+ "inbox.subject.approval": "Схвалення",
+ "inbox.subject.question": "Запитання",
+ "inbox.subject.message": "Повідомлення",
+ "inbox.subject.result": "Звіт рутини",
+ "inbox.subject.notice": "Потрібно глянути",
+ "inbox.reviewInChat": "Щоб відповісти, перегляньте це в чаті, звідки воно прийшло.",
+ "inbox.youReplied": "Ваша відповідь",
"sidebar.people.mention": "Написати: {name}",
"orgChart.mode.departments": "Відділи",
"orgChart.mode.people": "Хто кому звітує",
diff --git a/src/locales/vi.json b/src/locales/vi.json
index 3742cd03ce..d4c8c2dbff 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -1176,6 +1176,26 @@
"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}",
+ "inbox.panel.title": "Hộp thư",
+ "inbox.tab.info": "Để bạn biết",
+ "inbox.tab.done": "Xong",
+ "inbox.card.summary": "{needs} cần bạn · {info} để bạn biết",
+ "inbox.card.forInfo": "{count} để bạn biết",
+ "inbox.card.caughtUp": "Đã xử lý hết",
+ "inbox.card.open": "Mở hộp thư",
+ "inbox.action.openInChat": "Mở trong cuộc trò chuyện",
+ "inbox.action.back": "Quay lại danh sách",
+ "inbox.reply.placeholder": "Viết câu trả lời",
+ "inbox.empty.needsYou": "Không có gì chờ bạn.",
+ "inbox.empty.info": "Không có tin mới cho bạn.",
+ "inbox.empty.done": "Chưa có gì xong ở đây.",
+ "inbox.subject.approval": "Phê duyệt",
+ "inbox.subject.question": "Câu hỏi",
+ "inbox.subject.message": "Tin nhắn",
+ "inbox.subject.result": "Báo cáo quy trình",
+ "inbox.subject.notice": "Cần xem",
+ "inbox.reviewInChat": "Xem trong cuộc trò chuyện mà nó đến để trả lời.",
+ "inbox.youReplied": "Câu trả lời của bạn",
"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.json
index 25fc04ff1d..1875be7f0a 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -1009,6 +1009,26 @@
"sidebar.people.you": "{name}(你)",
"sidebar.people.yourInbox": "你的收件匣:寄給你的一切都在這裡",
"sidebar.people.yourInboxWaiting": "你的收件匣:待你處理,{count}",
+ "inbox.panel.title": "收件匣",
+ "inbox.tab.info": "供你參考",
+ "inbox.tab.done": "已完成",
+ "inbox.card.summary": "{needs} 項待你處理 · {info} 項供你參考",
+ "inbox.card.forInfo": "{count} 項供你參考",
+ "inbox.card.caughtUp": "全部處理完畢",
+ "inbox.card.open": "開啟收件匣",
+ "inbox.action.openInChat": "在聊天中開啟",
+ "inbox.action.back": "回到清單",
+ "inbox.reply.placeholder": "寫下你的回覆",
+ "inbox.empty.needsYou": "沒有待你處理的事。",
+ "inbox.empty.info": "沒有給你的新消息。",
+ "inbox.empty.done": "這裡還沒有已完成的項目。",
+ "inbox.subject.approval": "核准",
+ "inbox.subject.question": "問題",
+ "inbox.subject.message": "訊息",
+ "inbox.subject.result": "例行報告",
+ "inbox.subject.notice": "需要查看",
+ "inbox.reviewInChat": "請到它來自的聊天中查看並回覆。",
+ "inbox.youReplied": "你的回覆",
"sidebar.people.mention": "寫給 {name}",
"orgChart.mode.departments": "部門",
"orgChart.mode.people": "回報關係",
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 4b45b3645a..03134bb73a 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -702,6 +702,26 @@
"sidebar.people.you": "{name}(你)",
"sidebar.people.yourInbox": "你的收件箱:发给你的一切都在这里",
"sidebar.people.yourInboxWaiting": "你的收件箱:待你处理,{count}",
+ "inbox.panel.title": "收件箱",
+ "inbox.tab.info": "供你参考",
+ "inbox.tab.done": "已完成",
+ "inbox.card.summary": "{needs} 项待你处理 · {info} 项供你参考",
+ "inbox.card.forInfo": "{count} 项供你参考",
+ "inbox.card.caughtUp": "全部处理完毕",
+ "inbox.card.open": "打开收件箱",
+ "inbox.action.openInChat": "在聊天中打开",
+ "inbox.action.back": "返回列表",
+ "inbox.reply.placeholder": "写下你的回复",
+ "inbox.empty.needsYou": "没有待你处理的事。",
+ "inbox.empty.info": "没有给你的新消息。",
+ "inbox.empty.done": "这里还没有已完成的项。",
+ "inbox.subject.approval": "批准",
+ "inbox.subject.question": "问题",
+ "inbox.subject.message": "消息",
+ "inbox.subject.result": "例行报告",
+ "inbox.subject.notice": "需要查看",
+ "inbox.reviewInChat": "请到它来自的聊天中查看并回复。",
+ "inbox.youReplied": "你的回复",
"sidebar.people.mention": "写给 {name}",
"orgChart.mode.departments": "部门",
"orgChart.mode.people": "汇报关系",
diff --git a/src/state/inbox.ts b/src/state/inbox.ts
new file mode 100644
index 0000000000..39cb37229d
--- /dev/null
+++ b/src/state/inbox.ts
@@ -0,0 +1,104 @@
+// On a Team Cloud: the person's inbox as its panel and its card in the chat show it. One copy of the server's list, read
+// again whenever their inbox's task says what it lists changed, and the panel's own place (open, tab, the line read).
+// Null anywhere but a team's Cloud, where no task is anyone's inbox.
+import { useEffect, useSyncExternalStore } from "react";
+import type { InboxRow, InboxTab, InboxView } from "../../shared/inbox";
+import { api } from "./api";
+
+type InboxTaskLike = { threadId: string; inbox?: true; openAsks?: number; inboxChangedAt?: number };
+
+/** What the list depends on, from the person's own inbox task; null when they have none. */
+export function inboxVersion(bots: ReadonlyArray<{ id: string; tasks?: readonly InboxTaskLike[] }>): string | null {
+ for (const bot of bots) {
+ const task = bot.tasks?.find((one) => one.inbox);
+ if (task) return `${bot.id}:${task.threadId}:${task.inboxChangedAt ?? 0}:${task.openAsks ?? 0}`;
+ }
+ return null;
+}
+
+function store<T>(initial: T) {
+ let value = initial;
+ const listeners = new Set<() => void>();
+ return {
+ get: () => value,
+ set(next: T) { value = next; for (const listener of listeners) listener(); },
+ subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; },
+ };
+}
+
+const list = store<InboxView | null>(null);
+export const currentInbox = list.get;
+export const useInboxView = (): InboxView | null => useSyncExternalStore(list.subscribe, list.get, list.get);
+/** Tests and previews show a list of their own. */
+export const setInboxView = list.set;
+
+let reading: Promise<void> | null = null;
+let readAgain = false;
+/** Reads the list now, or once more after the read on its way, so the newest answer always lands last. */
+export function refreshInbox(): Promise<void> {
+ if (reading) { readAgain = true; return reading; }
+ reading = (async () => {
+ try {
+ do {
+ readAgain = false;
+ const view = await api<InboxView>("/api/inbox", { background: true }).catch(() => null);
+ if (view && Array.isArray(view.rows)) list.set(view);
+ } while (readAgain);
+ } finally {
+ reading = null;
+ }
+ })();
+ return reading;
+}
+
+/** Keeps the list in step with the person's inbox task; nothing off a team. */
+export function useInboxLoader(version: string | null): void {
+ useEffect(() => {
+ if (version === null) { list.set(null); return; }
+ void refreshInbox();
+ }, [version]);
+}
+
+const patchRow = (id: string, patch: Partial<InboxRow>) => {
+ const view = list.get();
+ if (view) list.set({ ...view, rows: view.rows.map((row) => (row.id === id ? { ...row, ...patch } : row)) });
+};
+
+async function mark(id: string, what: "read" | "done"): Promise<void> {
+ const view = await api<InboxView>(`/api/inbox/${id}/${what}`, { method: "POST", background: true }).catch(() => null);
+ if (view && Array.isArray(view.rows)) list.set(view);
+ else void refreshInbox();
+}
+
+/** The person read a line: it is no longer bold. */
+export function readInboxRow(row: Pick<InboxRow, "id" | "unread">): void {
+ if (!row.unread) return;
+ patchRow(row.id, { unread: false });
+ void mark(row.id, "read");
+}
+
+/** The person is done with a line of news: it moves to Done. */
+export function doneInboxRow(row: Pick<InboxRow, "id">): void {
+ patchRow(row.id, { tab: "done", unread: false });
+ void mark(row.id, "done");
+}
+
+/** A reply to a line of news that waits on one: it goes back where the line came from, as a Reply in the chat does. */
+export async function replyToInboxRow(view: Pick<InboxView, "botId" | "threadId">, row: Pick<InboxRow, "id">, text: string): Promise<void> {
+ await api(`/api/bots/${view.botId}/messages`, { method: "POST", body: JSON.stringify({ text, threadId: view.threadId, replyToId: row.id, sendId: crypto.randomUUID() }) });
+ void refreshInbox();
+}
+
+export interface InboxPanelState { open: boolean; tab: InboxTab; reading: string | null }
+const panel = store<InboxPanelState>({ open: false, tab: "needs-you", reading: null });
+export const useInboxPanel = (): InboxPanelState => useSyncExternalStore(panel.subscribe, panel.get, panel.get);
+export const currentInboxPanel = panel.get;
+
+/** Opens the inbox in the right panel: on a tab, or straight on one line. */
+export function openInbox(at: { tab?: InboxTab; reading?: string } = {}): void {
+ panel.set({ open: true, tab: at.tab ?? panel.get().tab, reading: at.reading ?? null });
+ void refreshInbox();
+}
+export const closeInbox = (): void => panel.set({ ...panel.get(), open: false, reading: null });
+export const showInboxTab = (tab: InboxTab): void => panel.set({ ...panel.get(), tab, reading: null });
+export const readInboxLine = (id: string | null): void => panel.set({ ...panel.get(), reading: id });
diff --git a/src/testing/inbox-fixture.ts b/src/testing/inbox-fixture.ts
new file mode 100644
index 0000000000..874345a93b
--- /dev/null
+++ b/src/testing/inbox-fixture.ts
@@ -0,0 +1,33 @@
+// A person's inbox for the inbox panel's tests and preview: two asks waiting on them, news, and one settled ask.
+import type { InboxRow, InboxView } from "../../shared/inbox";
+
+export const INBOX_NOW = new Date(2026, 9, 28, 15, 0).getTime();
+
+export const approvalRow: InboxRow = {
+ id: "line-approval", kind: "ask", tab: "needs-you", unread: true, at: INBOX_NOW - 2 * 60_000,
+ from: { name: "Reporter", botId: "reporter" }, origin: { botId: "reporter", threadId: "rep-main", title: "Reporter" }, text: "Run: rm -rf ./build",
+ card: { title: "Approval needed", subtitle: "rm -rf ./build", options: ["Allow", "Deny"], requestId: "req-approval", tool: "Bash", requestType: "permission" },
+};
+export const questionRow: InboxRow = {
+ id: "line-question", kind: "ask", tab: "needs-you", unread: false, at: INBOX_NOW - 20 * 60_000,
+ from: { name: "Scout", botId: "scout" }, origin: { botId: "scout", threadId: "scout-main", title: "Launch page" }, text: "Which landing page should I rewrite?",
+ card: { title: "Your bot has a question", subtitle: "Which landing page should I rewrite?", options: ["Home", "Pricing"], requestId: "req-question", requestType: "question" },
+};
+export const messageRow: InboxRow = {
+ id: "line-message", kind: "message", tab: "info", unread: true, at: INBOX_NOW - 65 * 60_000, replies: true,
+ from: { name: "Philipp", email: "[email protected]" }, via: { botId: "scout", name: "Scout" }, text: "The launch moved to Friday. Can you check the numbers before then?",
+};
+export const reportRow: InboxRow = {
+ id: "line-report", kind: "result", tab: "info", unread: false, at: INBOX_NOW - 3 * 60 * 60_000,
+ from: { name: "Reporter", botId: "reporter" }, origin: { botId: "reporter", threadId: "rep-daily", title: "Daily digest" }, text: "Daily digest: 3 new leads, 1 reply waiting.",
+};
+export const settledRow: InboxRow = {
+ id: "line-settled", kind: "ask", tab: "done", unread: false, at: INBOX_NOW - 26 * 60 * 60_000,
+ from: { name: "Reporter", botId: "reporter" }, text: "Run: npm test",
+ card: { title: "Approval needed", subtitle: "npm test", options: ["Allow", "Deny"], requestId: "req-settled", tool: "Bash", requestType: "permission", answered: "allow" },
+};
+
+export const inboxView = (rows: InboxRow[] = [approvalRow, questionRow, messageRow, reportRow, settledRow]): InboxView => ({
+ botId: "marcos-chief", threadId: "inbox", rows,
+ anchor: rows.find((row) => row.kind === "ask")?.id ?? rows[0]?.id ?? null,
+});