Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Merge remote-tracking branch 'upstream/main' into up/fix/thread-notification-reads
Sebastian B1960001108ca
diff --cc server/client-notifications.e2e.test.tsindex 0000000000,d636e3fa36..b53b3e3468mode 000000,100644..100644--- a/server/client-notifications.e2e.test.ts+++ b/server/client-notifications.e2e.test.ts@@@ -1,0 -1,96 +1,105 @@@+ import { join } from "node:path";+ import { DatabaseSync } from "node:sqlite";+ import { expect, it } from "vitest";++ import { launchCloudSendFixture } from "../scripts/testing/cloud-send-fixture.ts";+ import { personKey } from "./person-key.ts";+ import { hostTimeout } from "./testing/host-timeout.ts";++ 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" } });+ 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 opened = await team.as(owner.token!, "POST", `/api/bots/${bot.id}/tasks`, { title: "Ada's private chat" });+ expect(opened.status).toBe(201);+ expect((await team.as(owner.token!, "GET", "/api/notifications")).status).toBe(200);+ 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, for_person) VALUES (?, ?, ?, ?, 'Scout', ?, 'Fixture', '', ?)");+ const ada = personKey({ id: "", email: "[email protected]" });+ for (const [id, kind, threadId, person] of [+ ["own-a", "done", bot.mainThreadId, null], ["own-b", "done", bot.mainThreadId, null],+ ["private", "done", opened.body.task.threadId, null],+ ["spend", "spend", bot.mainThreadId, null],+ ["owners-ask", "question", bot.mainThreadId, null], ["targeted", "done", bot.mainThreadId, ada],+ ] as const) insert.run(id, Date.now(), kind, bot.id, threadId, person);++ const listed = await team.as(member.token!, "GET", "/api/notifications");+ expect(listed.status).toBe(200);+ expect(listed.body.notifications.map((entry: { id: string }) => entry.id).sort()).toEqual(["own-a", "own-b"]);+ expect((await team.as(member.token!, "POST", "/api/notifications/own-a/read")).status).toBe(200);+ for (const id of ["private", "owners-ask", "targeted", "spend"]) {+ 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"]);+ } finally {+ db.close();+ }+ } finally {+ await fixture.close();+ }+ }, hostTimeout(120_000));+-it("keeps admin spend alerts unread when a Team Cloud member opens a shared conversation", async () => {++it("reads only the opener's notifications in shared conversations and keeps spend alerts for admins", 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, "");++ const insert = db.prepare("INSERT INTO notification_log(id, at, kind, bot_id, bot_name, thread_id, title, body, for_person) VALUES (?, ?, ?, ?, 'Scout', ?, 'Fixture', '', ?)");++ const ada = personKey({ id: "", email: "[email protected]" });++ const bob = personKey({ id: "", email: "[email protected]" });++ for (const [id, kind, threadId, person] of [++ ["shared-spend", "spend", bot.mainThreadId, null], ["workspace-spend", "spend", "", null],++ ["shared-done", "done", bot.mainThreadId, null], ["adas-ask", "question", bot.mainThreadId, ada],++ ["bobs-ask", "question", bot.mainThreadId, bob],++ ] as const) insert.run(id, Date.now(), kind, bot.id, threadId, person);+ 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"]);++ 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"]],++ ] as const) {++ db.prepare("UPDATE notification_log SET read = 0").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(await unread(), path).toEqual(unreadIds);++ }+ }+ } finally {+ db.close();+ }+ } finally {+ await fixture.close();+ }+ }, hostTimeout(120_000));diff --cc server/index.tsindex a0a841bf84,3cae1003a8..c50c234e51--- a/server/index.ts+++ b/server/index.ts@@@ -12617,9 -12601,9 +12601,9 @@@ ROUTES.push(createBotMemoryRoutes(broadcast({ kind: "config", ...configStatus() });},}));- const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin") ? { person: actorKey(auth), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true }), 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, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager }, connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }));-const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin") ? { person: actorKey(auth), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager }, connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }));++const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin") ? { person: actorKey(auth), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, 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, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager }, connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }));if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));- ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, active: (source, zone, language) => proactive.brief.active(source, zone, language), ...(teamOwners.presence ? { member: teamOwners.presence } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => publicUrl() ?? (auth.kind === "session" ? requestOrigin(req) : null) }),+ ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: teamMessages.arrived } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => publicUrl() ?? (auth.kind === "session" ? requestOrigin(req) : null) }),createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: settleSignIn, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: { error: memberLoginRefusal(CLOUD_TEAM) } }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId) }));ROUTES.push(createRoomHoldRoutes({group: (id) => store.group(id),diff --cc server/message-db.test.tsindex 39eefa57b4,1bbf0a2f4a..b9f4d2b5ee--- a/server/message-db.test.ts+++ b/server/message-db.test.ts@@@ -14,8 -14,10 +14,9 @@@ import { closeMessageDblastRowAt,latestPersonLineAts,logNotification,+ openRescueMessages,latestSaidByBot,markNotificationLogRead,- markThreadNotificationLogRead,readMessageText,recentMessages,recentNotificationLog,diff --cc server/routes/notifications-admin.test.tsindex 0000000000,4708d6ca53..a4ecb72171mode 000000,100644..100644--- a/server/routes/notifications-admin.test.ts+++ b/server/routes/notifications-admin.test.ts@@@ -1,0 -1,91 +1,91 @@@+ import { mkdirSync, rmSync } from "node:fs";+ import { createServer, type Server } from "node:http";+ import type { AddressInfo } from "node:net";+ import { afterEach, beforeEach, describe, expect, it } from "vitest";++ import type { NotificationLogEntry } from "../../shared/notification.ts";+ import { DATA_DIR } from "../config.ts";+ 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, readThreadNotifications } from "./notifications.ts";++import { createNotificationRoutes, notificationListedFor, readThreadNotifications } from "./notifications.ts";+ import { dispatchRoutes } from "./table.ts";++ const session: SessionRecord = { id: "fixture", tokenHash: "0".repeat(64), label: "Fixture", scopes: ["client"],+ createdAt: 1, lastSeenAt: 1, expiresAt: Number.MAX_SAFE_INTEGER };+ const client: RequestAuth = { kind: "session", session, via: "bearer", scopes: ["client"] };+ const callers: Array<{ label: string; auth: RequestAuth; admin: boolean }> = [+ { label: "Team Cloud member", auth: { ...client, session: { ...session, email: "[email protected]",+ membershipAuthority: "team", teamRole: "member" } }, admin: false },+ { label: "guest", auth: { ...client, via: "cookie" }, admin: false },+ { label: "paired client", auth: client, admin: false },+ { label: "service loopback", auth: { kind: "loopback", trust: "service", scopes: ["client"] }, admin: false },+ { label: "owner loopback", auth: { kind: "loopback", scopes: ["admin", "client"] }, admin: true },+ { label: "admin session", auth: { ...client, session: { ...session, scopes: ["admin", "client"] },+ scopes: ["admin", "client"] }, admin: true },+ ];+ const sample: NotificationLogEntry = { id: "done", at: 1, kind: "done", botId: "scout", botName: "Scout",+ threadId: "shared", title: "Done", body: "", read: false };+ let server: Server | undefined;++ beforeEach(() => {+ closeMessageDb();+ rmSync(DATA_DIR, { recursive: true, force: true });+ mkdirSync(DATA_DIR, { recursive: true });+ for (const entry of [sample, { ...sample, id: "spend", kind: "spend" as const, body: "$12 of $20 spent this month" },+ { ...sample, id: "workspace-spend", kind: "spend" as const, threadId: "" }]) insertNotificationLog(entry);+ });+ afterEach(async () => {+ if (server) await new Promise((done) => server!.close(done));+ server = undefined;+ });++ async function serve(auth: RequestAuth) {+ const routes = [createNotificationRoutes()];+ server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://localhost");+ if (!await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody })) {+ json(res, 404, { error: "no such route" });+ }+ });+ await new Promise<void>((ready) => server!.listen(0, "127.0.0.1", ready));+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/notifications`;+ }++ 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);++ readThreadNotifications("shared", (frame) => frames.push(frame), notificationListedFor()(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);+ expect(res.status).toBe(200);+ const { notifications } = await res.json() as { notifications: NotificationLogEntry[] };+ expect(notifications.map((entry) => entry.id).sort()).toEqual(admin ? ["done", "spend", "workspace-spend"] : ["done"]);+ });++ it("allows only admins to mark a spend alert read", async () => {+ const url = await serve(auth);+ for (const id of ["spend", "workspace-spend"]) {+ expect((await fetch(`${url}/${id}/read`, { method: "POST" })).status, id).toBe(admin ? 200 : 404);+ }+ expect(recentNotificationLog().filter((entry) => entry.read).map((entry) => entry.id).sort())+ .toEqual(admin ? ["spend", "workspace-spend"] : []);+ });++ it("preserves admin-only unread alerts when a non-admin reads all", async () => {+ const url = await serve(auth);+ expect((await fetch(`${url}/read-all`, { method: "POST" })).status).toBe(200);+ expect(recentNotificationLog().filter((entry) => entry.read).map((entry) => entry.id).sort())+ .toEqual(admin ? ["done", "spend", "workspace-spend"] : ["done"]);+ expect(recentNotificationLog().filter((entry) => !entry.read).map((entry) => entry.id).sort())+ .toEqual(admin ? [] : ["spend", "workspace-spend"]);+ });+ });diff --cc server/routes/notifications.tsindex b129f74301,06f47d6b63..f023f74e93--- a/server/routes/notifications.ts+++ b/server/routes/notifications.ts@@@ -1,34 -1,25 +1,35 @@@-import { markNotificationLogRead, markThreadNotificationLogRead, recentNotificationLog } from "../message-db.ts";+import { markNotificationLogRead, recentNotificationLog } from "../message-db.ts";import type { NotificationLogEntry } from "../../shared/notification.ts";- import type { RequestAuth } from "../request-auth.ts";+ import { ownerOrAdmin, type RequestAuth } from "../request-auth.ts";import { PASS, type RouteHandler } from "./table.ts";-/** 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 });+/** 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);+ if (!ids.length) return;+ markNotificationLogRead(ids);+ broadcast({ kind: "notifications.read", threadId, ids });}-/** `shown`: on a Team Cloud another person's private chat's notifications are theirs alone, an admin's list included. */-export function createNotificationRoutes(deps = {- recent: recentNotificationLog,- markRead: markNotificationLogRead,-}, shown: (auth: RequestAuth) => (threadId: string) => boolean = () => () => true,- reaches: (auth: RequestAuth, entry: NotificationLogEntry) => boolean = () => true): RouteHandler {- const visible = (auth: RequestAuth) => {+/** 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. */+export function notificationListedFor(shown: (auth: RequestAuth) => (threadId: string) => boolean = () => () => true,+ reaches: (auth: RequestAuth, entry: NotificationLogEntry) => boolean = () => true) {+ return (auth: RequestAuth) => {const seen = shown(auth);- return (entry: NotificationLogEntry) => (!entry.threadId || seen(entry.threadId)) && reaches(auth, entry);+ const admin = ownerOrAdmin(auth);- return deps.recent().filter((entry) => (entry.kind !== "spend" || admin) && (!entry.threadId || seen(entry.threadId)) && reaches(auth, entry));++ return (entry: NotificationLogEntry) => (entry.kind !== "spend" || admin) && (!entry.threadId || seen(entry.threadId)) && reaches(auth, entry);};+}++export type NotificationListed = ReturnType<typeof notificationListedFor>;++export function createNotificationRoutes(deps = {+ recent: recentNotificationLog,+ markRead: markNotificationLogRead,+}, listed: NotificationListed = notificationListedFor()): RouteHandler {+ const visible = (auth: RequestAuth) => deps.recent().filter(listed(auth));return async ({ res, path, method, auth, json }) => {if (method === "GET" && path === "/api/notifications") {return json(res, 200, { notifications: visible(auth) });