Skip to content

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

fix(notifications): preserve spend alerts during non-admin thread reads

Sebastian B1a06d8473426
diff --git a/server/client-notifications.e2e.test.ts b/server/client-notifications.e2e.test.ts
index 11dab2fb58..d636e3fa36 100644
--- a/server/client-notifications.e2e.test.ts
+++ b/server/client-notifications.e2e.test.ts
@@ -47,3 +47,50 @@ it("lets a Team Cloud member list and read only their own notification feed", as
await fixture.close();
}
}, hostTimeout(120_000));
+
+it("keeps admin spend alerts unread when a Team Cloud member opens a shared conversation", async () => {
+ const fixture = await launchCloudSendFixture({ onePasswordToken: "synthetic-spend-read-token",
+ team: { id: "team-spend-read", name: "Spend reads" } });
+ try {
+ const team = fixture.team!;
+ const owner = await team.pair({ email: "[email protected]", role: "owner" });
+ const member = await team.pair({ email: "[email protected]", role: "member" });
+ const created = await team.as(owner.token!, "POST", "/api/bots", { name: "Scout" });
+ expect(created.status).toBe(201);
+ const bot = created.body.bot;
+ const channel = await team.as(owner.token!, "POST", "/api/groups", { name: "Updates", memberIds: [bot.id],
+ setup: { bulletin: "", defaultResponder: { kind: "everyone" } } });
+ expect(channel.status).toBe(201);
+ const group = channel.body.group;
+ const unread = async () => {
+ const listed = await team.as(owner.token!, "GET", "/api/notifications");
+ expect(listed.status).toBe(200);
+ return listed.body.notifications.filter((entry: { read: boolean }) => !entry.read).map((entry: { id: string }) => entry.id).sort();
+ };
+ await unread();
+ const db = new DatabaseSync(join(team.home, ".openmausbot", "messages.db"));
+ try {
+ const insert = db.prepare("INSERT INTO notification_log(id, at, kind, bot_id, bot_name, thread_id, title, body) VALUES (?, ?, 'spend', ?, 'Scout', ?, 'Fixture spend', '$12 of $20 spent')");
+ insert.run("shared-spend", Date.now(), bot.id, bot.mainThreadId);
+ insert.run("workspace-spend", Date.now(), bot.id, "");
+ for (const [path, threadId] of [
+ [`/api/bots/${bot.id}/read`, bot.mainThreadId],
+ [`/api/bots/${bot.id}/tasks/${bot.mainThreadId}`, bot.mainThreadId],
+ [`/api/groups/${group.id}/read`, group.threadId],
+ [`/api/groups/${group.id}/tasks/${group.threadId}`, group.threadId],
+ ]) {
+ db.prepare("UPDATE notification_log SET read = 0").run();
+ db.prepare("UPDATE notification_log SET thread_id = ? WHERE id = 'shared-spend'").run(threadId);
+ expect(await unread()).toEqual(["shared-spend", "workspace-spend"]);
+ expect((await team.as(member.token!, "POST", path, { threadId })).status, path).toBe(200);
+ expect(await unread(), path).toEqual(["shared-spend", "workspace-spend"]);
+ expect((await team.as(owner.token!, "POST", path, { threadId })).status, path).toBe(200);
+ expect(await unread(), path).toEqual(["workspace-spend"]);
+ }
+ } finally {
+ db.close();
+ }
+ } finally {
+ await fixture.close();
+ }
+}, hostTimeout(120_000));
diff --git a/server/message-db.ts b/server/message-db.ts
index d503358d7c..6190e79baa 100644
--- a/server/message-db.ts
+++ b/server/message-db.ts
@@ -334,8 +334,8 @@ export function markNotificationLogRead(ids: readonly string[]): void {
}
/** Opening a conversation reads its notifications, questions and approvals included. Returns the ids it flipped. */
-export function markThreadNotificationLogRead(threadId: string): string[] {
- const rows = db().prepare("UPDATE notification_log SET read = 1 WHERE thread_id = ? AND read = 0 RETURNING id").all(threadId) as Array<{ id: string }>;
+export function markThreadNotificationLogRead(threadId: string, includeSpend = true): string[] {
+ const rows = db().prepare("UPDATE notification_log SET read = 1 WHERE thread_id = ? AND read = 0 AND (? OR kind != 'spend') RETURNING id").all(threadId, includeSpend ? 1 : 0) as Array<{ id: string }>;
return rows.map((row) => row.id);
}
diff --git a/server/routes/bot-settings.ts b/server/routes/bot-settings.ts
index f1e78926ba..d5f8c027e1 100644
--- a/server/routes/bot-settings.ts
+++ b/server/routes/bot-settings.ts
@@ -164,7 +164,7 @@ export function createBotSettingsRoutes(deps: BotSettingsRouteDeps): RouteHandle
sawThread(current.threadId);
deps.threadRead?.(auth, current.threadId);
store.patchTask(current.id, current.threadId, { unread: false, ...readCursor(current.threadId) });
- readThreadNotifications(current.threadId, broadcast);
+ readThreadNotifications(current.threadId, broadcast, auth);
const bot = store.bot(current.id)!;
const visible = wireBot(bot);
broadcast({ kind: "bot", bot: visible });
diff --git a/server/routes/channels.ts b/server/routes/channels.ts
index 0e888e328f..d327b0d8f1 100644
--- a/server/routes/channels.ts
+++ b/server/routes/channels.ts
@@ -182,7 +182,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
const switched = store.switchGroupTask(group.id, m[2]);
if (!switched) return json(res, 404, { error: "no such channel task" });
deps.threadRead?.(auth, switched.threadId);
- readThreadNotifications(switched.threadId, broadcast);
+ readThreadNotifications(switched.threadId, broadcast, auth);
const switchedSettings = publicGroupState(switched);
// "0": settings only (no `messages` key); a positive page: that tail; omitted: the whole transcript.
const responseGroup = requestedMessages === "0"
@@ -260,7 +260,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
sawThread(room.threadId);
deps.threadRead?.(auth, room.threadId);
const group = store.patchGroup(room.id, { unread: false, ...readCursor(room.threadId) })!;
- readThreadNotifications(room.threadId, broadcast);
+ readThreadNotifications(room.threadId, broadcast, auth);
broadcast({ kind: "group", group: publicGroupState(group) });
return json(res, 200, { group: publicGroupState(group) });
}
diff --git a/server/routes/notifications-admin.test.ts b/server/routes/notifications-admin.test.ts
index e79ac22d03..4708d6ca53 100644
--- a/server/routes/notifications-admin.test.ts
+++ b/server/routes/notifications-admin.test.ts
@@ -9,7 +9,7 @@ import { json, readBody } from "../harness/http.ts";
import { closeMessageDb, insertNotificationLog, recentNotificationLog } from "../message-db.ts";
import type { RequestAuth } from "../request-auth.ts";
import type { SessionRecord } from "../sessions.ts";
-import { createNotificationRoutes } from "./notifications.ts";
+import { createNotificationRoutes, readThreadNotifications } from "./notifications.ts";
import { dispatchRoutes } from "./table.ts";
const session: SessionRecord = { id: "fixture", tokenHash: "0".repeat(64), label: "Fixture", scopes: ["client"],
@@ -54,6 +54,15 @@ async function serve(auth: RequestAuth) {
}
describe.each(callers)("$label notification feed", ({ auth, admin }) => {
+ it("automatically reads spend alerts in a conversation only for admins", () => {
+ const frames: Record<string, unknown>[] = [];
+ readThreadNotifications("shared", (frame) => frames.push(frame), auth);
+ expect(recentNotificationLog().filter((entry) => entry.read).map((entry) => entry.id).sort())
+ .toEqual(admin ? ["done", "spend"] : ["done"]);
+ expect(frames.map((frame) => ({ ...frame, ids: (frame.ids as string[]).sort() })))
+ .toEqual([{ kind: "notifications.read", threadId: "shared", ids: admin ? ["done", "spend"] : ["done"] }]);
+ });
+
it("lists spend alerts only for admins, including alerts in visible shared conversations", async () => {
const url = await serve(auth);
const res = await fetch(url);
diff --git a/server/routes/notifications.ts b/server/routes/notifications.ts
index 8bfee874f0..06f47d6b63 100644
--- a/server/routes/notifications.ts
+++ b/server/routes/notifications.ts
@@ -3,9 +3,9 @@ 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 its notifications, so every open app's badge drops them too. */
-export function readThreadNotifications(threadId: string, broadcast: (payload: Record<string, unknown>) => void): void {
- const ids = markThreadNotificationLogRead(threadId);
+/** Automatic conversation reads keep spend alerts unread unless the opener is an owner or admin. */
+export function readThreadNotifications(threadId: string, broadcast: (payload: Record<string, unknown>) => void, auth: RequestAuth): void {
+ const ids = markThreadNotificationLogRead(threadId, ownerOrAdmin(auth));
if (ids.length) broadcast({ kind: "notifications.read", threadId, ids });
}
diff --git a/server/routes/tasks.ts b/server/routes/tasks.ts
index 4cffe0c1c1..21adc9eb96 100644
--- a/server/routes/tasks.ts
+++ b/server/routes/tasks.ts
@@ -230,7 +230,7 @@ export function createTaskRoutes(deps: TaskRouteDeps): RouteHandler & { deleteTa
if (!switched) return json(res, 404, { error: "no such task" });
sawThread(m[2]);
deps.threadRead?.(auth, m[2]);
- readThreadNotifications(m[2], broadcast);
+ readThreadNotifications(m[2], broadcast, auth);
const wiredSwitch = wireBot(switched);
const switchedSettings = { ...wiredSwitch, tasks: wiredSwitch.tasks ?? [] };
// "0": settings only; a positive page: that tail; omitted: the whole thread (search hits can be older than a page).