Skip to content

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

On a team, unread marks, notifications and bot order are each person's own (#5168)

Milind Sonif55d45c6e076
diff --git a/docs/team-cloud.md b/docs/team-cloud.md
index 03834baa3a..e64a07bdb8 100644
--- a/docs/team-cloud.md
+++ b/docs/team-cloud.md
@@ -20,8 +20,13 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes t
in the @ list too, and whatever is addressed to one of them reaches their inbox (below, "One inbox per person"). "New conversation"
is yours alone: no other Member and no Admin, the Super admin included, sees it, writes in it or learns of it, in
lists, counts, unread marks, searches, files, notifications, streams, a bot's tools or another bot. A group chat is
- seen by whoever sees it, and its unread mark is each person's own: a bot's reply there is unread for everyone until
- they read it, and one person reading it clears it for nobody else (`room-reads.json`). A bot's shared chats say who can read them, *"Shared · everyone in Acme can see"* or, on a bot set to Only people added (`onlyPeopleAdded` on everyone's copy of it), *"Shared · only people added and admins can see"*. Every private chat says so in its header, *"Private · only you"*, and the first one on a
+ seen by whoever sees it. Its unread mark, and that of a bot's shared chats, is each person's own: a bot's reply there is
+ unread for everyone until they read it, and one person reading it or marking it unread changes it for nobody else
+ (`room-reads.json`, a bot's chat as `thread:<id>`); each person's lists and stream carry only their own mark and read
+ line, and a read reaches only their own streams. A private chat keeps its one mark. A notification everyone who sees
+ a conversation gets (a "done", a mention) is one entry with each person's own read mark (`read_by` on the feed's
+ row, never sent): reading it, Read all and opening its conversation mark it read for that person alone and tell only
+ their own apps (`notifications.read`). A mark made before marks were each person's stays read for everyone. A person's read marks go when they leave the team. A bot's shared chats say who can read them, *"Shared · everyone in Acme can see"* or, on a bot set to Only people added (`onlyPeopleAdded` on everyone's copy of it), *"Shared · only people added and admins can see"*. Every private chat says so in its header, *"Private · only you"*, and the first one on a
device also says it as a sentence: *"Your chats in Acme are private. Only you can see them: not other members, not
Acme's admins."* The server marks such a conversation `private: true` on the wire (`WireTask.private`). When you leave
the team (or are removed), your private chats and everything only yours there are deleted, never handed to an admin
@@ -29,6 +34,11 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes t
(`server/workspace-backup-team-private.ts`): no private conversation, none of its work folders or files only it used, no
member's memory layer, no member's own MausBot, their inbox or anything under `people/`. Restoring such an export gives a
team back everything but those.
+- **The order of bots.** Each User's list of bots is in their own order (`bot-orders.json`): their reorder (`PUT
+ /api/bots/order`, any level, Can view included) changes only their list and reaches only their streams. Whoever has
+ never ordered theirs sees the team's order, which an Owner's or Admin's reorder sets: an admin's order is the team's,
+ for every admin and every User without their own. A bot added later takes its place in the team's order in every
+ list. A person's own order goes when they leave the team.
- **Who is speaking.** A bot knows who wrote each line it reads. Your own typed line in your own chat with it is the
only line that carries no note; every other line opens with one, written by the Cloud and never by the sender:
`[From <who> · <what> · <authority>]`, as in `[From Ben (person) · message · their own request]` on each person's
@@ -87,7 +97,10 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes t
sleep request as any home does ([Sleeping homes](cloud-pro.md#sleeping-homes-the-power-read-and-the-sleep-handshake)):
not while any member used it in the last minutes, a turn or routine runs, or work one bot handed another is still
moving (`handoff`). A member's app, phone or a webhook wakes it, and the Admin wakes it before a routine is due. Inbox
- lines and open cards live on its volume, so a person's answer after a sleep finds them. It keeps every member's
+ lines and open cards live on its volume, so a person's answer after a sleep finds them. The chat any member has open
+ while they use the app (`POST /api/presence/active` with its `threadId`) counts as in front of them, a User's as an
+ Admin's: its engine and prompt cache stay warm a while. That is all it does; it never holds back anyone's
+ notification. It keeps every member's
session across a restart; a My Cloud revokes every session that is not its owner's at each boot.
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs
index 3bfd3fb874..f3fe20b3f8 100644
--- a/scripts/ci-scope.mjs
+++ b/scripts/ci-scope.mjs
@@ -85,6 +85,7 @@ export const VITEST_SUBSETS = {
"server/cloud-team-open-reach.e2e.test.ts",
"server/cloud-team-owners.e2e.test.ts",
"server/cloud-team-people.e2e.test.ts",
+ "server/cloud-team-per-person.e2e.test.ts",
"server/cloud-team-phones.e2e.test.ts",
"server/cloud-team-pictures.e2e.test.ts",
"server/cloud-team-private.e2e.test.ts",
diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.ts
index 2e4504b120..0b89d92932 100644
--- a/scripts/ci-scope.test.ts
+++ b/scripts/ci-scope.test.ts
@@ -222,6 +222,7 @@ describe("CI outputs", () => {
"server/cloud-team-open-reach.e2e.test.ts",
"server/cloud-team-owners.e2e.test.ts",
"server/cloud-team-people.e2e.test.ts",
+ "server/cloud-team-per-person.e2e.test.ts",
"server/cloud-team-phones.e2e.test.ts",
"server/cloud-team-pictures.e2e.test.ts",
"server/cloud-team-private.e2e.test.ts",
diff --git a/server/bot-visibility.ts b/server/bot-visibility.ts
index 5172d4681b..f5cb08a153 100644
--- a/server/bot-visibility.ts
+++ b/server/bot-visibility.ts
@@ -17,6 +17,8 @@ export type { BotVisibility };
export interface ThreadAudiences {
of(threadId: string): Audience | undefined;
person: string | null;
+ /** A bot's conversation as this person has read it: its unread mark and read line their own (host/room-reads.ts). */
+ ownTask?<T extends { threadId: string; unread?: boolean; lastReadMessageId?: string }>(task: T): T;
}
/** `all`: every bot and room. On a Team Cloud an admin session is `all` with its address, and still sees only the
@@ -236,6 +238,11 @@ export class VisibleSet {
return members.length > 0 && members.every((member) => this.bot(member)) && viewerSees(this.viewer, group.audienceFloor);
}
+ /** A conversation's unread mark and read line as this viewer read it; the task as it is where everyone reads alike. */
+ ownTask<T extends { threadId: string; unread?: boolean; lastReadMessageId?: string }>(task: T): T {
+ return this.audiences?.ownTask ? this.audiences.ownTask(task) : task;
+ }
+
/** Conversations have audiences of their own (a Team Cloud): a bot's tasks are then filtered one by one. */
get filtersThreads(): boolean {
return this.audiences !== null;
@@ -415,10 +422,11 @@ function shownConversations<T extends object>(bot: T, visible: VisibleSet): T {
const record = bot as T & Record<string, unknown>;
let out: Record<string, unknown> = record;
const tasks = Array.isArray(record.tasks) ? record.tasks as unknown[] : [];
- const kept = tasks.filter((task) => !task || typeof task !== "object" || typeof (task as { threadId?: unknown }).threadId !== "string" || visible.thread((task as { threadId: string }).threadId));
- if (kept.length !== tasks.length) {
+ const isTask = (task: unknown): task is { threadId: string; unread?: boolean; routineRunId?: unknown } => Boolean(task) && typeof task === "object" && typeof (task as { threadId?: unknown }).threadId === "string";
+ const kept = tasks.filter((task) => !isTask(task) || visible.thread(task.threadId)).map((task) => (isTask(task) ? visible.ownTask(task) : task));
+ if (kept.length !== tasks.length || kept.some((task, index) => task !== tasks[index])) {
out = { ...record, tasks: kept };
- if (typeof record.unread === "boolean") out.unread = kept.some((task) => (task as { unread?: unknown } | null)?.unread === true);
+ if (typeof record.unread === "boolean") out.unread = kept.some((task) => isTask(task) && task.unread === true && !task.routineRunId);
}
const main = typeof record.mainThreadId === "string" && visible.thread(record.mainThreadId) ? record.mainThreadId : teamConversation(kept);
if (typeof record.mainThreadId === "string" && record.mainThreadId !== main) {
diff --git a/server/client-notifications.e2e.test.ts b/server/client-notifications.e2e.test.ts
index b53b3e3468..9453ce193e 100644
--- a/server/client-notifications.e2e.test.ts
+++ b/server/client-notifications.e2e.test.ts
@@ -6,6 +6,10 @@ import { launchCloudSendFixture } from "../scripts/testing/cloud-send-fixture.ts
import { personKey } from "./person-key.ts";
import { hostTimeout } from "./testing/host-timeout.ts";
+/** On a Team Cloud a notification's read mark is each person's own (`read_by`); its one `read` mark stays untouched. */
+const readBy = (db: DatabaseSync, person: string) => db.prepare("SELECT id FROM notification_log WHERE EXISTS (SELECT 1 FROM json_each(coalesce(read_by, '[]')) WHERE value = ?) ORDER BY id")
+ .all(person).map((row) => row.id);
+
it("lets a Team Cloud member list and read only their own notification feed", async () => {
const fixture = await launchCloudSendFixture({ onePasswordToken: "synthetic-notifications-token",
team: { id: "team-notifications", name: "Notifications" } });
@@ -38,8 +42,9 @@ it("lets a Team Cloud member list and read only their own notification feed", as
expect((await team.as(member.token!, "POST", `/api/notifications/${id}/read`)).status, id).toBe(404);
}
expect((await team.as(member.token!, "POST", "/api/notifications/read-all")).status).toBe(200);
- expect(db.prepare("SELECT id FROM notification_log WHERE read = 1 ORDER BY id").all().map((row) => row.id)).toEqual(["own-a", "own-b"]);
- expect(db.prepare("SELECT id FROM notification_log WHERE read = 0 ORDER BY id").all().map((row) => row.id)).toEqual(["owners-ask", "private", "spend", "targeted"]);
+ expect(readBy(db, personKey({ id: "", email: "[email protected]" }))).toEqual(["own-a", "own-b"]);
+ expect(readBy(db, ada), "Bob's reads are his alone").toEqual([]);
+ expect(db.prepare("SELECT id FROM notification_log WHERE read = 1").all(), "nobody's read reaches the one mark").toEqual([]);
} finally {
db.close();
}
@@ -85,14 +90,15 @@ it("reads only the opener's notifications in shared conversations and keeps spen
[`/api/groups/${group.id}/tasks/${group.threadId}`, group.threadId],
]) {
db.prepare("UPDATE notification_log SET thread_id = ? WHERE id != 'workspace-spend'").run(threadId);
- for (const [token, readIds, unreadIds] of [
- [member.token!, ["bobs-ask", "shared-done"], ["adas-ask", "shared-spend", "workspace-spend"]],
- [owner.token!, ["adas-ask", "shared-done", "shared-spend"], ["workspace-spend"]],
+ // Bob opening the conversation reads his own, and leaves Ada's list (unread() is hers) as it was.
+ for (const [token, reader, readIds, unreadIds] of [
+ [member.token!, bob, ["bobs-ask", "shared-done"], ["adas-ask", "shared-done", "shared-spend", "workspace-spend"]],
+ [owner.token!, ada, ["adas-ask", "shared-done", "shared-spend"], ["workspace-spend"]],
] as const) {
- db.prepare("UPDATE notification_log SET read = 0").run();
+ db.prepare("UPDATE notification_log SET read = 0, read_by = NULL").run();
expect(await unread()).toEqual(["adas-ask", "shared-done", "shared-spend", "workspace-spend"]);
expect((await team.as(token, "POST", path, { threadId })).status, path).toBe(200);
- expect(db.prepare("SELECT id FROM notification_log WHERE read = 1 ORDER BY id").all().map((row) => row.id), path).toEqual(readIds);
+ expect(readBy(db, reader), path).toEqual(readIds);
expect(await unread(), path).toEqual(unreadIds);
}
}
diff --git a/server/cloud-team-per-person.e2e.test.ts b/server/cloud-team-per-person.e2e.test.ts
new file mode 100644
index 0000000000..699c2ffca7
--- /dev/null
+++ b/server/cloud-team-per-person.e2e.test.ts
@@ -0,0 +1,224 @@
+// What each person on a Team Cloud keeps for themselves though the team shares the thing it is about (docs/team-cloud.md):
+// a bot's Shared chat's unread mark, a notification's read mark, and the order of their bots.
+// A real Team Cloud with the Owner, an Admin and two Users (Ada and Cleo), paired with the Admin's signed claims: one
+// person reading, marking or reordering changes nothing for another, and their streams hear only their own. The engine
+// is the synthetic Claude CLI.
+import { randomBytes } from "node:crypto";
+import { existsSync, readFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { DatabaseSync } from "node:sqlite";
+import { afterAll, beforeAll, expect, it } from "vitest";
+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";
+import { personKey } from "./person-key.ts";
+import { hostTimeout } from "./testing/host-timeout.ts";
+
+const OWNER = { email: "[email protected]", role: "owner" as const };
+const ADMIN = { email: "[email protected]", role: "admin" as const };
+const ADA = { email: "[email protected]", role: "member" as const };
+const CLEO = { email: "[email protected]", role: "member" as const };
+const ENGINE = `process.env.FAKE_CLAUDE_DUMP = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/dump.json";`;
+
+type Task = { threadId: string; unread?: boolean; lastReadMessageId?: string };
+type Bot = { id: string; mainThreadId: string; busy?: boolean; activity?: string; unread?: boolean; tasks: Task[] };
+type Note = { id: string; kind: string; threadId: string; read: boolean };
+
+let fx: CloudSendFixture, team: CloudTeamFixture;
+let owner = "", admin = "", ada = "", cleo = "";
+let scout: Bot, pilot: Bot;
+
+const bots = async (token: string) => (await team.as(token, "GET", "/api/bots")).body.bots as Bot[];
+const mainChat = async (token: string) => (await bots(token)).find((bot) => bot.id === scout.id)!.tasks.find((task) => task.threadId === scout.mainThreadId)!;
+const messages = async (token: string, threadId: string) => (await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages as unknown[];
+const idle = async (token: string) => (await bots(token)).every((bot) => bot.activity !== "working" && !bot.busy);
+async function until(done: () => Promise<boolean> | boolean, timeoutMs = 60_000): Promise<void> {
+ const end = Date.now() + timeoutMs;
+ while (!(await done())) {
+ if (Date.now() > end) throw new Error("timed out waiting");
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+}
+/** One line in Scout's Shared chat and its reply. */
+async function turn(token: string, text: string) {
+ rmSync(join(team.home, "dump.json"), { force: true });
+ const before = (await messages(token, scout.mainThreadId)).length;
+ const sent = await team.as(token, "POST", `/api/bots/${scout.id}/messages`, { text, threadId: scout.mainThreadId });
+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);
+ await until(async () => await idle(token) && (await messages(token, scout.mainThreadId)).length >= before + 2 && existsSync(join(team.home, "dump.json")));
+}
+/** One person's live stream: every frame it was sent. */
+async function listen(token: string) {
+ const controller = new AbortController();
+ const stream = await fetch(`${team.base}/api/events`, { headers: { ...fx.edge, authorization: `Bearer ${token}`, accept: "text/event-stream" }, signal: controller.signal });
+ expect(stream.status).toBe(200);
+ const reader = stream.body!.getReader();
+ const decoder = new TextDecoder();
+ let text = "";
+ const done = (async () => { for (;;) { const { value, done } = await reader.read(); if (done) return; text += decoder.decode(value, { stream: true }); } })().catch(() => {});
+ await until(() => text.includes("\"hello\""), 10_000);
+ const frames = () => text.split("\n\n").flatMap((part) => {
+ const data = part.split("\n").find((line) => line.startsWith("data: "));
+ try { return data ? [JSON.parse(data.slice(6)) as Record<string, any>] : []; } catch { return []; }
+ }).filter((frame) => frame.kind !== "hello");
+ return { frames, close: async () => { controller.abort(); await done; } };
+}
+/** Long enough for a frame fanned out in the same pass as one that arrived to have arrived too. */
+const settle = () => new Promise((resolve) => setTimeout(resolve, 500));
+
+beforeAll(async () => {
+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-1", name: "Acme", engine: ENGINE } });
+ team = fx.team!;
+ owner = (await team.pair(OWNER)).token!;
+ admin = (await team.pair(ADMIN)).token!;
+ ada = (await team.pair(ADA)).token!;
+ cleo = (await team.pair(CLEO)).token!;
+ for (const name of ["Scout", "Pilot"]) {
+ const created = await team.as(owner, "POST", "/api/bots", { name });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ if (name === "Scout") scout = created.body.bot; else pilot = created.body.bot;
+ }
+}, hostTimeout(120_000));
+
+afterAll(async () => {
+ await fx?.close();
+});
+
+it("the Shared chat's unread mark is each person's own: reading or marking it changes it for nobody else", async () => {
+ await turn(owner, "Morning, Scout.");
+ for (const token of [ada, cleo, admin]) expect((await mainChat(token)).unread).toBe(true);
+ const cleosBefore = await mainChat(cleo);
+ const read = await team.as(ada, "POST", `/api/bots/${scout.id}/read`, { threadId: scout.mainThreadId });
+ expect(read.status, JSON.stringify(read.body)).toBe(200);
+ expect((read.body.bot as Bot).tasks.find((task) => task.threadId === scout.mainThreadId)!.unread).toBe(false);
+ expect((await mainChat(ada)).unread).toBe(false);
+ for (const token of [cleo, admin]) expect((await mainChat(token)).unread, "Ada reading is Ada's alone").toBe(true);
+ const cleosAfter = await mainChat(cleo);
+ expect({ unread: cleosAfter.unread, lastReadMessageId: cleosAfter.lastReadMessageId }, "nothing of Ada's read reaches Cleo's copy")
+ .toEqual({ unread: cleosBefore.unread, lastReadMessageId: cleosBefore.lastReadMessageId });
+ // The bot's next reply is new to Ada again.
+ await turn(cleo, "And the afternoon?");
+ expect((await mainChat(ada)).unread).toBe(true);
+ // Marking it unread is hers alone too, and Cleo reading leaves Ada's mark.
+ for (const token of [ada, cleo]) expect((await team.as(token, "POST", `/api/bots/${scout.id}/read`, { threadId: scout.mainThreadId })).status).toBe(200);
+ const marked = await team.as(ada, "PATCH", `/api/bots/${scout.id}`, { unread: true });
+ expect(marked.status, JSON.stringify(marked.body)).toBe(200);
+ expect((await mainChat(ada)).unread).toBe(true);
+ expect((await mainChat(cleo)).unread, "Ada marking it unread is Ada's alone").toBe(false);
+ expect((await team.as(cleo, "POST", `/api/bots/${scout.id}/read`, { threadId: scout.mainThreadId })).status).toBe(200);
+ expect((await mainChat(ada)).unread, "Cleo reading leaves Ada's mark").toBe(true);
+}, hostTimeout(120_000));
+
+it("a person's read of the Shared chat reaches their own streams only", async () => {
+ await turn(owner, "Anything new?");
+ const adas = await listen(ada), cleos = await listen(cleo);
+ try {
+ expect((await team.as(ada, "POST", `/api/bots/${scout.id}/read`, { threadId: scout.mainThreadId })).status).toBe(200);
+ const scoutFrames = (frames: Array<Record<string, any>>) => frames.filter((frame) => frame.kind === "bot" && frame.bot?.id === scout.id);
+ await until(() => scoutFrames(adas.frames()).some((frame) => frame.bot.tasks?.find((task: Task) => task.threadId === scout.mainThreadId)?.unread === false), 10_000);
+ await settle();
+ expect(scoutFrames(cleos.frames()), "Ada's read never reaches Cleo's stream").toEqual([]);
+ expect((await mainChat(cleo)).unread).toBe(true);
+ } finally {
+ await adas.close();
+ await cleos.close();
+ }
+}, hostTimeout(90_000));
+
+it("reading a notification of the Shared chat is each person's own, and only their streams hear it", async () => {
+ const feed = async (token: string) => ((await team.as(token, "GET", "/api/notifications")).body.notifications as Note[])
+ .filter((note) => note.threadId === scout.mainThreadId && note.kind === "done");
+ const unreadIn = async (token: string) => (await feed(token)).filter((note) => !note.read).map((note) => note.id);
+ await turn(owner, "Draft the weekly note.");
+ await until(async () => (await unreadIn(ada)).length > 0);
+ const [first] = await unreadIn(ada);
+ for (const token of [cleo, admin, owner]) expect(await unreadIn(token)).toContain(first);
+ expect((await team.as(ada, "POST", `/api/notifications/${first}/read`)).status).toBe(200);
+ expect(await unreadIn(ada)).not.toContain(first);
+ for (const token of [cleo, admin, owner]) expect(await unreadIn(token), "Ada reading it is Ada's alone").toContain(first);
+ // Read all is the reader's own too.
+ expect((await team.as(cleo, "POST", "/api/notifications/read-all")).status).toBe(200);
+ expect(await unreadIn(cleo)).toEqual([]);
+ expect(await unreadIn(admin)).toContain(first);
+ // Opening the chat reads its notifications for the opener, and only the opener's streams hear it.
+ await turn(owner, "And the monthly one.");
+ await until(async () => (await unreadIn(cleo)).length > 0);
+ const adas = await listen(ada), cleos = await listen(cleo);
+ try {
+ expect((await team.as(ada, "POST", `/api/bots/${scout.id}/read`, { threadId: scout.mainThreadId })).status).toBe(200);
+ await until(() => adas.frames().some((frame) => frame.kind === "notifications.read"), 10_000);
+ await settle();
+ expect(cleos.frames().filter((frame) => frame.kind === "notifications.read"), "Ada's read never reaches Cleo's stream").toEqual([]);
+ expect(await unreadIn(ada)).toEqual([]);
+ expect((await unreadIn(cleo)).length, "Ada opening the chat leaves Cleo's unread").toBeGreaterThan(0);
+ } finally {
+ await adas.close();
+ await cleos.close();
+ }
+}, hostTimeout(120_000));
+
+it("each person orders their own bots; an Owner's or Admin's order is the team's default for whoever has not", async () => {
+ const order = async (token: string) => (await bots(token)).map((bot) => bot.id).filter((id) => id === scout.id || id === pilot.id);
+ const teams = await order(owner), flipped = [...teams].reverse();
+ for (const token of [admin, ada, cleo]) expect(await order(token)).toEqual(teams);
+ const cleos = await listen(cleo), adas = await listen(ada);
+ try {
+ const moved = await team.as(ada, "PUT", "/api/bots/order", { botIds: flipped });
+ expect(moved.status, JSON.stringify(moved.body)).toBe(200);
+ expect((moved.body.botIds as string[]).filter((id) => id === scout.id || id === pilot.id)).toEqual(flipped);
+ expect(await order(ada)).toEqual(flipped);
+ for (const token of [owner, admin, cleo]) expect(await order(token), "Ada's order is Ada's alone").toEqual(teams);
+ await until(() => adas.frames().some((frame) => frame.kind === "bots.order"), 10_000);
+ await settle();
+ expect(cleos.frames().filter((frame) => frame.kind === "bots.order"), "Ada's order never reaches Cleo's stream").toEqual([]);
+ } finally {
+ await cleos.close();
+ await adas.close();
+ }
+ // The Owner sets the team's default: everyone who never ordered their own follows it, Ada keeps hers.
+ expect((await team.as(owner, "PUT", "/api/bots/order", { botIds: flipped })).status).toBe(200);
+ for (const token of [owner, admin, cleo]) expect(await order(token)).toEqual(flipped);
+ expect((await team.as(admin, "PUT", "/api/bots/order", { botIds: teams })).status).toBe(200);
+ for (const token of [owner, admin, cleo]) expect(await order(token), "an Admin's order is the default too").toEqual(teams);
+ expect(await order(ada), "Ada keeps the order she chose").toEqual(flipped);
+ // A bot made after she ordered hers takes its place in the team's order in her list too.
+ const created = await team.as(owner, "POST", "/api/bots", { name: "Atlas" });
+ expect(created.status).toBe(201);
+ const atlas = created.body.bot.id as string;
+ const three = async (token: string) => (await bots(token)).map((bot) => bot.id).filter((id) => [scout.id, pilot.id, atlas].includes(id));
+ const atlasAt = (await three(owner)).indexOf(atlas);
+ expect(await three(cleo)).toEqual(await three(owner));
+ expect((await three(ada)).indexOf(atlas)).toBe(atlasAt);
+ expect((await three(ada)).filter((id) => id !== atlas)).toEqual(flipped);
+}, hostTimeout(90_000));
+
+it("a User's open chat counts as in front of them, and nobody can name another person's private chat as theirs", async () => {
+ const opened = await team.as(ada, "POST", `/api/bots/${scout.id}/tasks`, { title: "Ada's notes" });
+ expect(opened.status, JSON.stringify(opened.body)).toBe(201);
+ const private_ = opened.body.task.threadId as string;
+ expect((await team.as(ada, "POST", "/api/presence/active", { source: "desktop", threadId: private_ })).status).toBe(200);
+ for (const token of [cleo, owner]) expect((await team.as(token, "POST", "/api/presence/active", { source: "desktop", threadId: private_ })).status).toBe(404);
+}, hostTimeout(60_000));
+
+it("when Ada leaves the team, her own order and her read marks go with her, and Cleo's stay", async () => {
+ const dataDir = (...rest: string[]) => join(team.home, ".openmausbot", ...rest);
+ const adaKey = personKey({ id: "", email: ADA.email }), cleoKey = personKey({ id: "", email: CLEO.email });
+ const readers = () => {
+ const db = new DatabaseSync(dataDir("messages.db"), { readOnly: true });
+ try {
+ return (db.prepare("SELECT read_by FROM notification_log WHERE read_by IS NOT NULL").all() as Array<{ read_by: string }>).flatMap((row) => JSON.parse(row.read_by) as string[]);
+ } finally {
+ db.close();
+ }
+ };
+ // Ada and Cleo both read the same notification, so a row lists them both.
+ await turn(owner, "One more for the road.");
+ for (const token of [ada, cleo]) expect((await team.as(token, "POST", "/api/notifications/read-all")).status).toBe(200);
+ expect(readers()).toEqual(expect.arrayContaining([adaKey, cleoKey]));
+ expect(readFileSync(dataDir("bot-orders.json"), "utf8")).toContain(adaKey);
+ const left = await team.signed("POST", "/api/cloud/team/member-left", { email: ADA.email });
+ expect(left.status, JSON.stringify(left.body)).toBe(200);
+ expect(readers(), "her read marks are gone").not.toContain(adaKey);
+ expect(readers(), "Cleo's stay").toContain(cleoKey);
+ expect(readFileSync(dataDir("bot-orders.json"), "utf8"), "her order is gone").not.toContain(adaKey);
+ expect(readFileSync(dataDir("room-reads.json"), "utf8")).not.toContain(adaKey);
+ expect((await team.as(cleo, "GET", "/api/notifications")).status).toBe(200);
+}, hostTimeout(90_000));
diff --git a/server/host/person-bot-order.test.ts b/server/host/person-bot-order.test.ts
new file mode 100644
index 0000000000..eb8c6bae36
--- /dev/null
+++ b/server/host/person-bot-order.test.ts
@@ -0,0 +1,43 @@
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+
+import { createPersonBotOrder } from "./person-bot-order.ts";
+
+const fleet = (...ids: string[]) => ids.map((id) => ({ id }));
+const ids = (bots: ReadonlyArray<{ id: string }>) => bots.map((bot) => bot.id);
+
+it("keeps each person's own order across a restart, and the team's for whoever has none", () => {
+ const dir = mkdtempSync(join(tmpdir(), "bot-orders-"));
+ const orders = createPersonBotOrder(dir);
+ expect(ids(orders.reorder("p_ada", fleet("a", "b", "c"), ["c", "a"]))).toEqual(["c", "b", "a"]);
+ expect(ids(createPersonBotOrder(dir).ordered("p_ada", fleet("a", "b", "c")))).toEqual(["c", "b", "a"]);
+ expect(ids(orders.ordered("p_cleo", fleet("a", "b", "c")))).toEqual(["a", "b", "c"]);
+ // The team's order changing moves nothing she ordered; a new bot takes its place in the team's.
+ expect(ids(orders.ordered("p_ada", fleet("d", "b", "a", "c")))).toEqual(["d", "c", "b", "a"]);
+ // A later reorder of a few starts from her own list.
+ expect(ids(orders.reorder("p_ada", fleet("d", "b", "a", "c"), ["a", "b"]))).toEqual(["d", "c", "a", "b"]);
+ orders.forgetPerson("p_ada");
+ expect(ids(createPersonBotOrder(dir).ordered("p_ada", fleet("a", "b", "c")))).toEqual(["a", "b", "c"]);
+});
+
+it("sends a team order frame as each person's own list", () => {
+ const orders = createPersonBotOrder(mkdtempSync(join(tmpdir(), "bot-orders-")));
+ orders.reorder("p_ada", fleet("a", "b"), ["b", "a"]);
+ expect(orders.ownOrderFrame("p_ada", { kind: "bots.order", botIds: ["a", "b", "c"] })).toEqual({ kind: "bots.order", botIds: ["b", "a", "c"] });
+ expect(orders.ownOrderFrame("p_ada", { kind: "bots.order", botIds: ["b", "a"] }), "already hers").toBeNull();
+ expect(orders.ownOrderFrame("p_cleo", { kind: "bots.order", botIds: ["a", "b"] })).toBeNull();
+ expect(orders.ownOrderFrame("p_ada", { kind: "bot", bot: {} })).toBeNull();
+});
+
+it("orders a User's own list only, never an admin's, and sends each stream its own", () => {
+ const orders = createPersonBotOrder(mkdtempSync(join(tmpdir(), "bot-orders-")));
+ const session = (scopes: string[]) => ({ kind: "session", scopes, session: { id: "s", email: "[email protected]" } }) as never;
+ const ada = orders.personOf(session(["client"]))!;
+ expect(orders.personOf(session(["admin", "client"])), "an admin's order is the team's").toBeNull();
+ orders.reorder(ada, fleet("a", "b"), ["b", "a"]);
+ const frame = { kind: "bots.order", botIds: ["a", "b"] };
+ expect(orders.streamFrame({ person: { id: "", email: "[email protected]" }, admin: false }, frame)).toEqual({ kind: "bots.order", botIds: ["b", "a"] });
+ expect(orders.streamFrame({ person: { id: "", email: "[email protected]" }, admin: true }, frame)).toBeNull();
+});
diff --git a/server/host/person-bot-order.ts b/server/host/person-bot-order.ts
new file mode 100644
index 0000000000..39ca56dbc2
--- /dev/null
+++ b/server/host/person-bot-order.ts
@@ -0,0 +1,69 @@
+// The order of a Team Cloud's bots is each person's own (`bot-orders.json`): a User's reorder changes only their list.
+// Whoever has never ordered theirs sees the team's order, the one an Owner or Admin sets (the fleet's own order).
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { z } from "zod";
+
+import { reorderStable } from "../../shared/bot-order.ts";
+import { writeFileAtomic } from "../atomic.ts";
+import { personKey } from "../person-key.ts";
+import type { RequestAuth } from "../request-auth.ts";
+
+const BOT_ORDERS_FILE = "bot-orders.json";
+const fileSchema = z.object({ version: z.literal(1), orders: z.record(z.string(), z.array(z.string())) });
+
+export function createPersonBotOrder(dataDir: string) {
+ const file = join(dataDir, BOT_ORDERS_FILE);
+ let orders: Record<string, string[]> = {};
+ try {
+ const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));
+ if (parsed.success) orders = parsed.data.orders;
+ else console.warn(`bot orders: ${file} is not a bot orders file; starting fresh`);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.warn(`bot orders: ${file} is unreadable; starting fresh`);
+ }
+ const save = () => {
+ try {
+ writeFileAtomic(file, `${JSON.stringify({ version: 1, orders })}\n`, { mode: 0o600 });
+ } catch (error) {
+ console.warn(`bot orders: could not save ${file}: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ };
+ /** The team's bots as this person orders them: the bots they ordered keep their order among the places those bots hold
+ * in the team's; a bot made since keeps its place in the team's. */
+ function ordered<T extends { id: string }>(person: string, bots: readonly T[]): T[] {
+ const own = orders[person];
+ return own ? reorderStable(bots, own) : [...bots];
+ }
+ /** A `bots.order` frame as this person's own list; null when it is theirs as it is. */
+ function ownOrderFrame(person: string, payload: Record<string, unknown>): Record<string, unknown> | null {
+ if (payload.kind !== "bots.order" || !orders[person] || !Array.isArray(payload.botIds)) return null;
+ const botIds = payload.botIds.filter((id): id is string => typeof id === "string");
+ const own = ordered(person, botIds.map((id) => ({ id }))).map((bot) => bot.id);
+ return own.every((id, index) => id === botIds[index]) ? null : { ...payload, botIds: own };
+ }
+ return {
+ ordered,
+ /** A stable partial reorder of this person's own list (shared/bot-order.ts); the whole list is kept as theirs. */
+ reorder<T extends { id: string }>(person: string, bots: readonly T[], botIds: readonly string[]): T[] {
+ const next = reorderStable(ordered(person, bots), botIds);
+ orders[person] = next.map((bot) => bot.id);
+ save();
+ return next;
+ },
+ ownOrderFrame,
+ /** Whose own order a request reads and writes: a User's; null for an Owner's or Admin's, whose order is the team's. */
+ personOf: (auth: RequestAuth): string | null => (auth.kind === "session" && !auth.scopes.includes("admin") ? personKey(auth.session) : null),
+ /** A `bots.order` frame as a User's stream should get it; null when it goes as it is (an admin's stream included). */
+ streamFrame(client: { person?: { id: string; email?: string }; admin: boolean }, payload: Record<string, unknown>): Record<string, unknown> | null {
+ return client.person && !client.admin ? ownOrderFrame(personKey(client.person), payload) : null;
+ },
+ forgetPerson(person: string): void {
+ if (!orders[person]) return;
+ delete orders[person];
+ save();
+ },
+ };
+}
+
+export type PersonBotOrder = ReturnType<typeof createPersonBotOrder>;
diff --git a/server/host/room-reads.test.ts b/server/host/room-reads.test.ts
index 19b2be883c..e7425dc923 100644
--- a/server/host/room-reads.test.ts
+++ b/server/host/room-reads.test.ts
@@ -3,7 +3,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it } from "vitest";
-import { createRoomReads, roomUnreadFor } from "./room-reads.ts";
+import { personKey } from "../person-key.ts";
+import { createPersonRooms, createRoomReads, roomUnreadFor } from "./room-reads.ts";
const path = [{ id: "m1", role: "user" }, { id: "m2", role: "bot" }, { id: "m3", role: "user" }];
@@ -49,3 +50,38 @@ it("forgets a person's lines in every room, and one person's line in one room",
const reloaded = createRoomReads(dir);
expect([reloaded.readUpTo("a", "p_ada"), reloaded.readUpTo("b", "p_ada")]).toEqual([undefined, undefined]);
});
+
+it("reads a bot's shared chat per person, leaves a private chat's one mark alone, and marks unread before the newest reply", () => {
+ const dir = mkdtempSync(join(tmpdir(), "room-reads-"));
+ const thread = [{ id: "m1", role: "user" }, { id: "m2", role: "bot" }, { id: "m3", role: "user" }, { id: "m4", role: "bot" }];
+ const frames: Array<{ person: string }> = [];
+ const rooms = createPersonRooms({
+ reads: createRoomReads(dir),
+ store: () => ({ activePath: () => thread, messagesFor: () => thread, botByThread: () => ({ id: "scout" }) }),
+ shared: (threadId) => threadId === "main",
+ wireBot: (id) => ({ id }),
+ newestMessageId: () => "m4",
+ publicGroupState: (room) => room as never,
+ broadcast: (_payload, options) => frames.push(options),
+ });
+ const ada = { kind: "session", session: { id: "s1", email: "[email protected]" } } as never;
+ const adaKey = personKey({ id: "", email: "[email protected]" }), cleoKey = personKey({ id: "", email: "[email protected]" });
+ const main = { threadId: "main", unread: true, lastReadMessageId: "m2" };
+ expect(rooms.taskForPerson(main, cleoKey), "never read: the chat's own mark, without anyone's read line").toEqual({ threadId: "main", unread: true });
+ expect(rooms.personMarkThread!(ada, "main", false)).toBe(true);
+ expect(rooms.taskForPerson(main, adaKey)).toEqual({ threadId: "main", unread: false, lastReadMessageId: "m4" });
+ expect(rooms.taskForPerson(main, cleoKey).unread).toBe(true);
+ expect(frames, "told to Ada's streams alone").toEqual([{ person: adaKey }]);
+ expect(rooms.personMarkThread!(ada, "main", true)).toBe(true);
+ expect(rooms.taskForPerson(main, adaKey)).toEqual({ threadId: "main", unread: true, lastReadMessageId: "m3" });
+ const own = { threadId: "mine", unread: true, lastReadMessageId: "m2" };
+ expect(rooms.personMarkThread!(ada, "mine", false), "a private chat keeps its one mark").toBe(false);
+ expect(rooms.taskForPerson(own, adaKey)).toBe(own);
+});
+
+it("forgets a person's other marks of their own with their read lines", () => {
+ const forgotten: string[] = [];
+ const reads = createRoomReads(mkdtempSync(join(tmpdir(), "room-reads-")), (person) => forgotten.push(person));
+ reads.forgetPerson("p_ada");
+ expect(forgotten, "even with no read line of theirs").toEqual(["p_ada"]);
+});
diff --git a/server/host/room-reads.ts b/server/host/room-reads.ts
index af4002c6ad..48e323aa9e 100644
--- a/server/host/room-reads.ts
+++ b/server/host/room-reads.ts
@@ -1,5 +1,6 @@
-// A Team Cloud's group chats are read per person: each person's own "read up to" line in each room
-// (`room-reads.json`), so one person opening a room clears its unread mark for nobody else.
+// A Team Cloud's conversations that several people read are read per person: each person's own "read up to" line in
+// each room and in each bot's shared chat (`room-reads.json`), so one person reading one clears its unread mark for nobody
+// else.
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { z } from "zod";
@@ -31,7 +32,9 @@ export function roomUnreadFor(path: readonly PathMessage[], readUpTo: string | u
return path.slice(from).some(isReply);
}
-export function createRoomReads(dataDir: string) {
+/** `alsoForget`: a person's other marks of their own (their bots' order, their notification reads), which go with
+ * their read lines when they leave the team. */
+export function createRoomReads(dataDir: string, alsoForget?: (person: string) => void) {
const file = join(dataDir, ROOM_READS_FILE);
let reads: Record<string, Record<string, string>> = {};
try {
@@ -66,6 +69,7 @@ export function createRoomReads(dataDir: string) {
save();
},
forgetPerson(person: string): void {
+ alsoForget?.(person);
const rooms = Object.values(reads).filter((room) => room[person] !== undefined);
if (!rooms.length) return;
for (const room of rooms) delete room[person];
@@ -76,6 +80,9 @@ export function createRoomReads(dataDir: string) {
export type RoomReads = ReturnType<typeof createRoomReads>;
+/** A bot's shared conversation's key in `room-reads.json`, apart from every room's id. */
+export const threadReadKey = (threadId: string) => `thread:${threadId}`;
+
/** One stream frame's `group` payload as a person's own room, built once per person for that frame; null: theirs is the
* room as it is. */
export type OwnGroupFrames = Map<string, { payload: Record<string, unknown>; frame: string } | null>;
@@ -83,7 +90,11 @@ export type OwnGroupFrames = Map<string, { payload: Record<string, unknown>; fra
export interface PersonRoomsDeps {
/** Each person's own read line in each room, on a Team Cloud; null anywhere else, where a room reads the same for all. */
reads: RoomReads | null;
- store(): { activePath(threadId: string): readonly PathMessage[]; messagesFor(threadId: string): readonly PathMessage[] };
+ store(): { activePath(threadId: string): readonly PathMessage[]; messagesFor(threadId: string): readonly PathMessage[]; botByThread(threadId: string): { id: string } | null | undefined };
+ /** A bot's conversation more than one person reads (the team's, not someone's private chat). */
+ shared(threadId: string): boolean;
+ /** A bot as its `bot` frame carries it. */
+ wireBot(botId: string): object | null;
/** The newest message on a conversation's path, the line a room is read up to. */
newestMessageId(threadId: string): string | undefined;
publicGroupState(room: GroupRecord): WireGroup;
@@ -93,18 +104,35 @@ export interface PersonRoomsDeps {
/** Each person's view of a room (server/index.ts): its unread mark and read line as they read it, on a Team Cloud. */
export function createPersonRooms(deps: PersonRoomsDeps) {
const { reads } = deps;
+ const atOf = (threadId: string) => (id: string) => deps.store().messagesFor(threadId).find((message) => message.id === id)?.at;
/** A room's unread mark and read line as this person has read it, on a Team Cloud; the room as it is anywhere else. */
function groupForPerson(group: WireGroup, person: string | null): WireGroup {
if (!reads || !person) return group;
const readUpTo = reads.readUpTo(group.id, person);
- const unread = roomUnreadFor(deps.store().activePath(group.threadId), readUpTo, group.unread, (id) => deps.store().messagesFor(group.threadId).find((message) => message.id === id)?.at);
+ const unread = roomUnreadFor(deps.store().activePath(group.threadId), readUpTo, group.unread, atOf(group.threadId));
if (unread === group.unread && readUpTo === group.lastReadMessageId) return group;
const { lastReadMessageId: _shared, ...rest } = group;
return { ...rest, unread, ...(readUpTo ? { lastReadMessageId: readUpTo } : {}) };
}
+ /** A bot's shared conversation's unread mark and read line as this person read it, on a Team Cloud; the task as it is
+ * anywhere else and for a private chat. Nobody's read line but their own goes out. */
+ function taskForPerson<T extends { threadId: string; unread?: boolean; lastReadMessageId?: string }>(task: T, person: string): T {
+ if (!reads || !deps.shared(task.threadId)) return task;
+ const readUpTo = reads.readUpTo(threadReadKey(task.threadId), person);
+ const unread = roomUnreadFor(deps.store().activePath(task.threadId), readUpTo, task.unread === true, atOf(task.threadId));
+ if (unread === (task.unread === true) && readUpTo === task.lastReadMessageId) return task;
+ const { lastReadMessageId: _shared, ...rest } = task;
+ return { ...rest, unread, ...(readUpTo ? { lastReadMessageId: readUpTo } : {}) } as T;
+ }
return {
reads,
groupForPerson,
+ taskForPerson,
+ /** A deleted room's or conversation's read lines go with it. */
+ forgetDeleted(change: { type: string; groupId?: string; threadId?: string }): void {
+ if (change.type === "group.deleted" && change.groupId) reads?.forgetRoom(change.groupId);
+ else if (change.type === "thread.deleted" && change.threadId) reads?.forgetRoom(threadReadKey(change.threadId));
+ },
groupForAuth: (auth: RequestAuth, group: WireGroup): WireGroup => groupForPerson(group, auth.kind === "session" ? personKey(auth.session) : null),
/** A `group` frame as `person`'s own room (`frameOf` writes the stream's frame for a payload), kept in `ownGroups` for
* the rest of that frame's streams; null when it is the room as it is. */
@@ -129,6 +157,23 @@ export function createPersonRooms(deps: PersonRoomsDeps) {
const group = deps.publicGroupState(room);
deps.broadcast({ kind: "group", group }, { person });
return groupForPerson(group, person);
+ },
+ /** Marks a bot's shared conversation read or unread for the person signed in, told to their streams alone; false for
+ * a private chat, which keeps its one mark. Unread reads up to just before the conversation's newest reply. */
+ personMarkThread: (auth: RequestAuth, threadId: string, unread: boolean): boolean => {
+ if (auth.kind !== "session" || !deps.shared(threadId)) return false;
+ const person = personKey(auth.session), key = threadReadKey(threadId);
+ if (unread) {
+ const path = deps.store().activePath(threadId), reply = path.findLastIndex(isReply);
+ if (reply > 0) reads.read(key, person, path[reply - 1]!.id);
+ else reads.forget(key, person);
+ } else {
+ const newest = deps.newestMessageId(threadId);
+ if (newest) reads.read(key, person, newest);
+ }
+ const bot = deps.store().botByThread(threadId), frame = bot ? deps.wireBot(bot.id) : null;
+ if (frame) deps.broadcast({ kind: "bot", bot: frame }, { person });
+ return true;
} } : {}),
};
}
diff --git a/server/index.ts b/server/index.ts
index 263279a855..fec9794c80 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -236,7 +236,7 @@ import { createOneOnOneGoals } from "./host/one-on-one-goals.ts";
import { BUILT_IN_DRIVERS } from "./drivers/builtIn.ts";
import { openCodeProviderKeysAllowed, setOpenCodeProviderKeyPolicy } from "./drivers/acp/opencode-go.ts";
-import { liveAppRows, openCardRows, readMessageText, recallMessages, recentMessages, closeMessageSearch, closeMessageDb, chatFollowups, cancelledChatFollowup, settleChatFollowups, threadsReferencing, logNotification, lastRowAt, threadsWithCardsSince } from "./message-db.ts";
+import { forgetNotificationReader, liveAppRows, openCardRows, readMessageText, recallMessages, recentMessages, closeMessageSearch, closeMessageDb, chatFollowups, cancelledChatFollowup, settleChatFollowups, threadsReferencing, logNotification, lastRowAt, threadsWithCardsSince } from "./message-db.ts";
import { briefCrossingLabel, claimRecallCrossings, recallCrossingLabel } from "./recall-disclosure.ts";
import { parseSince, parseUntil, recentWork, recentWorkPrompt, turnOutcomeLine } from "./recent-work.ts";
import { chiefEscalationsEnabled, NEEDS_INPUT_GATE, peerApprovalGate, RAISED_GATE } from "./escalations.ts";
@@ -281,7 +281,7 @@ import { botBox, startBotBoxAtBoot } from "./bot-box/boot.ts"; import { attachme
import { createCloudSignedHost } from "./host/cloud-signed-host.ts"; import { createBotNameClash } from "./host/bot-name-clash.ts"; import { hiddenThreadRefusal, hideOthersSyncFolders } from "./host/team-private.ts"; import { createTeamMemberLeft } from "./host/team-member-left.ts"; import { createUploadOwners, uploadsFor } from "./host/member-uploads.ts"; import { createMemberOwnBot } from "./host/member-own-bot.ts"; import { createVisibilityHost } from "./host/visibility-host.ts"; import { createBotAccessHost, refusalFor, relayedSendRefusal } from "./host/bot-access-gate.ts"; import { createBotAccessRoutes, writeAccess } from "./routes/bot-access.ts"; import { createAccessRequests } from "./host/access-requests.ts";
import { cloudPowerNow, createCloudPower, registerCloudPower, wokeFromSleep, type CloudPower } from "./cloud-power.ts"; import { createWokeNotifier } from "./cloud-woke.ts"; import { createSharedComputerRoutes } from "./routes/shared-computers.ts";
import { lentCopies, noteSyncBotTurn } from "./routes/cloud-sync.ts"; import { mcpReconnectLine, retryBrokeredMcp } from "./bot-box/broker-mcp.ts";
-import { type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts";
+import { type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createPersonBotOrder } from "./host/person-bot-order.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts";
import { createCloudMoveRoutes } from "./cloud-move-http.ts";
import { RESTART_EXIT_CODE } from "./restart.ts";
import { applyIncludedXMessage, holdIncludedServices, researchCredential, trialCreditCredential, xCredential, xResearchStatus } from "./included-services.ts"; import { createResearchAvailability } from "./research.ts";
@@ -563,7 +563,7 @@ import {
} from "./admin-activity.ts";
import {
frameForMember,
- memberBody, memberFramePayload,
+ memberBody, memberBot, memberFramePayload,
noteSeen,
notFoundFor,
pathSubject,
@@ -959,7 +959,8 @@ let cloudEarlierOwners: Pick<CloudOwnership, "adopted" | "proven"> = { adopted:
let cloudHome: ReturnType<typeof settleCloudHome> | null = null; const teamHost = createCloudTeamHost({ team: CLOUD_TEAM, dataDir: DATA_DIR, store: { groupByThread: (threadId) => store.groupByThread(threadId), get bots() { return store.bots; } }, engineHomes, starters: threadStarters, markers: new Set([CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY]), language: appLanguage,
serverProfile: { read: () => cfg.profile, clear: () => { adminActorScope.exit(() => saveConfig({ profile: { name: "", email: "", aboutMe: "", avatarUrl: "" } })); Object.assign(cfg, loadConfig()); } } });
const teamOwners = createTeamOwners({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store: () => store, audienceOf: (threadId) => teamHost.audienceOf(threadId), starters: threadStarters }); const mausbotOwnChat = createMausBotOwnChat({ bots: () => store.bots, starters: threadStarters, personKey: (email) => personKey({ id: "", email }), moveNotes: (from, to, person) => moveMemoryLayer(from, to, personLanguages.forLine(person)) });
-const personRooms = createPersonRooms({ reads: CLOUD_TEAM ? createRoomReads(DATA_DIR) : null, store: () => store, newestMessageId: (threadId) => readCursor(threadId).lastReadMessageId, publicGroupState, broadcast });
+const personRooms = createPersonRooms({ reads: CLOUD_TEAM ? createRoomReads(DATA_DIR, (person) => { botOrders?.forgetPerson(person); forgetNotificationReader(person); }) : null, store: () => store, newestMessageId: (threadId) => readCursor(threadId).lastReadMessageId, publicGroupState, broadcast, shared: (threadId) => teamHost.privateTo(threadId) === null, wireBot: (botId) => { const bot = store.bot(botId); return bot ? wireBot(bot) : null; } });
+const botOrders = CLOUD_TEAM ? createPersonBotOrder(DATA_DIR) : null;
function actorKey(auth: RequestAuth & { kind: "session" }): string {
return CLOUD_OWNER_KEY && auth.scopes.includes("admin") ? CLOUD_OWNER_KEY : personKey(auth.session);
@@ -1139,7 +1140,7 @@ async function answeringCardAs(auth: RequestAuth, threadId: string, requestId: s
}
const { viewerFor, threadOwner, visibleTo, forgetVisibility, threadShown, subjectVisible, hiddenRoutineTarget, roomFeedsBot, settleRoomFloor } = createVisibilityHost({ store: () => store, routines: () => routines,
- team: Boolean(CLOUD_TEAM), audiencesFor: (viewer) => teamHost.audiencesFor(viewer), threadsReferencing }); if (CLOUD_TEAM) hideOthersSyncFolders(() => store.bots, threadShown); const notificationListed = notificationListedFor(threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined); const botAccess = createBotAccessHost({ visibleFor: (auth) => visibleTo(viewerFor(auth)), store: () => store, routines: () => routines, threadOwner, routineWriter: (id) => cloudRoutineAuthors?.writer(id) }), { levelOf } = botAccess; const accessRequests = createAccessRequests({ team: CLOUD_TEAM, store: () => store, people: () => teamOwners.people?.list() ?? [], profileName: (email) => teamHost.people.profile(personKey({ id: "", email })).name, inbox: () => teamMessages.inbox, visibleTo, levelOf, writeAccess: (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access), record: (row, by) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: by, email: by } }) });
+ team: Boolean(CLOUD_TEAM), audiencesFor: (viewer) => { const audiences = teamHost.audiencesFor(viewer), person = audiences?.person; return audiences && person ? { ...audiences, ownTask: (task) => personRooms.taskForPerson(task, person) } : audiences; }, threadsReferencing }); if (CLOUD_TEAM) hideOthersSyncFolders(() => store.bots, threadShown); const notificationListed = notificationListedFor(threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined, CLOUD_TEAM ? (auth) => (auth.kind === "session" ? personKey(auth.session) : null) : undefined); const botAccess = createBotAccessHost({ visibleFor: (auth) => visibleTo(viewerFor(auth)), store: () => store, routines: () => routines, threadOwner, routineWriter: (id) => cloudRoutineAuthors?.writer(id) }), { levelOf } = botAccess; const accessRequests = createAccessRequests({ team: CLOUD_TEAM, store: () => store, people: () => teamOwners.people?.list() ?? [], profileName: (email) => teamHost.people.profile(personKey({ id: "", email })).name, inbox: () => teamMessages.inbox, visibleTo, levelOf, writeAccess: (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access), record: (row, by) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: by, email: by } }) });
function recentWorkFilter(threadId: string): { include?: (threadId: string) => boolean; privateThread?: (threadId: string) => boolean } {
const include = CLOUD_TEAM ? (id: string) => teamHost.readableFrom(threadId)(id) && outsideLineage.mayReach(id, threadId) : CLOUD_HOME ? cloudOwnerOnlyThread : () => true; return { include: (id) => !botApiThread(id) && include(id), ...(CLOUD_TEAM ? { privateThread: (id: string) => teamHost.privateTo(id) !== null } : {}) };
@@ -4514,7 +4515,7 @@ function pageIfThreadChanged(id: string, threadId: string) {
}
store.onChange((change) => {
if (change.type !== "message" && change.type !== "message.patch" && change.type !== "thread" && change.type !== "sections") forgetVisibility();
- if (change.type === "group.deleted") personRooms.reads?.forgetRoom(change.groupId);
+ personRooms.forgetDeleted(change);
switch (change.type) {
case "sections":
broadcast({ kind: "sections", sections: store.sections });
@@ -4765,6 +4766,7 @@ const streamFor = (client: SseClient, person: string | undefined) => !person ||
function memberFrame(client: SseClient, seq: number, payload: Record<string, unknown>, clientFrame: string | null, ownGroups: OwnGroupFrames = new Map()): string | null {
const own = client.person && clientFrame !== null ? personRooms.ownGroupFrame(ownGroups, personKey(client.person), payload, (mine) => `id: ${STREAM_ID}:${seq}\ndata: ${JSON.stringify({ ...mine, seq })}\n\n`) : null;
if (own) { payload = own.payload; clientFrame = own.frame; }
+ const order = clientFrame === null ? null : botOrders?.streamFrame(client, payload); if (order) { payload = order; clientFrame = `id: ${STREAM_ID}:${seq}\ndata: ${JSON.stringify({ ...order, seq })}\n\n`; }
const visible = visibleTo(client.viewer);
if (clientFrame === null || (client.viewer.kind === "all" && !visible.filtersThreads)) return clientFrame;
if (visible.everything) {
@@ -12135,7 +12137,7 @@ const { react } = createReactions({
const publishedPages = createPublishedPages({ dataDir: DATA_DIR, cloudHome: CLOUD_HOME, selfHosted: !CLOUD_HOME && !HOSTED_WORKSPACE && utilityParentPort === undefined, patch: (threadId, messageId, text, publishedPage) => void store.patchMessage(threadId, messageId, { text, publishedPage }), liveRoots: (botId, threadId) => liveRoots(threadId, botId), paused: () => workspaceMaintenance.active || moveFreeze.frozen(), apps: { chat: chatApps, store } }); ROUTES.push(createReactionRoutes({ react, reactorFor, cloudGuestSendRefusal }), publishedPages.routes, savedSteps.routes, createPlacesElsewhereRoutes({ elsewhere: placesElsewhere, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (auth.kind === "loopback" || ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }));
// `let` slots are read per request.
ROUTES.push(createThreadRoutes({
- groupFor: personRooms.groupForAuth,
+ groupFor: personRooms.groupForAuth, ...(botOrders ? { botOrderFor: (auth: RequestAuth, bots: readonly BotRecord[]) => { const person = botOrders.personOf(auth); return person ? botOrders.ordered(person, bots) : bots; } } : {}),
store, userName: userNameFor, sessions, groupUsageReader, lendingEnabled,
hostedWorkspace: HOSTED_WORKSPACE, sessionCookie: SESSION_COOKIE, loopback: LOOPBACK, defaultPage: DEFAULT_PAGE,
workspaceAccess: () => workspaceAccess,
@@ -12164,16 +12166,16 @@ ROUTES.push(createBotSettingsRoutes({
cloudHome: Boolean(CLOUD_HOME), cloudOwnerProfileFields: CLOUD_OWNER_PROFILE_FIELDS,
hostedModels, supportsApprovalMode, directTurnBots, broadcast, notificationListed, wireBot, cloudOwnerSession, storedAvatarExists,
requestedTaskBot, threadBusy, activeGroupTurnForBot, checkedModelSelection, engineSwitchNeedsAsk, readCursor,
- canManageCommandAllowlist, commandAllowlistResponse, cardAnswerRefusal, threadRead: teamMessages.seen, levelOf,
+ canManageCommandAllowlist, commandAllowlistResponse, cardAnswerRefusal, threadRead: teamMessages.seen, levelOf, personMarkThread: personRooms.personMarkThread,
}));
-ROUTES.push(createBotOrderRoutes({ store, visibleFor: (auth) => visibleTo(viewerFor(auth)) }), createBotAccessRoutes({ team: CLOUD_TEAM, people: teamOwners.people, store, levelOf, wireBot, publicGroupState, broadcast, audienceChanged, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), accessRequests.routes);
+ROUTES.push(createBotOrderRoutes({ store, visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(botOrders ? { own: { person: botOrders.personOf, order: botOrders, told: (person, botIds) => broadcast({ kind: "bots.order", botIds }, { person }) } } : {}) }), createBotAccessRoutes({ team: CLOUD_TEAM, people: teamOwners.people, store, levelOf, wireBot, publicGroupState, broadcast, audienceChanged, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), accessRequests.routes);
ROUTES.push(createBotPatchRoutes({
store, cfg, registry, sessions, browserRuntime, browserLive, memoryUpkeep, cacheKeepWarm, hostedModels, supportsApprovalMode,
routines: () => routines, activeVpsThreads,
hostedWorkspace: HOSTED_WORKSPACE, hostedFullAccessRefusal: HOSTED_FULL_ACCESS_REFUSAL, desktopManaged: DESKTOP_MANAGED, maxWorkspaceBots: MAX_WORKSPACE_BOTS,
broadcast, wireBot, publicGroupState, audienceChanged, storedAvatarExists, requestedTaskBot, threadBusy, activeGroupTurnForBot,
checkedModelSelection, engineSwitchNeedsAsk, currentBrowserSession, interruptAllDirectThreads, cancelGroupTurnOperations,
- revokeInternalCapabilitiesForThread, runningTurnInstance, closeOpenApprovals, assertTeamComputerChangeIdle, forgetTemporaryBrowser, levelOf, team: Boolean(CLOUD_TEAM), mainThreadTasks,
+ revokeInternalCapabilitiesForThread, runningTurnInstance, closeOpenApprovals, assertTeamComputerChangeIdle, forgetTemporaryBrowser, levelOf, team: Boolean(CLOUD_TEAM), mainThreadTasks, ...(personRooms.personMarkThread ? { personMarkThread: personRooms.personMarkThread, shownThread: (auth: RequestAuth, bot: BotRecord) => memberBot(wireBot(bot), visibleTo(viewerFor(auth))).threadId } : {}),
}));
ROUTES.push(createBotLifecycleRoutes({
store, routines: () => routines, interruptAllDirectThreads, cancelDirectTurnDispatch, revokeInternalCapabilitiesForThread,
@@ -12218,7 +12220,7 @@ ROUTES.push(createBotMemoryRoutes({
}));
const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
-ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (auth, threadId) => { if (ownerOrAdmin(auth) && store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),
+ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),
createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) }));
ROUTES.push(createRoomHoldRoutes({
group: (id) => store.group(id),
diff --git a/server/message-db.ts b/server/message-db.ts
index 8c74d95d38..14ca989c0c 100644
--- a/server/message-db.ts
+++ b/server/message-db.ts
@@ -99,7 +99,7 @@ function open(): DatabaseSync {
CREATE INDEX IF NOT EXISTS notification_log_at ON notification_log(at);
`);
const notificationColumns = db.prepare("PRAGMA table_info(notification_log)").all() as Array<{ name: string }>;
- if (!notificationColumns.some((column) => column.name === "for_person")) db.exec("ALTER TABLE notification_log ADD COLUMN for_person TEXT");
+ for (const added of ["for_person", "read_by"]) if (!notificationColumns.some((column) => column.name === added)) db.exec(`ALTER TABLE notification_log ADD COLUMN ${added} TEXT`);
ensureRecallIndex(db);
ensureMemoryIndex(db);
return db;
@@ -321,16 +321,17 @@ export function logNotification(notification: Notification): NotificationLogEntr
return entry;
}
-export function recentNotificationLog(limit = NOTIFICATION_LOG_LIMIT): NotificationLogEntry[] {
- const rows = db().prepare(
- "SELECT id, at, kind, bot_id, bot_name, thread_id, group_id, title, body, avatar_url, for_person, read FROM notification_log ORDER BY at DESC, rowid DESC LIMIT ?",
- ).all(limit) as Array<Parameters<typeof rowToNotificationLogEntry>[0]>;
+export function recentNotificationLog(limit = NOTIFICATION_LOG_LIMIT, reader?: string): NotificationLogEntry[] {
+ const read = reader === undefined ? "read" : "(read = 1 OR EXISTS (SELECT 1 FROM json_each(coalesce(read_by, '[]')) WHERE value = ?)) AS read";
+ const rows = db().prepare(`SELECT id, at, kind, bot_id, bot_name, thread_id, group_id, title, body, avatar_url, for_person, ${read} FROM notification_log ORDER BY at DESC, rowid DESC LIMIT ?`)
+ .all(...(reader === undefined ? [] : [reader]), limit) as Array<Parameters<typeof rowToNotificationLogEntry>[0]>;
return rows.map(rowToNotificationLogEntry);
}
-
-export function markNotificationLogRead(ids: readonly string[]): void {
- db().prepare("UPDATE notification_log SET read = 1 WHERE read = 0 AND id IN (SELECT value FROM json_each(?))").run(JSON.stringify(ids));
+export function markNotificationLogRead(ids: readonly string[], reader?: string): void {
+ if (reader === undefined) db().prepare("UPDATE notification_log SET read = 1 WHERE read = 0 AND id IN (SELECT value FROM json_each(?))").run(JSON.stringify(ids));
+ else db().prepare("UPDATE notification_log SET read_by = json_insert(coalesce(read_by, '[]'), '$[#]', ?1) WHERE id IN (SELECT value FROM json_each(?2)) AND NOT EXISTS (SELECT 1 FROM json_each(coalesce(read_by, '[]')) WHERE value = ?1)").run(reader, JSON.stringify(ids));
}
+export function forgetNotificationReader(person: string): void { db().prepare("UPDATE notification_log SET read_by = (SELECT json_group_array(value) FROM json_each(read_by) WHERE value <> ?1) WHERE EXISTS (SELECT 1 FROM json_each(coalesce(read_by, '[]')) WHERE value = ?1)").run(person); }
export function saveChatFollowup(followup: Omit<ChatFollowup, "status">): void {
writeFollowups((connection) => connection.prepare(
diff --git a/server/routes/bot-order.ts b/server/routes/bot-order.ts
index acb92f559b..938e343844 100644
--- a/server/routes/bot-order.ts
+++ b/server/routes/bot-order.ts
@@ -1,16 +1,21 @@
import type { VisibleSet } from "../bot-visibility.ts";
import type { RequestAuth } from "../request-auth.ts";
+import type { PersonBotOrder } from "../host/person-bot-order.ts";
import type { Store } from "../store.ts";
import { PASS, type RouteHandler } from "./table.ts";
export interface BotOrderRouteDeps {
- store: Pick<Store, "bot" | "reorderBots">;
+ store: Pick<Store, "bot" | "bots" | "reorderBots">;
/** The same filter the GET /api/bots listing applies to this caller. */
visibleFor(auth: RequestAuth): VisibleSet;
+ /** A Team Cloud: a User's reorder is their own list, told to their streams alone; `person` is null for an Owner's or
+ * Admin's session, whose reorder is the team's order. */
+ own?: { person(auth: RequestAuth): string | null; order: PersonBotOrder; told(person: string, botIds: string[]): void };
}
-/** The fleet's order is one list every client shows (the desktop sidebar, a phone's roster). A reorder names only
- * the bots it moves (shared/bot-order.ts); the rest keep their places. */
+/** The fleet's order is one list every client shows (the desktop sidebar, a phone's roster); on a Team Cloud it is the
+ * team's, and a User's own list is theirs. A reorder names only the bots it moves (shared/bot-order.ts); the rest keep
+ * their places. */
export function createBotOrderRoutes(deps: BotOrderRouteDeps): RouteHandler {
const { store, visibleFor } = deps;
return async ({ req, res, path, method, auth, json, readBody }) => {
@@ -26,8 +31,11 @@ export function createBotOrderRoutes(deps: BotOrderRouteDeps): RouteHandler {
for (const id of botIds as string[]) {
if (!store.bot(id) || !visible.bot(id)) return json(res, 400, { error: `unknown bot: ${id}` });
}
- const bots = store.reorderBots(botIds as string[]);
+ const person = deps.own?.person(auth) ?? null;
+ const bots = person ? deps.own!.order.reorder(person, store.bots, botIds as string[]) : store.reorderBots(botIds as string[]);
if (!bots) return json(res, 400, { error: "botIds must be a non-empty array of distinct bot ids" });
- return json(res, 200, { botIds: bots.filter((bot) => visible.bot(bot.id)).map((bot) => bot.id) });
+ const shown = bots.filter((bot) => visible.bot(bot.id)).map((bot) => bot.id);
+ if (person) deps.own!.told(person, shown);
+ return json(res, 200, { botIds: shown });
};
}
diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.ts
index 439d7df0d7..efafb8fda4 100644
--- a/server/routes/bot-patch.ts
+++ b/server/routes/bot-patch.ts
@@ -79,6 +79,10 @@ export interface BotPatchRouteDeps {
team: boolean;
/** The bot's conversations the main-thread resolver may pick: a Team Cloud keeps only team-visible ones. */
mainThreadTasks(botId: string): readonly TaskRecord[];
+ /** A Team Cloud: marks a bot's shared conversation read or unread for this person alone; false for a private chat. */
+ personMarkThread?(auth: RequestAuth, threadId: string, unread: boolean): boolean;
+ /** The conversation this session sees the bot on (on a Team Cloud never someone else's private chat). */
+ shownThread?(auth: RequestAuth, bot: BotRecord): string;
}
export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {
@@ -127,6 +131,10 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {
}
const existingBot = store.bot(m[1]); const defaultBotRefused = defaultBotPatchRefusal(existingBot, body);
if (defaultBotRefused) return json(res, 400, { error: defaultBotRefused });
+ if (existingBot && typeof body.unread === "boolean" && deps.shownThread && deps.personMarkThread?.(auth, deps.shownThread(auth, existingBot), body.unread)) {
+ delete body.unread;
+ if (!Object.keys(body).length) return json(res, 200, { bot: wireBot(existingBot) });
+ }
const rawSelection = (body as Record<string, unknown>).modelSelection;
if (body.threadId !== undefined && rawSelection === undefined) {
return json(res, 400, { error: "threadId goes with modelSelection" });
diff --git a/server/routes/bot-settings.ts b/server/routes/bot-settings.ts
index 47a2a15c1f..8df70baf17 100644
--- a/server/routes/bot-settings.ts
+++ b/server/routes/bot-settings.ts
@@ -51,6 +51,9 @@ export interface BotSettingsRouteDeps {
cardAnswerRefusal(auth: RequestAuth, threadId: string, requestId: string, behavior: string): string | null;
/** A person opened this conversation (a Team Cloud's Needs you lines for them there are done). */
threadRead?(auth: RequestAuth, threadId: string): void;
+ /** A Team Cloud: marks a bot's shared conversation read or unread for this person alone (host/room-reads.ts); false
+ * for a private chat, which keeps its one mark. */
+ personMarkThread?(auth: RequestAuth, threadId: string, unread: boolean): boolean;
}
export function createBotSettingsRoutes(deps: BotSettingsRouteDeps): RouteHandler {
@@ -167,6 +170,10 @@ export function createBotSettingsRoutes(deps: BotSettingsRouteDeps): RouteHandle
const current = requestedTaskBot(m[1], body?.threadId);
sawThread(current.threadId);
deps.threadRead?.(auth, current.threadId);
+ if (deps.personMarkThread?.(auth, current.threadId, false)) {
+ readThreadNotifications(current.threadId, broadcast, notificationListed(auth));
+ return json(res, 200, { bot: wireBot(store.bot(current.id)!) });
+ }
const task = store.taskByThread(current.id, current.threadId), cursor = readCursor(current.threadId);
const changed = Boolean(task?.unread) || (cursor.lastReadMessageId !== undefined && task?.lastReadMessageId !== cursor.lastReadMessageId);
if (changed) store.patchTask(current.id, current.threadId, { unread: false, ...cursor });
diff --git a/server/routes/notifications.test.ts b/server/routes/notifications.test.ts
index fce2fd241d..dd6294e4b8 100644
--- a/server/routes/notifications.test.ts
+++ b/server/routes/notifications.test.ts
@@ -4,7 +4,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { json, readBody } from "../harness/http.ts";
import type { NotificationLogEntry } from "../../shared/notification.ts";
-import { insertNotificationLog, recentNotificationLog } from "../message-db.ts";
+import { forgetNotificationReader, insertNotificationLog, markNotificationLogRead, recentNotificationLog } from "../message-db.ts";
import type { RequestAuth } from "../request-auth.ts";
import { createNotificationRoutes, notificationListedFor, readThreadNotifications } from "./notifications.ts";
import { dispatchRoutes } from "./table.ts";
@@ -90,6 +90,35 @@ describe("notification routes", () => {
expect(recentNotificationLog().filter((entry) => !entry.read).map((entry) => entry.id)).toEqual(["n3"]);
});
+ it("on a team, reads each entry as one person read it, marks it for them alone and tells only their streams", () => {
+ const team = { ...sample, threadId: "team-t" };
+ for (const id of ["a0", "a1", "a2"]) insertNotificationLog({ ...team, id });
+ markNotificationLogRead(["a0"]);
+ const auth: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };
+ const as = (person: string) => notificationListedFor(undefined, undefined, () => person)(auth);
+ const unreadFor = (person: string) => recentNotificationLog(undefined, person).filter((entry) => entry.threadId === "team-t" && !entry.read).map((entry) => entry.id).sort();
+ const broadcast = vi.fn();
+ markNotificationLogRead(["a1"], "p_ada");
+ expect(unreadFor("p_ada")).toEqual(["a2"]);
+ expect(unreadFor("p_cleo"), "a mark from before marks were each person's own stays read").toEqual(["a1", "a2"]);
+ readThreadNotifications("team-t", broadcast, as("p_cleo"));
+ expect(broadcast).toHaveBeenCalledExactlyOnceWith({ kind: "notifications.read", threadId: "team-t", ids: ["a2", "a1"] }, { person: "p_cleo" });
+ expect(unreadFor("p_cleo")).toEqual([]);
+ expect(unreadFor("p_ada")).toEqual(["a2"]);
+ expect(recentNotificationLog().filter((entry) => entry.threadId === "team-t" && !entry.read).map((entry) => entry.id).sort(), "the one mark is untouched").toEqual(["a1", "a2"]);
+ expect(Object.keys(recentNotificationLog(undefined, "p_ada")[0]!)).not.toContain("readBy");
+ });
+
+ it("forgets one person's read marks, a row they alone read included, and nobody else's", () => {
+ for (const id of ["f1", "f2"]) insertNotificationLog({ ...sample, id, threadId: "leave-t" });
+ markNotificationLogRead(["f1", "f2"], "p_ada");
+ markNotificationLogRead(["f2"], "p_cleo");
+ forgetNotificationReader("p_ada");
+ const unread = (person: string) => recentNotificationLog(undefined, person).filter((entry) => entry.threadId === "leave-t" && !entry.read).map((entry) => entry.id).sort();
+ expect(unread("p_ada")).toEqual(["f1", "f2"]);
+ expect(unread("p_cleo")).toEqual(["f1"]);
+ });
+
it("leaves other paths and methods to the next handler", async () => {
const { base, deps } = await serve();
expect((await fetch(`${base}/api/notifications`, { method: "POST" })).status).toBe(404);
diff --git a/server/routes/notifications.ts b/server/routes/notifications.ts
index 876aaaaaf5..da8a6e1086 100644
--- a/server/routes/notifications.ts
+++ b/server/routes/notifications.ts
@@ -4,47 +4,65 @@ import type { NotificationLogEntry } from "../../shared/notification.ts";
import { ownerOrAdmin, type RequestAuth } from "../request-auth.ts";
import { PASS, type RouteHandler } from "./table.ts";
-/** Opening a conversation reads the notifications its opener's list shows, so every open app's badge drops them too. */
-export function readThreadNotifications(threadId: string, broadcast: (payload: Record<string, unknown>) => void,
- listed: (entry: NotificationLogEntry) => boolean): void {
- const ids = recentNotificationLog().filter((entry) => entry.threadId === threadId && !entry.read && listed(entry)).map((entry) => entry.id);
+/** Whether an entry is in one request's list; `reader` is the person whose own read marks it reads and writes (a Team
+ * Cloud: `read_by` on the feed's row, never sent; a mark made before stays read), absent where an entry has one mark. */
+export type NotificationListing = ((entry: NotificationLogEntry) => boolean) & { reader?: string };
+
+/** Opening a conversation reads the notifications its opener's list shows, so every open app of theirs drops them too:
+ * on a Team Cloud only the opener's. */
+export function readThreadNotifications(threadId: string, broadcast: (payload: Record<string, unknown>, options?: { person?: string }) => void,
+ listed: NotificationListing): void {
+ const { reader } = listed;
+ const ids = recentNotificationLog(undefined, reader).filter((entry) => entry.threadId === threadId && !entry.read && listed(entry)).map((entry) => entry.id);
if (!ids.length) return;
- markNotificationLogRead(ids);
- broadcast({ kind: "notifications.read", threadId, ids });
+ const payload = { kind: "notifications.read", threadId, ids };
+ if (reader === undefined) {
+ markNotificationLogRead(ids);
+ broadcast(payload);
+ } else {
+ markNotificationLogRead(ids, reader);
+ broadcast(payload, { person: reader });
+ }
}
/** Whether a notification is in a request's own list. `shown`: on a Team Cloud another person's private chat's
- * notifications are theirs alone, an admin's list included. `reaches`: an ask only its person. */
+ * notifications are theirs alone, an admin's list included. `reaches`: an ask only its person. `reader`: on a Team Cloud
+ * the person signed in, whose read marks are their own. */
export function notificationListedFor(shown: (auth: RequestAuth) => (threadId: string) => boolean = () => () => true,
- reaches: (auth: RequestAuth, entry: NotificationLogEntry) => boolean = () => true) {
- return (auth: RequestAuth) => {
+ reaches: (auth: RequestAuth, entry: NotificationLogEntry) => boolean = () => true,
+ reader: (auth: RequestAuth) => string | null = () => null) {
+ return (auth: RequestAuth): NotificationListing => {
const seen = shown(auth);
const admin = ownerOrAdmin(auth);
- return (entry: NotificationLogEntry) => (entry.kind !== "spend" || admin) && (!entry.threadId || seen(entry.threadId)) && reaches(auth, entry);
+ const person = reader(auth);
+ const listed = (entry: NotificationLogEntry) => (entry.kind !== "spend" || admin) && (!entry.threadId || seen(entry.threadId)) && reaches(auth, entry);
+ return person === null ? listed : Object.assign(listed, { reader: person });
};
}
export type NotificationListed = ReturnType<typeof notificationListedFor>;
-export function createNotificationRoutes(deps = {
- recent: recentNotificationLog,
+export function createNotificationRoutes(deps: { recent(reader?: string): NotificationLogEntry[]; markRead(ids: readonly string[], reader?: string): void } = {
+ recent: (reader) => recentNotificationLog(undefined, reader),
markRead: markNotificationLogRead,
}, listed: NotificationListed = notificationListedFor()): RouteHandler {
- const visible = (auth: RequestAuth) => deps.recent().filter(listed(auth));
+ const visible = (listing: NotificationListing) => deps.recent(listing.reader).filter(listing);
+ const markRead = (ids: string[], reader: string | undefined) => (reader === undefined ? deps.markRead(ids) : deps.markRead(ids, reader));
return async ({ res, path, method, auth, json }) => {
if (method === "GET" && path === "/api/notifications") {
- return json(res, 200, { notifications: visible(auth) });
+ return json(res, 200, { notifications: visible(listed(auth)) });
}
if (method !== "POST") return PASS;
+ const listing = listed(auth);
if (path === "/api/notifications/read-all") {
- const unread = visible(auth).filter((entry) => !entry.read).map((entry) => entry.id);
- if (unread.length) deps.markRead(unread);
+ const unread = visible(listing).filter((entry) => !entry.read).map((entry) => entry.id);
+ if (unread.length) markRead(unread, listing.reader);
return json(res, 200, { ok: true });
}
const m = path.match(/^\/api\/notifications\/([\w-]+)\/read$/);
if (!m) return PASS;
- if (!visible(auth).some((entry) => entry.id === m[1])) return json(res, 404, userError("serverError.notification.missing"));
- deps.markRead([m[1]!]);
+ if (!visible(listing).some((entry) => entry.id === m[1])) return json(res, 404, userError("serverError.notification.missing"));
+ markRead([m[1]!], listing.reader);
return json(res, 200, { ok: true });
};
}
diff --git a/server/routes/presence.test.ts b/server/routes/presence.test.ts
index 1685ba313c..0979418127 100644
--- a/server/routes/presence.test.ts
+++ b/server/routes/presence.test.ts
@@ -57,4 +57,14 @@ describe("POST /api/presence/active", () => {
expect(odd.sawChat).not.toHaveBeenCalled();
}
});
+
+ it("counts the open conversation of every member of a Team Cloud, and elsewhere only the owner's", async () => {
+ const member = { kind: "loopback", scopes: ["client"] } as RequestAuth;
+ const onTeam = call(member, { threadId: "t1" }, undefined, true);
+ await onTeam.done;
+ expect(onTeam.sawChat, "a User's open chat is in front of them as an admin's is").toHaveBeenCalledWith(member, "t1");
+ const guest = call(member, { threadId: "t1" });
+ await guest.done;
+ expect(guest.sawChat, "a My Cloud guest's is not the owner's").not.toHaveBeenCalled();
+ });
});
diff --git a/server/routes/presence.ts b/server/routes/presence.ts
index 26bd7abc71..11ae1705a3 100644
--- a/server/routes/presence.ts
+++ b/server/routes/presence.ts
@@ -11,7 +11,8 @@ export interface PresenceRouteDeps {
/** The language the app of a ping that counts shows (the owner's, or a member's), for the lines the server writes for
* that person (host/person-languages.ts). */
heard?(auth: RequestAuth, language: string): void;
- /** The conversation open in the app while the person was active: it is the one in front of them. */
+ /** The conversation open in the app while a person who counts was active (the owner, or on a Team Cloud any
+ * member): it is the one in front of them. */
sawChat?(auth: RequestAuth, threadId: string): void;
}
@@ -29,8 +30,9 @@ export function createPresenceRoutes(deps: PresenceRouteDeps): RouteHandler {
const source = given.source === "phone" ? "phone" : "desktop";
const timeZone = typeof given.timeZone === "string" && given.timeZone.length <= 128 && IANA_ZONE.test(given.timeZone) ? validZone(given.timeZone) : undefined;
const language = typeof given.language === "string" && LANGUAGE_TAG.test(given.language) ? given.language.toLowerCase() : undefined;
- if (language && (deps.member || deps.isOwner(auth))) deps.heard?.(auth, language);
- if (typeof given.threadId === "string" && THREAD_ID.test(given.threadId)) deps.sawChat?.(auth, given.threadId);
+ const counts = Boolean(deps.member) || deps.isOwner(auth);
+ if (language && counts) deps.heard?.(auth, language);
+ if (counts && typeof given.threadId === "string" && THREAD_ID.test(given.threadId)) deps.sawChat?.(auth, given.threadId);
if (deps.member) return json(res, 200, { ok: true, ...deps.member(auth, language) });
// A guest's activation is not the person's: answered, never recorded.
if (!deps.isOwner(auth)) return json(res, 200, { ok: true, returned: false });
diff --git a/server/routes/threads.ts b/server/routes/threads.ts
index 14f2149d59..347d744b0c 100644
--- a/server/routes/threads.ts
+++ b/server/routes/threads.ts
@@ -58,6 +58,8 @@ export interface ThreadRouteDeps {
viewerFor(auth: RequestAuth): Viewer;
/** A room's unread mark as this person has read it (a Team Cloud); the room as it is anywhere else. */
groupFor?(auth: RequestAuth, group: WireGroup): WireGroup;
+ /** The bots in this person's own order (a Team Cloud's User); the team's order anywhere else. */
+ botOrderFor?(auth: RequestAuth, bots: readonly BotRecord[]): readonly BotRecord[];
visibleTo(viewer: Viewer): VisibleSet;
/** A Team Cloud: gives a member their own MausBot once, before their first list of bots. */
memberDefaultBot?(email: string): unknown;
@@ -90,7 +92,7 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {
const limit = pageSize(url.searchParams.get("messages"));
if (limit === null) return json(res, 400, { error: "messages must be a non-negative whole number" });
// tasks stays explicit: clients expect [] where wireBot() would omit the key.
- const shownBots = store.bots.filter((bot) => visible.bot(bot.id));
+ const shownBots = (deps.botOrderFor?.(auth, store.bots) ?? store.bots).filter((bot) => visible.bot(bot.id));
const queued = publicBotQueuedMessages();
return json(res, 200, {
bots: shownBots.map((bot) => {