Skip to content

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

Inbox: each item says why it is here, For you and Activity, and reading doesn't move rows (#7573)

Milind Soni2cce85db6a97
diff --git a/docs/team-cloud.md b/docs/team-cloud.md
index 8d622a9e3c..39237b267e 100644
--- a/docs/team-cloud.md
+++ b/docs/team-cloud.md
@@ -974,9 +974,16 @@ count: the browser tab's title and the app's icon.
`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
+it), `POST /api/inbox/<line>/read` marks one line read and `/unread` makes it new again; each answers with the list as it
+is now. Each line says first why it is there (`shared/inbox-reason.ts`): "Asked you", "Needs your OK", "Mentioned you",
+"Replied to you", "Messaged you", "Needs a look", "Finished" or "Shared with you". Most follow from the line itself; a
+mention, a reply to the person, a share and a board item's question carry `InboxItem.reason`, because only the server
+can tell them apart. The app lists the lines in two groups: **For you** (what waits on the person or names them, the
+only lines the Inbox's number counts) and **Activity** (finished work and shares, which make the Inbox row bold and are
+never counted). The app shows the list in the right panel, opened from the card, the badge or the person's own row under
+People: rows with each line's quick answers, a reading view with the reply, and a sheet at phone width. An opened line is
+read after two seconds on screen with the window focused, or at once when the person answers it, with "Marked as read ·
+Undo"; it keeps its place in the list, read or settled, until the person picks another. 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.
diff --git a/inbox-preview.html b/inbox-preview.html
new file mode 100644
index 0000000000..d69f3b02d4
--- /dev/null
+++ b/inbox-preview.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Inbox Preview</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/src/inbox-preview.tsx"></script>
+ </body>
+</html>
diff --git a/packages/phone-protocol/src/inbox-reason.ts b/packages/phone-protocol/src/inbox-reason.ts
new file mode 100644
index 0000000000..ef54dce437
--- /dev/null
+++ b/packages/phone-protocol/src/inbox-reason.ts
@@ -0,0 +1,33 @@
+import type { InboxRow } from "./inbox.ts";
+import { cardKind } from "./live-approval.ts";
+
+/** Why a line is in a person's inbox, the first thing its row says. "asked": a bot's question, or a password, sign-in or
+ * app it needs; "approval": an action, a change to review or someone asking for access waits on their OK; "mentioned":
+ * a teammate or a bot @-named them; "replied": a teammate answered their message; "messaged": a bot or a teammate wrote to
+ * them; "notice": something went wrong that needs a look; "finished": a routine's report; "shared": a bot or a conversation
+ * was shared with them. */
+export type InboxReason = "asked" | "approval" | "mentioned" | "replied" | "messaged" | "notice" | "finished" | "shared";
+
+/** The reasons only the server can tell, carried on a line as `reason`; every other reason follows from the line itself. */
+export type InboxSaidReason = Extract<InboxReason, "asked" | "mentioned" | "replied" | "shared">;
+
+/** "for-you": it waits on the person or names them, and counts toward the inbox's number; "activity": news, shown
+ * bold while unread and never counted. */
+export type InboxGroup = "for-you" | "activity";
+
+type ReasonRow = Pick<InboxRow, "kind" | "card" | "reason">;
+
+export function inboxReason(row: ReasonRow): InboxReason {
+ if (row.kind === "ask") return row.card && (row.card.accessRequest || cardKind(row.card) !== "question") ? "approval" : "asked";
+ if (row.reason) return row.reason;
+ if (row.kind === "result") return "finished";
+ return row.kind === "notice" ? "notice" : "messaged";
+}
+
+const ACTIVITY: ReadonlySet<InboxReason> = new Set(["finished", "shared"]);
+
+export const inboxGroup = (row: ReasonRow): InboxGroup => (ACTIVITY.has(inboxReason(row)) ? "activity" : "for-you");
+
+/** A line the inbox's number counts: in For you, and waiting on the person or not read yet. */
+export const countsForYou = (row: ReasonRow & Pick<InboxRow, "tab" | "unread">): boolean =>
+ inboxGroup(row) === "for-you" && (row.tab === "needs-you" || (row.tab === "info" && row.unread));
diff --git a/packages/phone-protocol/src/inbox.ts b/packages/phone-protocol/src/inbox.ts
index 58f5e46c75..d25f12958d 100644
--- a/packages/phone-protocol/src/inbox.ts
+++ b/packages/phone-protocol/src/inbox.ts
@@ -1,4 +1,5 @@
import type { ConnectorCardData } from "./connector-card.ts";
+import type { InboxSaidReason } from "./inbox-reason.ts";
import type { OptionCardData, SecretRequestCardData, SignInRequestCardData } 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
@@ -21,6 +22,8 @@ export interface InboxItem {
assistant?: true;
/** 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 }>;
+ /** Why it is here, when the line itself can't tell: a mention, a reply to the person, a share, or a bot's question. */
+ reason?: InboxSaidReason;
}
/** A task's fields on a team's server when it is a person's inbox, sent to that person alone. */
@@ -57,6 +60,7 @@ export interface InboxRow {
unread: boolean;
replies?: true;
answers?: InboxItem["answers"];
+ reason?: InboxItem["reason"];
/** An ask's card as the inbox holds it: answering it answers the card where it was asked. */
card?: OptionCardData;
/** A password the bot asked for, answered with the chat's own card for it. */
diff --git a/packages/phone-protocol/src/live-approval.ts b/packages/phone-protocol/src/live-approval.ts
index 0187312b03..66a9b15cde 100644
--- a/packages/phone-protocol/src/live-approval.ts
+++ b/packages/phone-protocol/src/live-approval.ts
@@ -13,6 +13,11 @@ export type LiveCardKind = "approval" | "review" | "question";
* can answer it any more. */
export function liveCardKind(card: OptionCardData | undefined): LiveCardKind | null {
if (!card?.requestId || card.answered || card.dismissed || card.expired) return null;
+ return cardKind(card);
+}
+
+/** What a card asks, answered or not. */
+export function cardKind(card: OptionCardData): LiveCardKind {
if (card.skillRequest || card.routineRequest || card.profileRequest || card.modelRequest || card.teamSetupRequest || card.mcpRequest || card.quotaSwitch || card.lendingLift) {
return "review";
}
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs
index 97f13f2c35..1b51542309 100644
--- a/scripts/ci-scope.mjs
+++ b/scripts/ci-scope.mjs
@@ -102,6 +102,7 @@ export const VITEST_SUBSETS = {
"server/cloud-team-files.e2e.test.ts",
"server/cloud-team-gateway-mcp.e2e.test.ts",
"server/cloud-team-inbox.e2e.test.ts",
+ "server/cloud-team-inbox-reasons.e2e.test.ts",
"server/cloud-team-included-hosting.e2e.test.ts",
"server/cloud-team-mausbot-reach.e2e.test.ts",
"server/cloud-team-member-secrets.e2e.test.ts",
diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.ts
index fdb7d612ac..dff85ce9c6 100644
--- a/scripts/ci-scope.test.ts
+++ b/scripts/ci-scope.test.ts
@@ -242,6 +242,7 @@ describe("CI outputs", () => {
"server/cloud-team-files.e2e.test.ts",
"server/cloud-team-gateway-mcp.e2e.test.ts",
"server/cloud-team-inbox.e2e.test.ts",
+ "server/cloud-team-inbox-reasons.e2e.test.ts",
"server/cloud-team-included-hosting.e2e.test.ts",
"server/cloud-team-mausbot-reach.e2e.test.ts",
"server/cloud-team-member-secrets.e2e.test.ts",
diff --git a/server/cloud-team-inbox-reasons.e2e.test.ts b/server/cloud-team-inbox-reasons.e2e.test.ts
new file mode 100644
index 0000000000..9249e1543a
--- /dev/null
+++ b/server/cloud-team-inbox-reasons.e2e.test.ts
@@ -0,0 +1,81 @@
+// Why each line is in a person's inbox on a Team Cloud, end to end: Acme's Owner Cleo and a member Ben, with the fake
+// Claude CLI. Cleo's @Ben lands in Ben's inbox saying it mentioned him, in For you, counted; a routine Ben runs lands as
+// Finished, in Activity, never counted. A line read can be made new again.
+import { randomBytes } from "node:crypto";
+import { afterAll, beforeAll, expect, it } from "vitest";
+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";
+import type { InboxRow, InboxView } from "../shared/inbox.ts";
+import { countsForYou, inboxGroup, inboxReason } from "../shared/inbox-reason.ts";
+import { hostTimeout } from "./testing/host-timeout.ts";
+
+type Bot = { id: string; name: string; threadId: string; mainThreadId?: string; busy?: boolean; activity?: string };
+
+let fx: CloudSendFixture, team: CloudTeamFixture;
+let cleo = "", ben = "";
+let scout: Bot, reporter: Bot;
+
+async function until(done: () => Promise<boolean> | boolean, what: string, timeoutMs = 60_000): Promise<void> {
+ const end = Date.now() + timeoutMs;
+ while (!(await done())) {
+ if (Date.now() > end) throw new Error(`timed out waiting for ${what}\n${fx.logs().slice(-4_000)}`);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+}
+const inbox = async (token: string) => (await team.as(token, "GET", "/api/inbox")).body as InboxView;
+const rows = async (token: string) => (await inbox(token)).rows ?? [];
+const idle = async () => ((await team.as(cleo, "GET", "/api/bots")).body.bots as Bot[]).every((bot) => !bot.busy && bot.activity !== "working");
+
+beforeAll(async () => {
+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-reasons-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-reasons", name: "Acme" } });
+ team = fx.team!;
+ cleo = (await team.pair({ email: "[email protected]", role: "owner" })).token!;
+ ben = (await team.pair({ email: "[email protected]", role: "member" })).token!;
+ const create = async (body: Record<string, unknown>) => {
+ const created = await team.as(cleo, "POST", "/api/bots", { visibility: "everyone", ...body });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ return created.body.bot as Bot;
+ };
+ scout = await create({ name: "Scout" });
+ const chief = await create({ name: "Ben's Chief", reportsTo: "[email protected]" });
+ expect((await team.as(cleo, "PATCH", `/api/bots/${chief.id}`, { chiefOfStaff: true })).status).toBe(200);
+ reporter = await create({ name: "Reporter", reportsTo: "[email protected]" });
+}, hostTimeout(180_000));
+
+afterAll(async () => {
+ await fx?.close();
+});
+
+it("lands a teammate's @Ben in For you, saying it mentioned him, and counts it", async () => {
+ const sent = await team.as(cleo, "POST", `/api/bots/${scout.id}/messages`, { text: "@Ben can you look at the new header?", threadId: scout.mainThreadId ?? scout.threadId });
+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);
+ await until(async () => (await rows(ben)).some((row) => row.kind === "message"), "the mention in Ben's inbox");
+ const line = (await rows(ben)).find((row) => row.kind === "message")!;
+ expect(line).toMatchObject({ reason: "mentioned", from: { name: "Cleo" }, tab: "info", unread: true });
+ expect(inboxReason(line)).toBe("mentioned");
+ expect(inboxGroup(line)).toBe("for-you");
+ expect(countsForYou(line)).toBe(true);
+ await until(idle, "Scout to settle");
+}, hostTimeout(120_000));
+
+it("lands a bot's finished routine in Activity, never counted, and lets a read line be new again", async () => {
+ const made = await team.as(ben, "POST", "/api/routines", { name: "Weekly report", prompt: "Sum up this week's leads.", botId: reporter.id, resultsThreadId: null,
+ schedule: { type: "interval", everyMinutes: 1440, anchorAt: Date.now() + 86_400_000 } });
+ expect(made.status, JSON.stringify(made.body)).toBe(201);
+ expect((await team.as(ben, "POST", `/api/routines/${made.body.routine.id}/run`)).status).toBe(201);
+ await until(async () => (await rows(ben)).some((row) => row.kind === "result"), "the routine's report in Ben's inbox", 90_000);
+ const report = (await rows(ben)).find((row) => row.kind === "result")!;
+ expect(report.from.name).toBe("Reporter");
+ expect(inboxReason(report)).toBe("finished");
+ expect(inboxGroup(report)).toBe("activity");
+ expect(countsForYou(report)).toBe(false);
+ const forYou = (list: InboxRow[]) => list.filter((row) => inboxGroup(row) === "for-you").map((row) => row.kind);
+ expect(forYou(await rows(ben))).toEqual(["message"]);
+
+ const read = await team.as(ben, "POST", `/api/inbox/${report.id}/read`);
+ expect(read.status).toBe(200);
+ expect((read.body as InboxView).rows.find((row) => row.id === report.id)).toMatchObject({ unread: false, tab: "done" });
+ const again = await team.as(ben, "POST", `/api/inbox/${report.id}/unread`);
+ expect(again.status, JSON.stringify(again.body)).toBe(200);
+ expect((again.body as InboxView).rows.find((row) => row.id === report.id)).toMatchObject({ unread: true, tab: "info" });
+ expect((await team.as(cleo, "POST", `/api/inbox/${report.id}/unread`)).status, "only Ben's own lines").toBe(404);
+}, hostTimeout(180_000));
diff --git a/server/host/access-requests.ts b/server/host/access-requests.ts
index da8e9e0720..30fb5b149c 100644
--- a/server/host/access-requests.ts
+++ b/server/host/access-requests.ts
@@ -108,7 +108,7 @@ export function createAccessRequests(deps: AccessRequestDeps) {
if (raised) deps.writeAccess(bot, after);
deps.record?.({ category: "visibility", action: "access.allow", target: { kind: "bot", id: bot.id, name: bot.name }, before: { access, asked: ask.email }, after: { access: after, asked: ask.email } }, person.email);
deps.inbox().deliver(personKeyOf(ask.email), {
- kind: "notice", from: { name: nameOf(person.email), email: person.email },
+ kind: "notice", reason: "shared", from: { name: nameOf(person.email), email: person.email },
text: `${nameOf(person.email)} let you chat with ${bot.name}.`, title: `You can chat with ${bot.name}`, notify: "done",
});
}
diff --git a/server/host/person-inbox.test.ts b/server/host/person-inbox.test.ts
index 6934b6e60c..a9940b441d 100644
--- a/server/host/person-inbox.test.ts
+++ b/server/host/person-inbox.test.ts
@@ -193,6 +193,8 @@ describe("finished work in a person's inbox", () => {
f.team.inbox.markRead(person, row.id);
expect(f.team.inbox.view(person)!.rows[0]!.tab).toBe("done");
expect(f.team.inbox.view(person)!.rows.filter((one) => one.tab === "info"), "the inbox holds only what needs them").toEqual([]);
+ expect(f.team.inbox.markRead(person, row.id, false), "made new again").toBe(true);
+ expect(f.team.inbox.view(person)!.rows[0]).toMatchObject({ tab: "info", unread: true });
});
it("points the line at the message it came from, so a client can open the conversation there", () => {
@@ -391,3 +393,17 @@ describe("what a confined conversation says", () => {
expect(f.team.needsYou(session(BEN.email))).toEqual([]);
});
});
+
+describe("why a line is here", () => {
+ it("follows what a kept line says now: a share, then a message in the same conversation", () => {
+ const f = fixture();
+ const person = key(BEN.email);
+ const line = { kind: "message" as const, from: { name: "Cleo", email: CLEO.email }, origin: { botId: "scout", threadId: "scout-main" }, title: "Cleo", notify: "mention" as const };
+ expect(f.team.inbox.keepOne(person, { ...line, reason: "shared", text: "Cleo shared “Launch” with you." })?.created).toBe(true);
+ expect(f.team.inbox.view(person)!.rows).toEqual([expect.objectContaining({ reason: "shared" })]);
+ expect(f.team.inbox.keepOne(person, { ...line, text: "Cleo wrote in “Launch”." })?.created).toBe(false);
+ const [row] = f.team.inbox.view(person)!.rows;
+ expect(row).toMatchObject({ text: "Cleo wrote in “Launch”." });
+ expect(row!.reason).toBeUndefined();
+ });
+});
diff --git a/server/host/person-inbox.ts b/server/host/person-inbox.ts
index 770a360823..9c08440c09 100644
--- a/server/host/person-inbox.ts
+++ b/server/host/person-inbox.ts
@@ -72,6 +72,7 @@ export interface Delivery {
kind: Item["kind"];
from: { name: string; email?: string; botId?: string };
via?: { botId: string; name: string };
+ reason?: InboxItem["reason"];
to?: Item["to"];
asker?: string;
origin?: Origin;
@@ -122,6 +123,12 @@ export interface PersonInboxDeps {
now?: () => number;
}
+/** A line's wire with the reason of what it now says, or none. */
+function reasoned(wire: InboxItem, reason: InboxItem["reason"]): InboxItem {
+ const { reason: _was, ...rest } = wire;
+ return reason ? { ...rest, reason } : rest;
+}
+
export function createPersonInbox(deps: PersonInboxDeps) {
const { team, store } = deps;
const now = deps.now ?? Date.now;
@@ -299,7 +306,7 @@ export function createPersonInbox(deps: PersonInboxDeps) {
// The message it points at: the newest one in the conversation it came from, so a client can put the person there.
? { origin: { ...origin, title: titleOf(origin), ...(origin.messageId ? {} : focusOf(origin.threadId)) } }
: {}),
- ...(delivery.to ? { replies: true as const } : {}),
+ ...(delivery.to ? { replies: true as const } : {}), ...(delivery.reason ? { reason: delivery.reason } : {}),
...(delivery.assistant ? { assistant: true as const } : {}),
};
const posted = store.appendMessage(at.threadId, delivery.card
@@ -371,7 +378,7 @@ export function createPersonInbox(deps: PersonInboxDeps) {
passed = { status: 200, text: `Passed back to ${item.from}, who carries on with it.` };
} else if (item.to === "person" && item.asker) {
const delivered = deliver(item.asker, {
- kind: "message", from: { name: replier.name, email: replier.email }, to: "person", asker: item.person,
+ kind: "message", from: { name: replier.name, email: replier.email }, to: "person", asker: item.person, reason: "replied",
...(item.origin ? { origin: item.origin } : {}), text, title: label(item.origin?.threadId ?? ""), notify: "mention", ...(by === "assistant" ? { assistant: true } : {}),
});
if (!delivered) return { status: 409, text: `${item.from} has no inbox here, so the answer can't reach them.` };
@@ -462,7 +469,7 @@ export function createPersonInbox(deps: PersonInboxDeps) {
const item = deliver(to, { ...delivery, quiet: true });
return item ? { item, created: true } : null;
}
- store.patchMessage(open.threadId, open.id, { text: delivery.text, ...(posted.inbox ? { inbox: { ...posted.inbox, from: delivery.from, ...(posted.inbox.origin ? { origin: { ...posted.inbox.origin, ...delivery.origin } } : {}) } } : {}) });
+ store.patchMessage(open.threadId, open.id, { text: delivery.text, ...(posted.inbox ? { inbox: reasoned({ ...posted.inbox, from: delivery.from, ...(posted.inbox.origin ? { origin: { ...posted.inbox.origin, ...delivery.origin } } : {}) }, delivery.reason) } : {}) });
Object.assign(open, { text: oneLine(delivery.text, 400), from: delivery.from.name.slice(0, 200), origin: delivery.origin, at: now(), seen: false });
if (delivery.from.email) open.fromEmail = delivery.from.email; else delete open.fromEmail;
save();
@@ -510,7 +517,7 @@ export function createPersonInbox(deps: PersonInboxDeps) {
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 } : {}),
+ ...(posted.inbox?.replies ? { replies: true as const } : {}), ...(posted.inbox?.reason ? { reason: posted.inbox.reason } : {}), ...(posted.inbox?.answers?.length ? { answers: posted.inbox.answers } : {}),
...(item.kind === "ask" && posted.card ? { card: posted.card } : {}),
};
});
@@ -525,11 +532,11 @@ export function createPersonInbox(deps: PersonInboxDeps) {
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 {
+ /** The person read a line, or marked it unread again. */
+ markRead(person: string, id: string, read = true): 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); }
+ if (Boolean(item.seen) !== read) { item.seen = read; save(); touch(item.threadId); }
return true;
},
/** The person read every line of their inbox that still waits on them; an ask stays open, only unmarked as new. */
diff --git a/server/host/place-inbox.test.ts b/server/host/place-inbox.test.ts
index 89cc0b3fa2..965205708e 100644
--- a/server/host/place-inbox.test.ts
+++ b/server/host/place-inbox.test.ts
@@ -131,6 +131,8 @@ describe("finished work reaches the inbox once", () => {
expect(row.kind).toBe("message");
f.inbox.markRead(OWNER, row.id);
expect(f.inbox.view(OWNER).rows[0]!.tab, "it still waits for a reply").toBe("info");
+ expect(f.inbox.markRead(OWNER, row.id, false)).toBe(true);
+ expect(f.inbox.view(OWNER).rows[0]!.unread, "made new again").toBe(true);
});
it("points a line at the message it came from, so a client can open the conversation there", () => {
@@ -394,6 +396,8 @@ describe("the inbox of a place that is no team's", () => {
expect(f.inbox.markRead(OWNER, "card-q")).toBe(true);
expect(f.inbox.view(OWNER).rows[0]!.unread).toBe(false);
expect(f.inbox.count(OWNER)).toBe(1);
+ expect(f.inbox.markRead(OWNER, "card-q", false)).toBe(true);
+ expect(f.inbox.view(OWNER).rows[0]!.unread, "an ask made new again").toBe(true);
expect(f.inbox.markDone(OWNER, "card-q")).toBe("an ask");
expect(f.inbox.markRead(OWNER, "not-a-line")).toBe(false);
expect(f.inbox.markDone(OWNER, "not-a-line")).toBe("unknown");
diff --git a/server/host/place-inbox.ts b/server/host/place-inbox.ts
index 88aea60f34..1de349d759 100644
--- a/server/host/place-inbox.ts
+++ b/server/host/place-inbox.ts
@@ -282,14 +282,15 @@ export function createPlaceInbox(deps: PlaceInboxDeps) {
count(auth: RequestAuth): number {
return view(auth).rows.filter((row) => row.tab === "needs-you" || (row.tab === "info" && row.unread)).length;
},
- markRead(auth: RequestAuth, lineId: string): boolean {
+ /** The viewer read a line or an open ask, or marked it unread again. */
+ markRead(auth: RequestAuth, lineId: string, read = true): boolean {
const line = lines.find((one) => one.id === lineId && lineFor(auth, one));
if (line) {
- if (!line.seen) { line.seen = true; save(); }
+ if (Boolean(line.seen) !== read) { line.seen = read; save(); }
return true;
}
if (!askRows(auth).some((row) => row.id === lineId)) return false;
- if (!seenAsks.has(lineId)) { seenAsks.add(lineId); save(); }
+ if (seenAsks.has(lineId) !== read) { if (read) seenAsks.add(lineId); else seenAsks.delete(lineId); save(); }
return true;
},
/** Every line and open ask this viewer lists is read; an ask is only marked read, never answered. */
diff --git a/server/host/share-notice.test.ts b/server/host/share-notice.test.ts
index 76415df914..1a3a388b9d 100644
--- a/server/host/share-notice.test.ts
+++ b/server/host/share-notice.test.ts
@@ -37,7 +37,7 @@ describe("who is told a bot was shared with them", () => {
const bot = { id: "quotes", name: "Quotes" } as BotRecord;
notice({ kind: "session", session: { email: "[email protected]" } } as unknown as RequestAuth, bot, only(), only({ [MARTA]: "chat", [RUI]: "chat" }));
expect(delivered.map(([person]) => person).sort()).toEqual([personKey({ id: "", email: MARTA }), personKey({ id: "", email: RUI })].sort());
- expect(delivered[0]![1]).toEqual({ kind: "notice", from: { name: "Ada", email: ADA }, origin: { botId: "quotes", threadId: "main" },
+ expect(delivered[0]![1]).toEqual({ kind: "notice", reason: "shared", from: { name: "Ada", email: ADA }, origin: { botId: "quotes", threadId: "main" },
text: "Ada shared Quotes with you.", title: "Quotes is shared with you", notify: "done" });
delivered.length = 0;
diff --git a/server/host/share-notice.ts b/server/host/share-notice.ts
index 87777f148c..4e8444e9ac 100644
--- a/server/host/share-notice.ts
+++ b/server/host/share-notice.ts
@@ -32,7 +32,7 @@ export function createShareNotice(deps: ShareNoticeDeps) {
for (const email of newlyShared(before, after, deps.people())) {
if (email === by) continue;
deps.inbox().deliver(personKey({ id: "", email }), {
- kind: "notice", from: { name, ...(by ? { email: by } : {}) }, ...(main ? { origin: { botId: bot.id, threadId: main.threadId } } : {}),
+ kind: "notice", reason: "shared", from: { name, ...(by ? { email: by } : {}) }, ...(main ? { origin: { botId: bot.id, threadId: main.threadId } } : {}),
text: `${name} shared ${bot.name} with you.`, title: `${bot.name} is shared with you`, notify: "done",
});
}
diff --git a/server/host/team-messages.test.ts b/server/host/team-messages.test.ts
index 2f1ce847a0..729c49a4bd 100644
--- a/server/host/team-messages.test.ts
+++ b/server/host/team-messages.test.ts
@@ -230,7 +230,7 @@ describe("@Ben", () => {
const line = f.said("scout-main", "@Ben can you check the numbers? @Ada too", CLEO);
const inbox = f.inboxOf(BEN);
expect(f.lines(inbox.threadId).at(-1)).toMatchObject({ text: "@Ben can you check the numbers? @Ada too", inbox: {
- kind: "message", from: { name: "Cleo", email: CLEO.email }, origin: { botId: "scout", threadId: "scout-main", title: "Scout", messageId: line.id }, replies: true,
+ kind: "message", reason: "mentioned", from: { name: "Cleo", email: CLEO.email }, origin: { botId: "scout", threadId: "scout-main", title: "Scout", messageId: line.id }, replies: true,
} });
expect(f.notified.map((one) => [one.forPerson, one.title, one.threadId])).toEqual([
[key(BEN.email), "Cleo mentioned you in Scout", inbox.threadId], [key(ADA.email), "Cleo mentioned you in Scout", "scout-main"],
@@ -251,7 +251,8 @@ describe("@Ben", () => {
f.team.replyIn(session(BEN.email), inbox.threadId, item.id, "Sure, after 10.", {});
const cleos = f.inboxOf(CLEO);
expect(cleos.bot.id).toBe("cleos-chief");
- expect(f.lines(cleos.threadId).at(-1)).toMatchObject({ text: "Sure, after 10.", inbox: { from: { name: "Ben", email: BEN.email }, replies: true } });
+ expect(f.lines(cleos.threadId).at(-1)).toMatchObject({ text: "Sure, after 10.", inbox: { reason: "replied", from: { name: "Ben", email: BEN.email }, replies: true } });
+ expect(f.team.view(session(CLEO.email))!.rows[0]).toMatchObject({ reason: "replied", text: "Sure, after 10." });
expect(f.continued, "nobody's turn carries on: a person asked").toEqual([]);
});
@@ -271,7 +272,7 @@ describe("@Ben", () => {
f.store.patchMessage("scout-main", reply.id, { reactions: [] });
f.store.patchMessage("cleo-private", hidden.id, { turnSucceeded: true });
expect(f.notified.map((one) => [one.forPerson, one.title])).toEqual([[key(BEN.email), "Scout mentioned you"]]);
- expect(f.lines(f.inboxOf(BEN).threadId).at(-1)!.inbox).toMatchObject({ from: { name: "Scout", botId: "scout" }, origin: { threadId: "scout-main" } });
+ expect(f.lines(f.inboxOf(BEN).threadId).at(-1)!.inbox).toMatchObject({ reason: "mentioned", from: { name: "Scout", botId: "scout" }, origin: { threadId: "scout-main" } });
});
it("never tells twice what message_person already passed in the same turn, nor the writer themselves", () => {
diff --git a/server/host/team-messages.ts b/server/host/team-messages.ts
index 78f6dc9c4c..db282de55a 100644
--- a/server/host/team-messages.ts
+++ b/server/host/team-messages.ts
@@ -220,7 +220,7 @@ export function createTeamMessages(deps: TeamMessagesDeps) {
const person = found.person;
if (!person) return { status: 404, text: "Nobody here was named, and nobody made this item: name the person to ask." };
if (!deps.sees(person).thread(threadId)) return { status: 403, text: `${person.name} can't see this room, so they can't answer here. Ask someone who can.` };
- const delivered = inbox.deliver(person.key, { kind: "message", from: { name: at.bot.name, botId: at.bot.id }, to: "bot", origin: originOf(at, threadId), text: question, title, notify: "mention" });
+ const delivered = inbox.deliver(person.key, { kind: "message", reason: "asked", from: { name: at.bot.name, botId: at.bot.id }, to: "bot", origin: originOf(at, threadId), text: question, title, notify: "mention" });
if (!delivered) return { status: 409, text: `${person.name} has no inbox here yet, so the question waits in this thread for anyone who sees it.` };
return { status: 200, text: `Asked ${person.name} in their inbox.`, person: person.key };
}
@@ -251,7 +251,7 @@ export function createTeamMessages(deps: TeamMessagesDeps) {
if (!to || to.key === writer?.key) continue;
const shown = deps.sees(to).thread(threadId);
inbox.deliver(to.key, {
- kind: "message", from: writer ? { name: writer.name, email: writer.email } : { name: writerName },
+ kind: "message", reason: "mentioned", from: writer ? { name: writer.name, email: writer.email } : { name: writerName },
...(writer ? { to: "person" as const, asker: writer.key } : {}), origin: originOf(at, threadId, line.id), text: hit.excerpt,
title: shown ? `${writerName} mentioned you in ${at.group?.name ?? at.bot.name}` : `Message from ${writerName}`, notify: "mention", representable: Boolean(writer),
});
@@ -279,7 +279,7 @@ export function createTeamMessages(deps: TeamMessagesDeps) {
if (!to || told.has(to.key) || !deps.sees(to).thread(threadId)) continue;
told.add(to.key);
inbox.deliver(to.key, {
- kind: "message", from: { name: speaker.name, botId: speaker.id }, to: "bot", origin: originOf(at, threadId, text.id), text: hit.excerpt,
+ kind: "message", reason: "mentioned", from: { name: speaker.name, botId: speaker.id }, to: "bot", origin: originOf(at, threadId, text.id), text: hit.excerpt,
title: group ? `${speaker.name} mentioned you in ${group.name}` : `${speaker.name} mentioned you`, notify: "mention", representable: true,
});
}
@@ -413,11 +413,11 @@ export function createTeamMessages(deps: TeamMessagesDeps) {
const me = sessionPerson(auth);
return team && me ? inbox.markDone(me.key, id) : "unknown";
},
- /** The viewer read a line of their inbox. */
- markRead(auth: RequestAuth, id: string): boolean {
- if (!team && deps.place) return deps.place.markRead(auth, id);
+ /** The viewer read a line of their inbox, or marked it unread again. */
+ markRead(auth: RequestAuth, id: string, read = true): boolean {
+ if (!team && deps.place) return deps.place.markRead(auth, id, read);
const me = sessionPerson(auth);
- return Boolean(team && me && inbox.markRead(me.key, id));
+ return Boolean(team && me && inbox.markRead(me.key, id, read));
},
/** The viewer read every line of their inbox; null for someone on a team without one. */
markAllRead(auth: RequestAuth): number | null {
diff --git a/server/request-auth.ts b/server/request-auth.ts
index 0aed1cd807..d74eb5a8dc 100644
--- a/server/request-auth.ts
+++ b/server/request-auth.ts
@@ -482,10 +482,10 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg
{ methods: ["POST"], path: /^\/api\/presence\/here$/ },
// what a bot asks of this person: their own questions and approvals only
{ methods: ["GET"], path: /^\/api\/needs-you$/ },
- // a person's own inbox: its lines, how many wait, and one of them read or done; the handler serves the session's own alone
+ // a person's own inbox: its lines, how many wait, and one of them read, unread again or done; the handler serves the session's own alone
{ methods: ["GET"], path: /^\/api\/inbox(?:\/count)?$/ },
{ methods: ["POST"], path: /^\/api\/inbox\/read-all$/ },
- { methods: ["POST"], path: /^\/api\/inbox\/[\w-]+\/(?:read|done)$/ },
+ { methods: ["POST"], path: /^\/api\/inbox\/[\w-]+\/(?:read|unread|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$/ },
// the workspace's banner picture: everyone signed in here sees it; changing it (PUT, DELETE) is an admin's
diff --git a/server/routes/conversation-share.ts b/server/routes/conversation-share.ts
index 2297edaa39..4cdc7c8129 100644
--- a/server/routes/conversation-share.ts
+++ b/server/routes/conversation-share.ts
@@ -129,7 +129,7 @@ export function createConversationSharing(deps: ConversationShareDeps): { routes
const saved = deps.shares.share(threadId, me.person, to);
deps.audienceChanged(bot.id, threadId);
deps.changed(bot.id);
- if (recipient) tell(to, bot, threadId, "server.share.withYouTitle", "server.share.withYou", { name: deps.nameOf(me.email), title: task.title || bot.name, bot: bot.name }, { name: deps.nameOf(me.email), email: me.email });
+ if (recipient) tell(to, bot, threadId, "server.share.withYouTitle", "server.share.withYou", { name: deps.nameOf(me.email), title: task.title || bot.name, bot: bot.name }, { name: deps.nameOf(me.email), email: me.email }, "shared");
return json(res, 200, { shared: sharedAs(saved) });
}
@@ -173,11 +173,11 @@ export function createConversationSharing(deps: ConversationShareDeps): { routes
return { routes, personLeft };
/** The one line in `to`'s inbox about this conversation, and one notification linking it when the line is new. */
- function tell(to: string, bot: BotRecord, threadId: string, titleKey: ServerLineKey, textKey: ServerLineKey, params: Record<string, string>, from: { name: string; email?: string; botId?: string }): void {
+ function tell(to: string, bot: BotRecord, threadId: string, titleKey: ServerLineKey, textKey: ServerLineKey, params: Record<string, string>, from: { name: string; email?: string; botId?: string }, reason?: "shared"): void {
const language = deps.language(to);
const heading = serverLine(language, titleKey, params);
const kept = deps.inbox().keepOne(to, {
- kind: "message", from, origin: { botId: bot.id, threadId },
+ kind: "message", ...(reason ? { reason } : {}), from, origin: { botId: bot.id, threadId },
text: serverLine(language, textKey, params), title: heading, notify: "mention",
});
if (kept?.created) deps.notify({ kind: "mention", botId: bot.id, botName: bot.name, threadId, title: heading, body: params.title ?? "", forPerson: to, ...(bot.avatarUrl ? { avatarUrl: bot.avatarUrl } : {}) });
diff --git a/server/routes/inbox.test.ts b/server/routes/inbox.test.ts
index a33b8c8549..52e34437a4 100644
--- a/server/routes/inbox.test.ts
+++ b/server/routes/inbox.test.ts
@@ -34,12 +34,14 @@ it("answers each member with their own inbox, which a client session may read an
expect(mine).toMatchObject({ status: 200, body: { botId: "bens-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}/unread`)).body.rows[0]).toMatchObject({ unread: true, tab: "info" });
+ expect(await call("POST", `/api/inbox/${line}/unread`, session(CLEO.email)), "someone else's line").toMatchObject({ status: 404 });
expect((await call("POST", `/api/inbox/${line}/done`)).body.rows[0]).toMatchObject({ tab: "done" });
expect(await call("POST", `/api/inbox/${line}/done`, session(CLEO.email)), "someone else's line").toMatchObject({ status: 404, body: { error: "That line is not in your inbox.", errorKey: "serverError.inbox.lineMissing" } });
expect((await call("GET", "/api/inbox", session(CLEO.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) {
+ for (const [method, path] of [["GET", "/api/inbox"], ["POST", `/api/inbox/${line}/read`], ["POST", `/api/inbox/${line}/unread`], ["POST", `/api/inbox/${line}/done`]] as const) {
expect(requiredScope(method, path), `${method} ${path}`).toBe("client");
}
});
diff --git a/server/routes/inbox.ts b/server/routes/inbox.ts
index ccb65ff371..501e4a57dc 100644
--- a/server/routes/inbox.ts
+++ b/server/routes/inbox.ts
@@ -9,13 +9,13 @@ export interface InboxRouteDeps {
/** How many of its lines wait on them; null for someone on a team without one. */
count(auth: RequestAuth): number | null;
markDone(auth: RequestAuth, id: string): "done" | "unknown" | "an ask";
- markRead(auth: RequestAuth, id: string): boolean;
+ markRead(auth: RequestAuth, id: string, read?: boolean): boolean;
/** Every line of this viewer's inbox read, asks included but none answered; null for someone on a team without one. */
markAllRead(auth: RequestAuth): number | null;
}
-/** GET /api/inbox: this viewer's inbox as its panel lists it. GET /api/inbox/count: how many of its lines wait on them. POST /api/inbox/read-all: all of its lines read, and 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. */
+/** GET /api/inbox: this viewer's inbox as its panel lists it. GET /api/inbox/count: how many of its lines wait on them. POST /api/inbox/read-all: all of its lines read, and POST /api/inbox/<line>/read, /unread and /done: one of its
+ * lines read, unread again, 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") {
@@ -34,10 +34,10 @@ export function createInboxRoutes(deps: InboxRouteDeps): RouteHandler {
const view = deps.view(auth);
return view ? json(res, 200, view) : json(res, 404, { ...userError("serverError.inbox.missing") });
}
- const m = /^\/api\/inbox\/([\w-]+)\/(read|done)$/.exec(path);
+ const m = /^\/api\/inbox\/([\w-]+)\/(read|unread|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]!);
+ const marked = m[2] === "done" ? deps.markDone(auth, m[1]!) : deps.markRead(auth, m[1]!, m[2] === "read") ? "done" : "unknown";
if (marked === "unknown") return json(res, 404, { ...userError("serverError.inbox.lineMissing") });
if (marked === "an ask") return json(res, 409, { ...userError("serverError.inbox.answerRequired") });
const view = deps.view(auth);
diff --git a/shared/inbox-reason.ts b/shared/inbox-reason.ts
new file mode 100644
index 0000000000..05d3888ad1
--- /dev/null
+++ b/shared/inbox-reason.ts
@@ -0,0 +1 @@
+export * from "../packages/phone-protocol/src/inbox-reason.ts";
diff --git a/src/components/SidebarInboxRow.tsx b/src/components/SidebarInboxRow.tsx
index b88d893aed..f84d236de0 100644
--- a/src/components/SidebarInboxRow.tsx
+++ b/src/components/SidebarInboxRow.tsx
@@ -1,12 +1,13 @@
-// The one Inbox row at the top of the sidebar, on every plan and with no account: shaped like a bot's row, with what waits
-// on the person as its count and a dot while any bot is at work. It stays when nothing waits, with no count.
+// The one Inbox row at the top of the sidebar, on every plan and with no account: shaped like a bot's row, with what is
+// for the person as its count, its name bold while there is activity they haven't read, and a dot while any bot is at
+// work. It stays when nothing waits, with no count.
import { Inbox } from "lucide-react";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import { closeInbox, openInbox, useInboxPanel, useInboxSupport, useInboxView } from "@/state/inbox";
import { useStore } from "@/state/store";
import { useTeamPeople } from "@/state/team-people";
-import { inboxFixes, waitingCount } from "./inbox/inbox-view";
+import { activityUnread, forYouCount, inboxFixes } from "./inbox/inbox-view";
import { inboxAttentionEntries, unreadConversations } from "./inbox/InboxActive";
export function SidebarInboxRow({ icons, large, running, onOpened }: {
@@ -22,9 +23,10 @@ export function SidebarInboxRow({ icons, large, running, onOpened }: {
const team = useTeamPeople();
const { open } = useInboxPanel();
if (support === "no") return null;
- const count = waitingCount(view) + inboxFixes(team?.needsYou, view).length + unreadConversations(inboxAttentionEntries(state, view), view);
+ const count = forYouCount(view) + inboxFixes(team?.needsYou, view).length;
+ const activity = count === 0 && (activityUnread(view) || unreadConversations(inboxAttentionEntries(state, view), view) > 0);
const shown = count > 9 ? "9+" : String(count);
- const label = count > 0 ? t("inbox.row.count", { count }) : t("inbox.panel.title");
+ const label = count > 0 ? t("inbox.row.count", { count }) : activity ? t("inbox.row.activity") : t("inbox.panel.title");
const toggle = () => {
if (open) closeInbox();
else { openInbox(); onOpened?.(); }
@@ -32,23 +34,24 @@ export function SidebarInboxRow({ icons, large, running, onOpened }: {
const dot = running && <span data-inbox-running="" aria-hidden="true" className={cn("absolute -bottom-0.5 -right-0.5 rounded-full border-2 border-panel bg-success", icons ? "size-3" : "size-2.5")} />;
if (icons) {
return (
- <button type="button" data-sidebar-inbox={count} aria-label={label} title={label} aria-pressed={open} onClick={toggle}
+ <button type="button" data-sidebar-inbox={count} data-inbox-activity={activity ? "" : undefined} aria-label={label} title={label} aria-pressed={open} onClick={toggle}
className={cn("relative mx-auto mb-1 flex size-[46px] shrink-0 items-center justify-center rounded-xl text-ink-secondary hover:bg-raised hover:text-ink focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus", open && "bg-raised text-ink")}>
<Inbox size={20} aria-hidden="true" />
{count > 0 && <span aria-hidden="true" data-inbox-count className="absolute -right-0.5 -top-0.5 flex min-w-4 items-center justify-center rounded-full bg-warning px-0.5 text-[10px] font-semibold leading-4 text-panel">{shown}</span>}
+ {activity && <span aria-hidden="true" className="absolute right-1 top-1 size-2 rounded-full bg-accent" />}
{dot}
</button>
);
}
return (
<div className="px-3 pb-1">
- <button type="button" data-sidebar-inbox={count} aria-label={label} title={label} aria-pressed={open} onClick={toggle}
+ <button type="button" data-sidebar-inbox={count} data-inbox-activity={activity ? "" : undefined} aria-label={label} title={label} aria-pressed={open} onClick={toggle}
className={cn("flex w-full min-w-0 items-center gap-2.5 rounded-lg px-2 py-1.5 text-left outline-none hover:bg-raised/60 focus-visible:ring-2 focus-visible:ring-accent/60")}>
<span className={cn("relative grid shrink-0 place-items-center rounded-full", open ? "bg-ink/[0.16] text-ink" : "bg-raised text-ink-secondary", large ? "size-9" : "size-8")}>
<Inbox size={16} aria-hidden="true" />
{dot}
</span>
- <span className="min-w-0 flex-1 truncate text-[14px] font-medium leading-5 text-ink">{t("inbox.panel.title")}</span>
+ <span className={cn("min-w-0 flex-1 truncate text-[14px] leading-5 text-ink", activity ? "font-semibold" : "font-medium")}>{t("inbox.panel.title")}</span>
{count > 0 && <span aria-hidden="true" data-inbox-count className="shrink-0 rounded-full bg-warning px-1.5 text-[11px] font-semibold tabular-nums text-panel">{shown}</span>}
</button>
</div>
diff --git a/src/components/inbox/InboxCard.tsx b/src/components/inbox/InboxCard.tsx
index 2e32ff6d7c..240a4c507e 100644
--- a/src/components/inbox/InboxCard.tsx
+++ b/src/components/inbox/InboxCard.tsx
@@ -7,7 +7,7 @@ import { Check, CornerUpLeft, Inbox } from "lucide-react";
import type { InboxRow, InboxView } from "../../../shared/inbox";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
-import { openInbox, readInboxRow, useInboxView } from "@/state/inbox";
+import { openInbox, useInboxView } from "@/state/inbox";
import { pendingApprovals, PendingApprovalActions } from "../PendingApproval";
import { ASK_QUIET_ANSWER, ASK_QUIET_BUTTON, AskChoices, AskError } from "../AskCard";
import { ELEVATED_CARD } from "../elevated";
@@ -33,7 +33,7 @@ function Answers({ row, view }: { row: InboxRow; view: InboxView }) {
const [failed, setFailed] = useState(false);
const ask = askOf(row);
const choices = choicesOf(row);
- const reading = () => { readInboxRow(row); openInbox({ reading: row.id }); };
+ const reading = () => openInbox({ reading: row.id });
if (ask === "approval") {
const pending = view.threadId ? pendingApprovals([asMessage(row)])[0] : undefined;
return pending ? (
@@ -69,7 +69,7 @@ export function InboxCard({ view }: { view: InboxView }) {
}, []);
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 openRow = (row: InboxRow) => openInbox({ reading: row.id });
const openAll = () => openInbox();
const shell = cn("my-1 w-full max-w-[560px] rounded-[18px]", ELEVATED_CARD);
if (!rows.length) {
diff --git a/src/components/inbox/InboxGroups.tsx b/src/components/inbox/InboxGroups.tsx
new file mode 100644
index 0000000000..59277fd868
--- /dev/null
+++ b/src/components/inbox/InboxGroups.tsx
@@ -0,0 +1,40 @@
+import type { InboxRow } from "../../../shared/inbox";
+import type { InboxGroup } from "../../../shared/inbox-reason";
+import { t } from "@/lib/i18n";
+import type { LocaleKey } from "@/locales";
+import { InboxRowItem } from "./InboxRow";
+import type { QuickAction } from "./inbox-view";
+
+const GROUP_TITLE: Record<InboxGroup, LocaleKey> = { "for-you": "inbox.group.forYou", activity: "inbox.group.activity" };
+
+/** The inbox's lines in two groups: For you (what waits on the person or names them), then Activity. For you shows calm
+ * when it is empty and nothing else is for the person; Activity only when there is some. */
+export function InboxGroups({ groups, now, current, onOpen, onAction, moreForYou = false }: {
+ groups: Record<InboxGroup, InboxRow[]>;
+ now: number;
+ current: string | null;
+ onOpen(row: InboxRow): void;
+ onAction(row: InboxRow, action: QuickAction): void;
+ /** Something for the person is listed further down (a fix on a team), so For you is not "all caught up". */
+ moreForYou?: boolean;
+}) {
+ return (
+ <>
+ {(["for-you", "activity"] as const).map((group) => {
+ const rows = groups[group];
+ if (!rows.length && (group === "activity" || moreForYou)) return null;
+ const heading = `inbox-group-${group}`;
+ return (
+ <section key={group} data-inbox-group={group} aria-labelledby={heading} className="pb-1">
+ <h3 id={heading} className="px-2.5 pb-1 pt-2 text-[12px] font-medium text-ink-tertiary">{t(GROUP_TITLE[group])}</h3>
+ {rows.length ? (
+ <div role="list" aria-labelledby={heading} className="space-y-0.5">
+ {rows.map((row) => <InboxRowItem key={row.id} row={row} now={now} current={row.id === current} onOpen={onOpen} onAction={onAction} />)}
+ </div>
+ ) : <p data-inbox-caught-up className="px-2.5 pb-2 text-[13px] text-ink-tertiary">{t("inbox.forYou.empty")}</p>}
+ </section>
+ );
+ })}
+ </>
+ );
+}
diff --git a/src/components/inbox/InboxHold.dom.test.ts b/src/components/inbox/InboxHold.dom.test.ts
new file mode 100644
index 0000000000..3abebf393e
--- /dev/null
+++ b/src/components/inbox/InboxHold.dom.test.ts
@@ -0,0 +1,170 @@
+// @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 }>, view: null as null | { rows: Array<{ id: string; tab: string; kind?: string; unread?: boolean }> } }));
+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));
+vi.mock("../../state/api", () => ({
+ api: vi.fn(async (path: string, init?: RequestInit) => {
+ server.calls.push({ path, method: init?.method ?? "GET" });
+ const marked = /^\/api\/inbox\/([\w-]+)\/(read|unread)$/.exec(path);
+ // As the server does: a finished report the person has read is settled.
+ if (marked && server.view) {
+ const read = marked[2] === "read";
+ server.view = { ...server.view, rows: server.view.rows.map((row) => (row.id !== marked[1] ? row
+ : { ...row, unread: !read, ...(row.kind === "result" ? { tab: read ? "done" : "info" } : {}) })) };
+ }
+ return server.view ?? {};
+ }),
+}));
+
+import { initialState, StoreContext, type AppState, type Bot } from "@/state/store";
+import { closeInbox, currentInbox, openInbox, replyToInboxRow, setInboxView } from "@/state/inbox";
+import { setTeamPeople } from "@/state/team-people";
+import { approvalRow, inboxView, messageRow, questionRow, reportRow } from "@/testing/inbox-fixture";
+import type { InboxView } from "../../../shared/inbox";
+import { SidebarInboxRow } from "../SidebarInboxRow";
+import { InboxPanel } from "./InboxPanel";
+import { READ_AFTER_MS } from "./use-inbox-hold";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: Root;
+let focused = true;
+const reporter = { id: "reporter", name: "Reporter", color: "orange", threadId: "rep-main", tasks: [{ threadId: "rep-daily", title: "Daily digest", createdAt: 0 }] } as unknown as Bot;
+const mount = (child: ReactElement) => act(async () => {
+ root.render(createElement(StoreContext.Provider,
+ { value: { state: { ...initialState, bots: [reporter] } as AppState, dispatch: vi.fn(), flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn() } as never }, child));
+});
+const click = (selector: string) => act(async () => { document.querySelector<HTMLElement>(selector)!.click(); });
+const wait = (ms: number) => act(async () => { await vi.advanceTimersByTimeAsync(ms); });
+const shown = (view: InboxView) => { server.view = view; setInboxView(view); };
+const reads = (id: string) => server.calls.filter((call) => call.path === `/api/inbox/${id}/read`).length;
+const listed = () => [...document.querySelectorAll<HTMLElement>("[data-inbox-row]")].map((row) => row.dataset.inboxRow);
+const rowOf = (id: string) => document.querySelector<HTMLElement>(`[data-inbox-row="${id}"]`);
+const windowIs = (now: boolean) => act(async () => { focused = now; window.dispatchEvent(new Event(now ? "focus" : "blur")); });
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval"] });
+ vi.spyOn(document, "hasFocus").mockImplementation(() => focused);
+ focused = true;
+ root = createRoot(document.body.appendChild(document.createElement("div")));
+ server.calls.length = 0;
+ shown(inboxView());
+});
+afterEach(() => {
+ act(() => root.unmount());
+ closeInbox();
+ setInboxView(null);
+ document.body.innerHTML = "";
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+describe("reading a line in the inbox", () => {
+ it("reads it after a moment on screen with the window focused, and Undo makes it new again for good", async () => {
+ openInbox();
+ await mount(createElement(InboxPanel));
+ await click(`[data-inbox-row="${messageRow.id}"] button`);
+ await wait(READ_AFTER_MS - 100);
+ expect(reads(messageRow.id), "not at once").toBe(0);
+ await windowIs(false);
+ await wait(READ_AFTER_MS * 3);
+ expect(reads(messageRow.id), "not while the person is in another window").toBe(0);
+ await windowIs(true);
+ await wait(READ_AFTER_MS);
+ expect(reads(messageRow.id)).toBe(1);
+ expect(currentInbox()!.rows.find((row) => row.id === messageRow.id)!.unread).toBe(false);
+ expect(document.querySelector("[data-inbox-marked]")?.textContent).toBe("Marked as read·Undo");
+
+ await click("[data-inbox-undo]");
+ expect(server.calls).toContainEqual({ path: `/api/inbox/${messageRow.id}/unread`, method: "POST" });
+ expect(currentInbox()!.rows.find((row) => row.id === messageRow.id)!.unread).toBe(true);
+ expect(document.querySelector("[data-inbox-marked]")).toBeNull();
+ await wait(READ_AFTER_MS * 3);
+ expect(reads(messageRow.id), "it stays new while the person still has it open").toBe(1);
+ await click('[aria-label="Back to the list"]');
+ expect(rowOf(messageRow.id)!.hasAttribute("data-unread")).toBe(true);
+ });
+
+ it("keeps a finished line in its place, muted, once read, until the person picks another", async () => {
+ openInbox();
+ await mount(createElement(InboxPanel));
+ const before = listed();
+ await click(`[data-inbox-row="${reportRow.id}"] button`);
+ await wait(READ_AFTER_MS);
+ expect(reads(reportRow.id)).toBe(1);
+ expect(currentInbox()!.rows.find((row) => row.id === reportRow.id)!.tab, "the server settled it").toBe("done");
+ expect(listed(), "no row moved").toEqual(before);
+ expect(rowOf(reportRow.id)!.hasAttribute("data-unread")).toBe(false);
+ expect(rowOf(reportRow.id)!.hasAttribute("data-inbox-current")).toBe(true);
+ expect(document.querySelector("[data-inbox-done-toggle] .tabular-nums")?.textContent, "it is not listed twice: Done holds only the older settled ask").toBe("1");
+
+ await click(`[data-inbox-row="${questionRow.id}"] button`);
+ expect(document.querySelector("[data-inbox-marked]"), "the note goes with the pick").toBeNull();
+ await click('[aria-label="Back to the list"]');
+ expect(listed()).toEqual(before.filter((id) => id !== reportRow.id));
+ });
+
+ it("says so, with the same Undo, when opening its conversation read the line first", async () => {
+ openInbox();
+ await mount(createElement(InboxPanel));
+ await click(`[data-inbox-row="${reportRow.id}"] button`);
+ await act(async () => { shown(inboxView([approvalRow, questionRow, messageRow, { ...reportRow, unread: false, tab: "done" }])); });
+ expect(reads(reportRow.id), "the server read it, not the panel").toBe(0);
+ expect(document.querySelector("[data-inbox-marked]")).not.toBeNull();
+ expect(rowOf(reportRow.id), "it keeps its place").not.toBeNull();
+ await click("[data-inbox-undo]");
+ expect(server.calls).toContainEqual({ path: `/api/inbox/${reportRow.id}/unread`, method: "POST" });
+ });
+
+ it("shows no note for a line the person answered", async () => {
+ openInbox();
+ await mount(createElement(InboxPanel));
+ await click(`[data-inbox-row="${approvalRow.id}"] [data-inbox-action="allow"]`);
+ await wait(READ_AFTER_MS * 2);
+ expect(document.querySelector("[data-inbox-marked]")).toBeNull();
+ });
+
+ it("reads a line at once when the person replies to it", async () => {
+ await replyToInboxRow(inboxView(), messageRow, "Friday works.");
+ expect(server.calls.map((call) => call.path)).toEqual(["/api/bots/bens-chief/messages", `/api/inbox/${messageRow.id}/read`, "/api/inbox"]);
+ });
+
+ it("shows For you first and Activity after, calm when nothing is for the person", async () => {
+ openInbox();
+ await mount(createElement(InboxPanel));
+ const group = (name: string) => [...document.querySelectorAll<HTMLElement>(`[data-inbox-group="${name}"] [data-inbox-row]`)].map((row) => row.dataset.inboxRow);
+ expect(group("for-you")).toEqual([approvalRow.id, questionRow.id, messageRow.id]);
+ expect(group("activity")).toEqual([reportRow.id]);
+ expect(document.querySelector(`[data-inbox-row="${messageRow.id}"] [data-inbox-reason]`)?.textContent).toBe("Messaged you");
+ expect(document.querySelector("[data-inbox-tab-count]")?.textContent).toBe("3");
+
+ await act(async () => { shown(inboxView([reportRow])); });
+ expect(document.querySelector('[data-inbox-group="for-you"] [data-inbox-caught-up]')?.textContent).toBe("You're all caught up.");
+ expect(group("activity")).toEqual([reportRow.id]);
+ expect(document.querySelector("[data-inbox-tab-count]")).toBeNull();
+
+ await act(async () => { setTeamPeople({ people: [], me: null, admin: true, needsYou: [{ kind: "connection", id: "c", at: 1, app: "github", botIds: ["reporter"], threadId: "rep-main", text: "Reconnect GitHub" }] }); });
+ expect(document.querySelector("[data-inbox-caught-up]"), "a fix further down is for the person").toBeNull();
+ expect(document.querySelector("[data-inbox-tab-count]")?.textContent).toBe("1");
+ await act(async () => { setTeamPeople(null); });
+ });
+});
+
+describe("the sidebar's Inbox row", () => {
+ it("counts For you only, and is bold with no number while only Activity is new", async () => {
+ await mount(createElement(SidebarInboxRow, { icons: false, large: true, running: false }));
+ const row = () => document.querySelector<HTMLElement>("[data-sidebar-inbox]")!;
+ expect(row().dataset.sidebarInbox).toBe("3");
+ expect(row().hasAttribute("data-inbox-activity")).toBe(false);
+
+ await act(async () => { shown(inboxView([reportRow, { ...messageRow, unread: false }])); });
+ expect(row().dataset.sidebarInbox).toBe("0");
+ expect(document.querySelector("[data-inbox-count]")).toBeNull();
+ expect(row().hasAttribute("data-inbox-activity")).toBe(true);
+ expect(row().getAttribute("aria-label")).toBe("Inbox, new activity");
+ expect(row().querySelector(".font-semibold")?.textContent).toBe("Inbox");
+ });
+});
diff --git a/src/components/inbox/InboxPanel.dom.test.ts b/src/components/inbox/InboxPanel.dom.test.ts
index 149badeddc..430e5a0c8b 100644
--- a/src/components/inbox/InboxPanel.dom.test.ts
+++ b/src/components/inbox/InboxPanel.dom.test.ts
@@ -63,7 +63,7 @@ describe("the inbox panel", () => {
expect(document.querySelector(`[data-inbox-row="${approvalRow.id}"]`)!.hasAttribute("data-unread")).toBe(true);
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(server.calls, "it is read after a moment on screen, not at once").not.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([approvalRow.id, questionRow.id, messageRow.id, reportRow.id]);
@@ -136,7 +136,7 @@ describe("the inbox panel", () => {
expect(document.querySelector('[data-inbox-panel="side"]')).toBeNull();
});
- it("shows a pinned conversation once, and counts its unread news once", async () => {
+ it("shows a pinned conversation once, and counts none of its finished work", async () => {
const reporter = {
id: "reporter", name: "Reporter", threadId: "rep-main", tasks: [
{ threadId: "rep-daily", title: "Daily digest", createdAt: 0, updatedAt: INBOX_NOW, pinned: true, unread: true },
@@ -151,7 +151,7 @@ describe("the inbox panel", () => {
expect(active, "the pinned section already shows it").not.toContain("Daily digest");
const finished = [...document.querySelectorAll("[data-inbox-finished] button")].map((button) => button.textContent).join(" ");
expect(finished).not.toContain("Older digest");
- expect(document.querySelector("[data-inbox-tab-count]")?.textContent, "one line plus the same conversation is one").toBe("1");
+ expect(document.querySelector("[data-inbox-tab-count]"), "finished work is Activity, which has no number").toBeNull();
});
});
diff --git a/src/components/inbox/InboxPanel.tsx b/src/components/inbox/InboxPanel.tsx
index b8141d7d1c..d13b76ef63 100644
--- a/src/components/inbox/InboxPanel.tsx
+++ b/src/components/inbox/InboxPanel.tsx
@@ -6,19 +6,22 @@ import { cn } from "@/lib/cn";
import { useAdvancedMode } from "@/lib/interface-mode";
import { t } from "@/lib/i18n";
import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";
-import { closeInbox, markAllInboxRead, readInboxLine, readInboxRow, useInboxMarkingAll, useInboxPanel, useInboxView, widenInbox } from "@/state/inbox";
+import { closeInbox, markAllInboxRead, readInboxLine, useInboxMarkingAll, useInboxPanel, useInboxView, widenInbox } from "@/state/inbox";
import { sameJson } from "@/state/same-json";
import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { useActiveLocale } from "@/lib/use-active-locale";
-import { InboxActive, inboxAttentionEntries, inboxOpenThread, readNewsThreads, unreadConversations } from "./InboxActive";
+import { useTeamPeople } from "@/state/team-people";
+import { InboxActive, inboxAttentionEntries, inboxOpenThread, readNewsThreads } from "./InboxActive";
import { attentionUnpinAction, botFaces } from "../SidebarBotActivity";
import { InboxReading } from "./InboxReading";
-import { InboxRowItem } from "./InboxRow";
+import { InboxGroups } from "./InboxGroups";
import { FINISHED_LIMIT, FinishedThreads, finishedThreads } from "./FinishedThreads";
import { PinnedThreads, pinnedThreadRows } from "./PinnedThreads";
import { matchesSearch, nextAfter } from "./inbox-answer";
-import { listedRows, rowsIn, waitingCount } from "./inbox-view";
+import { forYouCount, groupRows, inboxFixes, listedRows, rowsIn, type QuickAction } from "./inbox-view";
+import { InboxRowItem } from "./InboxRow";
import { useInboxActions, useInboxJump } from "./use-inbox-actions";
+import { useInboxHold } from "./use-inbox-hold";
import { roundButtonCls } from "../bot-panel/rows";
import { matchesThreadFilter, threadFilterOn, threadOwners, type ThreadFilter } from "./thread-filter";
import { ThreadFilterBar } from "./ThreadFilterBar";
@@ -48,17 +51,23 @@ export const InboxPanel = memo(function InboxPanel() {
else closeInbox();
};
const reading = panel.reading ? view?.rows.find((row) => row.id === panel.reading) : undefined;
+ const { held, marked, pick, undo } = useInboxHold(view, panel.reading);
/** An ask waits for an answer here and a message waits for a reply, so those open in the panel; finished work opens
* the conversation it came from, at the message it is about. */
const open = (row: InboxRow) => {
- readInboxRow(row);
+ pick(row);
if (row.tab === "needs-you" || row.replies) { readInboxLine(row.id); return; }
openInChat(row);
};
+ const act = (row: InboxRow, action: QuickAction) => {
+ if (action === "open") pick(row);
+ run(row, action);
+ };
// Finished work the person has read leaves the list for the Done line at the foot; its conversation moves to Finished.
- const listed = listedRows(view);
- const rows = listed.filter((row) => matchesSearch(row, query));
- const done = rowsIn(view, "done").filter((row) => matchesSearch(row, query)).sort((a, b) => b.at - a.at);
+ const listed = listedRows(view, held);
+ const groups = groupRows(listed.filter((row) => matchesSearch(row, query)));
+ const rows = [...groups["for-you"], ...groups.activity];
+ const done = rowsIn(view, "done").filter((row) => row.id !== held && matchesSearch(row, query)).sort((a, b) => b.at - a.at);
const ids = rows.map((row) => row.id);
const at = reading ? ids.indexOf(reading.id) : -1;
@@ -72,9 +81,9 @@ export const InboxPanel = memo(function InboxPanel() {
waited.current = null;
const next = nextAfter(order.current.filter((id) => id === reading.id || ids.includes(id)), reading.id);
const row = next ? view?.rows.find((one) => one.id === next) : undefined;
- if (row) readInboxRow(row);
+ if (row) pick(row);
readInboxLine(row ? row.id : null);
- }, [reading, ids, view]);
+ }, [reading, ids, view, pick]);
const step = (by: -1 | 1) => {
const row = rows[at + by];
@@ -90,11 +99,13 @@ export const InboxPanel = memo(function InboxPanel() {
const finished = finishedThreads(state.bots, state.groups, state.pendingQueued, Infinity, readNewsThreads(view), pinnedThreads);
const finishedRows = finished.filter((row) => matchesThreadFilter(row, filter)).slice(0, FINISHED_LIMIT);
return {
- owners: threadOwners([...active, ...finished], filter.owner), finishedRows, unread: unreadConversations(entries, view),
+ owners: threadOwners([...active, ...finished], filter.owner), finishedRows,
any: finishedRows.length > 0 || active.some((entry) => matchesThreadFilter(entry, filter)),
};
}, sameJson);
- const count = waitingCount(view) + threads.unread;
+ const team = useTeamPeople();
+ const fixes = inboxFixes(team?.needsYou, view).length;
+ const count = forYouCount(view) + fixes;
const openThread = useStoreSelector((state) => inboxOpenThread(state), sameJson);
const body = (
<>
@@ -133,7 +144,7 @@ export const InboxPanel = memo(function InboxPanel() {
<input type="search" value={query} onChange={(event) => setQuery(event.target.value)} placeholder={t("inbox.search")} aria-label={t("inbox.search")}
className="min-w-0 flex-1 bg-transparent text-[13px] text-ink outline-none placeholder:text-ink-tertiary [&::-webkit-search-cancel-button]:hidden" />
</label>}
- <div role="list" data-inbox-list aria-label={t("inbox.panel.title")} className="space-y-0.5 px-1.5 pb-1.5">
+ <div data-inbox-list className="px-1.5 pb-1.5">
{rows.length === 0
? query.trim() && listed.length
? <p className="px-4 py-8 text-center text-[13px] text-ink-secondary">{t("inbox.noMatch")}</p>
@@ -144,7 +155,7 @@ export const InboxPanel = memo(function InboxPanel() {
<p className="mt-1 text-[13px] leading-[18px] text-ink-tertiary">{t("inbox.emptyHint")}</p>
</div>
)
- : rows.map((row) => <InboxRowItem key={row.id} row={row} now={now} onOpen={open} onAction={run} />)}
+ : <InboxGroups groups={groups} now={now} current={held} onOpen={open} onAction={act} moreForYou={fixes > 0} />}
</div>
{!query.trim() && threads.owners.length > 0 && <ThreadFilterBar owners={threads.owners} filter={filter} onChange={setFilter} />}
{!query.trim() && threadFilterOn(filter) && !threads.any && (
@@ -164,12 +175,18 @@ export const InboxPanel = memo(function InboxPanel() {
<span className="font-medium">{t("common.done")}</span>
<span className="tabular-nums">{done.length}</span>
</button>
- {showDone && done.map((row) => <InboxRowItem key={row.id} row={row} now={now} onOpen={open} onAction={run} />)}
+ {showDone && done.map((row) => <InboxRowItem key={row.id} row={row} now={now} onOpen={open} onAction={act} />)}
</section>
)}
</div>
</>
)}
+ {marked && (
+ <p role="status" data-inbox-marked className="flex shrink-0 items-center justify-center gap-1.5 border-t border-hairline/40 px-3 py-2 text-[12px] text-ink-tertiary">
+ {t("inbox.markedRead")}<span aria-hidden="true">·</span>
+ <button type="button" data-inbox-undo onClick={undo} className="font-medium text-accent hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus">{t("common.undo")}</button>
+ </p>
+ )}
</div>
</>
);
diff --git a/src/components/inbox/InboxReading.tsx b/src/components/inbox/InboxReading.tsx
index 6c8613eb2a..39b50cc808 100644
--- a/src/components/inbox/InboxReading.tsx
+++ b/src/components/inbox/InboxReading.tsx
@@ -9,7 +9,7 @@ import { threadUpdatedLabel } from "../SidebarThreadRow";
import { accessRequestWords } from "../bot-access/access-card";
import { InboxAnswer } from "./InboxAnswer";
import { answerKindOf, headlineOf, singleQuestion } from "./inbox-answer";
-import { askOf, closeResponse, senderLabel, textOf } from "./inbox-view";
+import { askOf, closeResponse, reasonOf, senderLabel, textOf } from "./inbox-view";
import { useAskContext } from "./use-ask-context";
import { useInboxActions, useInboxAsker } from "./use-inbox-actions";
@@ -78,7 +78,7 @@ export function InboxReading({ view, row, now, position, onStep }: {
</header>
<nav aria-label={t("inbox.breadcrumb")} className="flex min-w-0 items-center gap-1 border-b border-hairline/40 px-3.5 pb-2 text-[12px] text-ink-tertiary">
<button type="button" data-inbox-action="open" onClick={() => openInChat(row)} title={t("inbox.action.openInChat")}
- className="min-w-0 max-w-[45%] shrink truncate rounded hover:text-ink hover:underline">{place}</button>
+ className="min-w-0 max-w-[45%] shrink-0 truncate rounded hover:text-ink hover:underline">{place}</button>
<ChevronRight size={12} aria-hidden="true" className="shrink-0 rtl:rotate-180" />
<span className="min-w-0 truncate font-medium text-ink-secondary">{headline}</span>
</nav>
@@ -88,7 +88,8 @@ export function InboxReading({ view, row, now, position, onStep }: {
<div className="min-w-0 flex-1">
<div className="flex items-baseline gap-2">
<span className="min-w-0 truncate text-[13px] font-semibold text-ink">{senderLabel(row)}</span>
- <span className="shrink-0 text-[11px] tabular-nums text-ink-tertiary">{threadUpdatedLabel(row.at, now)}</span>
+ <span data-inbox-reason className="shrink-0 text-[12px] text-ink-tertiary">{reasonOf(row)}</span>
+ <span className="ms-auto shrink-0 text-[12px] tabular-nums text-ink-tertiary">{threadUpdatedLabel(row.at, now)}</span>
</div>
{row.via && <div className="truncate text-[12px] text-ink-tertiary">{t("inbox.via", { name: row.via.name })}</div>}
<div data-inbox-words className="mt-1 space-y-2 text-[14px] leading-6 text-ink">
diff --git a/src/components/inbox/InboxRow.tsx b/src/components/inbox/InboxRow.tsx
index 4eac681b08..0f69f8b0ee 100644
--- a/src/components/inbox/InboxRow.tsx
+++ b/src/components/inbox/InboxRow.tsx
@@ -5,8 +5,8 @@ import { t } from "@/lib/i18n";
import type { LocaleKey } from "@/locales";
import { InboxSender } from "../InboxLine";
import { threadUpdatedLabel } from "../SidebarThreadRow";
-import { choicesLine, headlineOf, snippetOf } from "./inbox-answer";
-import { placeOf, quickActions, senderLabel, subjectOf, textOf, type QuickAction } from "./inbox-view";
+import { choicesLine, headlineOf } from "./inbox-answer";
+import { placeOf, quickActions, reasonOf, senderLabel, textOf, type QuickAction } from "./inbox-view";
const ACTION_LOOK: Record<QuickAction, { Icon: LucideIcon; label: LocaleKey }> = {
allow: { Icon: Check, label: "approval.action.allowOnce" },
@@ -19,27 +19,28 @@ const ACTION_LOOK: Record<QuickAction, { Icon: LucideIcon; label: LocaleKey }> =
const ROW_ACTION = "flex size-7 shrink-0 items-center justify-center rounded-full text-ink-secondary transition-colors hover:bg-ink/[0.07] hover:text-ink active:bg-ink/[0.11] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus pointer-coarse:size-9";
-export function InboxRowItem({ row, now, onOpen, onAction, inCard = false }: {
+export function InboxRowItem({ row, now, onOpen, onAction, inCard = false, current = 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;
+ /** The line the person opened last: it keeps its place, marked, until they pick another. */
+ current?: boolean;
}) {
- const subject = subjectOf(row);
+ const reason = reasonOf(row);
const actions = quickActions(row);
const sender = senderLabel(row);
const place = placeOf(row);
const headline = inCard ? "" : headlineOf(row);
const choices = inCard ? null : choicesLine(row);
- const snippet = inCard || choices ? null : snippetOf(row);
const unreadish = row.unread || row.tab === "needs-you";
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 pr-1.5 focus-within:bg-raised/70 hover:bg-raised/70",
- inCard ? (row.unread ? "bg-raised/45" : "bg-transparent") : "rounded-lg")}>
- <button type="button" onClick={() => onOpen(row)} title={[sender, inCard ? subject : headline, place].filter(Boolean).join(" · ")}
+ <div data-inbox-row={row.id} data-tab={row.tab} data-unread={row.unread ? "" : undefined} data-inbox-current={current ? "" : undefined}
+ className={cn("group relative flex min-w-0 items-center gap-2 pe-1.5 focus-within:bg-raised/70 hover:bg-raised/70",
+ inCard ? (row.unread ? "bg-raised/45" : "bg-transparent") : "rounded-lg", current && "bg-raised/70")}>
+ <button type="button" onClick={() => onOpen(row)} aria-current={current || undefined} title={[reason, sender, inCard ? textOf(row) : headline, place].filter(Boolean).join(" · ")}
className={cn("flex min-w-0 flex-1 gap-2 pl-2.5 text-left text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent/60", inCard ? "items-center py-1.5" : "items-start py-2",
row.unread ? "font-semibold text-ink" : "font-normal text-ink-secondary")}>
{row.tab === "needs-you" ? <span data-inbox-waits className={cn("size-1.5 shrink-0 rounded-full", inCard ? "bg-warning" : "mt-[7px] bg-accent")} role="img" aria-label={t("inbox.waitsOnYou")} />
@@ -49,7 +50,7 @@ export function InboxRowItem({ row, now, onOpen, onAction, inCard = false }: {
<>
<span className="w-[7.5rem] shrink-0 truncate">{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 data-inbox-reason className="max-w-[45%] shrink-0 truncate">{reason}</span>
<span className="min-w-0 truncate font-normal text-ink-tertiary">{textOf(row)}</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>
@@ -57,17 +58,20 @@ export function InboxRowItem({ row, now, onOpen, onAction, inCard = false }: {
) : (
<span className="min-w-0 flex-1 space-y-px">
<span className="flex items-baseline gap-1.5">
- <span data-inbox-from className="min-w-0 shrink truncate font-semibold">{sender}</span>
- {place && <span data-inbox-place className="min-w-0 flex-1 truncate text-[12px] font-normal text-ink-tertiary">{place}</span>}
- <span className="ms-auto shrink-0 ps-1 text-[11px] font-normal tabular-nums text-ink-tertiary group-focus-within:invisible group-hover:invisible">{threadUpdatedLabel(row.at, now)}</span>
+ <span data-inbox-reason className={cn("min-w-0 shrink truncate", unreadish ? "font-semibold text-ink" : "font-medium text-ink-secondary")}>{reason}</span>
+ <span className="ms-auto shrink-0 ps-1 text-[12px] font-normal tabular-nums text-ink-tertiary group-focus-within:invisible group-hover:invisible">{threadUpdatedLabel(row.at, now)}</span>
</span>
- <span data-inbox-subject className={cn("block truncate text-[13px] font-semibold", unreadish ? "text-ink" : "text-ink-secondary")}>{headline}</span>
- {choices ? (
+ <span className="flex min-w-0 items-baseline gap-1 text-[12px] font-normal text-ink-tertiary">
+ <span data-inbox-from className="min-w-0 shrink truncate font-medium text-ink-secondary">{sender}</span>
+ {place && <span data-inbox-place className="min-w-0 flex-1 truncate">{place}</span>}
+ </span>
+ <span data-inbox-subject className={cn("block truncate text-[13px] font-normal", unreadish ? "text-ink" : "text-ink-tertiary")}>{headline}</span>
+ {choices && (
<span data-inbox-choices className="flex min-w-0 items-center gap-1.5 text-[12px] font-normal text-ink-secondary">
<Split size={12} aria-hidden="true" className="shrink-0 rotate-180 text-warning" />
<span className="min-w-0 truncate">{choices}</span>
</span>
- ) : snippet && <span className="block truncate text-[12px] font-normal text-ink-tertiary">{snippet}</span>}
+ )}
</span>
)}
</button>
diff --git a/src/components/inbox/inbox-answer.ts b/src/components/inbox/inbox-answer.ts
index 281a8bdad8..d308bc9154 100644
--- a/src/components/inbox/inbox-answer.ts
+++ b/src/components/inbox/inbox-answer.ts
@@ -69,14 +69,6 @@ export function headlineOf(row: InboxRow): string {
return firstLine(textOf(row)) || subjectOf(row);
}
-/** The muted line under the headline when there is more to say and no choices to show. */
-export function snippetOf(row: InboxRow): string | null {
- const text = textOf(row).replace(/\s+/g, " ").trim();
- const headline = headlineOf(row);
- if (!text || text === headline) return null;
- return text.startsWith(headline) ? text.slice(headline.length).trim() || null : text;
-}
-
/** The search box keeps a line whose sender, conversation, headline, words or choices hold every word typed. */
export function matchesSearch(row: InboxRow, query: string): boolean {
const words = query.toLowerCase().split(/\s+/).filter(Boolean);
diff --git a/src/components/inbox/inbox-reason.test.ts b/src/components/inbox/inbox-reason.test.ts
new file mode 100644
index 0000000000..2ad053fa2b
--- /dev/null
+++ b/src/components/inbox/inbox-reason.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest";
+
+import type { InboxRow } from "../../../shared/inbox";
+import { countsForYou, inboxGroup, inboxReason } from "../../../shared/inbox-reason";
+import { approvalRow, inboxView, messageRow, questionRow, reportRow, settledRow } from "@/testing/inbox-fixture";
+import { activityUnread, forYouCount, groupRows, listedRows, reasonOf, waitingCount } from "./inbox-view";
+
+const line = (fields: Partial<InboxRow>): InboxRow => ({ ...messageRow, id: `line-${Math.random()}`, ...fields });
+
+describe("why a line is in the inbox", () => {
+ it("follows from the line itself where it can", () => {
+ expect(inboxReason(questionRow)).toBe("asked");
+ expect(inboxReason(approvalRow)).toBe("approval");
+ expect(inboxReason(settledRow), "an answered approval still says what it was").toBe("approval");
+ expect(inboxReason(reportRow)).toBe("finished");
+ expect(inboxReason(messageRow), "a message with no reason of its own").toBe("messaged");
+ expect(inboxReason(line({ kind: "notice", replies: undefined }))).toBe("notice");
+ expect(inboxReason(line({ kind: "ask", card: undefined, secret: { label: "OpenAI key" } as unknown as InboxRow["secret"] })), "a password it needs").toBe("asked");
+ });
+
+ it("asks for an OK on a change to review and on someone asking for access", () => {
+ const card = questionRow.card!;
+ expect(inboxReason({ ...questionRow, card: { ...card, skillRequest: { name: "x" } as never } })).toBe("approval");
+ expect(inboxReason({ ...questionRow, card: { ...card, accessRequest: { botId: "b", botName: "Ledger", email: "[email protected]", name: "Ben" } } })).toBe("approval");
+ });
+
+ it("takes what the server says when only the server can tell", () => {
+ expect(inboxReason(line({ reason: "mentioned" }))).toBe("mentioned");
+ expect(inboxReason(line({ reason: "replied" }))).toBe("replied");
+ expect(inboxReason(line({ reason: "asked" }))).toBe("asked");
+ expect(inboxReason(line({ kind: "notice", reason: "shared" }))).toBe("shared");
+ expect(inboxReason({ ...approvalRow, reason: "mentioned" }), "an ask is its card, whatever else it carries").toBe("approval");
+ });
+
+ it("says it in the person's words", () => {
+ expect([questionRow, approvalRow, line({ reason: "mentioned" }), line({ reason: "replied" }), messageRow, line({ kind: "notice" }), reportRow, line({ kind: "notice", reason: "shared" })].map(reasonOf))
+ .toEqual(["Asked you", "Needs your OK", "Mentioned you", "Replied to you", "Messaged you", "Needs a look", "Finished", "Shared with you"]);
+ });
+});
+
+describe("For you and Activity", () => {
+ it("puts what waits on the person or names them in For you, and finished work and shares in Activity", () => {
+ expect([questionRow, approvalRow, messageRow, line({ reason: "mentioned" }), line({ reason: "replied" }), line({ kind: "notice" })].map(inboxGroup)).toEqual(Array(6).fill("for-you"));
+ expect([reportRow, line({ kind: "notice", reason: "shared" }), line({ reason: "shared" })].map(inboxGroup)).toEqual(["activity", "activity", "activity"]);
+ });
+
+ it("splits the listed lines into the two groups, keeping their order", () => {
+ const groups = groupRows(listedRows(inboxView()));
+ expect(groups["for-you"].map((row) => row.id)).toEqual([approvalRow.id, questionRow.id, messageRow.id]);
+ expect(groups.activity.map((row) => row.id)).toEqual([reportRow.id]);
+ });
+
+ it("counts only For you: an open ask, read or not, and an unread message; never finished work", () => {
+ const view = inboxView();
+ expect(forYouCount(view)).toBe(3);
+ expect(waitingCount(view), "the older count, kept for what still reads it, still counts the report").toBe(4);
+ expect(countsForYou({ ...messageRow, unread: false })).toBe(false);
+ expect(countsForYou(settledRow)).toBe(false);
+ expect(forYouCount(inboxView([reportRow]))).toBe(0);
+ expect(forYouCount(null)).toBe(0);
+ });
+
+ it("tells when unread Activity alone is left, for the Inbox row's bold", () => {
+ expect(activityUnread(inboxView([reportRow]))).toBe(true);
+ expect(activityUnread(inboxView([{ ...reportRow, unread: false }, messageRow]))).toBe(false);
+ });
+
+ it("keeps the line the person has open in the list once it is settled", () => {
+ const view = inboxView([approvalRow, { ...reportRow, tab: "done" }]);
+ expect(listedRows(view).map((row) => row.id)).toEqual([approvalRow.id]);
+ expect(listedRows(view, reportRow.id).map((row) => row.id)).toEqual([approvalRow.id, reportRow.id]);
+ });
+});
diff --git a/src/components/inbox/inbox-view.ts b/src/components/inbox/inbox-view.ts
index 205939c7d2..7f1e970ad2 100644
--- a/src/components/inbox/inbox-view.ts
+++ b/src/components/inbox/inbox-view.ts
@@ -1,8 +1,10 @@
import { formatQuestionAnswers, questionChoices } from "../../../shared/ask-question";
import type { InboxRow, InboxTab, InboxView } from "../../../shared/inbox";
+import { countsForYou, inboxGroup, inboxReason, type InboxGroup, type InboxReason } from "../../../shared/inbox-reason";
import type { NeedsYouItem } from "../../../shared/today";
import { liveCardKind } from "../../../shared/live-approval";
import { t } from "@/lib/i18n";
+import type { LocaleKey } from "@/locales";
import { dismissResponse, type CardResponse } from "@/lib/card-answer";
import { accessRequestWords, cardAnswerFor } from "../bot-access/access-card";
@@ -12,8 +14,9 @@ export const CARD_ROWS = 3;
export const rowsIn = (view: InboxView | null, tab: InboxTab): InboxRow[] => (view?.rows ?? []).filter((row) => row.tab === tab);
/** The inbox as one list, newest first: what waits on the person and their news; a settled line is read from where it
- * came, not listed again. */
-export const listedRows = (view: InboxView | null): InboxRow[] => (view?.rows ?? []).filter((row) => row.tab !== "done").sort((a, b) => b.at - a.at);
+ * came, not listed again, except the one the person has open, which keeps its place. */
+export const listedRows = (view: InboxView | null, held?: string | null): InboxRow[] =>
+ (view?.rows ?? []).filter((row) => row.tab !== "done" || row.id === held).sort((a, b) => b.at - a.at);
export function tabCounts(view: InboxView | null): Record<InboxTab, number> {
const counts: Record<InboxTab, number> = { "needs-you": 0, info: 0, done: 0 };
@@ -24,6 +27,28 @@ export function tabCounts(view: InboxView | null): Record<InboxTab, number> {
/** What the Inbox row counts: every line waiting on the person, and news they have not read. */
export const waitingCount = (view: InboxView | null): number => (view?.rows ?? []).filter((row) => row.tab === "needs-you" || (row.tab === "info" && row.unread)).length;
+/** What the inbox's number counts: the For you lines that wait on the person or are new. Activity is never counted. */
+export const forYouCount = (view: InboxView | null): number => (view?.rows ?? []).filter(countsForYou).length;
+
+/** Activity the person has not read yet: it makes the Inbox row bold, with no number. */
+export const activityUnread = (view: InboxView | null): boolean =>
+ (view?.rows ?? []).some((row) => row.tab === "info" && row.unread && inboxGroup(row) === "activity");
+
+/** The listed lines in their two groups, each newest first as given. */
+export function groupRows(rows: readonly InboxRow[]): Record<InboxGroup, InboxRow[]> {
+ const groups: Record<InboxGroup, InboxRow[]> = { "for-you": [], activity: [] };
+ for (const row of rows) groups[inboxGroup(row)].push(row);
+ return groups;
+}
+
+const REASON_WORDS: Record<InboxReason, LocaleKey> = {
+ asked: "inbox.reason.asked", approval: "inbox.reason.approval", mentioned: "inbox.reason.mentioned", replied: "inbox.reason.replied",
+ messaged: "inbox.reason.messaged", notice: "inbox.reason.notice", finished: "inbox.reason.finished", shared: "inbox.reason.shared",
+};
+
+/** Why a line is here, in the person's words: what its row says first. */
+export const reasonOf = (row: InboxRow): string => t(REASON_WORDS[inboxReason(row)]);
+
/** What a team's person is told needs them beyond the inbox's lines: something to fix, or a question in their own chat. */
export const inboxFixes = (items: readonly NeedsYouItem[] | undefined, view: InboxView | null): NeedsYouItem[] =>
(items ?? []).filter((item) => item.kind !== "message" && !(item.kind === "question" && view?.rows.some((row) => row.tab === "needs-you" && row.origin?.threadId === item.threadId)));
@@ -38,8 +63,8 @@ export function senderLabel(row: Pick<InboxRow, "from" | "workingFor" | "askedBy
return row.workingFor ? t("inbox.workingFor", { name, other: row.workingFor.name }) : name;
}
-/** The conversation a line came from, when its subject doesn't already say it. */
-export const placeOf = (row: Pick<InboxRow, "kind" | "origin">): string | null => (row.kind !== "message" && row.origin?.title ? t("inbox.in", { title: row.origin.title }) : null);
+/** Where a line came from: its room or conversation. */
+export const placeOf = (row: Pick<InboxRow, "origin">): string | null => (row.origin?.title ? t("inbox.in", { title: row.origin.title }) : null);
/** 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. */
diff --git a/src/components/inbox/use-inbox-actions.ts b/src/components/inbox/use-inbox-actions.ts
index 14419b79e4..16fb67d032 100644
--- a/src/components/inbox/use-inbox-actions.ts
+++ b/src/components/inbox/use-inbox-actions.ts
@@ -6,7 +6,7 @@ import { openThreadBeside } from "@/lib/room-feed";
import { openThread } from "@/state/store";
import { useStoreRef } from "@/state/store-ref";
import { useStoreSelector } from "@/state/store-select";
-import { closeInbox, doneInboxRow, openInbox, readInboxRow, refreshInbox } from "@/state/inbox";
+import { closeInbox, currentInboxPanel, doneInboxRow, openInbox, readInboxRow, refreshInbox } from "@/state/inbox";
import type { CardResponse } from "@/lib/card-answer";
import { answerThread, closeResponse, type QuickAction } from "./inbox-view";
import { attentionJumpAction, type AttentionThread } from "../SidebarBotActivity";
@@ -27,7 +27,8 @@ export function useInboxActions(view: InboxView | null) {
}, [view, dispatch]);
const openInChat = useCallback((row: InboxRow) => {
- readInboxRow(row);
+ const sidePanelReadsIt = !phone && currentInboxPanel().open;
+ if (!sidePanelReadsIt) readInboxRow(row);
const target = row.origin ? { botId: row.origin.botId, threadId: row.origin.threadId, messageId: row.origin.messageId }
: view?.threadId && view.botId ? { botId: view.botId, threadId: view.threadId, messageId: row.id } : null;
if (!target) return;
@@ -42,7 +43,7 @@ export function useInboxActions(view: InboxView | null) {
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 }); }
+ else openInbox({ reading: row.id });
}, [answer, openInChat]);
return { run, answer, openInChat };
diff --git a/src/components/inbox/use-inbox-hold.ts b/src/components/inbox/use-inbox-hold.ts
new file mode 100644
index 0000000000..dc6965d1c5
--- /dev/null
+++ b/src/components/inbox/use-inbox-hold.ts
@@ -0,0 +1,78 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import type { InboxRow, InboxView } from "../../../shared/inbox";
+import { readInboxRow, unreadInboxRow } from "@/state/inbox";
+
+/** How long an opened line stays on screen, with the window focused, before it counts as read. */
+export const READ_AFTER_MS = 2_000;
+
+const looking = () => document.visibilityState !== "hidden" && document.hasFocus();
+
+/** Reads `row` once it has been on screen for READ_AFTER_MS with the window focused; leaving the window pauses it. */
+function useReadAfterLooking(row: InboxRow | undefined, onRead: (row: InboxRow) => void): void {
+ const latest = useRef({ row, onRead });
+ latest.current = { row, onRead };
+ const id = row?.unread ? row.id : null;
+ useEffect(() => {
+ if (!id) return;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const stop = () => { clearTimeout(timer); timer = undefined; };
+ const start = () => {
+ stop();
+ if (!looking()) return;
+ timer = setTimeout(() => {
+ const { row: now, onRead: read } = latest.current;
+ if (now?.id === id && now.unread) read(now);
+ }, READ_AFTER_MS);
+ };
+ start();
+ window.addEventListener("focus", start);
+ window.addEventListener("blur", stop);
+ document.addEventListener("visibilitychange", start);
+ return () => {
+ stop();
+ window.removeEventListener("focus", start);
+ window.removeEventListener("blur", stop);
+ document.removeEventListener("visibilitychange", start);
+ };
+ }, [id]);
+}
+
+/** Calls `onRead` when `row` turns read while it stays open, by anything but an answer: opening its conversation reads
+ * it as well. */
+function useReadWithoutAnswer(row: InboxRow | undefined, onRead: (id: string) => void): void {
+ const was = useRef<Pick<InboxRow, "id" | "unread" | "tab"> | null>(null);
+ const latest = useRef(onRead);
+ latest.current = onRead;
+ const id = row?.id, unread = row?.unread, tab = row?.tab, kind = row?.kind;
+ useEffect(() => {
+ const before = was.current;
+ was.current = id && tab ? { id, unread: Boolean(unread), tab } : null;
+ if (!id || before?.id !== id || !before.unread || unread) return;
+ const answered = kind === "ask" || (tab === "done" && before.tab !== "done" && kind !== "result");
+ if (!answered) latest.current(id);
+ }, [id, unread, tab, kind]);
+}
+
+/** The line the person opened last. It keeps its place in the list, read or settled, until they pick another, so no row
+ * moves under the pointer; it is read after a moment on screen, with an Undo for that. */
+export function useInboxHold(view: InboxView | null, reading: string | null) {
+ const [held, setHeld] = useState<string | null>(reading);
+ const [marked, setMarked] = useState<string | null>(null);
+ const [kept, setKept] = useState<string | null>(null);
+ const pick = useCallback((row: Pick<InboxRow, "id">) => {
+ setHeld(row.id);
+ setMarked(null);
+ setKept(null);
+ }, []);
+ useEffect(() => { if (reading) pick({ id: reading }); }, [reading, pick]);
+ const row = held && held !== kept ? view?.rows.find((one) => one.id === held) : undefined;
+ useReadAfterLooking(row, (seen) => { readInboxRow(seen); setMarked(seen.id); });
+ useReadWithoutAnswer(row, setMarked);
+ const undo = useCallback(() => {
+ if (!marked) return;
+ unreadInboxRow({ id: marked });
+ setKept(marked);
+ setMarked(null);
+ }, [marked]);
+ return { held, marked, pick, undo };
+}
diff --git a/src/inbox-preview.tsx b/src/inbox-preview.tsx
new file mode 100644
index 0000000000..12ca42a5b6
--- /dev/null
+++ b/src/inbox-preview.tsx
@@ -0,0 +1,118 @@
+// Dev-only gallery of the Inbox panel with every kind of line, served at /inbox-preview.html; not in the packaged app. It
+// mounts the real sidebar Inbox row and the real panel over a fixed store, with no server behind it.
+// ?scope=team|personal&skin=midnight|daylight&mode=simple|advanced&lang=de&reading=<line id>&only=activity
+import { StrictMode } from "react";
+import { createRoot } from "react-dom/client";
+import type { InboxRow, InboxView } from "../shared/inbox";
+import { inboxGroup } from "../shared/inbox-reason";
+import { InboxPanel } from "@/components/inbox/InboxPanel";
+import { SidebarInboxRow } from "@/components/SidebarInboxRow";
+import { loadLocale } from "@/lib/i18n";
+import { setAdvancedMode } from "@/lib/interface-mode";
+import { applySkinChoice, SKIN_IDS, type SkinId } from "@/lib/skins";
+import { currentInbox, openInbox, setInboxView } from "@/state/inbox";
+import { initialState, StoreContext, type AppState, type Bot } from "@/state/store";
+import { setTeamPeople } from "@/state/team-people";
+import "./styles.css";
+
+const params = new URLSearchParams(location.search);
+const team = params.get("scope") !== "personal";
+const skin = params.get("skin") ?? "midnight";
+setAdvancedMode(params.get("mode") === "advanced");
+applySkinChoice(SKIN_IDS.includes(skin as SkinId) ? (skin as SkinId) : "midnight");
+await loadLocale(params.get("lang") ?? "en");
+
+const NOW = Date.now();
+const ago = (minutes: number) => NOW - minutes * 60_000;
+const BEN = { name: "Ben", email: "[email protected]" };
+const LEDGER = { name: "Ledger", botId: "ledger" };
+const SCOUT = { name: "Scout", botId: "scout" };
+const origin = (botId: string, threadId: string, title: string, groupId?: string) => ({ botId, threadId, title, ...(groupId ? { groupId } : {}) });
+
+const question: InboxRow = {
+ id: "question", kind: "ask", tab: "needs-you", unread: true, at: ago(3), from: LEDGER, origin: origin("ledger", "ledger-work", "Pricing page: fix"),
+ text: "Should I apply the fix to the pricing page?",
+ card: { title: "Your bot has a question", subtitle: "Should I apply the fix to the pricing page?", options: ["Yes, only the footer", "Yes, the welcome text too", "No"], requestId: "req-q", requestType: "question" },
+};
+const approval: InboxRow = {
+ id: "approval", kind: "ask", tab: "needs-you", unread: false, at: ago(26), from: LEDGER, origin: origin("ledger", "ledger-work", "Pricing page: fix"),
+ text: "git push origin fix/pricing-page-footer",
+ card: { title: "Approval needed", subtitle: "git push origin fix/pricing-page-footer", options: ["Allow", "Deny"], requestId: "req-a", requestType: "permission", tool: "Bash" },
+};
+const finished: InboxRow = {
+ id: "finished", kind: "result", tab: "info", unread: true, at: ago(15), from: SCOUT, origin: origin("scout", "scout-weekly", "Weekly report"),
+ text: "Weekly report is ready: 4 new leads, 2 replies still open.",
+};
+const finishedRead: InboxRow = {
+ id: "finished-read", kind: "result", tab: "info", unread: false, at: ago(190), from: SCOUT, origin: origin("scout", "scout-daily", "Daily summary"),
+ text: "Daily summary: 3 new leads, 1 reply open.",
+};
+
+const teamRows: InboxRow[] = [
+ question,
+ { id: "mention", kind: "message", tab: "info", unread: true, at: ago(8), from: BEN, origin: { ...origin("ledger", "room-design", "Design", "design"), messageId: "m1" }, replies: true, reason: "mentioned",
+ text: "@Cleo can you look at the new header before Friday?" },
+ finished,
+ approval,
+ { id: "reply", kind: "message", tab: "info", unread: true, at: ago(41), from: BEN, origin: { ...origin("ledger", "room-launch", "Launch plan", "launch"), messageId: "m2" }, replies: true, reason: "replied",
+ text: "Yes, Thursday works. I'll take the slides." },
+ { id: "message", kind: "message", tab: "info", unread: false, at: ago(64), from: LEDGER, origin: origin("ledger", "ledger-deploy", "Staging deploy"), replies: true,
+ text: "The staging deploy is done. Want me to ship it to everyone?" },
+ { id: "shared", kind: "notice", tab: "info", unread: true, at: ago(130), from: BEN, origin: origin("ledger", "ledger-main", "Ledger"), reason: "shared",
+ text: "Ben shared Ledger with you." },
+ finishedRead,
+];
+
+const personalRows: InboxRow[] = [
+ question,
+ finished,
+ approval,
+ { id: "message", kind: "message", tab: "info", unread: true, at: ago(52), from: LEDGER, origin: origin("ledger", "ledger-deploy", "Staging deploy"), replies: true,
+ text: "The staging deploy is done. Want me to ship it to everyone?" },
+ { id: "notice", kind: "notice", tab: "info", unread: false, at: ago(95), from: SCOUT, origin: origin("scout", "scout-crm", "CRM sync"),
+ text: "The CRM sync stopped: the sign-in to the CRM expired." },
+ finishedRead,
+];
+
+const BASE = { title: "", description: "", notifications: true, unread: false, modelSelection: { instanceId: "claude", model: "claude-opus-5-5" } } as const;
+const bots: Bot[] = [
+ { ...BASE, id: "ledger", name: "Ledger", title: "Developer", color: "teal", threadId: "ledger-work", tasks: [{ threadId: "ledger-work", title: "Pricing page: fix", createdAt: ago(600) }], messages: [] },
+ { ...BASE, id: "scout", name: "Scout", title: "Cleo's Chief", color: "orange", chiefOfStaff: team, threadId: "scout-inbox",
+ tasks: [{ threadId: "scout-inbox", title: "Inbox", createdAt: ago(6000), ...(team ? { inbox: true } : {}) }], messages: [] },
+] as Bot[];
+
+const rows = (team ? teamRows : personalRows).filter((row) => params.get("only") !== "activity" || inboxGroup(row) === "activity");
+const view: InboxView = team ? { botId: "scout", threadId: "scout-inbox", rows, anchor: rows[0]!.id } : { botId: null, threadId: null, rows, anchor: null };
+setInboxView(view);
+openInbox(params.get("reading") ? { reading: params.get("reading")! } : {});
+if (team) setTeamPeople({ people: [{ email: "[email protected]", name: "Cleo", role: "owner", you: true }, { ...BEN, role: "member" }], me: { email: "[email protected]", name: "Cleo", role: "owner", you: true }, admin: true, needsYou: [] });
+
+function Gallery() {
+ const state: AppState = { ...initialState, bots, selectedId: "scout", connected: true };
+ const value = { state, dispatch: () => {}, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };
+ return (
+ <StoreContext.Provider value={value}>
+ <div className="flex h-dvh w-full overflow-hidden bg-app text-ink">
+ <nav className="w-[260px] shrink-0 border-e border-hairline/40 bg-panel pt-3 max-md:hidden"><SidebarInboxRow icons={false} large running={false} /></nav>
+ <main className="min-w-0 flex-1" />
+ <InboxPanel />
+ </div>
+ </StoreContext.Provider>
+ );
+}
+
+const realFetch = window.fetch.bind(window);
+window.fetch = async (input, init) => {
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
+ const path = new URL(url, location.href).pathname;
+ if (!path.startsWith("/api/")) return realFetch(input, init);
+ const marked = /^\/api\/inbox\/([\w-]+)\/(read|unread)$/.exec(path);
+ if (marked) {
+ const shown = currentInbox() ?? view;
+ const next = { ...shown, rows: shown.rows.map((row) => (row.id === marked[1] ? { ...row, unread: marked[2] === "unread" } : row)) };
+ return new Response(JSON.stringify(next), { status: 200, headers: { "content-type": "application/json" } });
+ }
+ return new Response(path === "/api/inbox" ? JSON.stringify(currentInbox() ?? view) : "{}", { status: 200, headers: { "content-type": "application/json" } });
+};
+
+createRoot(document.getElementById("root")!).render(<StrictMode><Gallery /></StrictMode>);
diff --git a/src/locales/de.json b/src/locales/de.json
index c4cb789f92..8b8b012693 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -2971,6 +2971,19 @@
"ask.detail.more": "Alles anzeigen",
"inbox.action.closeQuestion": "Ohne Antwort schließen",
"inbox.markAllRead": "Alle als gelesen markieren",
+ "inbox.reason.asked": "Hat dich gefragt",
+ "inbox.reason.approval": "Braucht dein OK",
+ "inbox.reason.mentioned": "Hat dich erwähnt",
+ "inbox.reason.replied": "Hat dir geantwortet",
+ "inbox.reason.messaged": "Hat dir geschrieben",
+ "inbox.reason.notice": "Bitte ansehen",
+ "inbox.reason.finished": "Fertig",
+ "inbox.reason.shared": "Mit dir geteilt",
+ "inbox.group.forYou": "Für dich",
+ "inbox.group.activity": "Aktivität",
+ "inbox.forYou.empty": "Du bist auf dem neuesten Stand.",
+ "inbox.markedRead": "Als gelesen markiert",
+ "inbox.row.activity": "Posteingang, neue Aktivität",
"question.somethingElse": "Etwas anderes…",
"question.answerPlaceholder": "Deine Antwort",
"question.status.closed": "Ohne Antwort geschlossen",
diff --git a/src/locales/en.json b/src/locales/en.json
index 93fd223a92..aac855d04c 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -2450,6 +2450,19 @@
"inbox.headline.connect": "Connect {app}",
"inbox.youReplied": "You replied",
"inbox.markAllRead": "Mark all as read",
+ "inbox.reason.asked": "Asked you",
+ "inbox.reason.approval": "Needs your OK",
+ "inbox.reason.mentioned": "Mentioned you",
+ "inbox.reason.replied": "Replied to you",
+ "inbox.reason.messaged": "Messaged you",
+ "inbox.reason.notice": "Needs a look",
+ "inbox.reason.finished": "Finished",
+ "inbox.reason.shared": "Shared with you",
+ "inbox.group.forYou": "For you",
+ "inbox.group.activity": "Activity",
+ "inbox.forYou.empty": "You're all caught up.",
+ "inbox.markedRead": "Marked as read",
+ "inbox.row.activity": "Inbox, new activity",
"sidebar.people.mention": "Write to {name}",
"sidebar.people.mentionHere": "Write to {name}. Here now",
"sidebar.people.loading": "Loading people…",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index f297875c67..4165209349 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -8287,6 +8287,19 @@
"ask.detail.more": "Mostrar tudo",
"inbox.action.closeQuestion": "Fechar sem responder",
"inbox.markAllRead": "Marcar tudo como lido",
+ "inbox.reason.asked": "Perguntou a você",
+ "inbox.reason.approval": "Precisa do seu OK",
+ "inbox.reason.mentioned": "Mencionou você",
+ "inbox.reason.replied": "Respondeu a você",
+ "inbox.reason.messaged": "Enviou uma mensagem para você",
+ "inbox.reason.notice": "Precisa de atenção",
+ "inbox.reason.finished": "Concluído",
+ "inbox.reason.shared": "Compartilhado com você",
+ "inbox.group.forYou": "Para você",
+ "inbox.group.activity": "Atividade",
+ "inbox.forYou.empty": "Tudo em dia por aqui.",
+ "inbox.markedRead": "Marcado como lido",
+ "inbox.row.activity": "Caixa de entrada, nova atividade",
"inbox.settled.title": "Concluído",
"inbox.filter.owner": "Bot ou sala",
"inbox.filter.allOwners": "Todos os bots e salas",
diff --git a/src/state/inbox.ts b/src/state/inbox.ts
index 12a4fbd5d5..421535f611 100644
--- a/src/state/inbox.ts
+++ b/src/state/inbox.ts
@@ -94,7 +94,7 @@ const patchRow = (id: string, patch: Partial<InboxRow>) => {
};
/** Tells the server; if it can't be told, the row goes back to how it was (`undo`) and the list is read again. */
-async function mark(id: string, what: "read" | "done", undo: Partial<InboxRow>): Promise<void> {
+async function mark(id: string, what: "read" | "unread" | "done", undo: Partial<InboxRow>): Promise<void> {
const seq = ++sent;
const view = await api<InboxView>(`/api/inbox/${id}/${what}`, { method: "POST", background: true }).catch(() => null);
if (view && Array.isArray(view.rows)) return show(seq, view);
@@ -109,6 +109,12 @@ export function readInboxRow(row: Pick<InboxRow, "id" | "unread">): void {
void mark(row.id, "read", { unread: true });
}
+/** The person wants a line they read to stay new: it is bold again, and counted again where it counts. */
+export function unreadInboxRow(row: Pick<InboxRow, "id">): void {
+ patchRow(row.id, { unread: true });
+ void mark(row.id, "unread", { unread: false });
+}
+
const marking = store(false);
export const useInboxMarkingAll = (): boolean => useSyncExternalStore(marking.subscribe, marking.get, marking.get);
@@ -137,10 +143,11 @@ export function doneInboxRow(row: Pick<InboxRow, "id">): void {
}
/** 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" | "origin">, text: string): Promise<void> {
+export async function replyToInboxRow(view: Pick<InboxView, "botId" | "threadId">, row: Pick<InboxRow, "id" | "origin" | "unread">, text: string): Promise<void> {
const origin = view.threadId ? null : row.origin;
const path = origin?.groupId ? `/api/groups/${origin.groupId}/messages` : `/api/bots/${origin?.botId ?? view.botId}/messages`;
await api(path, { method: "POST", body: JSON.stringify({ text, threadId: origin?.threadId ?? view.threadId, replyToId: row.id, sendId: randomUuid() }) });
+ readInboxRow(row);
void refreshInbox();
}