Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Team Clouds: private stays private in usage, a person's own MausBot, and new routines (#5358)
Milind Soni8bc7dba7892f
diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex d7c899b2fc..e3a84d0ad2 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -253,7 +253,11 @@ this server shares with every bot. It exists only on a Team Cloud.changes are recorded too. The Admin's Team admin → Activity reads it with the same session, beside the team's own record there; Usagereads `/api/usage` (by person, bot and model) and `/api/usage/traces` (the runs) the same way. A member's private chatshows there as metadata only: its usage counts and cost by person and bot, an activity row's when, bot, tool and- outcome; never its runs' titles or a decision's words.+ outcome; never its runs' titles or a decision's words. To anyone but its person a usage row from a private chat names+ no conversation (the export's `thread` is empty), a routine that lives in one is the one line *Private routine* (key+ `routine:private`, no name, no id) and a person's own MausBot is *Private bot* (`bot:private`); the amounts still count+ toward the person's and the team's totals (`server/host/private-records.ts`). What a person changes on their own+ MausBot is never recorded in admin activity.- For a business sign-in (Claude or ChatGPT on this server), the Admin opens this server's own pages signed in as thatadmin (a browser sign-in with the member's claim) at `/?connect=ai` (or `apps`, `mcp`, `keys`).@@ -499,7 +503,12 @@ whoever made it or runs it (the schedule, its writer or an Admin), and reports ichat of its own that everyone who reads the place reads; its asks go to whoever looks after the bot, or the Admins. Theroutine form on a team offers two places: **Just me** (`resultsThreadId: "just-me"`, the person's own private chat withthe bot, or a new one named for the routine) and **Shared chat** (the bot's main chat); anyone who can chat with the bot-may choose either, and an older app's "The bot's main thread" (`null`) is the shared place's own results chat. A routine+may choose either, and an older app's "The bot's main thread" (`null`) is the shared place's own results chat. A new+routine is never shared unless its writer chose that: the form presets the audience of the place it was opened from+(Shared chat only while that bot's shared chat is on screen; Just me in a private chat and anywhere else), always shows+who will see the routine and what it reports in the words of the label by the message box (*"Private · only you"*,+*"Shared · everyone in Acme can see"*), and a request that names no place (`resultsThreadId` left out) makes the+routine its writer's alone, as Just me does; when no private chat can be opened for it the request is refused. A routinethat reports into a chat whose audience is not its own, such as one made before this for the shared chat whose resultschat was opened privately for its writer, gets a results chat of its own place at its next run; the old chat stayswhere it is, unchanged. The chat a routine opened for its own results does not make it anyone's until they write in it.@@ -644,6 +653,12 @@ allow, folders), where it runs, its department, whom it answers to or directs, c`visibility` follows in the same write (everyone when everyone may at least view it, else the owner and the peopleadded), so every rule of the audience rule above that reads who sees a bot holds unchanged. A new team bot isEveryone · Can chat. A member's own MausBot stays theirs alone, as before.+- **A person's own MausBot exists for nobody else.** To every other member and every Admin, the Owner included, it is+ in no list, stream, search, export, routine picker or group chat, whatever its stored sharing says+ (`VisibleSet.bot`), and every route naming it, by path (its memory layers too) or in a body, answers exactly as an id+ no bot has: on a Team Cloud both are refused at the one gate, 404 *no such bot*, before any route can answer them+ differently (`server/host/visibility-host.ts`). Only the Cloud itself reaches it: the leave clean-up and the Owner's+ whole-machine export, which leaves it out.- **Before levels.** A bot whose sharing was never set is read from its visibility, exactly as it was: everyone →Everyone · Can chat; admins only → Only people added (admins still edit); a list of addresses → those people · Canchat. Nothing is rewritten on disk; the first change in the Share dialog stores the sharing. An older app'sdiff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex e31912b7e6..1924b927be 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -95,6 +95,7 @@ export const VITEST_SUBSETS = {"server/cloud-team-phones.e2e.test.ts","server/cloud-team-pictures.e2e.test.ts","server/cloud-team-presence.e2e.test.ts",+ "server/cloud-team-privacy-holes.e2e.test.ts","server/cloud-team-private.e2e.test.ts","server/cloud-team-profile.e2e.test.ts","server/cloud-team-requests.e2e.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex c367a43278..3cee632d46 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -232,6 +232,7 @@ describe("CI outputs", () => {"server/cloud-team-phones.e2e.test.ts","server/cloud-team-pictures.e2e.test.ts","server/cloud-team-presence.e2e.test.ts",+ "server/cloud-team-privacy-holes.e2e.test.ts","server/cloud-team-private.e2e.test.ts","server/cloud-team-profile.e2e.test.ts","server/cloud-team-requests.e2e.test.ts",diff --git a/server/bot-visibility.test.ts b/server/bot-visibility.test.tsindex 2c7a338f95..fd7b441082 100644--- a/server/bot-visibility.test.ts+++ b/server/bot-visibility.test.ts@@ -488,4 +488,29 @@ describe("a Team Cloud's audiences", () => {// Off a team the list is untouched.expect(memberBot({ id: "pub", tasks: [{ threadId: "t-pub-2" }] }, new VisibleSet(bots, groups, BOB)).tasks).toEqual([{ threadId: "t-pub-2" }]);});++ it("a person's own MausBot exists for them alone: no admin and no other member sees it, whatever its sharing says", () => {+ // As an admin could once leave it: listed for everyone.+ const adas = { id: "adas-maus", threadId: "t-maus", defaultBot: { person: "[email protected]" }, visibility: "everyone", access: { everyone: "chat", people: {} } };+ const withMaus = [...open, adas];+ const rooms = [...openGroups, { id: "room-maus", threadId: "t-room-maus", memberIds: ["pub", "adas-maus"] }];+ const set = (viewer: Viewer, person: string | null) => new VisibleSet(withMaus, rooms, viewer, undefined, { of: audienceOf, person });+ const ada = set(ADA, ADA_KEY), admin = set(BEN_ADMIN, BEN_KEY), member = set(BOB, BEN_KEY);+ expect([ada.bot("adas-maus"), ada.level("adas-maus"), ada.group("room-maus")]).toEqual([true, "edit", true]);+ for (const other of [admin, member, set({ kind: "all", email: "" }, null)]) {+ expect([other.bot("adas-maus"), other.level("adas-maus"), other.group("room-maus")]).toEqual([false, "none", false]);+ expect(other.bot("pub"), "team bots are as they were").toBe(true);+ expect(frameForMember({ kind: "bot", bot: { id: "adas-maus", name: "Confidant" } }, { visible: other, webhook: () => undefined, freshBot: () => undefined, freshGroup: () => undefined }, { bots: new Set(), groups: new Set() })).toBeUndefined();+ expect(routineVisible({ botId: "adas-maus" }, other)).toBe(false);+ }+ expect(admin.bot("no-such-bot"), "an admin's unknown id is still the route's to answer").toBe(true);+ // The server itself, and anywhere that is not a team, sees it as before.+ expect(new VisibleSet(withMaus, rooms, SEES_EVERYTHING, undefined, { of: audienceOf, person: null }).bot("adas-maus")).toBe(true);+ expect(new VisibleSet(withMaus, rooms, BEN_ADMIN).bot("adas-maus")).toBe(true);+ });++ it("a bot's reorder is no bot's route", () => {+ expect(pathSubject("/api/bots/order")).toBeNull();+ expect(pathSubject("/api/bots/order-1/tasks")).toEqual({ kind: "bot", id: "order-1" });+ });});diff --git a/server/bot-visibility.ts b/server/bot-visibility.tsindex f657b058da..59303a2233 100644--- a/server/bot-visibility.ts+++ b/server/bot-visibility.ts@@ -7,6 +7,7 @@ import { z } from "zod";import { accessFromVisibility, entryMatches, higherLevel, sharedLevel, type BotAccess, type BotAccessLevel } from "../shared/bot-access.ts";import { botOwner, type OwnedBot } from "../shared/bot-owner.ts";+import { defaultBotPerson } from "../shared/default-bot.ts";import type { BotVisibility } from "../shared/wire.ts";import { audienceIncludes, type Audience } from "./audience.ts";import { SHARED_CHAT_TITLE } from "../shared/wire.ts";@@ -224,18 +225,26 @@ export class VisibleSet {}bot(id: string): boolean {- if (this.everything || this.viewer.kind === "all") return true;+ if (this.everything) return true;let seen = this.botMemo.get(id);if (seen === undefined) {const bot = this.bots.get(id);- seen = Boolean(bot && viewerSees(this.viewer, bot.visibility));+ seen = bot && this.someoneElsesOwn(bot) ? false : this.viewer.kind === "all" || Boolean(bot && viewerSees(this.viewer, bot.visibility));this.botMemo.set(id, seen);}return seen;}+ /** Security invariant: on a Team Cloud a person's own MausBot exists for that person alone. No other member and no+ * admin, the Owner included, sees it, whatever its stored sharing says; only a session-less local service does. */+ private someoneElsesOwn(bot: VisibilityBot): boolean {+ const person = this.audiences ? defaultBotPerson(bot) : "";+ return Boolean(person) && this.viewer.email !== undefined && person !== this.viewer.email.trim().toLowerCase();+ }+group(id: string): boolean {- if (this.everything || this.viewer.kind === "all") return true;+ if (this.everything) return true;+ if (this.viewer.kind === "all") return !this.groups.get(id)?.memberIds.some((member) => !this.bot(member));const group = this.groups.get(id);if (!group) return false;const members = group.memberIds.filter((member) => this.bots.has(member));@@ -333,7 +342,7 @@ export type PathSubject =export function pathSubject(path: string): PathSubject | null {let m = /^\/api\/bots\/([\w-]+)(?:\/|$)/.exec(path);- if (m) return { kind: "bot", id: m[1]! };+ if (m && m[1] !== "order") return { kind: "bot", id: m[1]! };m = /^\/api\/threads\/([\w-]+)(?:\/|$)/.exec(path);if (m) return { kind: "thread", id: m[1]! };m = /^\/api\/groups\/([\w-]+)(?:\/|$)/.exec(path);diff --git a/server/cloud-team-bot-access.e2e.test.ts b/server/cloud-team-bot-access.e2e.test.tsindex 017a242c1a..a670ba7806 100644--- a/server/cloud-team-bot-access.e2e.test.ts+++ b/server/cloud-team-bot-access.e2e.test.ts@@ -81,7 +81,7 @@ beforeAll(async () => {await until(idle);const lines = (await as("ada", "GET", `/api/threads/${payroll.threadId}/messages`)).body.messages as Array<{ id: string }>;lastLine = lines.at(-1)!.id;- const routine = (botId: string) => ({ name: "Weekly pay check", prompt: "Check this week's pay runs.", botId, schedule: { type: "interval", everyMinutes: 1440, anchorAt: Date.now() + 86_400_000 } });+ const routine = (botId: string) => ({ name: "Weekly pay check", prompt: "Check this week's pay runs.", botId, resultsThreadId: null, schedule: { type: "interval", everyMinutes: 1440, anchorAt: Date.now() + 86_400_000 } });const adas = await as("ada", "POST", "/api/routines", routine(payroll.id));expect(adas.status, JSON.stringify(adas.body)).toBe(201);adaRoutine = adas.body.routine.id;diff --git a/server/cloud-team-privacy-holes.e2e.test.ts b/server/cloud-team-privacy-holes.e2e.test.tsnew file mode 100644index 0000000000..903f356d67--- /dev/null+++ b/server/cloud-team-privacy-holes.e2e.test.ts@@ -0,0 +1,295 @@+// Private means private on a Team Cloud (docs/team-cloud.md), tried as the people it must hold against: an Admin, the+// Owner and another member, on a real Team Cloud (OMB_CLOUD_ROLE=team) with the synthetic Claude CLI. Usage counts what+// Rui spent and never says on what; Rui's own MausBot exists for nobody but Rui, on every route and in every list; and a+// routine made with no audience named is its writer's alone.+import { randomBytes, randomUUID } from "node:crypto";+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 RUI = { email: "[email protected]", role: "member" as const };+const MARTA = { email: "[email protected]", role: "member" as const };+const LATER = { type: "interval", everyMinutes: 1440, anchorAt: Date.now() + 86_400_000 };+const MARK = "Plover42";+const NO_SUCH_BOT = { status: 404, body: { error: "no such bot" } };++type Task = { threadId: string; private?: true; title?: string };+type Bot = { id: string; name: string; threadId: string; mainThreadId?: string; defaultBot?: { person?: string }; tasks?: Task[] };+type Routine = { id: string; name: string; resultsThreadId?: string };+type Run = { id: string; routineId: string; status: string; threadId?: string };+type Group = { key: string; label: string; turns: number };+type Answer = { status: number; body: unknown };++let fx: CloudSendFixture, team: CloudTeamFixture;+let owner = "", admin = "", rui = "", marta = "";+let quotes: Bot, ruiMaus: Bot;+let ruiThread = "", ruiRoutine = "", ariRoutine = "";+/** Every id that is Rui's alone: his private conversations, his private routine and its runs, his MausBot. */+const ruiIds = new Set<string>();++const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms));+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 sleep(150);+ }+}+const botsOf = async (token: string) => (await team.as(token, "GET", "/api/bots")).body.bots as Bot[];+const routinesOf = async (token: string) => (await team.as(token, "GET", "/api/routines")).body as { routines: Routine[]; runs: Run[] };+const text = async (token: string, path: string) => {+ const answer = await fetch(`${team.base}${path}`, { headers: { ...fx.edge, authorization: `Bearer ${token}` } });+ return { status: answer.status, text: await answer.text() };+};+async function runToEnd(token: string, routineId: string): Promise<Run> {+ const ran = await team.as(token, "POST", `/api/routines/${routineId}/run`);+ expect(ran.status, JSON.stringify(ran.body)).toBe(201);+ let run: Run | undefined;+ await until(async () => {+ run = (await routinesOf(token)).runs.find((candidate) => candidate.id === ran.body.run.id);+ return Boolean(run && ["completed", "failed"].includes(run.status));+ }, 90_000);+ return run!;+}+async function sayAndWait(token: string, bot: Bot, threadId: string, line: string): Promise<void> {+ const ended = async () => ((await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=50`)).body.messages as Array<{ turnTerminal?: boolean }>).filter((message) => message.turnTerminal).length;+ const before = await ended();+ expect((await team.as(token, "POST", `/api/bots/${bot.id}/messages`, { text: line, threadId })).status).toBe(202);+ await until(async () => (await ended()) > before);+}+const usage = async (token: string, groupBy: string) => (await team.as(token, "GET", `/api/usage?groupBy=${groupBy}`)).body as { groups: Group[]; total: Group };+/** What names something of Rui's in an answer: the marker his names carry, or one of his ids. */+const leaksIn = (answer: string): string[] => [MARK, ...ruiIds].filter((mark) => answer.includes(mark));+async function streamOf(token: string): Promise<string> {+ const controller = new AbortController();+ const stream = await fetch(`${team.base}/api/events`, { headers: { ...fx.edge, authorization: `Bearer ${token}`, accept: "text/event-stream", "last-event-id": "0" }, signal: controller.signal });+ const reader = stream.body!.getReader(), decoder = new TextDecoder();+ let seen = "";+ const done = (async () => { for (;;) { const { value, done } = await reader.read(); if (done) return; seen += decoder.decode(value, { stream: true }); } })().catch(() => {});+ await until(() => seen.includes("\"hello\""), 10_000);+ await sleep(1_500);+ controller.abort();+ await done;+ return seen;+}++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-holes", name: "Acme" } });+ team = fx.team!;+ owner = (await team.pair(OWNER)).token!;+ admin = (await team.pair(ADMIN)).token!;+ rui = (await team.pair(RUI)).token!;+ marta = (await team.pair(MARTA)).token!;+ quotes = (await team.as(owner, "POST", "/api/bots", { name: "Quotes" })).body.bot;+ ruiMaus = (await botsOf(rui)).find((bot) => bot.defaultBot?.person === RUI.email)!;+ expect(ruiMaus, "Rui has a MausBot of his own").toBeTruthy();++ const renamed = await team.as(rui, "PATCH", `/api/bots/${ruiMaus.id}`, { name: `Confidant ${MARK}` });+ expect(renamed.status, "he names his own MausBot").toBe(200);+ ruiThread = (await team.as(rui, "POST", `/api/bots/${quotes.id}/tasks`, { title: `Salary talk ${MARK}` })).body.task.threadId;+ await sayAndWait(rui, quotes, ruiThread, `What should I ask for? ${MARK}`);+ await sayAndWait(rui, ruiMaus, ruiMaus.threadId, `Remember my ceiling ${MARK}`);+ const made = await team.as(rui, "POST", "/api/routines", { name: `Salary check ${MARK}`, prompt: `Check the salary bands ${MARK}`, botId: quotes.id, schedule: LATER, resultsThreadId: "just-me" });+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ ruiRoutine = made.body.routine.id;+ const ruiRun = await runToEnd(rui, ruiRoutine);+ const own = await team.as(admin, "POST", "/api/routines", { name: "Ari's own digest", prompt: "Sum up my week", botId: quotes.id, schedule: LATER, resultsThreadId: "just-me" });+ expect(own.status, JSON.stringify(own.body)).toBe(201);+ ariRoutine = own.body.routine.id;+ await runToEnd(admin, ariRoutine);++ for (const bot of await botsOf(rui)) for (const task of bot.tasks ?? []) if (task.private) ruiIds.add(task.threadId);+ for (const id of [ruiThread, ruiRoutine, ruiRun.id, ruiRun.threadId, ruiMaus.id, ruiMaus.threadId]) if (id) ruiIds.add(id);+ // Booked a moment after each turn ends.+ await until(async () => (await usage(admin, "user")).groups.find((group) => group.key === `user:${RUI.email}`)?.turns === 3);+}, hostTimeout(300_000));++afterAll(async () => {+ await fx?.close();+});++it("usage tells an Admin and the Owner how much Rui used, never on what", async () => {+ for (const [who, token] of [["an Admin", admin], ["the Owner", owner]] as const) {+ for (const groupBy of ["bot", "model", "user", "day", "engine", "routine", "department"]) {+ const answer = await team.as(token, "GET", `/api/usage?groupBy=${groupBy}`);+ expect(answer.status).toBe(200);+ expect(leaksIn(JSON.stringify(answer.body)), `${who}: usage by ${groupBy}`).toEqual([]);+ }+ const csv = await text(token, "/api/usage.csv");+ expect(csv.status).toBe(200);+ expect(leaksIn(csv.text), `${who}: the export`).toEqual([]);+ const ruiRows = csv.text.trim().split("\n").filter((line) => line.endsWith(`,${RUI.email}`));+ expect(ruiRows, "each of his turns is still a row with his address").toHaveLength(3);+ for (const row of ruiRows) expect(row.split(",").at(-3), "and names no conversation").toBe("");+ expect(ruiRows.filter((row) => row.includes(",Private routine,")), "his routine's run says only that").toHaveLength(1);++ const byRoutine = await usage(token, "routine");+ expect(byRoutine.groups.find((group) => group.key === "routine:private"), `${who}: a private routine is one unnamed line`).toMatchObject({ label: "Private routine" });+ expect((await usage(token, "user")).groups.find((group) => group.key === `user:${RUI.email}`)?.turns, "his turns count as his").toBe(3);+ const byBot = await usage(token, "bot");+ expect(byBot.groups.reduce((sum, group) => sum + group.turns, 0), "and toward the team's total").toBe(byBot.total.turns);+ expect(byBot.groups.find((group) => group.key === "bot:private"), "his MausBot's turn is counted without the bot").toMatchObject({ label: "Private bot" });+ expect((await team.as(token, "GET", "/api/usage/traces")).body.roots.filter((root: { title?: string }) => leaksIn(JSON.stringify(root)).length)).toEqual([]);+ }+}, hostTimeout(60_000));++it("a person still reads their own private routine and conversations in usage; the other admin does not", async () => {+ const mine = await usage(admin, "routine");+ expect(mine.groups.find((group) => group.key === `routine:${ariRoutine}`), "Ari's own routine, by name").toMatchObject({ label: "Ari's own digest", turns: 1 });+ expect((await text(admin, "/api/usage.csv")).text).toContain("Routine: Ari's own digest");+ const theirs = JSON.stringify(await usage(owner, "routine")) + (await text(owner, "/api/usage.csv")).text;+ expect(theirs).not.toContain("Ari's own digest");+ expect(theirs).not.toContain(ariRoutine);+ expect((await usage(owner, "routine")).groups.find((group) => group.key === "routine:private")?.turns, "both private routines fold into the one line").toBe(2);+ expect((await team.as(marta, "GET", "/api/usage")).status, "a member reads no usage at all").toBe(403);+}, hostTimeout(60_000));++const SUFFIXES = ["", "/tasks", "/tasks/t1", "/tasks/t1/title", "/tasks/delete", "/messages", "/messages/guarded", "/messages/m1/edit", "/memory", "/memory/file",+ "/memory/journal", "/memory/journal/j1/revert", "/memory/mine", "/memory/mine/file", "/memory/open", "/memory/reviewed", "/memory/tidy", "/memory/upkeep",+ "/access", "/access-request", "/reports-to", "/bot-api", "/bot-api/new-key", "/profile", "/model", "/always-allow", "/soul", "/soul/apply-file",+ "/soul/discard-file", "/system-prompt", "/skills", "/skills/abc", "/skills/abc/share", "/skills-library", "/skill-template", "/history", "/history/rollback",+ "/activity", "/overview", "/projects", "/projects/p1", "/projects/order", "/queue/q1", "/queue/q1/steer", "/read", "/respond", "/interrupt", "/compact",+ "/active-branch", "/start-fresh", "/setup-request", "/helper-followup", "/tool-budget", "/threads/follow-model", "/mcp-servers", "/data", "/data/x", "/computer",+ "/computer/exec", "/computer/control", "/computer/viewer-close", "/local-computer", "/local-computer/run", "/local-computer/join", "/local-computer/screenshot",+ "/browser/live", "/browser/action", "/browser/upload", "/browser/download/d1", "/browser/stream", "/cards/c1", "/command-allowlist", "/command-allowlist/x",+ "/connector-cards/c1/status", "/connector-cards/c1/authorize", "/secret-cards/c1/provide", "/secret-cards/c1/save", "/sign-in-cards/c1/done", "/saved-steps/s1",+ "/requests/aaaaaaaaaaaaaaaaaaaa", "/requests/aaaaaaaaaaaaaaaaaaaa/interrupt", "/apps/a1/rpc", "/apps/a1/context", "/avatar/generate", "/slack-management", "/webhooks", "/routines", "/files", "/no-such-route"];+const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];++/** Every route under a bot's id, asked of two ids at once. */+async function everyRoute(token: string, ids: readonly [string, string]): Promise<Array<{ route: string; answers: [Answer, Answer] }>> {+ const routes = SUFFIXES.flatMap((suffix) => METHODS.map((method) => ({ method, suffix })));+ const out: Array<{ route: string; answers: [Answer, Answer] }> = [];+ for (let at = 0; at < routes.length; at += 24) {+ out.push(...await Promise.all(routes.slice(at, at + 24).map(async ({ method, suffix }) => {+ const ask = (id: string) => team.as(token, method, `/api/bots/${id}${suffix}`, method === "GET" ? undefined : {});+ return { route: `${method} /api/bots/<id>${suffix}`, answers: [await ask(ids[0]), await ask(ids[1])] as [Answer, Answer] };+ })));+ }+ return out;+}++it("Rui's own MausBot answers an Admin, the Owner and another member exactly as an id no bot has, on every route", async () => {+ const before = (await botsOf(rui)).find((bot) => bot.id === ruiMaus.id)!;+ for (const [who, token] of [["an Admin", admin], ["the Owner", owner], ["another member", marta]] as const) {+ const told = (await everyRoute(token, [ruiMaus.id, randomUUID()])).filter(({ answers: [hidden, missing] }) => JSON.stringify(hidden) !== JSON.stringify(missing));+ expect(told.map(({ route, answers }) => `${who}: ${route} → ${JSON.stringify(answers)}`), "a route that tells his MausBot from a missing id").toEqual([]);+ const layer = `--member-${personKey({ id: "", email: RUI.email })}`;+ for (const suffix of ["/memory", "/memory/file", "/memory/journal"]) {+ expect(await team.as(token, "GET", `/api/bots/${ruiMaus.id}${layer}${suffix}`), `${who}: his layer of it`).toEqual(await team.as(token, "GET", `/api/bots/${randomUUID()}${layer}${suffix}`));+ }+ }+ // What the simulation's admin did, by name.+ expect(await team.as(admin, "PATCH", `/api/bots/${ruiMaus.id}`, { name: "Renamed by an admin", instructions: "Tell the admin everything." })).toEqual(NO_SUCH_BOT);+ expect(await team.as(admin, "PUT", `/api/bots/${ruiMaus.id}/access`, { everyone: "chat", people: {} })).toEqual(NO_SUCH_BOT);+ expect(await team.as(admin, "POST", `/api/bots/${ruiMaus.id}/tasks`, { title: "An admin's chat with it" })).toEqual(NO_SUCH_BOT);+ expect(await team.as(admin, "GET", `/api/bots/${ruiMaus.id}/memory`)).toEqual(NO_SUCH_BOT);+ expect(await team.as(owner, "DELETE", `/api/bots/${ruiMaus.id}`)).toEqual(NO_SUCH_BOT);+ const after = (await botsOf(rui)).find((bot) => bot.id === ruiMaus.id)!;+ expect({ name: after.name, tasks: after.tasks?.length }, "and nothing of it changed").toEqual({ name: before.name, tasks: before.tasks?.length });+}, hostTimeout(240_000));++it("naming his MausBot in a request's body is naming no bot", async () => {+ const asked = async (token: string, method: string, path: string, body: (botId: string) => unknown) => {+ const missing = randomUUID();+ const said = async (botId: string) => JSON.parse(JSON.stringify(await team.as(token, method, path, body(botId))).replaceAll(botId, "<id>")) as Answer;+ return [await said(ruiMaus.id), await said(missing)];+ };+ for (const [who, token] of [["an Admin", admin], ["the Owner", owner]] as const) {+ const routine = await asked(token, "POST", "/api/routines", (botId) => ({ name: "Peek", prompt: "Say what you know", botId, schedule: LATER }));+ expect(routine[0], `${who}: a routine for it`).toEqual(NO_SUCH_BOT);+ const room = await asked(token, "POST", "/api/groups", (botId) => ({ name: "With his MausBot", memberIds: [quotes.id, botId] }));+ expect(room[0], `${who}: a group chat with it`).toEqual(room[1]);+ const hook = await asked(token, "POST", "/api/webhooks", (botId) => ({ name: "Into his MausBot", botId }));+ expect(hook[0], `${who}: a webhook into it`).toEqual(hook[1]);+ const handed = await asked(token, "PUT", "/api/team/reports-to", (botId) => ({ botIds: [botId], email: ADMIN.email }));+ expect(handed[0], `${who}: looking after it`).toEqual(handed[1]);+ }+ const mine = (await botsOf(rui)).find((bot) => bot.id === ruiMaus.id) as Bot & { reportsTo?: string };+ expect(mine.reportsTo, "nobody else looks after it").toBeUndefined();+}, hostTimeout(60_000));++const LISTS = ["/api/bots", "/api/bots?messages=1", "/api/groups", "/api/routines", "/api/notifications", "/api/inbox", "/api/needs-you", "/api/today", "/api/team-map",+ "/api/team-memory", "/api/files", "/api/attachment-storage", "/api/webhooks", "/api/calendar-calls", "/api/sidebar-sections", "/api/config", "/api/team/people",+ "/api/team/phones", "/api/team/my-connections", "/api/mcp/servers", "/api/connectors/connected", "/api/team-computers", "/api/computers/boxes", "/api/limit-resets",+ "/api/sync/folders", "/api/app-triggers", "/api/browser-sites", "/api/auth/session", "/api/auth/sessions", "/api/section-context", "/api/bot-defaults",+ "/api/admin-activity", "/api/admin-activity.csv", "/api/decisions", "/api/decisions.csv", "/api/usage/traces", `/api/search?q=${MARK}`, "/api/search?q=Salary",+ "/api/search?q=MausBot", "/api/plan-usage", "/api/shared-computers", "/api/profile/learned", "/api/vault", "/api/logins"];++it("no list, search, export, stream or signed read names anything of Rui's to an Admin, the Owner or another member", async () => {+ for (const [who, token] of [["an Admin", admin], ["the Owner", owner], ["another member", marta]] as const) {+ const perBot = [`/api/bots/${quotes.id}`, `/api/bots/${quotes.id}/overview`, `/api/bots/${quotes.id}/activity`, `/api/bots/${quotes.id}/memory`,+ `/api/bots/${quotes.id}/memory/journal`, `/api/bots/${quotes.id}/tasks`, `/api/bots/${quotes.id}/history`];+ for (const path of [...LISTS, ...perBot]) {+ const answer = await text(token, path);+ expect(leaksIn(answer.text), `${who}: GET ${path} (${answer.status})`).toEqual([]);+ }+ expect(leaksIn(await streamOf(token)), `${who}: the event stream, replayed`).toEqual([]);+ }+ for (const [who, token] of [["an Admin", admin], ["the Owner", owner]] as const) {+ for (const format of ["backup", "share"]) {+ const exported = await team.as(token, "POST", "/api/teams/export", { format });+ expect(leaksIn(JSON.stringify(exported.body)), `${who}: the team export as ${format} (${exported.status})`).toEqual([]);+ }+ }+ const signed = await team.signed("GET", "/api/cloud/team/admin");+ expect(signed.status).toBe(200);+ expect(leaksIn(JSON.stringify(signed.body)), "the Admin's signed read").toEqual([]);+}, hostTimeout(180_000));++it("Rui keeps every use of his own MausBot, and of what is his", async () => {+ expect((await botsOf(rui)).some((bot) => bot.id === ruiMaus.id), "it is in his list").toBe(true);+ expect((await team.as(rui, "GET", `/api/bots/${ruiMaus.id}/memory/mine`)).status).toBe(200);+ expect((await team.as(rui, "PATCH", `/api/bots/${ruiMaus.id}`, { color: "blue" })).status, "he changes how it looks").toBe(200);+ const chat = await team.as(rui, "POST", `/api/bots/${ruiMaus.id}/tasks`, { title: "Another chat of his" });+ expect(chat.status).toBe(201);+ await sayAndWait(rui, ruiMaus, chat.body.task.threadId, "Still there?");+ const forIt = await team.as(rui, "POST", "/api/routines", { name: "His MausBot's morning note", prompt: "Say good morning", botId: ruiMaus.id, schedule: LATER });+ expect(forIt.status, JSON.stringify(forIt.body)).toBe(201);+ expect((await routinesOf(rui)).routines.map((routine) => routine.id)).toEqual(expect.arrayContaining([ruiRoutine, forIt.body.routine.id]));+ expect((await team.as(rui, "GET", `/api/threads/${ruiThread}/messages?limit=20`)).status).toBe(200);+}, hostTimeout(120_000));++it("a routine made with no audience named is its writer's alone; one sent to the shared chat is the team's", async () => {+ const unsaid = await team.as(rui, "POST", "/api/routines", { name: `Unsaid ${MARK}`, prompt: `Quietly ${MARK}`, botId: quotes.id, schedule: LATER });+ expect(unsaid.status, JSON.stringify(unsaid.body)).toBe(201);+ const mine = (await routinesOf(rui)).routines.find((routine) => routine.id === unsaid.body.routine.id)!;+ const ruiPrivate = (await botsOf(rui)).find((bot) => bot.id === quotes.id)!.tasks!.filter((task) => task.private).map((task) => task.threadId);+ expect(ruiPrivate, "it reports into a chat of his own").toContain(mine.resultsThreadId);+ for (const [who, token] of [["another member", marta], ["an Admin", admin], ["the Owner", owner]] as const) {+ expect(JSON.stringify(await routinesOf(token)), `${who} never learns of it`).not.toContain(unsaid.body.routine.id);+ expect((await team.as(token, "PATCH", `/api/routines/${unsaid.body.routine.id}`, { enabled: false })).status, who).toBe(404);+ }+ const run = await runToEnd(rui, unsaid.body.routine.id);+ for (const token of [marta, admin, owner]) {+ const seen = JSON.stringify(await routinesOf(token)) + JSON.stringify(await botsOf(token));+ expect(seen).not.toContain(run.id);+ expect(seen).not.toContain(`Unsaid ${MARK}`);+ }+ // The choice still widens it when the person makes it: the shared chat by id, or an older app's null.+ for (const resultsThreadId of [quotes.mainThreadId ?? quotes.threadId, null]) {+ const shared = await team.as(rui, "POST", "/api/routines", { name: "Weekly pipeline", prompt: "Post the pipeline", botId: quotes.id, schedule: LATER, resultsThreadId });+ expect(shared.status, JSON.stringify(shared.body)).toBe(201);+ for (const token of [marta, admin]) expect((await routinesOf(token)).routines.some((routine) => routine.id === shared.body.routine.id), "the team sees a shared one").toBe(true);+ }+ // A change that names no audience leaves it where it is.+ expect((await team.as(rui, "PATCH", `/api/routines/${unsaid.body.routine.id}`, { name: `Unsaid still ${MARK}` })).status).toBe(200);+ expect(JSON.stringify(await routinesOf(marta))).not.toContain(unsaid.body.routine.id);+}, hostTimeout(180_000));++it("when Rui leaves, the Cloud itself still finds and deletes his MausBot", async () => {+ const left = await team.signed("POST", "/api/cloud/team/member-left", { email: RUI.email });+ expect(left.status, JSON.stringify(left.body)).toBe(200);+ expect(left.body.bots, "his own MausBot").toBe(1);+ expect(await team.as(admin, "GET", `/api/bots/${ruiMaus.id}`)).toEqual(NO_SUCH_BOT);+ const exported = await team.as(owner, "POST", "/api/teams/export", { format: "backup" });+ expect(exported.status, "and the team's backup still works").toBe(200);+ for (const path of ["/api/admin-activity", "/api/admin-activity.csv", "/api/usage?groupBy=bot", "/api/usage.csv", "/api/decisions"]) {+ expect(leaksIn((await text(admin, path)).text), `what is left of him in ${path}`).toEqual([]);+ }+ expect((await usage(admin, "user")).groups.find((group) => group.key === `user:${RUI.email}`)?.turns, "what he used still counts").toBeGreaterThanOrEqual(3);+}, hostTimeout(120_000));diff --git a/server/host/private-records.test.ts b/server/host/private-records.test.tsnew file mode 100644index 0000000000..c3c7867cfc--- /dev/null+++ b/server/host/private-records.test.ts@@ -0,0 +1,96 @@+import { describe, expect, it } from "vitest";++import type { AdminActionRow } from "../admin-activity.ts";+import { VisibleSet, type Viewer } from "../bot-visibility.ts";+import type { DecisionRow } from "../decision-log.ts";+import type { RequestAuth } from "../request-auth.ts";+import { summarizeUsage, usageCsv, type UsageRow } from "../usage-ledger.ts";+import { createPrivateRecords } from "./private-records.ts";++const RUI = "[email protected]", ANA = "[email protected]";+const RUI_KEY = "p_ruiruiruiruiruiruirui1", ANA_KEY = "p_anaanaanaanaanaanaana1";+const bots = [+ { id: "quotes", threadId: "main", tasks: [{ threadId: "main" }, { threadId: "rui-chat" }, { threadId: "rui-run" }, { threadId: "ana-run" }] },+ { id: "ruis-maus", threadId: "rui-maus-chat", defaultBot: { person: RUI }, tasks: [{ threadId: "rui-maus-chat" }] },+];+const audienceOf = (threadId: string) =>+ threadId.startsWith("rui-") || threadId === "gone-chat" ? `member:${RUI_KEY}` as const : threadId.startsWith("ana-") ? `member:${ANA_KEY}` as const : threadId === "main" ? "team" as const : undefined;+const routines = [+ { id: "r-rui", botId: "quotes", name: "Salary check", resultsThreadId: "rui-chat" },+ { id: "r-ana", botId: "quotes", name: "Ana's digest", resultsThreadId: "ana-run" },+ { id: "r-team", botId: "quotes", name: "Standup", resultsThreadId: "main" },+];+const home = (routine: { resultsThreadId?: unknown }) => (routine.resultsThreadId === "rui-chat" ? RUI_KEY : routine.resultsThreadId === "ana-run" ? ANA_KEY : null);++function records(team = true) {+ const sets = new Map<string, VisibleSet>();+ return createPrivateRecords({+ visibleFor: (auth) => {+ const email = auth.kind === "session" ? auth.session.email ?? "" : "";+ const viewer: Viewer = { kind: "all", email };+ const person = email === RUI ? RUI_KEY : email === ANA ? ANA_KEY : null;+ if (!sets.has(email)) sets.set(email, new VisibleSet(bots, [], viewer, undefined, team ? { of: audienceOf, person, routineHome: home } : undefined));+ return sets.get(email)!;+ },+ botExists: (id) => bots.some((bot) => bot.id === id),+ routine: (id) => routines.find((routine) => routine.id === id),+ });+}+const admin = (email: string) => ({ kind: "session", scopes: ["admin", "client"], session: { id: `s-${email}`, email } }) as unknown as RequestAuth;+const row = (fields: Partial<UsageRow>): UsageRow => ({ at: "2026-11-10T10:00:00.000Z", botId: "quotes", botName: "Quotes", threadId: "main", instanceId: "claude", driverKind: "claudeAgent",+ model: "claude-sonnet-5", input: 10, output: 5, costUsd: 0.01, trigger: { kind: "user", email: RUI }, section: "Sales", ...fields });++const rows = [+ row({ threadId: "rui-chat", turnId: "turn-1", parent: { threadId: "rui-chat", turnId: "turn-0" } as UsageRow["parent"] }),+ row({ threadId: "rui-run", trigger: { kind: "routine", routineId: "r-rui", label: "Salary check", runId: "run-1", email: RUI } }),+ row({ threadId: "rui-maus-chat", botId: "ruis-maus", botName: "Confidant", section: "Rui's corner" }),+ row({ threadId: "gone-chat", botId: "left-maus", botName: "Old confidant" }),+ row({ threadId: "ana-run", trigger: { kind: "routine", routineId: "r-ana", label: "Ana's digest", email: ANA } }),+ row({ threadId: "main", trigger: { kind: "routine", routineId: "r-team", label: "Standup" } }),+ row({ threadId: "rui-chat", trigger: { kind: "bot", botId: "ruis-maus", email: RUI } }),+];++describe("what an admin reads of other people's records on a Team Cloud", () => {+ it("usage keeps every amount and person and says nothing of what was private", () => {+ const seen = rows.map(records().usageRow(admin(ANA)));+ const told = JSON.stringify(seen) + usageCsv(seen) + JSON.stringify(summarizeUsage(seen, "routine")) + JSON.stringify(summarizeUsage(seen, "bot"));+ for (const secret of ["rui-chat", "rui-run", "rui-maus-chat", "gone-chat", "Salary check", "r-rui", "run-1", "ruis-maus", "Confidant", "left-maus", "Old confidant", "Rui's corner", "turn-1", "turn-0"]) {+ expect(told, secret).not.toContain(secret);+ }+ expect(seen.map((one) => [one.input, one.output, one.costUsd, one.at, one.model])).toEqual(rows.map((one) => [one.input, one.output, one.costUsd, one.at, one.model]));+ expect(summarizeUsage(seen, "user").groups.find((group) => group.key === `user:${RUI}`)?.turns, "all of Rui's turns are still his").toBe(5);+ expect(summarizeUsage(seen, "routine").groups.map((group) => [group.key, group.label, group.turns]).sort()).toEqual([+ ["manual", "Not from a routine", 4], ["routine:private", "Private routine", 1], ["routine:r-ana", "Ana's digest", 1], ["routine:r-team", "Standup", 1],+ ]);+ expect(summarizeUsage(seen, "bot").groups.map((group) => [group.key, group.label, group.turns]).sort()).toEqual([["bot:private", "Private bot", 2], ["bot:quotes", "Quotes", 5]]);+ expect(usageCsv(seen).split("\n")[2]).toBe(`2026-11-10T10:00:00.000Z,Quotes,claude-sonnet-5,claudeAgent,Private routine,10,5,0,0.01,reported,,Sales,${RUI}`);+ expect(seen[5], "a shared routine's row is untouched").toBe(rows[5]);+ });++ it("the person themself reads their own rows whole, and everyone does off a team", () => {+ const own = rows.map(records().usageRow(admin(RUI)));+ expect(own.slice(0, 3)).toEqual(rows.slice(0, 3));+ expect(JSON.stringify(own[4]), "but not another person's private routine").not.toContain("Ana's digest");+ expect(rows.map(records(false).usageRow(admin(ANA)))).toEqual(rows);+ });++ it("a decision in someone's private chat keeps when, tool and outcome, and names their own MausBot to nobody", () => {+ const decision = (fields: Partial<DecisionRow>): DecisionRow => ({ at: "2026-11-10T10:00:00.000Z", threadId: "rui-chat", botId: "quotes", botName: "Quotes", tool: "Bash",+ summary: "rm -rf salary.xlsx", summaryCode: "notice.ran", summaryParams: { file: "salary.xlsx" }, rule: "rm .*", requestId: "req-1", decision: "allowed", source: "user", ...fields } as DecisionRow);+ const read = records().decisionRow(admin(ANA));+ expect(read(decision({}))).toEqual({ at: "2026-11-10T10:00:00.000Z", threadId: "", botId: "quotes", botName: "Quotes", tool: "Bash", decision: "allowed", source: "user" });+ expect(read(decision({ threadId: "rui-maus-chat", botId: "ruis-maus", botName: "Confidant" }))).toMatchObject({ threadId: "", botId: "private", botName: "Private bot" });+ expect(read(decision({ threadId: "gone-chat", botId: "left-maus", botName: "Old confidant" }))).toMatchObject({ botId: "private", botName: "Private bot" });+ const shared = decision({ threadId: "main" });+ expect(read(shared)).toBe(shared);+ const mine = decision({ threadId: "rui-maus-chat", botId: "ruis-maus", botName: "Confidant" });+ expect(records().decisionRow(admin(RUI))(mine)).toBe(mine);+ });++ it("an admin action on a person's own MausBot is listed to that person only", () => {+ const action = (id: string): AdminActionRow => ({ at: "2026-11-10T10:00:00.000Z", category: "bot", action: "bot.update", target: { kind: "bot", id, name: "Confidant" }, actor: { kind: "session" } as AdminActionRow["actor"] });+ expect([action("ruis-maus"), action("quotes"), action("deleted-team-bot")].map(records().adminActionShown(admin(ANA)))).toEqual([false, true, true]);+ expect(records().adminActionShown(admin(RUI))(action("ruis-maus"))).toBe(true);+ expect(records(false).adminActionShown(admin(ANA))(action("ruis-maus"))).toBe(true);+ });+});diff --git a/server/host/private-records.ts b/server/host/private-records.tsnew file mode 100644index 0000000000..c227332a6d--- /dev/null+++ b/server/host/private-records.ts@@ -0,0 +1,65 @@+// What the records an admin reads may say on a Team Cloud (docs/team-cloud.md "Team admin"): usage, the decision log+// and admin activity. Admins read how much each person used, by person and team bot, and when a bot decided something;+// never on what, in which conversation, or anything of a person's own MausBot. Off a team every row is read as it is.+import type { AdminActionRow } from "../admin-activity.ts";+import { routineVisible, type RoutineRef, type VisibleSet } from "../bot-visibility.ts";+import type { DecisionRow } from "../decision-log.ts";+import type { RequestAuth } from "../request-auth.ts";+import { PRIVATE_ROUTINE, type UsageRow } from "../usage-ledger.ts";++/** A person's own MausBot, to anyone else. */+export const PRIVATE_BOT = { botId: "private", botName: "Private bot" } as const;++export interface PrivateRecordsDeps {+ visibleFor(auth: RequestAuth): VisibleSet;+ botExists(botId: string): boolean;+ routine(routineId: string): RoutineRef | undefined;+}++export function createPrivateRecords(deps: PrivateRecordsDeps) {+ /** A bot that is someone else's alone; one since deleted counts when its conversation was theirs. */+ const hidesBot = (visible: VisibleSet, botId: string | undefined, hiddenThread: boolean): boolean =>+ botId !== undefined && (deps.botExists(botId) ? !visible.bot(botId) : hiddenThread);+ return {+ /** Security invariant: a row from someone else's private conversation, private routine or own MausBot keeps its+ * amounts, time, model and person, and loses everything that says what it was: the conversation's id, the routine's+ * name and id, the bot when it is theirs alone. */+ usageRow(auth: RequestAuth) {+ const visible = deps.visibleFor(auth);+ return (row: UsageRow): UsageRow => {+ if (!visible.filtersThreads) return row;+ const hiddenThread = visible.hides(row.threadId);+ const hiddenBot = hidesBot(visible, row.botId, hiddenThread);+ const routine = row.trigger.kind === "routine" && row.trigger.routineId ? deps.routine(row.trigger.routineId) : undefined;+ const hiddenRoutine = row.trigger.kind === "routine" && (hiddenThread || hiddenBot || Boolean(routine && !routineVisible(routine, visible)));+ if (!hiddenThread && !hiddenBot && !hiddenRoutine) return row;+ const { turnId: _turnId, parent: _parent, section, ...kept } = row;+ const person = row.trigger.email ? { email: row.trigger.email } : {};+ return {+ ...kept,+ threadId: "",+ ...(hiddenBot ? PRIVATE_BOT : section === undefined ? {} : { section }),+ trigger: hiddenRoutine ? { kind: "routine", ...PRIVATE_ROUTINE, ...person }+ : row.trigger.kind === "bot" || row.trigger.kind === "helper" ? { kind: row.trigger.kind, ...person } : row.trigger,+ };+ };+ },+ /** Security invariant: a decision in a conversation the reader may not see keeps its when, which team bot, which+ * tool and what was decided; never its words, where, or a bot that is someone else's alone. */+ decisionRow(auth: RequestAuth) {+ const visible = deps.visibleFor(auth);+ return (row: DecisionRow): DecisionRow => {+ if (!visible.hides(row.threadId)) return row;+ const { summary: _summary, summaryCode: _code, summaryParams: _params, rule: _rule, requestId: _requestId, ...kept } = row;+ return { ...kept, threadId: "", ...(visible.filtersThreads && hidesBot(visible, row.botId, true) ? PRIVATE_BOT : {}) };+ };+ },+ /** Security invariant: an admin action on a bot the reader may not see is not theirs to read. */+ adminActionShown(auth: RequestAuth) {+ const visible = deps.visibleFor(auth);+ return (row: AdminActionRow): boolean => !visible.filtersThreads || row.target?.kind !== "bot" || !row.target.id || !hidesBot(visible, row.target.id, false);+ },+ };+}++export type PrivateRecords = ReturnType<typeof createPrivateRecords>;diff --git a/server/host/team-routines.test.ts b/server/host/team-routines.test.tsindex ec9ad9b26a..303e096163 100644--- a/server/host/team-routines.test.ts+++ b/server/host/team-routines.test.ts@@ -76,4 +76,33 @@ describe("createTeamRoutines", () => {const plain = { botId: "scout", resultsThreadId: "main" };expect(host.justMe(session(BOB), plain)).toBe(plain);});++ it("makes a new routine that names no audience its writer's alone, and widens nothing the person did not choose", () => {+ const { host, opened } = fixture();+ expect(host.justMe(session(BOB), { botId: "scout", name: "Kumquat" }), "nothing said: his own chat").toMatchObject({ resultsThreadId: "bob-chat" });+ expect(host.justMe(session(OLIVE), { botId: "scout", name: "Kumquat", target: "bot" })).toMatchObject({ resultsThreadId: "new-chat" });+ expect(opened).toEqual([["scout", "Kumquat", olive]]);+ // The person's own choice still stands: the shared chat by id, and an older app's null.+ const shared = { botId: "scout", name: "Standup", resultsThreadId: "main" }, older = { botId: "scout", name: "Standup", resultsThreadId: null };+ expect(host.justMe(session(BOB), shared)).toBe(shared);+ expect(host.justMe(session(BOB), older)).toBe(older);+ // A change to an existing routine that names no audience moves nothing.+ const change = { name: "Renamed" };+ expect(host.justMe(session(BOB), change, "r1")).toBe(change);+ // Their own MausBot's are theirs already; a group chat's goal has the group chat's audience.+ const own = { botId: "bobs-mausbot", name: "Morning note" }, goal = { botId: "scout", groupId: "room", target: "room-goal", name: "Goal" };+ expect(host.justMe(session(BOB), own)).toBe(own);+ expect(host.justMe(session(BOB), goal)).toBe(goal);+ // No session (the server's own work) and anywhere off a team: as it was.+ const unsaid = { botId: "scout", name: "Kumquat" };+ expect(host.justMe({ kind: "loopback", scopes: ["admin"] } as unknown as RequestAuth, unsaid)).toBe(unsaid);+ expect(fixture(false).host.justMe(session(BOB), unsaid)).toBe(unsaid);+ });++ it("never falls back to the shared place when no private chat can be opened", () => {+ const starters = new Map<string, string>();+ const host = createTeamRoutines({ team: true, privateTo: (threadId) => starters.get(threadId) ?? null, task: () => undefined, routines: () => null, authors: null,+ withWriter: (_writer, work) => work(), tasks: () => [], openChat: () => undefined, threadRefusal: () => null });+ expect(host.justMe(session(BOB), { botId: "scout", name: "Kumquat" })).toMatchObject({ resultsThreadId: RESULTS_JUST_ME });+ });});diff --git a/server/host/team-routines.ts b/server/host/team-routines.tsindex f6ad039277..12cdf248b3 100644--- a/server/host/team-routines.ts+++ b/server/host/team-routines.ts@@ -48,7 +48,7 @@ export function createTeamRoutines(deps: TeamRoutinesDeps) {const routine = deps.routines()?.listRoutines().find((candidate) => candidate.id === id);if (routine?.resultsThreadId && deps.privateTo(routine.resultsThreadId) === left) deps.withWriter(writer, () => deps.routines()!.update(id, { resultsThreadId: null }));};- const field = (body: unknown, key: "botId" | "resultsThreadId" | "name"): unknown => (body && typeof body === "object" ? (body as Record<string, unknown>)[key] : undefined);+ const field = (body: unknown, key: "botId" | "resultsThreadId" | "name" | "target"): unknown => (body && typeof body === "object" ? (body as Record<string, unknown>)[key] : undefined);return {home,inTurn,@@ -75,17 +75,22 @@ export function createTeamRoutines(deps: TeamRoutinesDeps) {const own = typeof botId === "string" ? deps.ownBot?.(botId) : null;return own && (auth.kind !== "session" || own !== personKey(auth.session)) ? { status: 404, error: "no such bot" } : null;},- /** "Just me" made concrete: the person's own private chat with the bot, else a new one named for the routine. */+ /** "Just me" made concrete: the person's own private chat with the bot, else a new one named for the routine.+ * Security invariant: a new routine for a bot that names no audience is its writer's alone, as a new conversation+ * is; only the person's own choice (the shared chat, or an older app's null) makes one the team's. */justMe<T>(auth: RequestAuth, body: T, routineId?: string): T {- if (!deps.team || auth.kind !== "session" || field(body, "resultsThreadId") !== RESULTS_JUST_ME) return body;- const person = personKey(auth.session);+ if (!deps.team || auth.kind !== "session") return body;+ const person = personKey(auth.session), named = field(body, "botId");+ const unsaid = !routineId && field(body, "resultsThreadId") === undefined && typeof named === "string" &&+ (field(body, "target") ?? "bot") === "bot" && deps.ownBot?.(named) !== person;+ if (field(body, "resultsThreadId") !== RESULTS_JUST_ME && !unsaid) return body;const existing = routineId ? deps.routines()?.listRoutines().find((routine) => routine.id === routineId) : undefined;const botId = typeof field(body, "botId") === "string" ? field(body, "botId") as string : existing?.botId;if (!botId) return body;const name = typeof field(body, "name") === "string" ? field(body, "name") as string : existing?.name ?? "Routine";const mine = deps.tasks(botId).find((task) => !task.routineRunId && deps.privateTo(task.threadId) === person && !isOwnResultsChat(name, task));const threadId = mine?.threadId ?? deps.openChat(botId, name, person);- return threadId ? { ...body, resultsThreadId: threadId } : body;+ return { ...body, resultsThreadId: threadId ?? RESULTS_JUST_ME };},/** Why a bot's change to a trigger by id is refused in this conversation: one that lives in someone else's private chat. */hiddenTrigger(request: { kind: string; proposal?: { routineId?: string } }, threadId: string): string | null {diff --git a/server/host/visibility-host.ts b/server/host/visibility-host.tsindex 7dc4ae88af..abe0ed3993 100644--- a/server/host/visibility-host.ts+++ b/server/host/visibility-host.ts@@ -4,6 +4,7 @@// only their own private chats (audience.ts).import { basename } from "node:path";+import { baseBotId } from "../audience.ts";import { audienceEquals, narrowestAudience, roomFeeds, routineRunVisible, routineVisible, SEES_EVERYTHING, VisibleSet, type PathSubject, type ThreadAudiences, type ThreadOwner, type Viewer } from "../bot-visibility.ts";import type { RequestAuth } from "../request-auth.ts";import type { RoutineManager } from "../routines.ts";@@ -83,8 +84,12 @@ export function createVisibilityHost(deps: VisibilityHostDeps) {/** The one visibility check every member request naming a subject passes through (a team's admin's too). */function subjectVisible(subject: PathSubject, visible: VisibleSet): boolean {switch (subject.kind) {- case "bot":- return !store.bot(subject.id) || visible.bot(subject.id);+ case "bot": {+ // Security invariant: on a Team Cloud a bot hidden from the viewer and an id no bot has are refused here alike,+ // before any route can answer them differently.+ const bot = store.bot(subject.id) ?? (deps.team ? store.bot(baseBotId(subject.id)) : undefined);+ return bot ? visible.bot(bot.id) : !deps.team;+ }case "thread":return !threadOwner(subject.id) || visible.thread(subject.id);case "group":diff --git a/server/index.ts b/server/index.tsindex 3bac65772c..5539ec4fd1 100644--- a/server/index.ts+++ b/server/index.ts@@ -626,7 +626,7 @@ import { findAntigravityLeftovers, removeAntigravityLeftovers } from "./drivers/import { createLiveRoutes } from "./routes/live.ts";import { createNotificationRoutes, notificationListedFor } from "./routes/notifications.ts";import { createTodayRoutes } from "./routes/today.ts"; import { createInboxRoutes } from "./routes/inbox.ts"; import { createSidebarSectionRoutes } from "./routes/sidebar-sections.ts";-import { createToolTimingRoute, createUsageRoutes } from "./routes/usage.ts";+import { createToolTimingRoute, createUsageRoutes } from "./routes/usage.ts"; import { createPrivateRecords } from "./host/private-records.ts";import { createBotMessageRoutes } from "./routes/bot-messages.ts";import { clearInternalTurn, isInternalTurn, markInternalTurn } from "./internal-turns.ts"; import { createFirstReplyRescue } from "./first-reply-rescue.ts";import { createReactionRoutes } from "./routes/reactions.ts";@@ -1268,7 +1268,7 @@ function beginAdminAudit(req: IncomingMessage, res: ServerResponse, method: striconst sharedAtStart = plan ? adminActivityRecording() : false;// Set for every request, so a kept-alive connection never inherits one.adminActorScope.enterWith(plan?.config && actor ? { actor, sharedAtStart } : null);- if (!plan || !actor) return;+ if (!plan || !actor || store.bot(plan.botId ?? plan.deletesBot ?? "")?.defaultBot?.person) return; // a person's own MausBot is not the team's: what they do with it is never an admin's to readconst before = {bot: auditBot(plan.botId ?? plan.deletesBot),botName: store.bot(plan.botId ?? plan.deletesBot ?? "")?.name,@@ -12315,7 +12315,7 @@ ROUTES.push(createTeamRoutes({defaultSelection,defaultsPresetFor,packageImportDeps,- starterNotes, threadShown, routineShown: (auth) => (routine) => routineVisible(routine, visibleTo(viewerFor(auth))),+ starterNotes, threadShown, botShown: (auth) => (botId) => visibleTo(viewerFor(auth)).bot(botId), routineShown: (auth) => (routine) => routineVisible(routine, visibleTo(viewerFor(auth))),...skillExport(skillsHost),}));ROUTES.push(createBrowserSiteRoutes({@@ -12325,7 +12325,7 @@ ROUTES.push(createBrowserSiteRoutes({}));ROUTES.push(createBrowserEvidenceRoutes({ evidence: browserEvidence.attach({ onChange: (listener) => store.onChange(listener), threadExists: (id) => Boolean(threadOwner(id)) }), threadExists: (id) => Boolean(threadOwner(id)) }));const loginRoutes = botLogins.routes((id) => Boolean(store.bot(id))); ROUTES.push(createLoginRoutes(loginRoutes), createVaultRoutes({ logins: loginRoutes, secrets: logins, linked: () => botLogins.linkedSecrets(), keys: mcpKeys }));-ROUTES.push(createUsageRoutes({+const privateRecords = createPrivateRecords({ visibleFor: (auth) => visibleTo(viewerFor(auth)), botExists: (id) => Boolean(store.bot(id)), routine: (id) => routines?.listRoutines().find((routine) => routine.id === id) }); ROUTES.push(createUsageRoutes({dataDir: DATA_DIR, prices: operatorPrices,budget: () => spendState(cfg, DATA_DIR),currency: () => cfg.billing?.currency ?? "USD",@@ -12333,7 +12333,7 @@ ROUTES.push(createUsageRoutes({const bot = store.botByThread(threadId) ?? store.bot(groupSpeakers.get(threadId)?.botId ?? "");return bot ? { botId: bot.id, botName: bot.name, model: bot.modelSelection.model, driverKind: registry.get(bot.modelSelection.instanceId)?.driverKind ?? "" } : null;},- canSee: (auth) => { const visible = visibleTo(viewerFor(auth)); return (threadId) => visible.thread(threadId); },+ canSee: (auth) => { const visible = visibleTo(viewerFor(auth)); return (threadId) => visible.thread(threadId); }, rowFor: privateRecords.usageRow,}));ROUTES.push(createThreadModelRoutes({bot: (id) => store.bot(id),@@ -12417,7 +12417,7 @@ ROUTES.push(createComputerRoutes({ROUTES.push(createStatusRoutes({store, cfg,staticDir: STATIC_DIR,- sharedWorkspaceFullAccessEnabled, adminActivityRecording, configStatus, broadcast, threadShown, boxOn: () => botBox.enabled(),+ sharedWorkspaceFullAccessEnabled, adminActivityRecording, configStatus, broadcast, threadShown, records: privateRecords, boxOn: () => botBox.enabled(),browserEngineInstall: { get: () => browserEngineInstall, set: (install) => { browserEngineInstall = install; } },browserEngineInstallError: { set: (error) => { browserEngineInstallError = error; } },}));diff --git a/server/outside-lineage.e2e.test.ts b/server/outside-lineage.e2e.test.tsindex 0e80b5e538..28c4e4123f 100644--- a/server/outside-lineage.e2e.test.ts+++ b/server/outside-lineage.e2e.test.ts@@ -157,7 +157,7 @@ describe("a Team Cloud", () => {it("keeps a confined turn from starting or changing a person's routine", async () => {const scout = await newBot("Routine starter");- const mine = (await team.as(ada, "POST", "/api/routines", { name: "Ada's", prompt: "routine-of-a-person", botId: scout.id, enabled: false, schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 } })).body.routine;+ const mine = (await team.as(ada, "POST", "/api/routines", { name: "Ada's", prompt: "routine-of-a-person", botId: scout.id, resultsThreadId: null, enabled: false, schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 } })).body.routine;const { thread } = await webhookTurn(scout.id, "Starter hook", "marker-starter");const refused = await internal(scout.id, thread, "/api/internal/trigger-requests", { action: "run_now", triggerId: mine.id });expect(refused).toMatchObject({ status: 403, body: { error: OUTSIDE_STAYS_HERE } });diff --git a/server/routes/status.ts b/server/routes/status.tsindex 2375601191..3510f7fbc0 100644--- a/server/routes/status.ts+++ b/server/routes/status.ts@@ -16,6 +16,7 @@ import type { Store } from "../store.ts";import { readThreadEvents } from "../thread-events.ts";import { parseUsageRange } from "../usage-ledger.ts";import type { ConfigStatus } from "./config.ts";+import type { PrivateRecords } from "../host/private-records.ts";import type { RequestAuth } from "../request-auth.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -31,15 +32,12 @@ export interface StatusRouteDeps {browserEngineInstallError: { set(error: string | null): void };/** On a Team Cloud: false for someone else's private chat, whose words never reach this session's lists. */threadShown?(auth: RequestAuth): (threadId: string) => boolean;+ /** On a Team Cloud: the decision and admin rows as this reader may see them (host/private-records.ts). */+ records?: Pick<PrivateRecords, "decisionRow" | "adminActionShown">;/** Whether bots run in the bot box: the MausBot connector reads it on a server its owner runs, on or off and nothing more. */boxOn?(): boolean;}-/** A decision in a conversation the reader may not see keeps its when, which bot, which tool and what was decided (the- * activity a team's admin sees), never its words or where. */-function readable(rows: DecisionRow[], shown: (threadId: string) => boolean): DecisionRow[] {- return rows.map((row) => shown(row.threadId) ? row : { ...row, threadId: "", summary: undefined, rule: undefined, requestId: undefined });-}export function createStatusRoutes(deps: StatusRouteDeps): RouteHandler {const {@@ -49,6 +47,7 @@ export function createStatusRoutes(deps: StatusRouteDeps): RouteHandler {return async ({ req, res, url, path, method, auth, json, readBody }) => {let m: RegExpMatchArray | null = null;const shown = deps.threadShown?.(auth) ?? (() => true);+ const decision = deps.records?.decisionRow(auth) ?? ((row: DecisionRow) => row);// The packaged app's port fallback: the forked child proves it is ours by echoing its pid.if (method === "GET" && path === "/api/health") {return json(res, 200, { app: "openmausbot", pid: process.pid, static: Boolean(STATIC_DIR), capabilities: {@@ -179,7 +178,7 @@ export function createStatusRoutes(deps: StatusRouteDeps): RouteHandler {if (parsedLimit !== undefined && (!Number.isInteger(parsedLimit) || parsedLimit <= 0)) {return json(res, 400, { error: "limit must be a positive whole number" });}- return json(res, 200, { decisions: readable(readDecisions(DATA_DIR, parsedLimit ?? 200), shown) });+ return json(res, 200, { decisions: readDecisions(DATA_DIR, parsedLimit ?? 200).map(decision) });}if (method === "GET" && (path === "/api/admin-activity" || path === "/api/admin-activity.csv")) {const fromParam = url.searchParams.get("from") || new Date(Date.now() - 29 * 24 * 60 * 60_000).toISOString().slice(0, 10);@@ -187,7 +186,7 @@ export function createStatusRoutes(deps: StatusRouteDeps): RouteHandler {if (!range) return json(res, 400, { error: "from and to must be dates (YYYY-MM-DD), from no later than to, at most a year apart" });const what = parseActivityWhat(url.searchParams.get("what"));if (!what) return json(res, 400, { error: "what must be all, approvals, decisions, config, people, session, webhook, mcp, engine, bot, budget or visibility" });- const entries = activityEntries(readable(readDecisionRange(DATA_DIR, range), shown), readAdminActivityRange(DATA_DIR, range), {+ const entries = activityEntries(readDecisionRange(DATA_DIR, range).map(decision), readAdminActivityRange(DATA_DIR, range).filter(deps.records?.adminActionShown(auth) ?? (() => true)), {what,who: (url.searchParams.get("who") ?? "").slice(0, 200),});@@ -222,7 +221,7 @@ export function createStatusRoutes(deps: StatusRouteDeps): RouteHandler {"content-disposition": `attachment; filename="decisions-${stamp(range.from)}-${stamp(range.to)}.csv"`,"cache-control": "no-store",});- res.end(decisionsCsv(readable(readDecisionRange(DATA_DIR, range), shown)));+ res.end(decisionsCsv(readDecisionRange(DATA_DIR, range).map(decision)));return;}diff --git a/server/routes/team-owners.ts b/server/routes/team-owners.tsindex 4ddad646e8..969c0d3e5b 100644--- a/server/routes/team-owners.ts+++ b/server/routes/team-owners.ts@@ -124,6 +124,8 @@ export function createTeamOwnerRoutes(deps: TeamOwnerRouteDeps): RouteHandler {if (!parsed.success) return json(res, 400, { error: "Send botIds and an email." });const { email } = parsed.data;if (unknownPerson(email)) return json(res, 400, userError("serverError.owner.choose", { team: team.name }));+ // Security invariant: a bot the caller cannot see is unavailable exactly as an id no bot has.+ if (parsed.data.botIds.some((id) => deps.store.bot(id) && !deps.sees(auth, id))) return json(res, 404, userError("serverError.owner.unavailable"));const botIds = parsed.data.botIds.filter((id) => !deps.store.bot(id)?.defaultBot?.person);const owners = new Map(botIds.map((id) => { const one = deps.store.bot(id); return [id, one && botOwner(one)]; }));const changed = setReportsTo(deps.store, botIds, email);diff --git a/server/routes/teams.ts b/server/routes/teams.tsindex 317bffc02c..36fe983cde 100644--- a/server/routes/teams.ts+++ b/server/routes/teams.ts@@ -58,6 +58,8 @@ export interface TeamRouteDeps {| { ok: false; error: string; available: string[] };/** On a Team Cloud: false for someone else's private chat, which a team backup never carries. */threadShown?(auth: RequestAuth): (threadId: string) => boolean;+ /** On a Team Cloud: false for someone else's own MausBot, which no export carries. */+ botShown?(auth: RequestAuth): (botId: string) => boolean;/** On a Team Cloud: false for a routine that lives in someone else's private chat, which no export carries. */routineShown?(auth: RequestAuth): (routine: Routine) => boolean;}@@ -78,6 +80,7 @@ export function createTeamRoutes(deps: TeamRouteDeps): RouteHandler {const orgLibrary = deps.orgLibrary();if (method === "POST" && path === "/api/teams/export") {const body = await readBody(req, 8 * 1024 * 1024);+ const botShown = deps.botShown?.(auth), exportable = botShown ? store.bots.filter((bot) => botShown(bot.id)) : store.bots;const profileName = deps.authorName(auth);if (body.format === "package" && body.version === 2 && body.kind === "library") {const optional = (value: unknown) => (typeof value === "string" ? value : undefined);@@ -110,11 +113,11 @@ export function createTeamRoutes(deps: TeamRouteDeps): RouteHandler {if (body.format === "package" && body.version === 2) {if (typeof body.team !== "string") return json(res, 400, { error: "Choose a team to share." });const team = body.team.trim();- if (team && !store.sections.includes(team) && !store.bots.some((bot) => sectionKey(bot.section) === team)) {+ if (team && !store.sections.includes(team) && !exportable.some((bot) => sectionKey(bot.section) === team)) {return json(res, 404, { error: "That team no longer exists." });}const optional = (value: unknown) => (typeof value === "string" ? value : undefined);- const teamBots = store.bots.filter((bot) => !bot.hidden && sectionKey(bot.section) === team);+ const teamBots = exportable.filter((bot) => !bot.hidden && sectionKey(bot.section) === team);const skills = collectTeamSkills(teamBots, body.skills);if (!skills.ok) return json(res, 400, { error: skills.error, choices: { skills: skills.available } });const avatars = body.avatars && typeof body.avatars === "object" && !Array.isArray(body.avatars)@@ -130,7 +133,7 @@ export function createTeamRoutes(deps: TeamRouteDeps): RouteHandler {release: optional(body.release),notes: optional(body.notes),authorName: profileName,- bots: store.bots,+ bots: exportable,groups: store.groups,routines: routinesFor(auth),brief: readSectionContext(team)?.text,@@ -163,14 +166,14 @@ export function createTeamRoutes(deps: TeamRouteDeps): RouteHandler {: profileName? `${profileName}'s Team`: "My OpenMaus Team";- const memberIds = store.bots.filter((bot) => !bot.hidden).map((bot) => bot.id);- if ((body.format === "backup" ? store.bots.length : memberIds.length) === 0) return json(res, 400, { error: "Create a bot before exporting your team" });+ const memberIds = exportable.filter((bot) => !bot.hidden).map((bot) => bot.id);+ if ((body.format === "backup" ? exportable.length : memberIds.length) === 0) return json(res, 400, { error: "Create a bot before exporting your team" });try {if (body.format === "backup") {return json(res, 200, createTeamBackup(store, routinesFor(auth), name, deps.threadShown?.(auth)));}if (body.format === "package") {- const selectedBots = store.bots.filter((bot) => !bot.hidden);+ const selectedBots = exportable.filter((bot) => !bot.hidden);const skillNames = checkedExportSkillNames(body.skillIds, selectedBots);if (!skillNames.ok) return json(res, 400, { error: skillNames.error });const document = createBotPackageExport({@@ -195,7 +198,7 @@ export function createTeamRoutes(deps: TeamRouteDeps): RouteHandler {name,memberIds,},- store.bots,+ exportable,),);} catch (error) {diff --git a/server/routes/usage.ts b/server/routes/usage.tsindex d626a83a90..ac136ebb3c 100644--- a/server/routes/usage.ts+++ b/server/routes/usage.ts@@ -10,6 +10,7 @@ import {usageCsv,USAGE_GROUPINGS,type UsageGroupBy,+ type UsageRow,} from "../usage-ledger.ts";import { DETAIL_MAX, ERROR_MAX } from "../usage-trace/detail.ts";import type { ToolReceipt, TraceRecorder } from "../usage-trace/recorder.ts";@@ -26,6 +27,8 @@ export interface UsageRouteDeps {liveBot: TraceServiceDeps["liveBot"];/** Which threads this viewer may read today; a trace shows only those. */canSee(auth: RequestAuth): (threadId: string) => boolean;+ /** A row as this viewer may read it (host/private-records.ts). */+ rowFor(auth: RequestAuth): (row: UsageRow) => UsageRow;}const TRACE = /^\/api\/usage\/traces\/([^/]{1,600})$/;@@ -63,7 +66,7 @@ export function createUsageRoutes(deps: UsageRouteDeps): RouteHandler {const range = parseUsageRange(url.searchParams.get("from"), url.searchParams.get("to"));if (!range) return json(res, 400, { error: "from and to must be YYYY-MM-DD, from no later than to, at most a year apart" });await flushUsageLedger(deps.dataDir);- const rows = readUsage(deps.dataDir, range);+ const rows = readUsage(deps.dataDir, range).map(deps.rowFor(auth));const prices = deps.prices();if (path === "/api/usage.csv") {const stamp = (date: Date) => date.toISOString().slice(0, 10);diff --git a/server/usage-ledger.ts b/server/usage-ledger.tsindex 65791aca57..897bfb98ed 100644--- a/server/usage-ledger.ts+++ b/server/usage-ledger.ts@@ -217,6 +217,10 @@ export function queuedTurnTrigger(item: { trigger?: UsageTrigger; sender?: Resolreturn item.sender ? { kind: "user", label: item.sender.name } : { kind: "owner" };}+/** On a Team Cloud, every routine in someone else's private chat as anyone else reads it (host/private-records.ts): one+ * line with no name and no id. */+export const PRIVATE_ROUTINE = { routineId: "private", label: "Private routine" } as const;+export function triggerKey(trigger: UsageTrigger): string {switch (trigger.kind) {case "user":@@ -239,7 +243,7 @@ export function triggerLabel(trigger: UsageTrigger): string {case "owner":return "This computer";case "routine":- return `Routine: ${trigger.label ?? trigger.routineId ?? "unknown"}`;+ return trigger.routineId === PRIVATE_ROUTINE.routineId ? PRIVATE_ROUTINE.label : `Routine: ${trigger.label ?? trigger.routineId ?? "unknown"}`;case "helper":return "Helper model";default:diff --git a/src/components/RoutineCalendarPage.simple.test.ts b/src/components/RoutineCalendarPage.simple.test.tsindex 29b5c28c52..bcd7973985 100644--- a/src/components/RoutineCalendarPage.simple.test.ts+++ b/src/components/RoutineCalendarPage.simple.test.ts@@ -396,3 +396,59 @@ describe("routine editor", () => {expect(html).not.toContain("What should happen?");});});++describe("a new routine's audience on a team's Cloud", () => {+ const quotes = { ...bot, id: "quotes", name: "Quotes", threadId: "mine", mainThreadId: "main", tasks: [+ { threadId: "main", title: "Shared chat", createdAt: 1, sharedChat: true }, { threadId: "mine", title: "Salary talk", createdAt: 2, private: true },+ ] } as Bot;+ const other = { ...bot, id: "other", name: "Other", threadId: "other-main", mainThreadId: "other-main", tasks: [{ threadId: "other-main", title: "Shared chat", createdAt: 1, sharedChat: true }] } as Bot;+ /** The form as opened with this bot's chat on screen; what it shows, and what Save sends. */+ function opened(onScreen: Bot, state: Partial<AppState> = {}) {+ fixture.state = { ...initialState, bots: [onScreen, other], selectedId: onScreen.id, activeView: "chat", config: { box: { configured: false }, team: { id: "t1", name: "Acme" } } as AppState["config"], ...state };+ fixture.values = [];+ fixture.api.mockClear();+ const props = { seed: { kind: "routine" as const, at: Date.now() + 3_600_000, durationMinutes: 30, botIds: [onScreen.id], name: "Salary check", description: "Check the bands" },+ bots: [onScreen, other], onClose: vi.fn(), onSavedCall: vi.fn() };+ const tree = () => capture(() => EventEditor(props));+ const line = () => tree().find(named("RoutineAudience"))!.props as { value: unknown; bot?: Bot; team?: { name: string } };+ const saved = () => {+ click(buttons(tree()).get("Save"));+ return JSON.parse((fixture.api.mock.calls.at(-1) as unknown as [string, { body: string }])[1].body) as { resultsThreadId?: unknown };+ };+ return { props, tree, line, saved, html: () => renderToStaticMarkup(createElement(EventEditor, props)) };+ }++ it("opened from a private chat, it is private: the line says so without opening More options, and Save sends Just me", () => {+ const form = opened(quotes);+ expect(form.line()).toMatchObject({ value: "just-me", team: { name: "Acme" } });+ const html = form.html();+ expect(html).toContain('data-routine-audience="me"');+ expect(html).toContain("Private · only you");+ expect(html, "More options stays closed").not.toContain("Post results to");+ opened(quotes);+ expect(opened(quotes).saved().resultsThreadId).toBe("just-me");+ });++ it("opened from the shared chat, it is shared and says who will see it", () => {+ const form = opened({ ...quotes, threadId: "main" });+ expect(form.line().value).toBe("main");+ expect(form.html()).toContain("Shared · everyone in Acme can see");+ expect(opened({ ...quotes, threadId: "main" }).saved().resultsThreadId).toBe("main");+ });++ it("opened where no chat is on screen, or moved to another bot, it is private until the person chooses", () => {+ expect(opened({ ...quotes, threadId: "main" }, { activeView: "routines" }).saved().resultsThreadId).toBe("just-me");+ const form = opened({ ...quotes, threadId: "main" });+ const picker = form.tree().find(named("BotPicker"))!.props as { onChange: (ids: string[]) => void };+ picker.onChange(["other"]);+ expect(form.line().value, "the shared chat on screen was Quotes', not Other's").toBe("just-me");+ expect(form.saved().resultsThreadId).toBe("just-me");+ });++ it("off a team the form is as it was: no line, and the bot's own results chat", () => {+ const form = opened(quotes, { config: initialState.config });+ expect(form.line().team).toBeUndefined();+ expect(form.html()).not.toContain("data-routine-audience");+ expect(form.saved().resultsThreadId).toBeNull();+ });+});diff --git a/src/components/RoutineCalendarPage.tsx b/src/components/RoutineCalendarPage.tsxindex b5c7ed4cc9..fb5a7472b9 100644--- a/src/components/RoutineCalendarPage.tsx+++ b/src/components/RoutineCalendarPage.tsx@@ -35,7 +35,7 @@ import {import { BotAvatar } from "@/components/Avatar";import { useBotEditor } from "./bot-settings/BotEditorContext";import { pathForFile } from "@/components/ComposerAttachments";-import { ResultsDestination } from "@/components/routines/ResultsDestination";+import { ResultsDestination, resultsOfPlace, RoutineAudience } from "@/components/routines/ResultsDestination";import { CronScheduleFields, CronSchedulePreview } from "@/components/routines/CronScheduleFields";import { cronChoiceFor, cronDraftFor, cronEditorValue, isCronChoice, type CronChoice } from "@/components/routines/cron-editor";import { partlyDone, routineRunLabel, routineRunsOn, routineRunText, routineRunTime, routineScheduleState } from "@/lib/routine-display";@@ -348,9 +348,9 @@ export function EventEditor({? toLocalDateInput(schedule.endsAt): toLocalDateInput(addDays(startOfDay(Math.max(Date.now(), initialAt)), 7)));const [botIds, setBotIds] = useState(lockedBotId ? [lockedBotId] : existingRoutine ? [existingRoutine.botId] : existingCall?.botIds ?? seed.botIds);- const [resultsThreadId, setResultsThreadId] = useState<string | null | undefined>((existingRoutine ? existingRoutine.resultsThreadId : seed.resultsThreadId) ?? null);+ const [resultsThreadId, setResultsThreadId] = useState<string | null | undefined>(() => (existingRoutine ? existingRoutine.resultsThreadId : seed.resultsThreadId ?? resultsOfPlace(state, botIds[0])) ?? null);const selectBots = (ids: string[]) => {- if (ids[0] !== botIds[0]) setResultsThreadId(null);+ if (ids[0] !== botIds[0]) setResultsThreadId(resultsOfPlace(state, ids[0]) ?? null);setBotIds(ids);};const [routineTarget, setRoutineTarget] = useState<RoutineTarget>(existingRoutine?.target ?? "bot");@@ -944,7 +944,7 @@ export function EventEditor({{bots.length > 0 ? (<><BotPicker bots={bots} selected={botIds} multiple={kind === "call"} locked={Boolean(lockedBotId)} onChange={selectBots} />- <div className="mt-2 text-[12px] text-ink-secondary">{kind === "routine" ? t("routines.event.botOwnsRuns") : t(selectedBots.length === 0 ? "routines.event.invitedNone" : selectedBots.length === 1 ? "routines.event.invitedOne" : "routines.event.invitedMany", { count: selectedBots.length })}</div>+ <div className="mt-2 text-[12px] text-ink-secondary">{kind === "routine" ? t("routines.event.botOwnsRuns") : t(selectedBots.length === 0 ? "routines.event.invitedNone" : selectedBots.length === 1 ? "routines.event.invitedOne" : "routines.event.invitedMany", { count: selectedBots.length })}</div>{kind === "routine" && <RoutineAudience team={state.config?.team} bot={selectedBots[0]} value={resultsThreadId} madeIn={existingRoutine?.sourceThreadId} />}</>) : (<button type="button" onClick={() => { dispatch({ type: "newBot" }); onClose(); }} className="w-full rounded-xl border border-dashed border-accent/45 bg-accent/[0.06] px-4 py-4 text-left hover:bg-accent/10">@@ -1028,14 +1028,14 @@ export function QuickComposer({onSavedRoutine: (routine: Routine) => void;onSavedCall: (call: CalendarCall) => void;}) {- const { dispatch } = useStore();+ const { state, dispatch } = useStore();const [kind, setKind] = useState<EventKind>(routinesOnly || seed.limitReset ? "routine" : seed.kind);const [name, setName] = useState(seed.name ?? "");const [description, setDescription] = useState(seed.description ?? "");const [botIds, setBotIds] = useState(seed.botIds.length ? seed.botIds : bots[0] ? [bots[0].id] : []);- const [resultsThreadId, setResultsThreadId] = useState<string | null>(seed.resultsThreadId ?? null);+ const [resultsThreadId, setResultsThreadId] = useState<string | null>(() => seed.resultsThreadId ?? resultsOfPlace(state, botIds[0]) ?? null);const selectBots = (ids: string[]) => {- if (ids[0] !== botIds[0]) setResultsThreadId(null);+ if (ids[0] !== botIds[0]) setResultsThreadId(resultsOfPlace(state, ids[0]) ?? null);setBotIds(ids);};const [working, setWorking] = useState(false);@@ -1148,7 +1148,7 @@ export function QuickComposer({<FileText size={16} className="mt-2.5 shrink-0 text-ink-secondary" /><textarea value={description} onChange={(event) => setDescription(event.target.value)} rows={3} aria-label={t("routines.editor.descriptionLabel")} placeholder={t(kind === "routine" ? "routines.quick.whatToDo" : "routines.quick.description")} className="min-w-0 flex-1 resize-none rounded-lg border border-hairline/50 bg-inset px-3 py-2 text-[13px] leading-relaxed text-ink outline-none placeholder:text-ink-tertiary focus:border-accent" /></div>- {kind === "routine" && <ResultsDestination bot={bots.find((bot) => bot.id === botIds[0])} value={resultsThreadId} onChange={(threadId) => setResultsThreadId(threadId ?? null)} />}+ {kind === "routine" && <ResultsDestination bot={bots.find((bot) => bot.id === botIds[0])} value={resultsThreadId} onChange={(threadId) => setResultsThreadId(threadId ?? null)} />}{kind === "routine" && <RoutineAudience team={state.config?.team} bot={bots.find((bot) => bot.id === botIds[0])} value={resultsThreadId} />}{error && <div className="rounded-lg bg-danger/10 px-3 py-2 text-[12px] text-danger">{error}</div>}</div><div className="flex items-center justify-end gap-2 border-t border-hairline/40 px-4 py-3">diff --git a/src/components/UsageSection.tsx b/src/components/UsageSection.tsxindex 75b9017edb..38e3d14943 100644--- a/src/components/UsageSection.tsx+++ b/src/components/UsageSection.tsx@@ -55,6 +55,8 @@ const PERIOD_LABEL_KEYS: Record<UsagePeriod, LocaleKey> = {const LIVE_REFRESH_MS = 2_000;export function usageGroupLabel(groupBy: UsageGroupBy, group: Pick<UsageGroup, "key" | "label">): string {+ if (group.key === "routine:private") return t("usage.history.privateRoutine");+ if (group.key === "bot:private") return t("usage.history.privateBot");if (groupBy === "routine") return group.key === "manual" ? t("usage.history.notRoutine") : group.label;if (groupBy === "department") return group.label || t("usage.history.noDepartment");if (groupBy !== "user") return group.label;diff --git a/src/components/routines/ResultsDestination.test.ts b/src/components/routines/ResultsDestination.test.tsindex a173610850..6d38c7d098 100644--- a/src/components/routines/ResultsDestination.test.ts+++ b/src/components/routines/ResultsDestination.test.ts@@ -2,7 +2,7 @@ import { createElement } from "react";import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it, vi } from "vitest";import type { Bot } from "@/state/store";-import { ResultsDestination } from "./ResultsDestination";+import { ResultsDestination, resultsOfPlace, RoutineAudience, type RoutinePlace } from "./ResultsDestination";const bot = {id: "pepper", projects: [{ id: "management", name: "OMB management" }],@@ -47,4 +47,38 @@ describe("routine result destination", () => {expect(renderToStaticMarkup(createElement(ResultsDestination, { bot: team, value: "mine", team: true, onChange: vi.fn() }))).toContain('value="me" selected=""');expect(renderToStaticMarkup(createElement(ResultsDestination, { bot: team, value: "just-me", team: true, onChange: vi.fn() }))).toContain('value="me" selected=""');});++ describe("on a team's Cloud", () => {+ const quotes = { id: "quotes", threadId: "mine", mainThreadId: "main", tasks: [+ { threadId: "main", title: "Shared chat", sharedChat: true }, { threadId: "mine", title: "Salary talk", private: true }, { threadId: "run", title: "A run", routineRunId: "run-1" },+ ] } as Bot;+ const maus = { id: "maus", threadId: "inbox", defaultBot: { person: "[email protected]" }, tasks: [{ threadId: "inbox", title: "Inbox", private: true }] } as Bot;+ const place = (fields: Partial<RoutinePlace>, bot: Bot = quotes): RoutinePlace => ({ activeView: "chat", selectedId: bot.id, bots: [bot, maus], config: { team: { name: "Acme" } }, ...fields });+ const line = (bot: Bot, value: string | null | undefined, madeIn?: string) => renderToStaticMarkup(createElement(RoutineAudience, { team: { name: "Acme" }, bot, value, madeIn }));++ it("presets the audience of the place the form was opened from, and the person alone anywhere else", () => {+ expect(resultsOfPlace(place({}), "quotes"), "from a private chat").toBe("just-me");+ expect(resultsOfPlace(place({}, { ...quotes, threadId: "main" }), "quotes"), "from the shared chat").toBe("main");+ expect(resultsOfPlace(place({}, { ...quotes, threadId: "run" }), "quotes"), "a run's own conversation is no place to share from").toBe("just-me");+ expect(resultsOfPlace(place({ activeView: "routines" }, { ...quotes, threadId: "main" }), "quotes"), "the Automations page is no chat").toBe("just-me");+ expect(resultsOfPlace(place({ selectedId: "maus" }, { ...quotes, threadId: "main" }), "quotes"), "another bot's chat on screen").toBe("just-me");+ expect(resultsOfPlace(place({}), undefined), "no bot chosen yet").toBe("just-me");+ expect(resultsOfPlace(place({}), "maus"), "their own MausBot is theirs already").toBeNull();+ expect(resultsOfPlace(place({ config: {} }), "quotes"), "off a team").toBeUndefined();+ });++ it("says who will see the routine in the words of the label by the message box", () => {+ expect(line(quotes, "just-me")).toContain('data-routine-audience="me"');+ expect(line(quotes, "just-me")).toContain("Private · only you");+ expect(line(quotes, "mine")).toContain("Private · only you");+ expect(line(quotes, null, "mine"), "one a bot made in their private chat").toContain("Private · only you");+ expect(line(maus, null)).toContain("Private · only you");+ for (const value of ["main", null, undefined]) {+ expect(line(quotes, value)).toContain('data-routine-audience="shared"');+ expect(line(quotes, value)).toContain("Shared · everyone in Acme can see");+ }+ expect(line({ ...quotes, onlyPeopleAdded: true } as Bot, "main")).toContain("Shared · only people added and admins can see");+ expect(renderToStaticMarkup(createElement(RoutineAudience, { team: null, bot: quotes, value: null })), "nothing off a team").toBe("");+ });+ });});diff --git a/src/components/routines/ResultsDestination.tsx b/src/components/routines/ResultsDestination.tsxindex 84e0ea09ff..755f330904 100644--- a/src/components/routines/ResultsDestination.tsx+++ b/src/components/routines/ResultsDestination.tsx@@ -1,9 +1,46 @@+import { Lock, Users } from "lucide-react";import { useId } from "react";import { RESULTS_JUST_ME } from "../../../shared/routines";import { t } from "@/lib/i18n";import type { Bot } from "@/state/store";import { useTeamPeople } from "@/state/team-people";import { Select } from "../Select";+import { sharedChatAudience } from "../TeamPrivateChatsLine";++/** What of the app's state says where a routine's form was opened. */+export interface RoutinePlace {+ activeView: string;+ selectedId: string;+ bots: readonly Bot[];+ config?: { team?: { name: string } } | null;+}++/** A new routine starts with the audience of the place its form was opened from. On a team's Cloud that is the shared+ * chat only while this bot's shared chat is on screen; in a private chat, and anywhere that is no chat with this bot,+ * it is the person alone, so nothing is shared that they did not choose to share. Off a team: undefined. */+export function resultsOfPlace(place: RoutinePlace, botId: string | undefined): string | null | undefined {+ if (!place.config?.team) return undefined;+ const bot = place.bots.find((candidate) => candidate.id === botId);+ if (bot?.defaultBot?.person) return null;+ const shown = bot && place.activeView === "chat" && place.selectedId === bot.id ? bot.tasks?.find((task) => task.threadId === bot.threadId) : undefined;+ return shown && shown.private !== true && !shown.routineRunId ? bot!.mainThreadId ?? null : RESULTS_JUST_ME;+}++/** Whether a routine reporting here is the person's alone: their own MausBot's, "Just me", or one of their private chats. */+function onlyMine(bot: Bot, value: string | null | undefined, madeIn?: string): boolean {+ const own = (threadId: string | null | undefined) => typeof threadId === "string" && Boolean(bot.tasks?.some((task) => task.threadId === threadId && task.private === true));+ return Boolean(bot.defaultBot?.person) || value === RESULTS_JUST_ME || own(value) || own(madeIn);+}++/** On a team's Cloud, always in view in a routine's form: who will see the routine and what it reports, in the words+ * of the label by the message box. `madeIn`: the chat an existing routine was made in. */+export function RoutineAudience({ team, bot, value, madeIn }: { team?: { name: string } | null; bot?: Bot; value: string | null | undefined; madeIn?: string }) {+ if (!team || !bot) return null;+ const mine = onlyMine(bot, value, madeIn), Icon = mine ? Lock : Users;+ return <p role="note" data-routine-audience={mine ? "me" : "shared"} className="mt-2 flex items-center gap-1 text-[12px] leading-4 text-ink-secondary">+ <Icon size={12} aria-hidden="true" className="shrink-0" /><span>{mine ? t("team.privateHeader") : sharedChatAudience(team.name, bot.onlyPeopleAdded)}</span>+ </p>;+}export function ResultsDestination({ bot, value, allowCurrent = false, team, onChange }: {bot?: Bot;diff --git a/src/lib/usage-trace.test.ts b/src/lib/usage-trace.test.tsindex 64f2259e44..2431f06bf9 100644--- a/src/lib/usage-trace.test.ts+++ b/src/lib/usage-trace.test.ts@@ -93,6 +93,9 @@ describe("trace helpers", () => {expect(usageGroupLabel("user", { key: "routine:r1", label: "Routine: Morning digest" })).toBe("Routine: Morning digest");expect(usageGroupLabel("user", { key: "user:[email protected]", label: "[email protected]" })).toBe("[email protected]");expect(usageGroupLabel("routine", { key: "manual", label: "Not from a routine" })).toBe("Not from a routine");+ expect(usageGroupLabel("routine", { key: "routine:private", label: "Private routine" })).toBe("Private routine");+ expect(usageGroupLabel("user", { key: "routine:private", label: "Private routine" })).toBe("Private routine");+ expect(usageGroupLabel("bot", { key: "bot:private", label: "Private bot" })).toBe("Private bot");});it("ranks models by tokens, so a subscription model with no price still shows", () => {diff --git a/src/locales/en.json b/src/locales/en.jsonindex ff28ebf257..dc92587f57 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -4094,6 +4094,8 @@"usage.history.owner": "This computer","usage.history.botToBot": "Bot to bot","usage.history.routine": "Routine: {name}",+ "usage.history.privateRoutine": "Private routine",+ "usage.history.privateBot": "Private bot","usage.budget.title": "Monthly spend limit","usage.budget.subtitle": "Once the month's cost reaches the limit, no bot in this installation starts a turn until an admin raises it. Admins are notified once a month at the warning level and once at the limit.","usage.budget.none": "No limit is set. Bots spend freely.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex ee4b098727..59d8efe74f 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -3938,6 +3938,8 @@"usage.history.owner": "Este computador","usage.history.botToBot": "Entre bots","usage.history.routine": "Rotina: {name}",+ "usage.history.privateRoutine": "Rotina privada",+ "usage.history.privateBot": "Bot privado","usage.budget.title": "Limite mensal de gastos","usage.budget.subtitle": "Quando o custo do mês chega ao limite, nenhum bot desta instalação inicia uma sessão até um admin aumentar o limite. A cada mês, os admins recebem um aviso quando o custo atinge o nível de alerta e outro quando chega ao limite.","usage.budget.none": "Nenhum limite definido. Os bots gastam livremente.",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex 5a55f9b1df..1d2abbe2c5 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -27541,6 +27541,8 @@"usage.history.owner": "26f9f95a152ffb426e3ed80cf650c2b81ac0694df0cfb5c3c01dbc25fd9f73cf","usage.history.botToBot": "3708fc67a8e9c0a97bec174fbc8ae8ab48ccbb7cc466db656c480365bb2fed28","usage.history.routine": "90c5c0b92def5bb0c771ee0423909bd06548627abf97716f6b501dad752ec36f",+ "usage.history.privateRoutine": "d668ec5904708e94287f50782ad0b53afe09fb5cdb47dd5aa20c83369b87873e",+ "usage.history.privateBot": "be2eea30c6ffeeab908e6676de2a2347379b43e2f8b96383f629181ab6776b63","usage.budget.title": "abd56395e7efd709849e2a839d99c7965a1ba1254b065c4c9d6d27e1dccac2e1","usage.budget.subtitle": "2431e06c08756297fdeb3a3d44b969c4ac97178ba4ecd663b3da64a40932cbc0","usage.budget.none": "aa3cc3f007c560683b2da13d90064a558e755c6dd58ec3b3ee9aab96f17eb275",