Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Team plan fixes from end-to-end testing (#3853)
Aditya Umaled124292a2aaf
diff --git a/docs/memory.md b/docs/memory.mdindex cf7ba12896..2ff53ef0d3 100644--- a/docs/memory.md+++ b/docs/memory.md@@ -423,6 +423,12 @@ free form, or one you rewrite by hand, works the same.All of them need the owner (admin) session, like the other bot-settings routes.+On a Team Cloud each person also reaches what a bot remembers about them, their own layer of its memory+(`workspaces/<bot>--member-<person>`, see [team-cloud.md](team-cloud.md)), from any session:+`GET /api/bots/:id/memory/mine` is its overview, and `GET`, `PUT` and `DELETE /api/bots/:id/memory/mine/file` read,+save and remove one of its files as above. Nobody reaches another person's layer. The bot panel's **What it+remembers** shows these notes on a team.+## Shared team memory integrityTeam memory ownership uses persistent keys. Renaming a team preserves its notesdiff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex 04c2eda4f4..23c6416121 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -15,14 +15,16 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes tin the @ list too, and whatever is addressed to one of them reaches their inbox (below, "One inbox per person"). "New conversation"is yours alone: no other Member and no Admin, the Super admin included, sees it, writes in it or learns of it, inlists, counts, unread marks, searches, files, notifications, streams, a bot's tools or another bot. A group chat is- seen by whoever sees it. Every private chat says so in its header, *"Private · only you"*, and the first one on a+ seen by whoever sees it, and its unread mark is each person's own: a bot's reply there is unread for everyone until+ they read it, and one person reading it clears it for nobody else (`room-reads.json`). Every private chat says so in its header, *"Private · only you"*, and the first one on adevice also says it as a sentence: *"Your chats in Acme are private. Only you can see them: not other members, notAcme's admins."* The server marks such a conversation `private: true` on the wire (`WireTask.private`). When you leavethe team (or are removed), your private chats and everything only yours there are deleted, never handed to an admin(below).- **Memory.** Each bot keeps three kinds of notes: the team's, a group chat's and a person's. A turn reads the team's notes andthe notes of where it is, and saves into where it is. What you tell a bot privately never reaches a room or another- person's chat; what a group chat decides never reaches your private chat. "About you" is yours alone: `GET`/`PUT /api/me`+ person's chat; what a group chat decides never reaches your private chat. You can open, edit and delete what a bot+ remembers about you (the bot panel's What it remembers, `/api/bots/<bot>/memory/mine`); nobody else can. "About you" is yours alone: `GET`/`PUT /api/me`(the app's Profile on a team), read into your own conversations only.- **Profile.** "You" is the person signed in: your own name, picture and About you (`people/<person>/profile.json` and`about.json`, `GET`/`PUT /api/me`), with the address of your verified sign-in, which nothing here changes. Settings →@@ -93,7 +95,8 @@ this server shares with every bot. It exists only on a Team Cloud.`/api/connectors/:slug/authorize` and `DELETE /api/connectors/:slug/accounts/:id` for apps. Every check, side effectand record is the app's own, and each change is that member's. A User's session is refused there as anywhere.- A Team Cloud always keeps its admin activity (`/api/admin-activity`), even with no User signed in: it is shared by- definition. The Admin's Team admin → Activity reads it with the same session, beside the team's own record there; Usage+ definition. Beside what any shared workspace records, a team bot's name, title, description, instructions and colour+ 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 andoutcome; never its runs' titles or a decision's words.@@ -167,9 +170,12 @@ the Admin (404). A session is also kept only across a clean restart.**When someone leaves.** The Admin tells the machine when a member is removed or leaves: `POST/api/cloud/team/member-left` with `{ "email": "<address>" }`, signed with its body like the sleep request (400`invalid_member` for a bad address; only on a Team Cloud). The machine then deletes what was that person's alone and-answers `{ ok, chats, layers, sessions, files, browsers }`: every session and phone of theirs and any open code of-theirs end at once; their private chats with every bot are deleted as the app deletes a conversation (messages,-notifications, follow-ups, a running turn stopped first), with the uploaded files only those chats used; their memory+answers `{ ok, chats, layers, sessions, files, browsers, bots }`: every session and phone of theirs and any open code of+theirs end at once; their own MausBot is deleted as the app deletes a bot, with its chats and notes (`bots`, its chats+counted in `chats`), and should they join again they get a new one; their private chats with every bot are deleted as+the app deletes a conversation (messages, notifications, follow-ups, a running turn stopped first), with the uploaded+files only those chats used and every file they uploaded that nothing uses (a file they took off a message before+sending goes at once: `DELETE /api/attachments/<name>`, its uploader only, while nothing uses it); their memorylayers (`workspaces/<bot>--member-<person>`, their journal and search index); their "About you" and profile(`people/<person>/`); their own connections, keys and MCP sign-ins; and their own browser of every bot and sharedprofile. Nothing of it is handed to an admin. Each conversation keeps its starter in `thread-starters.json` (a hash), so a@@ -180,8 +186,10 @@ own chats before they go is not built.code carrying the caller's `member` claim (address, role, the role's scopes) and the time the Admin last vouched forthem; on a Team Cloud `POST /api/auth/pairing` does the same for an admin session, so no team session makes a barecode. The session it opens is a team session that ends within the hour of that check, not of the scan; each later-Admin-signed pairing of the same member in the same role moves it (`SessionRegistry.memberChecked`). A role change-leaves it to end; a removed member's phone signs out within the hour.+Admin-signed pairing of the same member in the same role moves it (`SessionRegistry.memberChecked`). An Admin-signed+pairing at another role ends every session, phone and open code of that member at the old role at once+(`SessionRegistry.revokeMember` with the new role kept): the Admin signs one as soon as the Owner changes a role, so a+demoted Admin loses admin scope then, not within the hour.## The audience rulediff --git a/server/admin-activity.test.ts b/server/admin-activity.test.tsindex e6378f6318..410875464e 100644--- a/server/admin-activity.test.ts+++ b/server/admin-activity.test.ts@@ -19,6 +19,7 @@ import {readAdminActivityRange,sharedSignIn,signInListsOf,+ TEAM_BOT_AUDIT_FIELDS,type AdminActionRow,} from "./admin-activity.ts";import { bindDecisionRetention, DEFAULT_DECISION_RETENTION_DAYS, type DecisionRow } from "./decision-log.ts";@@ -136,6 +137,15 @@ describe("what a row records", () => {expect(botChangeRows({ id: "b" }, off, off)).toEqual([]);});+ it("records that a Team bot's instructions changed without keeping their text", () => {+ const before = botAuditSnapshot({ id: "b", soul: "Keep the vault code 4242 secret." }, TEAM_BOT_AUDIT_FIELDS);+ const after = botAuditSnapshot({ id: "b", soul: "Be brief." }, TEAM_BOT_AUDIT_FIELDS);+ const rows = botChangeRows({ id: "b" }, before, after, undefined, TEAM_BOT_AUDIT_FIELDS);+ expect(rows.map((row) => row.changed)).toEqual([["soul"]]);+ expect(JSON.stringify(rows)).not.toMatch(/4242|Be brief/);+ expect(botChangeRows({ id: "b" }, after, botAuditSnapshot({ id: "b", soul: "Be brief." }, TEAM_BOT_AUDIT_FIELDS), undefined, TEAM_BOT_AUDIT_FIELDS)).toEqual([]);+ });+it("records a bot moving to another VPS server, and back to the default", () => {const own = botAuditSnapshot({ id: "b", cloudBackend: "vps", vpsAlias: "alpha-vps" });const onDefault = botAuditSnapshot({ id: "b", cloudBackend: "vps" });diff --git a/server/admin-activity.ts b/server/admin-activity.tsindex e897d57d12..db223ab4b3 100644--- a/server/admin-activity.ts+++ b/server/admin-activity.ts@@ -1,6 +1,7 @@// Who changed what on this server: one NDJSON file per UTC month under <data>/admin-activity, 0600, pruned by the decision// log's retention window. Values are redacted (credential-named keys and every headers/env value become "[hidden]") and// nothing is sent anywhere. Fire-and-forget: a full disk must not undo a setting that already took effect.+import { createHash } from "node:crypto";import { readdirSync, readFileSync } from "node:fs";import { appendFile, mkdir } from "node:fs/promises";import { basename, join } from "node:path";@@ -228,11 +229,20 @@ export const BOT_AUDIT_FIELDS = ["parkDirectMessages", "hidden", "modelSelection", "helperModel", "visibility",] as const;-export function botAuditSnapshot(bot: Record<string, unknown> | null | undefined): Record<string, unknown> | null {+/** A Team Cloud's bots are everyone's: who renamed one, recoloured it or changed its instructions is recorded too. */+export const TEAM_BOT_AUDIT_FIELDS = [...BOT_AUDIT_FIELDS, "name", "title", "description", "soul", "color"] as const;++export function botAuditSnapshot(bot: Record<string, unknown> | null | undefined, fields: readonly string[] = BOT_AUDIT_FIELDS): Record<string, unknown> | null {if (!bot) return null;// "everyone" and no field are one audience.const present = (field: string) => bot[field] !== undefined && !(field === "visibility" && bot[field] === "everyone");- return Object.fromEntries(BOT_AUDIT_FIELDS.filter(present).map((field) => [field, structuredClone(bot[field])]));+ return Object.fromEntries(fields.filter(present).map((field) => [field, field === "soul" ? textDigest(bot[field]) : structuredClone(bot[field])]));+}++/** Instructions may hold anything a person typed: the log keeps only that they changed. */+function textDigest(value: unknown): { length: number; sha256: string } {+ const text = String(value);+ return { length: text.length, sha256: createHash("sha256").update(text).digest("hex").slice(0, 12) };}export function botChangeRows(@@ -240,9 +250,10 @@ export function botChangeRows(before: Record<string, unknown> | null,after: Record<string, unknown> | null,only?: readonly string[],+ fields: readonly string[] = BOT_AUDIT_FIELDS,): Array<Omit<AdminActionRow, "at" | "actor">> {if (!before || !after) return [];- const changed = BOT_AUDIT_FIELDS.filter((field) => (!only || only.includes(field)) && stable(before[field]) !== stable(after[field]));+ const changed = fields.filter((field) => (!only || only.includes(field)) && stable(before[field]) !== stable(after[field]));const rows: Array<Omit<AdminActionRow, "at" | "actor">> = [];const bot = { kind: "bot", id: target.id, ...(target.name ? { name: target.name } : {}) };if (changed.includes("visibility")) {diff --git a/server/admin-audit-plan.ts b/server/admin-audit-plan.tsindex 89493687b3..06e3d192f4 100644--- a/server/admin-audit-plan.ts+++ b/server/admin-audit-plan.ts@@ -26,8 +26,8 @@ export function adminAuditPlan(method: string, path: string, sharedComputers: bocreatesWebhook: method === "POST" && path === "/api/webhooks",pairing: method === "POST" && path === "/api/auth/pairing",};- let m = /^\/api\/bots\/([\w-]+)(?:\/(always-allow|model))?$/.exec(path);- if (m && ((!m[2] && method === "PATCH") || (m[2] === "model" && method === "PATCH") || (m[2] === "always-allow" && method === "POST"))) plan.botId = m[1];+ let m = /^\/api\/bots\/([\w-]+)(?:\/(always-allow|model|profile))?$/.exec(path);+ if (m && method === (m[2] === "always-allow" ? "POST" : "PATCH")) plan.botId = m[1];if (m && !m[2] && method === "DELETE") plan.deletesBot = m[1];m = /^\/api\/webhooks\/([\w-]+)(\/rotate)?$/.exec(path);if (m && ((m[2] && method === "POST") || (!m[2] && (method === "PATCH" || method === "DELETE")))) plan.webhookId = m[1];diff --git a/server/body-deadline.test.ts b/server/body-deadline.test.tsnew file mode 100644index 0000000000..d15e11d6c7--- /dev/null+++ b/server/body-deadline.test.ts@@ -0,0 +1,65 @@+import { createServer, type Server } from "node:http";+import { connect, type AddressInfo } from "node:net";+import { afterEach, describe, expect, it } from "vitest";++import { holdBodyDeadline } from "./body-deadline.ts";++let server: Server | null = null;++afterEach(() => new Promise<void>((resolve) => (server ? server.close(() => resolve()) : resolve())));++async function listen(baseMs: number): Promise<number> {+ server = createServer((req, res) => {+ holdBodyDeadline(req, res, baseMs);+ let bytes = 0;+ req.on("data", (chunk: Buffer) => { bytes += chunk.length; });+ req.on("end", () => res.end(String(bytes)));+ });+ await new Promise<void>((resolve) => server!.listen(0, "127.0.0.1", resolve));+ return (server.address() as AddressInfo).port;+}++function send(port: number, head: string, chunks: Array<{ after: number; data: string }>): Promise<string> {+ return new Promise((resolve, reject) => {+ const socket = connect(port, "127.0.0.1", () => {+ socket.write(head);+ for (const { after, data } of chunks) setTimeout(() => socket.writable && socket.write(data), after);+ });+ let text = "";+ socket.on("data", (chunk) => {+ text += chunk.toString("utf8");+ if (/\r\n\r\n\d+$/.test(text)) socket.end();+ });+ socket.on("close", () => resolve(text));+ socket.on("error", reject);+ });+}++describe("holdBodyDeadline", () => {+ it("answers 408 and closes a request whose body stops arriving", async () => {+ const port = await listen(200);+ const answer = await send(port, "POST / HTTP/1.1\r\nHost: x\r\nContent-Length: 10\r\n\r\nab", []);+ expect(answer).toMatch(/^HTTP\/1\.1 408 Request Timeout/);+ expect(answer).toContain("The request took too long.");+ });++ it("gives a large upload time in proportion to its size", async () => {+ const port = await listen(200);+ const piece = "x".repeat(64 * 1024);+ const answer = await send(port, `POST / HTTP/1.1\r\nHost: x\r\nContent-Length: ${piece.length * 4}\r\n\r\n`,+ [0, 300, 600, 900].map((after) => ({ after, data: piece })));+ expect(answer).toMatch(/^HTTP\/1\.1 200/);+ expect(answer).toMatch(/262144$/);+ });++ it("never times a request without a body", async () => {+ const port = await listen(50);+ server!.removeAllListeners("request");+ server!.on("request", (req, res) => {+ holdBodyDeadline(req, res, 50);+ setTimeout(() => res.end("late"), 300);+ });+ const answer = await send(port, "GET / HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n", []);+ expect(answer).toMatch(/^HTTP\/1\.1 200/);+ });+});diff --git a/server/body-deadline.ts b/server/body-deadline.tsnew file mode 100644index 0000000000..22e3f0aab2--- /dev/null+++ b/server/body-deadline.ts@@ -0,0 +1,26 @@+import type { IncomingMessage, ServerResponse } from "node:http";++export const BODY_DEADLINE_MS = 55_000;+/** The slowest upload still let through: past this pace a large body is cut off, never held open. */+const MIN_BODY_BYTES_PER_SECOND = 128 * 1024;+const UNKNOWN_LENGTH_BYTES = 32 * 1024 * 1024;+const TIMED_OUT_BODY = JSON.stringify({ error: "The request took too long. Check the connection and try again." });+const TIMED_OUT = `HTTP/1.1 408 Request Timeout\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(TIMED_OUT_BODY)}\r\n\r\n${TIMED_OUT_BODY}`;++/** Ends a request whose body has not all arrived in time, as Node's own `requestTimeout` does: a 408 written on the+ * socket, then the connection closed. A request without a body (a stream, a long poll) is never timed. */+export function holdBodyDeadline(req: IncomingMessage, res: ServerResponse, baseMs = BODY_DEADLINE_MS): void {+ const declared = Number(req.headers["content-length"] ?? 0);+ const chunked = req.headers["transfer-encoding"] !== undefined;+ if (req.complete || (!chunked && !(declared > 0))) return;+ const bytes = chunked ? UNKNOWN_LENGTH_BYTES : declared;+ const timer = setTimeout(() => {+ if (req.complete) return;+ const socket = req.socket;+ if (!res.headersSent && socket.writable) socket.end(TIMED_OUT, () => socket.destroy());+ else socket.destroy();+ }, baseMs + Math.ceil((bytes / MIN_BODY_BYTES_PER_SECOND) * 1000));+ timer.unref();+ req.once("end", () => clearTimeout(timer));+ req.once("close", () => clearTimeout(timer));+}diff --git a/server/bot-visibility.test.ts b/server/bot-visibility.test.tsindex e76b30c545..e573cac940 100644--- a/server/bot-visibility.test.ts+++ b/server/bot-visibility.test.ts@@ -381,6 +381,14 @@ describe("a Team Cloud's audiences", () => {expect(memberBot({ id: "pub", threadId: "t-pub-2" }, admin)).toEqual({ id: "pub" });});+ it("a main chat named as another person's private chat is replaced by a conversation the viewer reads, never sent", () => {+ const admin = new VisibleSet(open, openGroups, BEN_ADMIN, undefined, { of: audienceOf, person: BEN_KEY });+ const bot = { id: "pub", threadId: "t-pub-2", mainThreadId: "t-pub-2", tasks: [{ threadId: "t-pub-2" }, { threadId: "t-pub" }] };+ const sent = memberBot(bot, admin) as Record<string, unknown>;+ expect(sent).toEqual({ id: "pub", threadId: "t-pub", mainThreadId: "t-pub", tasks: [{ threadId: "t-pub" }] });+ expect(memberBot({ ...bot, threadId: "t-pub" }, admin)).toEqual({ id: "pub", threadId: "t-pub", mainThreadId: "t-pub", tasks: [{ threadId: "t-pub" }] });+ });+it("a live frame from another person's private chat never reaches an admin's stream", () => {const admin = new VisibleSet(open, openGroups, BEN_ADMIN, undefined, { of: audienceOf, person: BEN_KEY });const ctx: FrameContext = { visible: admin, webhook: () => undefined, freshBot: () => undefined, freshGroup: () => undefined };diff --git a/server/bot-visibility.ts b/server/bot-visibility.tsindex d888fd3d3d..3a1775aaad 100644--- a/server/bot-visibility.ts+++ b/server/bot-visibility.ts@@ -352,27 +352,37 @@ export function memberBot<T extends object>(bot: T, visible: VisibleSet): T {const SELECTED_THREAD_FIELDS = ["messages", "hasMore", "activeLeafId", "pinnedMessageId", "rewound", "waitingForTeammates"] as const;/** On a Team Cloud a person is sent only their own conversations with a bot and the team's (an admin too). The bot's- * selected conversation is the server's one choice for everyone; when it is someone else's private chat they get the- * main chat named instead, without that conversation's messages, and its unread mark counts only what they see. */+ * selected conversation and main chat are the server's one choice for everyone; when either is someone else's private+ * chat they get a team conversation they read instead (the other's id never goes out), without that conversation's+ * messages, and its unread mark counts only what they see. */function shownConversations<T extends object>(bot: T, visible: VisibleSet): T {const record = bot as T & Record<string, unknown>;- let out: Record<string, unknown> | null = null;- const tasks = record.tasks;- if (Array.isArray(tasks)) {- const kept = tasks.filter((task) => !task || typeof task !== "object" || typeof (task as { threadId?: unknown }).threadId !== "string" || visible.thread((task as { threadId: string }).threadId));- if (kept.length !== tasks.length) {- out = { ...record, tasks: kept };- if (typeof record.unread === "boolean") out.unread = kept.some((task) => (task as { unread?: unknown } | null)?.unread === true);- }+ let out: Record<string, unknown> = record;+ const tasks = Array.isArray(record.tasks) ? record.tasks as unknown[] : [];+ const kept = tasks.filter((task) => !task || typeof task !== "object" || typeof (task as { threadId?: unknown }).threadId !== "string" || visible.thread((task as { threadId: string }).threadId));+ if (kept.length !== tasks.length) {+ out = { ...record, tasks: kept };+ if (typeof record.unread === "boolean") out.unread = kept.some((task) => (task as { unread?: unknown } | null)?.unread === true);+ }+ const main = typeof record.mainThreadId === "string" && visible.thread(record.mainThreadId) ? record.mainThreadId : teamConversation(kept);+ if (typeof record.mainThreadId === "string" && record.mainThreadId !== main) {+ out = { ...out };+ if (main) out.mainThreadId = main; else delete out.mainThreadId;}if (typeof record.threadId === "string" && !visible.thread(record.threadId)) {- const next: Record<string, unknown> = { ...(out ?? record) };+ const next: Record<string, unknown> = { ...out };for (const field of SELECTED_THREAD_FIELDS) delete next[field];- if (typeof record.mainThreadId === "string" && visible.thread(record.mainThreadId)) next.threadId = record.mainThreadId;- else delete next.threadId;+ if (main) next.threadId = main; else delete next.threadId;out = next;}- return (out ?? record) as T;+ return out as T;+}++function teamConversation(tasks: readonly unknown[]): string | undefined {+ const shared = tasks.filter((task): task is { threadId: string; archivedAt?: unknown } =>+ Boolean(task) && typeof (task as { threadId?: unknown }).threadId === "string" &&+ (task as { private?: unknown }).private !== true && !(task as { routineRunId?: unknown }).routineRunId);+ return (shared.find((task) => task.archivedAt === undefined) ?? shared[0])?.threadId;}/** The SSH alias of the server a bot's VPS computer lives on: an admin's, like the default alias in config. */diff --git a/server/cloud-home.test.ts b/server/cloud-home.test.tsindex ffa0acf37b..e5733b2b4d 100644--- a/server/cloud-home.test.ts+++ b/server/cloud-home.test.ts@@ -628,6 +628,33 @@ it("a Team Cloud's pairing binds the Admin's member claim to the session it openexpect(sessions.authenticate((paired as { token: string }).token)).toBeNull();});+it("a Team Cloud pairing at a new role ends that person's sessions, phones and waiting codes at the old role at once", () => {+ const root = directory();+ const now = 1_800_000_000_000;+ const sessions = new SessionRegistry({ file: join(root, "sessions.json"), now: () => now });+ const pairing = createCloudPairing({ secret, sessions, team: { id: "team-1", name: "Acme" }, now: () => now });+ let counter = 0;+ const mint = (email: string, role: string) => {+ const body = JSON.stringify({ label: "OpenMausBot app (Team Cloud)", ttlSeconds: 300, member: { email, role } });+ const timestamp = String(Math.floor(now / 1000)), nonce = `nonce-${String(++counter).padStart(12, "0")}`;+ return pairing.handle({ timestamp, nonce, signature: `v1=${cloudPairingSignature(secret, timestamp, nonce, body)}`, body: Buffer.from(body), source: "203.0.113.9" });+ };+ const redeem = (code: string) => sessions.exchange({ code, label: "", source: "198.51.100.4" }) as { ok: true; token: string; session: { id: string } };+ const admin = redeem(mint("[email protected]", "admin").body.code as string);+ const phone = redeem(sessions.openPairing({ scopes: ["admin", "client"], member: { email: "[email protected]", role: "admin" }, memberCheckedAt: now }).code);+ const waiting = mint("[email protected]", "admin").body.code as string;+ const ben = redeem(mint("[email protected]", "admin").body.code as string);+ const again = mint("[email protected]", "member");+ expect(again.status).toBe(200);+ expect([sessions.authenticate(admin.token), sessions.authenticate(phone.token)]).toEqual([null, null]);+ expect(sessions.exchange({ code: waiting, label: "", source: "198.51.100.4" })).toMatchObject({ ok: false });+ expect(sessions.authenticate(ben.token)).toBeTruthy();+ const member = redeem(again.body.code as string);+ expect(sessions.authenticate(member.token)).toMatchObject({ teamRole: "member", scopes: ["client"] });+ expect(mint("[email protected]", "member").status).toBe(200);+ expect(sessions.authenticate(member.token)).toBeTruthy();+});+it("a My Cloud refuses a team claim: it is one person's", () => {const f = fixture();expect(f.mint(f.sign(JSON.stringify({ member: { email: "[email protected]", role: "member" } })))).toEqual({ status: 400, body: { error: "not_a_team" } });diff --git a/server/cloud-home.ts b/server/cloud-home.tsindex b37cb08c28..7fee3c7a3b 100644--- a/server/cloud-home.ts+++ b/server/cloud-home.ts@@ -166,7 +166,7 @@ export interface CloudPairingResult {body: Record<string, unknown>;}-type PairingSessions = Pick<SessionRegistry, "openPairing" | "attemptAllowed" | "noteFailure" | "clearFailures">;+type PairingSessions = Pick<SessionRegistry, "openPairing" | "revokeMember" | "attemptAllowed" | "noteFailure" | "clearFailures">;export function createCloudPairing(options: {secret: string;@@ -205,6 +205,7 @@ export function createCloudPairing(options: {return { status: 400, body: { error: "invalid_owner" } };}const ttl = Math.min((ttlSeconds as number | undefined) ?? CLOUD_PAIRING_DEFAULT_TTL_S, browser ? CLOUD_BROWSER_SIGN_IN_MAX_TTL_S : CLOUD_PAIRING_MAX_TTL_S);+ if (member) sessions.revokeMember(member.email, member.role);const opened = sessions.openPairing({scopes: member ? teamRoleScopes(member.role) : ["admin", "client"],label: typeof label === "string" && label.trim() ? label.trim() : "MausBot Cloud",diff --git a/server/cloud-team-private.e2e.test.ts b/server/cloud-team-private.e2e.test.tsindex 437dcd5f60..cf45d660d6 100644--- a/server/cloud-team-private.e2e.test.ts+++ b/server/cloud-team-private.e2e.test.ts@@ -24,7 +24,7 @@ const bobKey = personKey({ id: "", email: BOB.email });let fx: CloudSendFixture, team: CloudTeamFixture;let owner = "", admin = "", bob = "";let bot: { id: string; mainThreadId: string };-let bobThread = "", bobFile = "", adminThread = "";+let bobThread = "", bobFile = "", bobDoc = "", bobUnsent = "", adminThread = "";const dump = () => JSON.parse(readFileSync(join(team.home, "dump.json"), "utf8")) as { systemPrompt: string };const scriptToolCalls = (calls: unknown[] | null) => {@@ -83,8 +83,14 @@ beforeAll(async () => {const upload = await fetch(`${team.base}/api/attachments`, { method: "POST", headers: { ...fx.edge, authorization: `Bearer ${bob}`, "content-type": "image/png" }, body: PNG });expect(upload.status).toBe(201);bobFile = ((await upload.json()) as { path: string }).path.split(/[\\/]/).pop()!;+ const doc = await fetch(`${team.base}/api/files?name=offer.txt`, { method: "POST", headers: { ...fx.edge, authorization: `Bearer ${bob}`, "content-type": "text/plain" }, body: "Offer letter" });+ expect(doc.status).toBe(201);+ const docPath = ((await doc.json()) as { path: string }).path;+ bobDoc = docPath.split(/[\\/]/).pop()!;+ const unsent = await fetch(`${team.base}/api/attachments`, { method: "POST", headers: { ...fx.edge, authorization: `Bearer ${bob}`, "content-type": "image/png" }, body: PNG });+ bobUnsent = ((await unsent.json()) as { path: string }).path.split(/[\\/]/).pop()!;scriptToolCalls([{ name: "memory_update", server: "agents", input: { action: "append", text: "Bob is interviewing at Kumquat Labs" } }]);- await turn(bob, bobThread, `I am interviewing at Kumquat Labs next week. `);+ await turn(bob, bobThread, `I am interviewing at Kumquat Labs next week.  <attached-file path="${docPath}" name="offer.txt"/>`);scriptToolCalls(null);}, hostTimeout(180_000));@@ -102,10 +108,40 @@ it("Bob reads and writes his own private chat, with its words, its file, his seaexpect(JSON.stringify((await team.as(bob, "GET", "/api/search?q=Kumquat")).body)).toContain(bobThread);expect((await team.as(bob, "PATCH", `/api/bots/${bot.id}/tasks/${bobThread}`, { title: "Bob's plans" })).status).toBe(200);expect(readFileSync(dataDir("workspaces", `${bot.id}--member-${bobKey}`, "MEMORY.md"), "utf8")).toContain("Kumquat Labs");+ // A file he took off a message before sending is his alone to discard, and one a message uses stays.+ const discard = await fetch(`${team.base}/api/attachments`, { method: "POST", headers: { ...fx.edge, authorization: `Bearer ${bob}`, "content-type": "image/png" }, body: PNG });+ const discarded = ((await discard.json()) as { path: string }).path.split(/[\\/]/).pop()!;+ expect((await team.as(admin, "DELETE", `/api/attachments/${discarded}`)).status).toBe(404);+ expect((await team.as(bob, "DELETE", `/api/attachments/${bobFile}`)).status).toBe(409);+ expect((await team.as(bob, "DELETE", `/api/attachments/${discarded}`)).status).toBe(200);+ expect(existsSync(dataDir("attachments", discarded))).toBe(false);+ // He changes no team bot's look, which everyone sees; his own MausBot's he does.+ const recolour = await team.as(bob, "PATCH", `/api/bots/${bot.id}`, { color: "blue" });+ expect(recolour.status).toBe(403);+ expect(recolour.body.error).toContain("\"color\"");+ const mausBot = ((await team.as(bob, "GET", "/api/bots")).body.bots as Array<{ id: string; name: string }>).find((entry) => entry.name === "MausBot")!;+ expect((await team.as(bob, "PATCH", `/api/bots/${mausBot.id}`, { color: "blue" })).status).toBe(200);// The session says which conversations are his.expect((await team.as(bob, "GET", "/api/auth/session")).body.openedThreads).toContain(bobThread);}, hostTimeout(60_000));+it("Bob opens, edits and deletes what the bot remembers about him, and nobody else reaches it", async () => {+ const mine = `/api/bots/${bot.id}/memory/mine`;+ expect((await team.as(bob, "GET", `/api/bots/${bot.id}/memory`)).status, "the team's notes stay an admin's").toBe(403);+ const overview = await team.as(bob, "GET", mine);+ expect(overview.status, JSON.stringify(overview.body)).toBe(200);+ const index = await team.as(bob, "GET", `${mine}/file?path=MEMORY.md`);+ expect(index.body.text).toContain("Kumquat Labs");+ for (const token of [owner, admin]) expect(JSON.stringify((await team.as(token, "GET", `${mine}/file?path=MEMORY.md`)).body)).not.toContain("Kumquat");+ const saved = await team.as(bob, "PUT", `${mine}/file`, { path: "memory/food.md", text: "- Bob's favourite fruit is durian\n" });+ expect(saved.status, JSON.stringify(saved.body)).toBe(200);+ expect(readFileSync(dataDir("workspaces", `${bot.id}--member-${bobKey}`, "memory", "food.md"), "utf8")).toContain("durian");+ expect(((await team.as(bob, "GET", mine)).body.topics as Array<{ path: string }>).map((topic) => topic.path)).toContain("memory/food.md");+ expect((await team.as(bob, "DELETE", `${mine}/file?path=memory/food.md`)).status).toBe(200);+ expect(existsSync(dataDir("workspaces", `${bot.id}--member-${bobKey}`, "memory", "food.md"))).toBe(false);+ expect(existsSync(dataDir("workspaces", bot.id, "memory", "food.md")), "never the team's folder").toBe(false);+}, hostTimeout(30_000));+it("the Owner and an Admin never see Bob's chat: not by id, not in lists, counts, search, files, notifications or traces", async () => {// The bot's selected conversation is the server's one choice for everyone: Bob's, now.expect((await team.as(bob, "POST", `/api/bots/${bot.id}/tasks/${bobThread}`, {})).status).toBe(200);@@ -249,13 +285,21 @@ it("when Bob leaves the team, his private chats and everything only his are deleconst adminsLayer = dataDir("workspaces", `${bot.id}--member-${personKey({ id: "", email: ADMIN.email })}`);expect(existsSync(layer)).toBe(true);expect(existsSync(adminsLayer)).toBe(true);- expect(existsSync(dataDir("attachments", bobFile))).toBe(true);+ for (const file of [bobFile, bobDoc, bobUnsent]) expect(existsSync(dataDir("attachments", file))).toBe(true);+ const bobsMausBot = ((await team.as(bob, "GET", "/api/bots")).body.bots as Array<{ id: string; threadId: string; name: string }>).find((entry) => entry.name === "MausBot")!;+ expect(bobsMausBot).toBeDefined();+ const room = (await team.as(owner, "POST", "/api/groups", { name: "Desk", memberIds: [bot.id], setup: { bulletin: "", defaultResponder: { kind: "everyone" } } })).body.group as { id: string; threadId: string };+ expect((await team.as(owner, "POST", `/api/groups/${room.id}/messages`, { text: "@Scout hello" })).status).toBe(202);+ await until(async () => await idle(owner) && ((await messages(owner, room.threadId)).body.messages as unknown[]).length >= 2);+ for (const token of [bob, owner]) expect((await team.as(token, "POST", `/api/groups/${room.id}/read`)).status).toBe(200);+ const roomReads = () => readFileSync(dataDir("room-reads.json"), "utf8");+ expect(roomReads()).toContain(bobKey);// Only the Admin's signed request, and only on a team.expect((await fetch(`${team.base}/api/cloud/team/member-left`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email: BOB.email }) })).status).toBe(401);expect((await team.signed("POST", "/api/cloud/team/member-left", { email: "not an address" })).status).toBe(400);const left = await team.signed("POST", "/api/cloud/team/member-left", { email: BOB.email });expect(left.status, JSON.stringify(left.body)).toBe(200);- expect(left.body).toMatchObject({ ok: true, chats: 1, layers: 1, files: 1 });+ expect(left.body).toMatchObject({ ok: true, chats: 2, layers: 1, files: 3, bots: 1 });expect(left.body.sessions).toBeGreaterThanOrEqual(1);// His sessions end at once.expect((await team.as(bob, "GET", "/api/auth/session")).status).toBe(401);@@ -273,8 +317,17 @@ it("when Bob leaves the team, his private chats and everything only his are dele}}expect(existsSync(layer)).toBe(false);- expect(existsSync(dataDir("attachments", bobFile))).toBe(false);+ for (const file of [bobFile, bobDoc, bobUnsent]) expect(existsSync(dataDir("attachments", file))).toBe(false);expect(existsSync(dataDir("people", bobKey))).toBe(false);+ expect(roomReads(), "where he read up to in each room goes too").not.toContain(bobKey);+ expect((await team.as(owner, "DELETE", `/api/groups/${room.id}`)).status).toBe(200);+ expect(roomReads(), "a deleted room's read lines go with it").not.toContain(room.id);+ // His own MausBot and its chat go with him.+ for (const token of [owner, admin]) {+ expect(((await team.as(token, "GET", "/api/bots")).body.bots as Array<{ id: string }>).map((entry) => entry.id)).not.toContain(bobsMausBot.id);+ expect((await messages(token, bobsMausBot.threadId)).status).toBe(404);+ }+ expect(existsSync(dataDir("workspaces", bobsMausBot.id))).toBe(false);// The team's own things stay: the bot, its main chat, and the Admin's own chat and notes.expect((await messages(owner, bot.mainThreadId)).status).toBe(200);expect((await messages(admin, adminThread)).status).toBe(200);diff --git a/server/cloud-team-requests.e2e.test.ts b/server/cloud-team-requests.e2e.test.tsnew file mode 100644index 0000000000..9ae8344080--- /dev/null+++ b/server/cloud-team-requests.e2e.test.ts@@ -0,0 +1,100 @@+// What a Team Cloud refuses at the door: a request whose body never finishes arriving (ended with a 408 within the+// deadline, while an event stream, which has no body, stays open past it), names that do not fit on one line, message+// text that is not a string, and a member's webhook requests; and its refusals are plain sentences.+import { randomBytes } from "node:crypto";+import { connect } from "node:net";+import { afterAll, beforeAll, expect, it } from "vitest";++import { CLOUD_HOST, launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { BODY_DEADLINE_MS } from "./body-deadline.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const OWNER = { email: "[email protected]", role: "owner" as const };+const ADA = { email: "[email protected]", role: "member" as const };++let fx: CloudSendFixture, team: CloudTeamFixture;+let owner = "", ada = "";+let bot: { id: string; mainThreadId: string; color: string };++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-1", name: "Acme", env: { OMB_WEBHOOK_PUBLIC_URL: `https://${CLOUD_HOST}` } } });+ team = fx.team!;+ owner = (await team.pair(OWNER)).token!;+ ada = (await team.pair(ADA)).token!;+ const created = await team.as(owner, "POST", "/api/bots", { name: "Scout" });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ bot = created.body.bot;+}, hostTimeout(180_000));++afterAll(async () => {+ await fx?.close();+});++it("refuses a room name with a null byte or a line break, as a bot's name is refused", async () => {+ for (const name of ["weird-grp-\u0000x", "weird-grp-a\nb"]) {+ const created = await team.as(owner, "POST", "/api/groups", { name, memberIds: [bot.id] });+ expect(created, JSON.stringify(name)).toMatchObject({ status: 400, body: { error: "room name must fit on one line" } });+ }+ const room = await team.as(owner, "POST", "/api/groups", { name: "Kitchen", memberIds: [bot.id] });+ expect(room.status).toBe(201);+ expect(await team.as(owner, "PATCH", `/api/groups/${room.body.group.id}`, { name: "a\nb" })).toMatchObject({ status: 400, body: { error: "room name must fit on one line" } });+}, hostTimeout(60_000));++it("takes message text only as a string without a null byte", async () => {+ const send = (text: unknown) => team.as(owner, "POST", `/api/bots/${bot.id}/messages`, { text, threadId: bot.mainThreadId });+ expect(await send(123)).toMatchObject({ status: 400, body: { error: "text must be a string" } });+ expect(await send("a\u0000b")).toMatchObject({ status: 400, body: { error: "text must not contain a null byte" } });+ const room = await team.as(owner, "POST", "/api/groups", { name: "Den", memberIds: [bot.id] });+ expect(await team.as(owner, "POST", `/api/groups/${room.body.group.id}/messages`, { text: 123 })).toMatchObject({ status: 400, body: { error: "text must be a string" } });+}, hostTimeout(60_000));++it("answers a bad new bot with a plain sentence", async () => {+ const created = await team.as(owner, "POST", "/api/bots", { name: "x".repeat(101) });+ expect(created).toMatchObject({ status: 400, body: { error: "name must be at most 100 characters" } });+ expect(await team.as(owner, "POST", "/api/bots", { description: "x".repeat(4001) })).toMatchObject({ status: 400, body: { error: "description must be at most 4000 characters" } });+}, hostTimeout(60_000));++it("records a team bot's rename, colour and instructions in the admin activity", async () => {+ // A new bot's colour is picked at random: change it to one it doesn't have.+ const color = bot.color === "blue" ? "green" : "blue";+ expect((await team.as(owner, "PATCH", `/api/bots/${bot.id}`, { name: "Scout 2", color })).status).toBe(200);+ expect((await team.as(owner, "PATCH", `/api/bots/${bot.id}/profile`, { soul: "Be brief." })).status).toBe(200);+ await new Promise((resolve) => setTimeout(resolve, 300));+ const entries = (await team.as(owner, "GET", "/api/admin-activity?what=bot")).body.entries as Array<{ action?: string; changed?: string[] }>;+ const changed = entries.filter((entry) => entry.action === "bot.update").flatMap((entry) => entry.changed ?? []);+ expect(changed).toEqual(expect.arrayContaining(["name", "color", "soul"]));+}, hostTimeout(60_000));++it("lets a member read the webhook list, which carries no credential, and keeps creating one an admin's", async () => {+ const list = await team.as(ada, "GET", "/api/webhooks");+ expect(list.status).toBe(200);+ expect(JSON.stringify(list.body)).not.toMatch(/omb_wh_|secret/i);+ // As cloud-home-start runs it, the address it shows is the Cloud's public one, never the loopback listener.+ expect(list.body.ingress.baseUrl).toBe(`https://${CLOUD_HOST}`);+ expect(JSON.stringify(list.body)).not.toContain("127.0.0.1");+ expect((await team.as(ada, "POST", "/api/webhooks", { name: "Mine" })).status).toBe(403);+}, hostTimeout(60_000));++it("ends a sign-in request whose body stops arriving with a 408, and leaves an event stream open", async () => {+ const stream = await fetch(`${team.base}/api/events`, { headers: { ...fx.edge, authorization: `Bearer ${owner}`, accept: "text/event-stream" } });+ expect(stream.status).toBe(200);+ const reader = stream.body!.getReader();+ let streamEnded = false;+ void (async () => { for (;;) if ((await reader.read()).done) { streamEnded = true; return; } })().catch(() => { streamEnded = true; });++ const { port, hostname } = new URL(team.base);+ const started = Date.now();+ const answer = await new Promise<string>((resolve, reject) => {+ const socket = connect(Number(port), hostname, () => {+ socket.write(`POST /api/auth/pair HTTP/1.1\r\nHost: ${hostname}:${port}\r\nContent-Type: application/json\r\nContent-Length: 64\r\n\r\n{"co`);+ });+ let text = "";+ socket.on("data", (chunk) => { text += chunk.toString("utf8"); });+ socket.on("close", () => resolve(text));+ socket.on("error", reject);+ });+ expect(answer).toMatch(/^HTTP\/1\.1 408/);+ expect(Date.now() - started).toBeLessThan(BODY_DEADLINE_MS + 15_000);+ expect(streamEnded).toBe(false);+ await reader.cancel();+}, hostTimeout(BODY_DEADLINE_MS + 60_000));diff --git a/server/cloud-team.e2e.test.ts b/server/cloud-team.e2e.test.tsindex 2502ff5814..e3852b4404 100644--- a/server/cloud-team.e2e.test.ts+++ b/server/cloud-team.e2e.test.ts@@ -165,6 +165,57 @@ it("a room's turn reads the room's layer and the team's, never a member's notes,expect(JSON.stringify((await messages(ada, roomThread)).body)).toContain("Ben says Wednesday");}, hostTimeout(120_000));+it("a room's bot reply is unread for each person until they read it, and one person reading clears it for nobody else", async () => {+ const room = async (token: string) => ((await team.as(token, "GET", "/api/bots")).body.groups as Array<{ id: string; unread?: boolean; lastReadMessageId?: string }>)+ .find((group) => group.id === roomId)!;+ for (const token of [ada, admin, cleo]) expect((await room(token)).unread).toBe(true);+ const read = await team.as(ada, "POST", `/api/groups/${roomId}/read`);+ expect(read.status, JSON.stringify(read.body)).toBe(200);+ expect(read.body.group.unread).toBe(false);+ expect((await room(ada)).unread).toBe(false);+ for (const token of [admin, cleo]) expect((await room(token)).unread, "Ada reading is Ada's alone").toBe(true);+ await turn(admin, roomThread, "@Scout and Friday?", roomId);+ expect((await room(ada)).unread, "the bot's next reply is new to Ada").toBe(true);+ const marked = await team.as(ada, "PATCH", `/api/groups/${roomId}`, { unread: false });+ expect(marked.status, JSON.stringify(marked.body)).toBe(200);+ expect(marked.body.group.unread).toBe(false);+ expect((await room(ada)).unread, "marking a room read is reading it").toBe(false);+ expect((await room(cleo)).unread, "Ada marking it read is Ada's alone").toBe(true);+ expect((await team.as(ada, "PATCH", `/api/groups/${roomId}`, { unread: true })).body.group.unread).toBe(true);+ expect((await room(ada)).unread).toBe(true);+ expect((await team.as(cleo, "POST", `/api/groups/${roomId}/read`)).body.group.unread).toBe(false);+ expect((await room(ada)).unread, "Cleo reading leaves Ada's mark").toBe(true);+}, hostTimeout(120_000));++it("sends a person's read of a room to their own streams only", async () => {+ const listen = async (token: string) => {+ const controller = new AbortController();+ const stream = await fetch(`${team.base}/api/events`, { headers: { ...fx.edge, authorization: `Bearer ${token}`, accept: "text/event-stream" }, signal: controller.signal });+ expect(stream.status).toBe(200);+ const reader = stream.body!.getReader();+ const decoder = new TextDecoder();+ let text = "";+ const done = (async () => { for (;;) { const { value, done } = await reader.read(); if (done) return; text += decoder.decode(value, { stream: true }); } })().catch(() => {});+ const rooms = () => text.split("\n").filter((line) => line.startsWith("data: ")).map((line) => JSON.parse(line.slice(6)) as { kind: string; group?: { id: string } })+ .filter((frame) => frame.kind === "group" && frame.group?.id === roomId);+ await expect.poll(() => text.includes("\"hello\""), { timeout: 10_000 }).toBe(true);+ return { rooms, close: async () => { controller.abort(); await done; } };+ };+ const adas = await listen(ada), cleos = await listen(cleo);+ try {+ expect((await team.as(ada, "POST", `/api/groups/${roomId}/read`)).status).toBe(200);+ expect((await team.as(cleo, "POST", `/api/groups/${roomId}/read`)).status).toBe(200);+ expect((await team.as(ada, "POST", `/api/groups/${roomId}/read`)).status).toBe(200);+ await expect.poll(() => adas.rooms().length, { timeout: 10_000 }).toBe(2);+ await expect.poll(() => cleos.rooms().length, { timeout: 10_000 }).toBe(1);+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect([adas.rooms().length, cleos.rooms().length], "nobody else's read reaches a stream").toEqual([2, 1]);+ } finally {+ await adas.close();+ await cleos.close();+ }+}, hostTimeout(60_000));+it("recall never crosses: a room's fact never surfaces in a private chat and a private chat's never in the room", async () => {const search = async (threadId: string, q: string) => {const token = await team.capability(bot.id, threadId);diff --git a/server/default-bot.ts b/server/default-bot.tsindex f475a49707..f264728c49 100644--- a/server/default-bot.ts+++ b/server/default-bot.ts@@ -65,6 +65,14 @@ function remember(dataDir: string, person: string, botId: string): void {writeFileAtomic(join(dataDir, LEDGER), JSON.stringify({ v: 1, places: { ...places, [person]: botId } }), { mode: 0o600 });}+/** A member who left: should they join again, they are given a MausBot of their own again. */+export function forgetDefaultBot(dataDir: string, person: string): void {+ const places = ledger(dataDir);+ if (!person || !Object.hasOwn(places, person)) return;+ delete places[person];+ writeFileAtomic(join(dataDir, LEDGER), JSON.stringify({ v: 1, places }), { mode: 0o600 });+}+/** A new install's own MausBot from before it was marked: the place's oldest bot, still live, outside any department,* not installed from a package, and still named MausBot or still in the colour a new install gave it. */export function seededMausBot(bots: readonly BotRecord[]): BotRecord | undefined {diff --git a/server/environment.test.ts b/server/environment.test.tsindex c238013bd3..4b68e6e529 100644--- a/server/environment.test.ts+++ b/server/environment.test.ts@@ -148,6 +148,12 @@ describe("environment identity", () => {expect(environmentDescriptor({ ...base, sharedComputers: false, cloudHome: true }).capabilities).not.toHaveProperty("myChromeLink");});+ it("says a team's Cloud home is a team's, so a sign-in page names the team", () => {+ const base = { environmentId: "abc", desktopManaged: false, label: "Acme Labs" };+ expect(environmentDescriptor({ ...base, cloudHome: true, cloudTeam: true }).capabilities.cloudTeam).toBe(true);+ expect(environmentDescriptor({ ...base, cloudHome: true }).capabilities).not.toHaveProperty("cloudTeam");+ });+it("falls back to the checkout's package.json version, then to unknown", () => {delete process.env.OMB_APP_VERSION;expect(serverVersion()).toMatch(/^\d+\.\d+\.\d+/);diff --git a/server/environment.ts b/server/environment.tsindex a49abfcea0..a561f3a92a 100644--- a/server/environment.ts+++ b/server/environment.ts@@ -34,6 +34,8 @@ export interface EnvironmentDescriptor {commandTimeouts?: true;/** A person's own OMB Cloud home. */cloudHome?: true;+ /** A team's Cloud home: `label` is the team's name. */+ cloudTeam?: true;/** A Cloud home that takes the one-time move from the person's computer: by-row chats, the manifest, the chats and* credentials checks, and lines its owner wrote there stamped as the owner's. */move?: 1;@@ -137,6 +139,7 @@ export function environmentDescriptor(input: { environmentId: string; desktopMan...(input.sharedComputers === true && input.cloudHome === true ? { deviceLink: true as const } : {}),...(input.sharedComputers === true && input.cloudHome === true && input.cloudTeam !== true ? { myChromeLink: true as const } : {}),...(input.cloudHome === true ? { cloudHome: true as const, move: 1 as const } : {}),+ ...(input.cloudHome === true && input.cloudTeam === true ? { cloudTeam: true as const } : {}),selfUpdate: input.desktopManaged ? "desktop-managed" : "operator",emailSignIn: input.emailSignIn === true,jobs: true,diff --git a/server/host/cloud-signed-host.ts b/server/host/cloud-signed-host.tsindex 25caf71be7..001e5e9d29 100644--- a/server/host/cloud-signed-host.ts+++ b/server/host/cloud-signed-host.ts@@ -12,7 +12,7 @@ import type { SessionRegistry } from "../sessions.ts";export interface CloudSignedHostDeps {cloudHome: CloudHomeConfig | null;health: Omit<CloudHealthDeps, "box">;- sessions: Pick<SessionRegistry, "openPairing" | "attemptAllowed" | "noteFailure" | "clearFailures">;+ sessions: Pick<SessionRegistry, "openPairing" | "revokeMember" | "attemptAllowed" | "noteFailure" | "clearFailures">;/** The home's power once the server listens (a late-bound singleton of index.ts). */power: () => Pick<CloudPower, "report" | "prepareSleep"> | null;box: () => BoxReport;diff --git a/server/host/member-own-bot.ts b/server/host/member-own-bot.tsnew file mode 100644index 0000000000..2794082943--- /dev/null+++ b/server/host/member-own-bot.ts@@ -0,0 +1,53 @@+// A Team Cloud member's own MausBot when they leave (team-member-left.ts `stopBot` and `deleteBot`): every turn of it+// stops, then it is deleted the app's own way.+import type { RoutineManager } from "../routines.ts";+import type { BotRecord, Store } from "../store.ts";++export interface MemberOwnBotDeps {+ store(): Pick<Store, "bot" | "patchBot">;+ routines(): Pick<RoutineManager, "activeRunForBot" | "cancelRun"> | null;+ activeGroupTurnForBot(botId: string): { group: { id: string }; threadId: string } | null;+ cancelGroupTurnOperations(groupId: string, threadId: string): void;+ revokeInternalCapabilitiesForThread(threadId: string): void;+ interruptAllDirectThreads(botId: string): Promise<void>;+ /** Interrupts the bot's running turn in this conversation, if it has one. */+ interruptTurn(bot: BotRecord, threadId: string): Promise<unknown> | undefined;+ closeOpenApprovals(threadId: string): void;+ /** The app's own deletion of a bot (server/index.ts `deleteBotWithLifecycle`). */+ deleteBot(botId: string): Promise<{ status: number; body: { error?: string } }>;+}++export function createMemberOwnBot(deps: MemberOwnBotDeps) {+ return {+ /** Stops every turn of a bot: its chats, its routine run and the room turn it is in. */+ async stopWork(botId: string, cause: string): Promise<void> {+ const bot = deps.store().bot(botId);+ if (!bot) return;+ const routines = deps.routines();+ const run = routines?.activeRunForBot(botId);+ const groupTurn = deps.activeGroupTurnForBot(botId);+ if (groupTurn) {+ deps.cancelGroupTurnOperations(groupTurn.group.id, groupTurn.threadId);+ deps.revokeInternalCapabilitiesForThread(groupTurn.threadId);+ }+ await Promise.allSettled([+ deps.interruptAllDirectThreads(botId),+ run ? routines!.cancelRun(run.id, cause) : undefined,+ groupTurn ? deps.interruptTurn(bot, groupTurn.threadId) : undefined,+ ]);+ if (groupTurn) deps.closeOpenApprovals(groupTurn.threadId);+ },+ /** Deletes a member's own MausBot, which stops being their default bot first; it is theirs again if that fails. */+ async remove(botId: string): Promise<boolean> {+ const store = deps.store();+ const bot = store.bot(botId);+ if (!bot) return false;+ store.patchBot(botId, { defaultBot: undefined, sidebarHidden: undefined });+ const result = await deps.deleteBot(botId).catch((error: unknown) => ({ status: 500, body: { error: error instanceof Error ? error.message : String(error) } }));+ if (result.status < 400) return true;+ console.warn(`team member left: could not delete their MausBot ${botId}: ${result.body.error ?? result.status}`);+ if (store.bot(botId)) store.patchBot(botId, { defaultBot: bot.defaultBot, sidebarHidden: bot.sidebarHidden });+ return false;+ },+ };+}diff --git a/server/host/member-uploads.ts b/server/host/member-uploads.tsnew file mode 100644index 0000000000..35bafbfba5--- /dev/null+++ b/server/host/member-uploads.ts@@ -0,0 +1,53 @@+// Who uploaded a file to attachments/: the file's uploader alone may discard it before it is sent, and on a Team Cloud a+// member's uploads are kept in people/<person>/uploads.json, so the ones nothing uses go when they leave.+import { mkdirSync, readFileSync } from "node:fs";+import { join } from "node:path";++import { writeFileAtomic } from "../atomic.ts";+import { personKey } from "../person-key.ts";+import type { RequestAuth } from "../request-auth.ts";++const UPLOADS = "uploads.json";+const MAX_UPLOADS = 5_000;+const MAX_RECENT = 1_000;++const uploadsFile = (dataDir: string, person: string) => join(dataDir, "people", person, UPLOADS);++export function memberUploads(dataDir: string, person: string): string[] {+ try {+ const names: unknown = JSON.parse(readFileSync(uploadsFile(dataDir, person), "utf8"));+ return Array.isArray(names) ? names.filter((name): name is string => typeof name === "string") : [];+ } catch {+ return [];+ }+}++/** `member`: the uploader's person key when they are a Team Cloud member, so their uploads are remembered past a restart. */+export function createUploadOwners(dataDir: string) {+ const recent = new Map<string, string>();+ return {+ note(uploader: string, name: string, member?: string): void {+ recent.delete(name);+ recent.set(name, uploader);+ if (recent.size > MAX_RECENT) recent.delete(recent.keys().next().value!);+ if (!member) return;+ const names = memberUploads(dataDir, member).filter((known) => known !== name);+ mkdirSync(join(dataDir, "people", member), { recursive: true, mode: 0o700 });+ writeFileAtomic(uploadsFile(dataDir, member), JSON.stringify([...names, name].slice(-MAX_UPLOADS)), { mode: 0o600 });+ },+ owns(uploader: string, name: string, member?: string): boolean {+ return recent.get(name) === uploader || Boolean(member && memberUploads(dataDir, member).includes(name));+ },+ };+}++/** The thread routes' `uploads` (server/routes/threads.ts): a session's uploader is its person, anything else "local";+ * on a Team Cloud (`team`) a member's are remembered past a restart. */+export function uploadsFor(owners: ReturnType<typeof createUploadOwners>, team: boolean) {+ const uploaderOf = (auth: RequestAuth) => auth.kind === "session" ? personKey(auth.session) : "local";+ const teamMemberOf = (auth: RequestAuth) => team && auth.kind === "session" && auth.session.membershipAuthority === "team" ? personKey(auth.session) : undefined;+ return {+ note: (auth: RequestAuth, name: string) => owners.note(uploaderOf(auth), name, teamMemberOf(auth)),+ owns: (auth: RequestAuth, name: string) => owners.owns(uploaderOf(auth), name, teamMemberOf(auth)),+ };+}diff --git a/server/host/room-reads.test.ts b/server/host/room-reads.test.tsnew file mode 100644index 0000000000..19b2be883c--- /dev/null+++ b/server/host/room-reads.test.ts@@ -0,0 +1,51 @@+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { expect, it } from "vitest";++import { createRoomReads, roomUnreadFor } from "./room-reads.ts";++const path = [{ id: "m1", role: "user" }, { id: "m2", role: "bot" }, { id: "m3", role: "user" }];++it("is unread for a person only while a bot's line follows where they read up to", () => {+ expect(roomUnreadFor(path, "m2", true)).toBe(false);+ expect(roomUnreadFor(path, "m1", false)).toBe(true);+ expect(roomUnreadFor(path, undefined, true), "never opened: the room's own mark").toBe(true);+});++it("counts only a bot's replies, not its tool or status lines", () => {+ const working = [{ id: "m1", role: "user", kind: "text" }, { id: "m2", role: "bot", kind: "activity" }, { id: "m3", role: "bot", kind: "screen" }];+ expect(roomUnreadFor(working, "m1", true)).toBe(false);+ expect(roomUnreadFor([...working, { id: "m4", role: "bot", kind: "text" }], "m1", false)).toBe(true);+});++it("reads a line no longer on the path as read up to the last message at or before it", () => {+ const timed = [{ id: "m1", role: "user", at: 1 }, { id: "m2", role: "bot", at: 2 }, { id: "m4", role: "bot", at: 4 }];+ expect(roomUnreadFor(timed, "edited", true, () => 3), "only the reply after it is unread").toBe(true);+ expect(roomUnreadFor(timed, "edited", true, () => 5)).toBe(false);+ expect(roomUnreadFor(timed, "gone", true, () => undefined), "a line gone from the room reads as read").toBe(false);+});++it("keeps each person's line apart and across a restart", () => {+ const dir = mkdtempSync(join(tmpdir(), "room-reads-"));+ const reads = createRoomReads(dir);+ reads.read("room", "p_ada", "m2");+ expect(reads.readUpTo("room", "p_ada")).toBe("m2");+ expect(reads.readUpTo("room", "p_ben")).toBeUndefined();+ expect(createRoomReads(dir).readUpTo("room", "p_ada")).toBe("m2");+ reads.forgetRoom("room");+ expect(createRoomReads(dir).readUpTo("room", "p_ada")).toBeUndefined();+});++it("forgets a person's lines in every room, and one person's line in one room", () => {+ const dir = mkdtempSync(join(tmpdir(), "room-reads-"));+ const reads = createRoomReads(dir);+ reads.read("a", "p_ada", "m1");+ reads.read("b", "p_ada", "m2");+ reads.read("b", "p_ben", "m3");+ reads.forget("b", "p_ben");+ expect(reads.readUpTo("b", "p_ben")).toBeUndefined();+ reads.forgetPerson("p_ada");+ const reloaded = createRoomReads(dir);+ expect([reloaded.readUpTo("a", "p_ada"), reloaded.readUpTo("b", "p_ada")]).toEqual([undefined, undefined]);+});diff --git a/server/host/room-reads.ts b/server/host/room-reads.tsnew file mode 100644index 0000000000..af4002c6ad--- /dev/null+++ b/server/host/room-reads.ts@@ -0,0 +1,134 @@+// A Team Cloud's group chats are read per person: each person's own "read up to" line in each room+// (`room-reads.json`), so one person opening a room clears its unread mark for nobody else.+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { z } from "zod";++import type { WireGroup } from "../../shared/wire.ts";+import { writeFileAtomic } from "../atomic.ts";+import { personKey } from "../person-key.ts";+import type { RequestAuth } from "../request-auth.ts";+import type { GroupRecord } from "../store.ts";++const ROOM_READS_FILE = "room-reads.json";+const fileSchema = z.object({ version: z.literal(1), reads: z.record(z.string(), z.record(z.string(), z.string())) });++type PathMessage = { id: string; role: string; kind?: string; at?: number };++const NOT_A_REPLY = new Set(["activity", "screen", "digest", "compaction"]);+const isReply = (message: PathMessage) => message.role === "bot" && !NOT_A_REPLY.has(message.kind ?? "text");++/** Unread for a person: a bot replied after where they read up to; with no line yet, the room's own mark. A line no+ * longer on the path (an edit or a retry moved it) reads up to the last message at or before it; `atOf` gives its time. */+export function roomUnreadFor(path: readonly PathMessage[], readUpTo: string | undefined, roomUnread: boolean, atOf?: (id: string) => number | undefined): boolean {+ if (readUpTo === undefined) return roomUnread;+ let from = path.findIndex((message) => message.id === readUpTo) + 1;+ if (from === 0) {+ const readAt = atOf?.(readUpTo);+ if (readAt === undefined) return false;+ from = path.findLastIndex((message) => (message.at ?? 0) <= readAt) + 1;+ }+ return path.slice(from).some(isReply);+}++export function createRoomReads(dataDir: string) {+ const file = join(dataDir, ROOM_READS_FILE);+ let reads: Record<string, Record<string, string>> = {};+ try {+ const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));+ if (parsed.success) reads = parsed.data.reads;+ else console.warn(`room reads: ${file} is not a room reads file; starting fresh`);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.warn(`room reads: ${file} is unreadable; starting fresh`);+ }+ const save = () => {+ try {+ writeFileAtomic(file, `${JSON.stringify({ version: 1, reads })}\n`, { mode: 0o600 });+ } catch (error) {+ console.warn(`room reads: could not save ${file}: ${error instanceof Error ? error.message : String(error)}`);+ }+ };+ return {+ readUpTo: (groupId: string, person: string): string | undefined => reads[groupId]?.[person],+ read(groupId: string, person: string, messageId: string): void {+ if (reads[groupId]?.[person] === messageId) return;+ (reads[groupId] ??= {})[person] = messageId;+ save();+ },+ forget(groupId: string, person: string): void {+ if (reads[groupId]?.[person] === undefined) return;+ delete reads[groupId]![person];+ save();+ },+ forgetRoom(groupId: string): void {+ if (!reads[groupId]) return;+ delete reads[groupId];+ save();+ },+ forgetPerson(person: string): void {+ const rooms = Object.values(reads).filter((room) => room[person] !== undefined);+ if (!rooms.length) return;+ for (const room of rooms) delete room[person];+ save();+ },+ };+}++export type RoomReads = ReturnType<typeof createRoomReads>;++/** One stream frame's `group` payload as a person's own room, built once per person for that frame; null: theirs is the+ * room as it is. */+export type OwnGroupFrames = Map<string, { payload: Record<string, unknown>; frame: string } | null>;++export interface PersonRoomsDeps {+ /** Each person's own read line in each room, on a Team Cloud; null anywhere else, where a room reads the same for all. */+ reads: RoomReads | null;+ store(): { activePath(threadId: string): readonly PathMessage[]; messagesFor(threadId: string): readonly PathMessage[] };+ /** The newest message on a conversation's path, the line a room is read up to. */+ newestMessageId(threadId: string): string | undefined;+ publicGroupState(room: GroupRecord): WireGroup;+ broadcast(payload: Record<string, unknown>, options: { person: string }): void;+}++/** Each person's view of a room (server/index.ts): its unread mark and read line as they read it, on a Team Cloud. */+export function createPersonRooms(deps: PersonRoomsDeps) {+ const { reads } = deps;+ /** A room's unread mark and read line as this person has read it, on a Team Cloud; the room as it is anywhere else. */+ function groupForPerson(group: WireGroup, person: string | null): WireGroup {+ if (!reads || !person) return group;+ const readUpTo = reads.readUpTo(group.id, person);+ const unread = roomUnreadFor(deps.store().activePath(group.threadId), readUpTo, group.unread, (id) => deps.store().messagesFor(group.threadId).find((message) => message.id === id)?.at);+ if (unread === group.unread && readUpTo === group.lastReadMessageId) return group;+ const { lastReadMessageId: _shared, ...rest } = group;+ return { ...rest, unread, ...(readUpTo ? { lastReadMessageId: readUpTo } : {}) };+ }+ return {+ reads,+ groupForPerson,+ groupForAuth: (auth: RequestAuth, group: WireGroup): WireGroup => groupForPerson(group, auth.kind === "session" ? personKey(auth.session) : null),+ /** A `group` frame as `person`'s own room (`frameOf` writes the stream's frame for a payload), kept in `ownGroups` for+ * the rest of that frame's streams; null when it is the room as it is. */+ ownGroupFrame(ownGroups: OwnGroupFrames, person: string, payload: Record<string, unknown>, frameOf: (payload: Record<string, unknown>) => string) {+ if (!reads || payload.kind !== "group") return null;+ if (!ownGroups.has(person)) {+ const group = payload.group as WireGroup;+ const own = groupForPerson(group, person);+ const ownPayload = { ...payload, group: own };+ ownGroups.set(person, own === group ? null : { payload: ownPayload, frame: frameOf(ownPayload) });+ }+ return ownGroups.get(person) ?? null;+ },+ /** Marks a room read or unread for the person signed in (server/routes/channels.ts `personMarkRoom`), told to their+ * streams alone; absent anywhere but a Team Cloud. */+ ...(reads ? { personMarkRoom: (auth: RequestAuth, room: GroupRecord, unread: boolean): WireGroup | null => {+ if (auth.kind !== "session") return null;+ const person = personKey(auth.session);+ const newest = deps.newestMessageId(room.threadId);+ if (unread) reads.forget(room.id, person);+ else if (newest) reads.read(room.id, person, newest);+ const group = deps.publicGroupState(room);+ deps.broadcast({ kind: "group", group }, { person });+ return groupForPerson(group, person);+ } } : {}),+ };+}diff --git a/server/host/room-routing-input.ts b/server/host/room-routing-input.tsnew file mode 100644index 0000000000..0b327e279e--- /dev/null+++ b/server/host/room-routing-input.ts@@ -0,0 +1,39 @@+// What the room router reads (decider/room-routing.ts): the room, its people and bots, and its recent lines, built here+// from the room so nothing secret or an attachment's markup leaves this machine.+import type { ResolvedSender } from "../../shared/wire.ts";+import type { RoomRoutingInput } from "../decider/room-routing.ts";+import { redactSecretsInText } from "../redact.ts";+import { speakerOf, type PersonName } from "../replies.ts";+import type { BotRecord, Message } from "../store.ts";+import { extractTurnImages } from "../turn-images.ts";++/** Scrubbed of secrets and attachment markup before it leaves this machine. */+export function roomRoutingInput(+ roomName: string,+ text: string,+ members: readonly BotRecord[],+ history: readonly Message[],+ userName: PersonName,+ sender?: ResolvedSender,+): RoomRoutingInput {+ const clean = (value: string) => redactSecretsInText(extractTurnImages(value).text);+ const humans = new Set<string>(typeof userName === "string" ? [userName] : []);+ const recent = history.flatMap((m) => {+ if (m.kind !== "text" || !m.text) return [];+ if (m.role === "user") {+ const person = speakerOf(userName, m);+ humans.add(person);+ return [{ from: person, text: clean(m.text) }];+ }+ return [{ from: `${m.from?.name ?? "A bot"} (bot)`, text: clean(m.text) }];+ });+ const from = speakerOf(userName, { sender });+ humans.add(from);+ return {+ room: roomName,+ humans: [...humans],+ members: members.map((member) => ({ id: member.id, name: member.name, title: member.title, description: member.description })),+ recent,+ message: { from, text: clean(text) },+ };+}diff --git a/server/host/sse-replay.ts b/server/host/sse-replay.tsindex 898647e6f3..234a0bde15 100644--- a/server/host/sse-replay.ts+++ b/server/host/sse-replay.ts@@ -4,6 +4,8 @@ export interface ReplayFrame {frame: string | null;clientFrame: string | null;payload: Record<string, unknown> | null;+ /** Only this person's streams get it (a Team Cloud's room as they read it). */+ person?: string;}export const REPLAY_MAX_FRAMES = 500;diff --git a/server/host/team-member-left.test.ts b/server/host/team-member-left.test.tsnew file mode 100644index 0000000000..5ddccdcca8--- /dev/null+++ b/server/host/team-member-left.test.ts@@ -0,0 +1,102 @@+import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { personKey } from "../person-key.ts";+import { createUploadOwners } from "./member-uploads.ts";+import { createTeamMemberLeft, type TeamMemberLeftDeps } from "./team-member-left.ts";++const BOB = "[email protected]";+const bob = personKey({ id: "", email: BOB });+const name = (n: number) => `0000000${n}-0000-4000-8000-000000000000.txt`;++function fixture() {+ const dataDir = mkdtempSync(join(tmpdir(), "omb-member-left-"));+ const attachments = join(dataDir, "attachments");+ mkdirSync(attachments, { recursive: true });+ const messages = new Map<string, unknown[]>();+ const bots = [+ { id: "scout", tasks: [{ threadId: "scout-main" }, { threadId: "bob-private" }] },+ { id: "bobs-mausbot", defaultBot: { person: BOB }, tasks: [{ threadId: "mausbot-main" }, { threadId: "mausbot-second" }] },+ ];+ const deleted: string[] = [];+ const deletedBots: string[] = [];+ const working = new Set<string>();+ const deps: TeamMemberLeftDeps = {+ dataDir,+ store: { get bots() { return bots; }, messagesFor: (threadId) => messages.get(threadId) ?? [] },+ openedBy: () => ["bob-private"],+ privateTo: (threadId) => threadId === "bob-private" ? bob : null,+ revokeSessions: () => 1,+ busy: () => false,+ stop: async () => {},+ stopBot: async (botId) => { working.delete(botId); },+ deleteTasks: (_botId, threadIds) => {+ for (const threadId of threadIds) messages.delete(threadId);+ return { deleted: threadIds };+ },+ deleteBot: async (botId) => {+ if (working.has(botId)) return false;+ const index = bots.findIndex((bot) => bot.id === botId);+ for (const task of bots[index]!.tasks) messages.delete(task.threadId);+ bots.splice(index, 1);+ deletedBots.push(botId);+ return true;+ },+ threadsReferencing: (fragment) => [...messages].filter(([, list]) => JSON.stringify(list).includes(fragment)).map(([threadId]) => threadId),+ deleteAttachment: (file) => deleted.push(file),+ eraseBrowsers: async () => true,+ forgetConnections: () => {},+ };+ const file = (n: number) => { writeFileSync(join(attachments, name(n)), "x"); return name(n); };+ return { dataDir, attachments, messages, bots, deleted, deletedBots, working, deps, file };+}++describe("createTeamMemberLeft", () => {+ it("deletes the departing member's own MausBot with its chats, and counts them", async () => {+ const fx = fixture();+ fx.messages.set("mausbot-main", [{ role: "user", text: "LC-L2-MAIN-9081" }]);+ const result = await createTeamMemberLeft(fx.deps)(BOB);+ expect(fx.deletedBots).toEqual(["bobs-mausbot"]);+ expect(fx.bots.map((bot) => bot.id)).toEqual(["scout"]);+ expect(result).toMatchObject({ chats: 3, bots: 1 });+ });++ it("stops the departing member's MausBot at work (a routine, a room turn) before deleting it", async () => {+ const fx = fixture();+ fx.working.add("bobs-mausbot");+ const result = await createTeamMemberLeft(fx.deps)(BOB);+ expect(fx.deletedBots).toEqual(["bobs-mausbot"]);+ expect(result).toMatchObject({ bots: 1, botsKept: 0 });+ });++ it("reports a MausBot it could not delete", async () => {+ const fx = fixture();+ const result = await createTeamMemberLeft({ ...fx.deps, deleteBot: async () => false })(BOB);+ expect(result).toMatchObject({ bots: 0, botsKept: 1 });+ });++ it("deletes a sent file its chat names by its full path, and keeps one another chat still uses", async () => {+ const fx = fixture();+ const sent = fx.file(1), shared = fx.file(2);+ fx.messages.set("bob-private", [{ role: "user", text: `<attached-file path="${join(fx.attachments, sent)}" name="a.txt"/> and ${join(fx.attachments, shared)}` }]);+ fx.messages.set("scout-main", [{ role: "user", text: `<attached-file path="${join(fx.attachments, shared)}"/>` }]);+ const result = await createTeamMemberLeft(fx.deps)(BOB);+ expect(fx.deleted).toEqual([sent]);+ expect(result.files).toBe(1);+ });++ it("deletes a file the member uploaded and never sent", async () => {+ const fx = fixture();+ const unsent = fx.file(3), used = fx.file(4);+ const owners = createUploadOwners(fx.dataDir);+ owners.note(bob, unsent, bob);+ owners.note(bob, used, bob);+ fx.messages.set("scout-main", [{ role: "user", text: `` }]);+ const result = await createTeamMemberLeft(fx.deps)(BOB);+ expect(fx.deleted).toEqual([unsent]);+ expect(result.files).toBe(1);+ expect(existsSync(join(fx.dataDir, "people", bob))).toBe(false);+ });+});diff --git a/server/host/team-member-left.ts b/server/host/team-member-left.tsindex 42d8784f41..b2cc3a5c6e 100644--- a/server/host/team-member-left.ts+++ b/server/host/team-member-left.ts@@ -1,27 +1,32 @@// When a person leaves a Team Cloud (an admin removes them, or they leave), what was theirs alone goes with them: their-// private chats with every bot (messages, notifications, the files only those chats used), their memory layers, their+// own MausBot with its chats and notes, their private chats with every bot (messages, notifications, the files only+// those chats used, and the files they uploaded and never sent), their memory layers, their// engine home (its transcripts), their "About you", their own connections, their own browsers, and every session and// phone of theirs. Nothing of it is handed to an admin. The Admin tells this machine with a signed request// (`POST /api/cloud/team/member-left`, cloud-signed.ts).//// Each conversation keeps its starter (thread-starters.json, a hash): what other records still name it (a decision's// row, a usage trace) stays someone else's, so no admin ever reads it there either.-import { readdirSync, rmSync } from "node:fs";+import { existsSync, readdirSync, rmSync } from "node:fs";import { basename, join } from "node:path";+import { defaultBotPerson, type DefaultBotFields } from "../../shared/default-bot.ts";import { memberAudience, type Audience } from "../audience.ts";+import { forgetDefaultBot } from "../default-bot.ts";import { audienceHome } from "../engine-homes/layout.ts";import { forgetBotMemoryJournal, journalFile } from "../memory-journal.ts";import { deleteBotMemoryFiles } from "../message-db.ts";import { personKey } from "../person-key.ts";+import { memberUploads } from "./member-uploads.ts";-const ATTACHMENT = /\/api\/attachments\/([A-Za-z0-9][\w.-]{0,200})/g;+/** A file in attachments/, by its URL or by its path (as JSON escapes it) a sent document's tag carries. */+const ATTACHMENT = /attachments(?:\/|\\)+([A-Za-z0-9][\w.-]{0,200})/g;const PERSON = /^p_[\w-]{22}$/;export interface TeamMemberLeftDeps {dataDir: string;store: {- readonly bots: ReadonlyArray<{ id: string; avatarUrl?: string | null; tasks?: ReadonlyArray<{ threadId: string }> }>;+ readonly bots: ReadonlyArray<{ id: string; avatarUrl?: string | null; tasks?: ReadonlyArray<{ threadId: string }> } & DefaultBotFields>;messagesFor(threadId: string): readonly unknown[];};/** The conversations a person opened (thread-starters.json). */@@ -32,8 +37,12 @@ export interface TeamMemberLeftDeps {revokeSessions(email: string): number;busy(botId: string, threadId: string): boolean;stop(botId: string, threadId: string): Promise<void>;+ /** Stops every turn of a bot: its chats, its routine run and the room turn it is in. */+ stopBot(botId: string): Promise<void>;/** The app's own deletion of a bot's conversations (routes/tasks.ts), with everything it lets go of. */deleteTasks(botId: string, threadIds: string[]): { deleted: string[] } | null;+ /** The app's own deletion of a bot (its chats, notes and folder), MausBot included; false when it could not. */+ deleteBot(botId: string): Promise<boolean>;/** Conversations whose messages still name this text (message-db.ts threadsReferencing). */threadsReferencing(fragment: string): readonly string[];deleteAttachment(name: string): void;@@ -42,10 +51,11 @@ export interface TeamMemberLeftDeps {forgetConnections(person: string): void;}-export type TeamMemberLeftResult = { chats: number; layers: number; sessions: number; files: number; browsers: boolean };+export type TeamMemberLeftResult = { chats: number; layers: number; sessions: number; files: number; browsers: boolean; bots: number; botsKept: number };export function createTeamMemberLeft(deps: TeamMemberLeftDeps): (email: string) => Promise<TeamMemberLeftResult> {const workspaces = join(deps.dataDir, "workspaces");+ const attachments = join(deps.dataDir, "attachments");return async (email) => {const person = personKey({ id: "", email });if (!PERSON.test(person)) throw new Error("not a person key");@@ -53,21 +63,39 @@ export function createTeamMemberLeft(deps: TeamMemberLeftDeps): (email: string)const sessions = deps.revokeSessions(email);const mine = new Set(deps.openedBy(person).filter((threadId) => deps.privateTo(threadId) === person));let chats = 0;- const files = new Set<string>();+ const files = new Set<string>(memberUploads(deps.dataDir, person));+ const noteFiles = (threadId: string) => {+ for (const match of JSON.stringify(deps.store.messagesFor(threadId)).matchAll(ATTACHMENT)) files.add(match[1]!);+ };+ let bots = 0;+ let botsKept = 0;+ const address = email.trim().toLowerCase();+ for (const bot of deps.store.bots.filter((candidate) => candidate.defaultBot && defaultBotPerson(candidate) === address)) {+ const threads = (bot.tasks ?? []).map((task) => task.threadId);+ threads.forEach(noteFiles);+ await deps.stopBot(bot.id).catch(() => {});+ if (!(await deps.deleteBot(bot.id).catch(() => false))) {+ botsKept++;+ continue;+ }+ bots++;+ chats += threads.length;+ }+ forgetDefaultBot(deps.dataDir, address);for (const bot of deps.store.bots) {const threads = (bot.tasks ?? []).map((task) => task.threadId).filter((threadId) => mine.has(threadId));if (!threads.length) continue;for (const threadId of threads) {if (deps.busy(bot.id, threadId)) await deps.stop(bot.id, threadId).catch(() => {});- for (const match of JSON.stringify(deps.store.messagesFor(threadId)).matchAll(ATTACHMENT)) files.add(match[1]!);+ noteFiles(threadId);}chats += deps.deleteTasks(bot.id, threads)?.deleted.length ?? 0;}- // A file only their chats used goes too; one a bot's picture or another conversation uses stays.+ // A file only their chats used, or that they never sent, goes too; one a bot's picture or another conversation uses stays.let removed = 0;for (const name of files) {const url = `/api/attachments/${name}`;- if (name.includes("..") || deps.threadsReferencing(url).length || deps.store.bots.some((bot) => bot.avatarUrl === url)) continue;+ if (name.includes("..") || !existsSync(join(attachments, name)) || deps.threadsReferencing(name).length || deps.store.bots.some((bot) => bot.avatarUrl === url)) continue;deps.deleteAttachment(basename(name));removed++;}@@ -85,6 +113,6 @@ export function createTeamMemberLeft(deps: TeamMemberLeftDeps): (email: string)rmSync(audienceHome(deps.dataDir, memberAudience(person)), { recursive: true, force: true });deps.forgetConnections(person);const browsers = await deps.eraseBrowsers(memberAudience(person)).catch(() => false);- return { chats, layers, sessions, files: removed, browsers };+ return { chats, layers, sessions, files: removed, browsers, bots, botsKept };};}diff --git a/server/index.ts b/server/index.tsindex c7cef9e2fa..d8939e1212 100644--- a/server/index.ts+++ b/server/index.ts@@ -276,10 +276,10 @@ import { computerKindForResource, ManagedDesktopPolicy, type ComputerKind } fromimport { hostedModelPolicy, HOSTED_MODEL_POLICY_HEADER } from "./hosted-models.ts";import { CLOUD_HOME_SECRET_KEYS, CLOUD_IGNORED_KEYS, cloudHomeConfiguration, cloudHomeOffersPlace, cloudHomePlaceRefusal, firstCloudTurnPatch } from "./cloud-home.ts";import { botBox, startBotBoxAtBoot } from "./bot-box/boot.ts";-import { createCloudSignedHost } from "./host/cloud-signed-host.ts"; import { hiddenThreadRefusal, hideOthersSyncFolders } from "./host/team-private.ts"; import { createTeamMemberLeft } from "./host/team-member-left.ts"; import { createVisibilityHost } from "./host/visibility-host.ts";+import { createCloudSignedHost } from "./host/cloud-signed-host.ts"; import { hiddenThreadRefusal, hideOthersSyncFolders } from "./host/team-private.ts"; import { createTeamMemberLeft } from "./host/team-member-left.ts"; import { createUploadOwners, uploadsFor } from "./host/member-uploads.ts"; import { createMemberOwnBot } from "./host/member-own-bot.ts"; import { createVisibilityHost } from "./host/visibility-host.ts";import { createCloudPower, registerCloudPower, wokeFromSleep, type CloudPower } from "./cloud-power.ts"; import { createSharedComputerRoutes } from "./routes/shared-computers.ts";import { lentCopies, noteSyncBotTurn } from "./routes/cloud-sync.ts";-import { CLOUD_PERSONAL_REFUSAL, type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember } from "./audience.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_OUTSIDE_KEY, outsideDriven } from "./cloud-sharing.ts";+import { CLOUD_PERSONAL_REFUSAL, type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_OUTSIDE_KEY, outsideDriven } from "./cloud-sharing.ts";import { createCloudMoveRoutes } from "./cloud-move-http.ts";import { RESTART_EXIT_CODE } from "./restart.ts";import { applyIncludedXMessage, holdIncludedServices, researchCredential, trialCreditCredential, xCredential, xResearchStatus } from "./included-services.ts";@@ -316,7 +316,7 @@ import {} from "./store.ts";import * as tts from "./tts/index.ts";import { createDecider, deciderReady, describeDecider } from "./decider/index.ts"; import { createExtractor, describeHelpers } from "./extractor/index.ts";-import { decideRoomResponder, type RoomRoutingInput } from "./decider/room-routing.ts";+import { decideRoomResponder } from "./decider/room-routing.ts"; import { roomRoutingInput } from "./host/room-routing-input.ts";import { createLiveSession, liveAttachUrl, liveHistoryFrom, LiveSessionError, type LiveBot, type LiveHistoryMessage } from "./live-call.ts";import { LiveCallController, LiveCallSignedOutError, type LiveSocket } from "./live-call-controller.ts";import { liveCallKey, liveSettingsFor } from "./live-settings.ts";@@ -540,8 +540,10 @@ import { cookieMaxAgeSeconds, formatPairingCode, SessionRegistry, type Scope, tyimport { ThreadStarters } from "./thread-starters.ts";import {appendAdminAction,+ BOT_AUDIT_FIELDS,botAuditSnapshot,botChangeRows,+ TEAM_BOT_AUDIT_FIELDS,configChangeRows,flushAdminActivity,pruneAdminActivity,@@ -568,6 +570,7 @@ import { deliverSseFrame, openSseHeartbeat } from "./sse-fanout.ts";import { PhoneSecretBridge, PhoneSecretSubmissionRegistry } from "./phone-secret.ts";// Keep these two last, so loading the route table leaves module start-up order as is.import { gzipTunnelReplies, json, onJsonBody, parsedBodyOf, readBody } from "./harness/http.ts";+import { holdBodyDeadline } from "./body-deadline.ts";import { PASS, ROUTES, dispatchRoutes } from "./routes/table.ts"; import { createSecretCards } from "./host/secret-cards.ts"; import { createInternalCredentialRequestRoutes, createSecretCardRoutes } from "./routes/secret-cards.ts"; import { applyIncludedPagesMessage } from "./pages/access.ts"; import { createPublishedPages } from "./pages/service.ts"; import { createInternalToolRoutes } from "./routes/internal-tools.ts"; import { createHelperSuggestionRoutes } from "./routes/helper-suggestion.ts"; import { createXConnectorRoutes } from "./routes/x-connector.ts"; import { createMoveFreeze, switchAutomationsOff } from "./move-freeze.ts"; import { createMoveFreezeRoutes } from "./routes/move-freeze.ts"; import { createMoveWaits } from "./move-waits.ts"; import { assertBotHere, createBotMoves } from "./bot-moves.ts"; import { createBotMoveRoutes } from "./routes/bot-moves.ts"; import { createTeamMoveIn, moveInRefusal } from "./team-move-in.ts";import { createHostedSlackRoutes } from "./routes/hosted-slack.ts";import { createBotPresetRoutes } from "./routes/bot-presets.ts"; import { createWorkspaceBannerRoutes, workspaceBannerSummary } from "./routes/workspace-banner.ts";@@ -945,6 +948,7 @@ let cloudEarlierOwners: Pick<CloudOwnership, "adopted" | "proven"> = { adopted:let cloudHome: ReturnType<typeof settleCloudHome> | null = null; const teamHost = createCloudTeamHost({ team: CLOUD_TEAM, dataDir: DATA_DIR, store: { groupByThread: (threadId) => store.groupByThread(threadId), get bots() { return store.bots; } }, engineHomes, starters: threadStarters, markers: new Set([CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY]), language: appLanguage,serverProfile: { read: () => cfg.profile, clear: () => { adminActorScope.exit(() => saveConfig({ profile: { name: "", email: "", aboutMe: "", avatarUrl: "" } })); Object.assign(cfg, loadConfig()); } } });const teamOwners = createTeamOwners({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store: () => store, audienceOf: (threadId) => teamHost.audienceOf(threadId), starters: threadStarters });+const personRooms = createPersonRooms({ reads: CLOUD_TEAM ? createRoomReads(DATA_DIR) : null, store: () => store, newestMessageId: (threadId) => readCursor(threadId).lastReadMessageId, publicGroupState, broadcast });function actorKey(auth: RequestAuth & { kind: "session" }): string {return CLOUD_OWNER_KEY && auth.scopes.includes("admin") ? CLOUD_OWNER_KEY : personKey(auth.session);@@ -1178,7 +1182,9 @@ async function answeringCardAs(auth: RequestAuth, threadId: string, requestId: sconst { viewerFor, threadOwner, visibleTo, forgetVisibility, threadShown, subjectVisible, hiddenRoutineTarget, roomFeedsBot, settleRoomFloor } = createVisibilityHost({ store: () => store, routines: () => routines,team: Boolean(CLOUD_TEAM), audiencesFor: (viewer) => teamHost.audiencesFor(viewer), threadsReferencing }); if (CLOUD_TEAM) hideOthersSyncFolders(() => store.bots, threadShown);-function recentWorkFilter(threadId: string): { include?: (threadId: string) => boolean } { return CLOUD_TEAM ? { include: teamHost.readableFrom(threadId) } : CLOUD_HOME ? { include: cloudOwnerOnlyThread } : {}; }+function recentWorkFilter(threadId: string): { include?: (threadId: string) => boolean; privateThread?: (threadId: string) => boolean } {+ return CLOUD_TEAM ? { include: teamHost.readableFrom(threadId), privateThread: (id) => teamHost.privateTo(id) !== null } : CLOUD_HOME ? { include: cloudOwnerOnlyThread } : {};+}function recentWorkSources(bot: BotRecord) {return {@@ -1280,7 +1286,8 @@ onConfigSaved((before, after) => {});const WEBHOOK_AUDIT_FIELDS = ["name", "prompt", "botId", "runOn", "enabled", "eventTypes"] as const;-const auditBot = (id: string | undefined) => (id ? botAuditSnapshot(store.bot(id) as unknown as Record<string, unknown> | null) : null);+const BOT_AUDITED = CLOUD_TEAM ? TEAM_BOT_AUDIT_FIELDS : BOT_AUDIT_FIELDS;+const auditBot = (id: string | undefined) => (id ? botAuditSnapshot(store.bot(id) as unknown as Record<string, unknown> | null, BOT_AUDITED) : null);const auditHook = (id: string | undefined) => (id ? webhooks.list().find((hook) => hook.id === id) : undefined);const hookFields = (hook: WebhookTrigger, fields: readonly string[] = WEBHOOK_AUDIT_FIELDS) =>Object.fromEntries(fields.map((field) => [field, (hook as unknown as Record<string, unknown>)[field] ?? null]));@@ -1334,7 +1341,7 @@ function adminAuditRows(const reply = answered && typeof answered === "object" ? answered as Record<string, unknown> : {};const idOf = (value: unknown) => (value && typeof value === "object" && typeof (value as { id?: unknown }).id === "string" ? (value as { id: string }).id : undefined);if (plan.botId) {- rows.push(...botChangeRows({ id: plan.botId, name: store.bot(plan.botId)?.name }, before.bot, auditBot(plan.botId), requestedBotFields(req, path)));+ rows.push(...botChangeRows({ id: plan.botId, name: store.bot(plan.botId)?.name }, before.bot, auditBot(plan.botId), requestedBotFields(req, path), BOT_AUDITED));}if (plan.createsBots) {const created = [idOf(reply.bot), ...(Array.isArray(reply.bots) ? reply.bots.map(idOf) : [])].filter((id): id is string => Boolean(id));@@ -3635,6 +3642,7 @@ function createChannel(value: unknown): GroupRecord {}const name = body.name?.trim() || `${store.bot(memberIds[0])!.name} & co.`;if (name.length > 100) throw Object.assign(new Error("channel name must be at most 100 characters"), { status: 400 });+ if (!fitsOnOneLine(name)) throw Object.assign(new Error("room name must fit on one line"), { status: 400 });let section: string | undefined;if (body.section !== undefined && body.section !== null) {if (typeof body.section !== "string") throw Object.assign(new Error("context must be a string"), { status: 400 });@@ -3687,6 +3695,7 @@ function updateChannel(groupId: string, value: unknown): GroupRecord {const name = body.name.trim();if (!name) throw Object.assign(new Error("room name must not be empty"), { status: 400 });if (name.length > 100) throw Object.assign(new Error("room name must be at most 100 characters"), { status: 400 });+ if (!fitsOnOneLine(name)) throw Object.assign(new Error("room name must fit on one line"), { status: 400 });patch.name = name;}if (body.bulletin !== undefined) {@@ -4555,6 +4564,7 @@ function pageIfThreadChanged(id: string, threadId: string) {}store.onChange((change) => {if (change.type !== "message" && change.type !== "message.patch" && change.type !== "thread" && change.type !== "sections") forgetVisibility();+ if (change.type === "group.deleted") personRooms.reads?.forgetRoom(change.groupId);switch (change.type) {case "sections":broadcast({ kind: "sections", sections: store.sections });@@ -4799,8 +4809,8 @@ function cursorSeq(raw: string | string[] | undefined): number | null {return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : null;}-/** `adminOnly` frames are withheld from client sessions, live and on replay. */-function broadcast(payload: Record<string, unknown>, options: { adminOnly?: boolean } = {}) {+/** `adminOnly` frames are withheld from client sessions, live and on replay; a `person`'s frames reach only their streams. */+function broadcast(payload: Record<string, unknown>, options: { adminOnly?: boolean; person?: string } = {}) {// Close stale email streams before any further workspace data is delivered.sessions.revalidateEmailSessions();const seq = ++lastSeq;@@ -4809,12 +4819,13 @@ function broadcast(payload: Record<string, unknown>, options: { adminOnly?: bool// Members get config as configured-or-not and every bot without its server alias.const clientPayload = options.adminOnly ? null : kind === "config" ? configForAccess(payload as ReturnType<typeof configStatus>, false) : memberFramePayload(payload);const clientFrame = clientPayload === null ? null : clientPayload === payload ? frame : `id: ${STREAM_ID}:${seq}\ndata: ${JSON.stringify({ ...clientPayload, seq })}\n\n`;- replayBuffer.push({ seq, kind, frame, clientFrame, payload });+ replayBuffer.push({ seq, kind, frame, clientFrame, payload, ...(options.person ? { person: options.person } : {}) });+ const ownGroups: OwnGroupFrames = new Map();for (const client of Array.from(sseClients)) {- if (!wants(client, kind) || !teamOwners.reaches(client.ask, payload)) continue;+ if (!wants(client, kind) || !teamOwners.reaches(client.ask, payload) || !streamFor(client, options.person)) continue;// Admin-only frames (clientFrame null) never reach members, and a member never falls back to the admin frame.const out = CLOUD_TEAM && kind === "config" && clientFrame !== null ? teamConfigFrame(client, seq, payload)- : memberFrame(client, seq, payload, client.admin ? frame : clientFrame);+ : memberFrame(client, seq, payload, client.admin ? frame : clientFrame, ownGroups);if (out === null) continue;if (deliverSseFrame(client, kind, out) === "disconnected") client.close();}@@ -4826,8 +4837,13 @@ function teamConfigFrame(client: SseClient, seq: number, payload: Record<string,return `id: ${STREAM_ID}:${seq}\ndata: ${JSON.stringify({ ...own, seq })}\n\n`;}-/** `clientFrame` is the frame this client would get unnarrowed: an admin's is the admin frame, narrowed on a Team Cloud. */-function memberFrame(client: SseClient, seq: number, payload: Record<string, unknown>, clientFrame: string | null): string | null {+const streamFor = (client: SseClient, person: string | undefined) => !person || (client.person !== undefined && personKey(client.person) === person);++/** `clientFrame` is the frame this client would get unnarrowed: an admin's is the admin frame, narrowed on a Team Cloud.+ * `ownGroups` keeps each person's room for one frame. */+function memberFrame(client: SseClient, seq: number, payload: Record<string, unknown>, clientFrame: string | null, ownGroups: OwnGroupFrames = new Map()): string | null {+ const own = client.person && clientFrame !== null ? personRooms.ownGroupFrame(ownGroups, personKey(client.person), payload, (mine) => `id: ${STREAM_ID}:${seq}\ndata: ${JSON.stringify({ ...mine, seq })}\n\n`) : null;+ if (own) { payload = own.payload; clientFrame = own.frame; }const visible = visibleTo(client.viewer);if (clientFrame === null || (client.viewer.kind === "all" && !visible.filtersThreads)) return clientFrame;if (visible.everything) {@@ -9106,6 +9122,9 @@ const routineRequests = new RoutineRequestService({return null;},});+const memberOwnBot = createMemberOwnBot({ store: () => store, routines: () => routines, activeGroupTurnForBot, cancelGroupTurnOperations, revokeInternalCapabilitiesForThread, interruptAllDirectThreads,+ interruptTurn: (bot, threadId) => runningTurnInstance(bot, threadId)?.adapter.interruptTurn(threadId), closeOpenApprovals, deleteBot: (botId) => deleteBotWithLifecycle(botId) });+async function deleteBotWithLifecycle(botId: string, revalidate: () => void = () => {}, setupRequest?: TeamSetupRequest) {const deletionResponse = (status: number, body: { error?: string; ok?: boolean; notice?: string }) => ({ status, body });revalidate();@@ -9698,37 +9717,6 @@ function teammateReportContext(requestId: string, readerBotId?: string): stringconst roomTranscript = createRoomTranscript({ store, teammateReportContext });-/** Scrubbed of secrets and attachment markup before it leaves this machine. */-function roomRoutingInput(- roomName: string,- text: string,- members: readonly BotRecord[],- history: readonly Message[],- userName: PersonName,- sender?: ResolvedSender,-): RoomRoutingInput {- const clean = (value: string) => redactSecretsInText(extractTurnImages(value).text);- const humans = new Set<string>(typeof userName === "string" ? [userName] : []);- const recent = history.flatMap((m) => {- if (m.kind !== "text" || !m.text) return [];- if (m.role === "user") {- const person = speakerOf(userName, m);- humans.add(person);- return [{ from: person, text: clean(m.text) }];- }- return [{ from: `${m.from?.name ?? "A bot"} (bot)`, text: clean(m.text) }];- });- const from = speakerOf(userName, { sender });- humans.add(from);- return {- room: roomName,- humans: [...humans],- members: members.map((member) => ({ id: member.id, name: member.name, title: member.title, description: member.description })),- recent,- message: { from, text: clean(text) },- };-}-const roomPostBudgets = new Map<string, RoomPostBudget>();const ROOM_POST_MAX_CHARS = 4_000;@@ -12282,6 +12270,7 @@ const { react } = createReactions({const publishedPages = createPublishedPages({ dataDir: DATA_DIR, cloudHome: CLOUD_HOME, patch: (threadId, messageId, text, publishedPage) => void store.patchMessage(threadId, messageId, { text, publishedPage }), apps: { chat: chatApps, store } }); ROUTES.push(createReactionRoutes({ react, reactorFor, cloudGuestSendRefusal }), publishedPages.routes, savedSteps.routes);// `let` slots are read per request.ROUTES.push(createThreadRoutes({+ groupFor: personRooms.groupForAuth,store, userName: userNameFor, sessions, groupUsageReader, lendingEnabled,hostedWorkspace: HOSTED_WORKSPACE, sessionCookie: SESSION_COOKIE, loopback: LOOPBACK, defaultPage: DEFAULT_PAGE,workspaceAccess: () => workspaceAccess,@@ -12290,6 +12279,8 @@ ROUTES.push(createThreadRoutes({cliOwnerToken: () => cliOwnerToken,pageSize, messagePage, messageWindow, publicBotQueuedMessages, publicGroupState, wireBot,botComputerControlSnapshot, messageFileRootsForThread, viewerFor, visibleTo, coordinator, groupThreadIsWorking, memberDefaultBot: CLOUD_TEAM ? (email) => ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM.name }) : undefined,+ uploads: uploadsFor(createUploadOwners(DATA_DIR), Boolean(CLOUD_TEAM)),+ attachmentInUse: (name) => threadsReferencing(name).length > 0 || store.bots.some((bot) => bot.avatarUrl === `/api/attachments/${name}`),}));ROUTES.push(createBotCreateRoutes({store, cfg, presetStore, orgInstallStatuses,@@ -12329,6 +12320,8 @@ ROUTES.push(createSkillShareRoutes({ enabled: () => skillsHost.mode() !== "off",ROUTES.push(createTeamContextRoutes({ store, teamMemory }));ROUTES.push(createBotMemoryRoutes({bot: (id) => store.bot(id),+ ...(CLOUD_TEAM ? { ownLayer: (auth: RequestAuth, botId: string) => auth.kind === "session" && visibleTo(viewerFor(auth)).bot(botId)+ ? layerId(botId, memberAudience(personKey(auth.session))) : null } : {}),taskByThread: (botId, threadId) => store.taskByThread(botId, threadId),upkeep: memoryUpkeep,...(lendingMemory ? {@@ -12362,6 +12355,7 @@ ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKcreateTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: { 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),+ groupFor: personRooms.groupForAuth,setHold: (groupId, botId, held) => {const updated = setRoomHold(groupId, botId, held);return updated ? publicGroupState(updated) : null;@@ -12376,9 +12370,12 @@ ROUTES.push(createGroupRoutes({threadStarters,createChannel,publicGroupState,+ groupFor: personRooms.groupForAuth,}));ROUTES.push(createChannelRoutes({store, threadRead: teamMessages.seen,+ personMarkRoom: personRooms.personMarkRoom,+ groupFor: personRooms.groupForAuth,cfg,userName: userNameFor,desktopManaged: DESKTOP_MANAGED,@@ -12451,7 +12448,7 @@ const taskRoutes = createTaskRoutes({revokeInternalCapabilitiesForThread,stagedSkillCleanupsForThread,rejectDeletedThreadSkillStages,-}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, revokeSessions: (email) => sessions.revokeMember(email), busy: threadBusy, stop: (botId, threadId) => interruptDirectThread(botId, threadId, "The person left the team"), deleteTasks: taskRoutes.deleteTasks, threadsReferencing, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), eraseBrowsers: eraseAudienceBrowsers, forgetConnections: (person) => teamConnections.forgetPerson(person) }) : null;+}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, revokeSessions: (email) => sessions.revokeMember(email), busy: threadBusy, stop: (botId, threadId) => interruptDirectThread(botId, threadId, "The person left the team"), deleteTasks: taskRoutes.deleteTasks, stopBot: (botId) => memberOwnBot.stopWork(botId, "The person left the team"), deleteBot: memberOwnBot.remove, threadsReferencing, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), eraseBrowsers: eraseAudienceBrowsers, forgetConnections: (person) => { teamConnections.forgetPerson(person); personRooms.reads?.forgetPerson(person); } }) : null;ROUTES.push(createTeamRoutes({store,cfg,@@ -12692,6 +12689,7 @@ ROUTES.push(createLiveRoutes({const toolResults = new ToolResults();const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {+ if (CLOUD_TEAM) holdBodyDeadline(req, res);let url: URL;try {url = new URL(req.url ?? "/", `http://localhost:${PORT}`);@@ -14949,7 +14947,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {return json(res, 400, { error: "single-bot events open that bot's chat directly" });}const group = ensureCalendarCallRoom(call);- return json(res, 200, { group: { ...publicGroupState(group), messages: store.messagesFor(group.threadId) } });+ return json(res, 200, { group: { ...personRooms.groupForAuth(auth, publicGroupState(group)), messages: store.messagesFor(group.threadId) } });}const calendarCallMatch = path.match(/^\/api\/calendar-calls\/([\w-]+)$/);if (calendarCallMatch && method === "PATCH") {@@ -15018,7 +15016,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {);if (resumed) {for (const buffered of replayBuffer) {- if (buffered.seq <= since || !wants(client, buffered.kind) || (buffered.payload && !teamOwners.reaches(client.ask, buffered.payload))) continue;+ if (buffered.seq <= since || !wants(client, buffered.kind) || (buffered.payload && !teamOwners.reaches(client.ask, buffered.payload)) || !streamFor(client, buffered.person)) continue;const frame = CLOUD_TEAM && buffered.kind === "config" && buffered.clientFrame !== null && buffered.payload? teamConfigFrame(client, buffered.seq, buffered.payload): buffered.payloaddiff --git a/server/message-text.ts b/server/message-text.tsnew file mode 100644index 0000000000..aaf72f7114--- /dev/null+++ b/server/message-text.ts@@ -0,0 +1,6 @@+/** Why a message's `text` is refused, or null; a missing or empty one is the caller's "text required". */+export function messageTextRefusal(text: unknown): string | null {+ if (text === undefined || text === null) return null;+ if (typeof text !== "string") return "text must be a string";+ return text.includes("\0") ? "text must not contain a null byte" : null;+}diff --git a/server/new-bot-defaults.ts b/server/new-bot-defaults.tsindex 05077553c9..97c09f6fec 100644--- a/server/new-bot-defaults.ts+++ b/server/new-bot-defaults.ts@@ -20,8 +20,9 @@ export const botDefaultModelSchema = z.object({// Preferences only: consent flags, live grants, bot IDs and execution state can never be replayed as permission grants.export const botDefaultsProfileSchema = profilePatchSchema.extend({- name: z.string().max(100).refine(fitsOnOneLine, "name must fit on one line").optional(),- section: z.string().trim().max(60).optional(),+ name: z.string({ error: "name must be a string" }).max(100, { error: "name must be at most 100 characters" })+ .refine(fitsOnOneLine, "name must fit on one line").optional(),+ section: z.string({ error: "section must be a string" }).trim().max(60, { error: "section must be at most 60 characters" }).optional(),color: z.enum(MAUS_COLOR_NAMES).optional(),mascotExpression: z.string().max(60).nullable().optional(),modelSelection: botDefaultModelSchema.optional(),@@ -106,20 +107,29 @@ export type BotDefaultsProfile = NewBotDefaults["profile"];export type BotRoutineTemplate = NewBotDefaults["routines"][number];export type BotSkillTemplate = NewBotDefaults["skills"][number];+/** The first thing wrong, as one sentence: a field's own message, else which field is not valid. */+function settingsError(error: z.ZodError): string {+ const issue = error.issues[0];+ if (!issue) return "These bot settings are not valid.";+ if (issue.code === "unrecognized_keys") return `unsupported bot field: ${issue.keys[0] ?? "unknown"}`;+ const field = issue.path.join(".");+ return field && issue.message.startsWith(String(issue.path[0])) ? issue.message : `${field || "the bot"} is not valid`;+}+export function resolveBotCreationDefaults(saved: NewBotDefaults | undefined, body: Record<string, unknown>) {if (body.useDefaults !== undefined && typeof body.useDefaults !== "boolean") {throw Object.assign(new Error("useDefaults must be true or false"), { status: 400 });}const template = newBotDefaultsSchema.parse(body.useDefaults === false ? {} : saved ?? {});const checked = botDefaultsProfileSchema.safeParse(body.settings === undefined ? {} : body.settings);- if (!checked.success) throw Object.assign(new Error(checked.error.message), { status: 400 });+ if (!checked.success) throw Object.assign(new Error(settingsError(checked.error)), { status: 400 });const explicit = checked.data;const profile = { ...template.profile, ...explicit };for (const key of ["name", "title", "description", "modelSelection", "section"] as const) {if (Object.hasOwn(body, key)) Object.assign(profile, { [key]: key === "section" && body[key] === null ? "" : body[key] });}const resolved = botDefaultsProfileSchema.safeParse(profile);- if (!resolved.success) throw Object.assign(new Error(resolved.error.message), { status: 400 });+ if (!resolved.success) throw Object.assign(new Error(settingsError(resolved.error)), { status: 400 });if (!resolved.data.name?.trim()) delete resolved.data.name;return { ...template, profile: resolved.data };}diff --git a/server/recent-work.test.ts b/server/recent-work.test.tsindex 8c3f5cef9e..9326bcd59e 100644--- a/server/recent-work.test.ts+++ b/server/recent-work.test.ts@@ -33,6 +33,11 @@ describe("botThreads", () => {expect(botThreads(store, withRun, "Milind").map((thread) => thread.threadId)).not.toContain("run-1");});+ it("on a Team Cloud calls only a chat private to one person private, never the bot's shared main chat", () => {+ const threads = botThreads(store, me, "Milind", (threadId) => threadId === "t-inv");+ expect(threads.filter((thread) => thread.private).map((thread) => thread.threadId)).toEqual(["t-inv", "dm-them"]);+ });+it("lists the main chat, tasks, and the rooms the bot belongs to, each named for the bot", () => {expect(botThreads(store, me, "Milind")).toEqual([{ threadId: "main", where: "1:1 with Milind", title: "Getting started", private: true },diff --git a/server/recent-work.ts b/server/recent-work.tsindex ee67410507..d72dae7766 100644--- a/server/recent-work.ts+++ b/server/recent-work.ts@@ -19,7 +19,9 @@ export interface RecentWorkStore {taskByThread(botId: string, threadId: string): TaskRecord | undefined;}-export function botThreads(store: RecentWorkStore, bot: Pick<BotRecord, "id" | "threadId" | "tasks">, userName: string): BotThread[] {+/** `privateThread`: on a Team Cloud, whether a conversation is one person's alone; elsewhere every 1:1 chat is private. */+export function botThreads(store: RecentWorkStore, bot: Pick<BotRecord, "id" | "threadId" | "tasks">, userName: string,+ privateThread: (threadId: string) => boolean = () => true): BotThread[] {const out: BotThread[] = [];const seen = new Set<string>();const add = (thread: BotThread) => {@@ -28,8 +30,8 @@ export function botThreads(store: RecentWorkStore, bot: Pick<BotRecord, "id" | "out.push(thread);};const direct = `1:1 with ${userName}`;- add({ threadId: bot.threadId, where: direct, title: store.taskByThread(bot.id, bot.threadId)?.title ?? null, private: true });- for (const task of bot.tasks ?? []) if (!task.routineRunId) add({ threadId: task.threadId, where: direct, title: task.title, private: true });+ add({ threadId: bot.threadId, where: direct, title: store.taskByThread(bot.id, bot.threadId)?.title ?? null, private: privateThread(bot.threadId) });+ for (const task of bot.tasks ?? []) if (!task.routineRunId) add({ threadId: task.threadId, where: direct, title: task.title, private: privateThread(task.threadId) });for (const group of store.groups) {if (!group.memberIds.includes(bot.id)) continue;const where = `room ${JSON.stringify(group.name)}`;@@ -70,9 +72,9 @@ export function recentWorkLines(threads: readonly BotThread[], latest: readonlyexport function recentWork(store: RecentWorkStore,bot: Pick<BotRecord, "id" | "threadId" | "tasks">,- opts: { userName: string; currentThreadId?: string; now?: number; windowMs?: number; include?: (threadId: string) => boolean },+ opts: { userName: string; currentThreadId?: string; now?: number; windowMs?: number; include?: (threadId: string) => boolean; privateThread?: (threadId: string) => boolean },): RecentWorkLine[] {- const threads = botThreads(store, bot, opts.userName).filter((thread) => thread.threadId !== opts.currentThreadId && (!opts.include || opts.include(thread.threadId)));+ const threads = botThreads(store, bot, opts.userName, opts.privateThread).filter((thread) => thread.threadId !== opts.currentThreadId && (!opts.include || opts.include(thread.threadId)));if (!threads.length) return [];const since = (opts.now ?? Date.now()) - (opts.windowMs ?? RECENT_WORK_WINDOW_MS);return recentWorkLines(threads, latestSaidByBot(threads.map((thread) => thread.threadId), bot.id, since, RECENT_WORK_MAX_LINES));diff --git a/server/request-auth.test.ts b/server/request-auth.test.tsindex 8b90a99679..a7136f08c5 100644--- a/server/request-auth.test.ts+++ b/server/request-auth.test.ts@@ -188,6 +188,12 @@ describe("scopes", () => {expect(clientBotPatchViolation({ xResearch: true })).toBe("xResearch");expect(clientBotPatchViolation({ recordBrowserSteps: true })).toBe("recordBrowserSteps");expect(clientBotPatchViolation([])).toBe("body");+ // A Team Cloud member changes no team bot's look, which everyone sees; their own MausBot's they do.+ expect(clientBotPatchViolation({ color: "blue" }, false, true)).toBe("color");+ expect(clientBotPatchViolation({ avatarUrl: null }, false, true)).toBe("avatarUrl");+ expect(clientBotPatchViolation({ mascotBody: "cursor" }, false, true)).toBe("mascotBody");+ expect(clientBotPatchViolation({ unread: false, pinned: true }, false, true)).toBeNull();+ expect(clientBotPatchViolation({ color: "blue", name: "Mine" }, true, true)).toBeNull();expect(clientGroupPatchViolation({ name: "Ops", unread: false, turnTimeoutMinutes: 30 })).toBeNull();expect(clientGroupPatchViolation({ cwd: "/tmp" })).toBe("cwd");expect(clientGroupPatchViolation({ memberIds: [] })).toBe("memberIds");diff --git a/server/request-auth.ts b/server/request-auth.tsindex e3130ecbe4..e1da1468d2 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -365,6 +365,7 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg{ methods: ["POST"], path: /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/reactions$/ },{ methods: ["POST"], path: /^\/api\/attachments$/ },{ methods: ["GET"], path: /^\/api\/attachments\/[\w.-]+$/ },+ { methods: ["DELETE"], path: /^\/api\/attachments\/[\w.-]+$/ }, // only the uploader's, only while nothing uses it{ methods: ["POST"], path: /^\/api\/files$/ },// voice: labels and audio, never the key{ methods: ["GET"], path: /^\/api\/tts\/voices$/ },@@ -387,6 +388,9 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg{ methods: ["GET"], path: /^\/api\/config$/ },// a person's own "About you" on a Team Cloud{ methods: ["GET", "PUT"], path: /^\/api\/me$/ },+ // what a bot remembers about the signed-in person on a Team Cloud: their own layer only (routes/bot-memory.ts ownLayer)+ { methods: ["GET"], path: /^\/api\/bots\/[\w-]+\/memory\/mine$/ },+ { methods: ["GET", "PUT", "DELETE"], path: /^\/api\/bots\/[\w-]+\/memory\/mine\/file$/ },// a Team Cloud's member moving a bot of their own in: it answers with a sign-in for that one bot{ methods: ["POST"], path: /^\/api\/team-move-in$/ },// a Team Cloud member's own connections: only the session's own person, never a value back@@ -424,10 +428,18 @@ const CLIENT_BOT_PATCH_FIELDS = new Set(["unread", "pinned", "pinnedMessageId", "color", "mascotExpression", "mascotBody", "mascotFaceColor","avatarUrl", "avatarCrop", "avatarZoom", "avatarFocusX", "avatarFocusY", "sidebarHidden", "welcomed",]);-/** `ownMausBot`: the session's own MausBot on a Team Cloud, which its member may also rename. */-export function clientBotPatchViolation(body: unknown, ownMausBot = false): string | null {+/** How a bot looks to everyone who sees it. */+const SHARED_LOOK_FIELDS = new Set([+ "color", "mascotExpression", "mascotBody", "mascotFaceColor", "avatarUrl", "avatarCrop", "avatarZoom", "avatarFocusX", "avatarFocusY",+]);+/** `ownMausBot`: the session's own MausBot on a Team Cloud, which its member may also rename. `teamMember`: a Team Cloud+ * member's session, which changes no other bot's look. */+export function clientBotPatchViolation(body: unknown, ownMausBot = false, teamMember = false): string | null {if (!body || typeof body !== "object" || Array.isArray(body)) return "body";- for (const key of Object.keys(body)) if (!CLIENT_BOT_PATCH_FIELDS.has(key) && !(ownMausBot && key === "name")) return key;+ for (const key of Object.keys(body)) {+ if (ownMausBot && key === "name") continue;+ if (!CLIENT_BOT_PATCH_FIELDS.has(key) || (teamMember && !ownMausBot && SHARED_LOOK_FIELDS.has(key))) return key;+ }return null;}diff --git a/server/routes/bot-memory.ts b/server/routes/bot-memory.tsindex 164b4946c2..3d0acfedeb 100644--- a/server/routes/bot-memory.ts+++ b/server/routes/bot-memory.ts@@ -37,6 +37,8 @@ export interface BotMemoryRouteDeps {owner(auth: RequestAuth): boolean;};ownersWrite?: <T>(auth: RequestAuth, botId: string, write: () => T) => T;+ /** Team Cloud only: the signed-in person's own layer of this bot's memory (`/memory/mine`); null for anyone else. */+ ownLayer?(auth: RequestAuth, botId: string): string | null;}export function createBotMemoryRoutes(deps: BotMemoryRouteDeps): RouteHandler {@@ -58,6 +60,39 @@ export function createBotMemoryRoutes(deps: BotMemoryRouteDeps): RouteHandler {return async ({ req, res, url, path, method, auth, json, readBody }) => {let m: RegExpMatchArray | null = null;const write = <T>(botId: string, change: () => T): T => deps.ownersWrite ? deps.ownersWrite(auth, botId, change) : change();+ /** One memory file of `id`, a bot's own folder or a layer of it. */+ const serveFile = async (id: string, guarded: <T>(change: () => T) => T) => {+ if (method === "GET") {+ try {+ return json(res, 200, readMemoryDoc(id, url.searchParams.get("path") ?? MEMORY_INDEX));+ } catch (error) {+ return replyMemoryError(res, error);+ }+ }+ if (method === "PUT") {+ const parsed = z+ .object({ path: z.string().default(MEMORY_INDEX), text: z.string(), expectedHash: z.string().optional() })+ .safeParse(await readBody(req));+ if (!parsed.success) return json(res, 400, { error: "text must be a string; path and expectedHash are optional strings" });+ try {+ const { doc, entry } = guarded(() => journalMemoryWrite(id, parsed.data.path, parsed.data.text, {+ actor: "person",+ via: "ui",+ expectedHash: parsed.data.expectedHash,+ }));+ return json(res, 200, { ok: true, ...doc, entry: entry ? journalEntryForClient(id, entry) : null, overview: memoryOverview(id) });+ } catch (error) {+ return replyMemoryError(res, error);+ }+ }+ const file = url.searchParams.get("path") ?? "";+ try {+ const entry = guarded(() => journalMemoryDelete(id, file, { actor: "person", via: "ui" }));+ return json(res, 200, { ok: true, path: file, entry: entry ? journalEntryForClient(id, entry) : null, overview: memoryOverview(id) });+ } catch (error) {+ return replyMemoryError(res, error);+ }+ };m = path.match(/^\/api\/bots\/([\w-]+)\/memory$/);if (m && method === "GET") {if (!deps.bot(m[1])) return json(res, 404, { error: "no such bot" });@@ -102,42 +137,18 @@ export function createBotMemoryRoutes(deps: BotMemoryRouteDeps): RouteHandler {return json(res, 200, { ok: true, lendingReview: false });}m = path.match(/^\/api\/bots\/([\w-]+)\/memory\/file$/);- if (m && method === "GET") {- if (!deps.bot(m[1])) return json(res, 404, { error: "no such bot" });- try {- return json(res, 200, readMemoryDoc(m[1], url.searchParams.get("path") ?? MEMORY_INDEX));- } catch (error) {- return replyMemoryError(res, error);- }- }- if (m && method === "PUT") {+ if (m && ["GET", "PUT", "DELETE"].includes(method)) {if (!deps.bot(m[1])) return json(res, 404, { error: "no such bot" });- const parsed = z- .object({ path: z.string().default(MEMORY_INDEX), text: z.string(), expectedHash: z.string().optional() })- .safeParse(await readBody(req));- if (!parsed.success) return json(res, 400, { error: "text must be a string; path and expectedHash are optional strings" });- try {- const botId = m[1];- const { doc, entry } = write(botId, () => journalMemoryWrite(botId, parsed.data.path, parsed.data.text, {- actor: "person",- via: "ui",- expectedHash: parsed.data.expectedHash,- }));- return json(res, 200, { ok: true, ...doc, entry: entry ? journalEntryForClient(m[1], entry) : null, overview: memoryOverview(m[1]) });- } catch (error) {- return replyMemoryError(res, error);- }+ const botId = m[1];+ return serveFile(botId, (change) => write(botId, change));}- if (m && method === "DELETE") {- if (!deps.bot(m[1])) return json(res, 404, { error: "no such bot" });- const file = url.searchParams.get("path") ?? "";- try {- const botId = m[1];- const entry = write(botId, () => journalMemoryDelete(botId, file, { actor: "person", via: "ui" }));- return json(res, 200, { ok: true, path: file, entry: entry ? journalEntryForClient(m[1], entry) : null, overview: memoryOverview(m[1]) });- } catch (error) {- return replyMemoryError(res, error);- }+ m = path.match(/^\/api\/bots\/([\w-]+)\/memory\/mine(\/file)?$/);+ if (m && (method === "GET" || m[2])) {+ const layer = deps.bot(m[1]) ? deps.ownLayer?.(auth, m[1]) ?? null : null;+ if (!layer) return json(res, 404, { error: "no such bot" });+ if (!m[2]) return json(res, 200, memoryOverview(layer));+ if (!["GET", "PUT", "DELETE"].includes(method)) return PASS;+ return serveFile(layer, (change) => change());}m = path.match(/^\/api\/bots\/([\w-]+)\/memory\/journal$/);if (m && method === "GET") {diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.tsindex 84acbdf49b..3b309f1f0d 100644--- a/server/routes/bot-messages.ts+++ b/server/routes/bot-messages.ts@@ -18,6 +18,7 @@ import type { Handoffs } from "../delta-context.ts";import type { OneOnOneGoals } from "../host/one-on-one-goals.ts";import type { ProviderRegistry } from "../harness/registry.ts";import { spokenLineFields } from "../live-call-record.ts";+import { messageTextRefusal } from "../message-text.ts";import { stopReachesLiveTurn } from "../person-stops.ts";import type { PhoneSecretSubmissionRegistry } from "../phone-secret.ts";import type { ReplyTarget } from "../replies.ts";@@ -200,6 +201,8 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerif (guardedBody?.data?.reaction !== undefined && (!reactionAnswer(relayed) || !body.replyToId || !guardedBody.data.onBehalfOf)) {return json(res, 400, { error: "a relayed reaction is a 👍 or 👎 on the message in replyToId, made by the person in onBehalfOf" });}+ const textRefused = pressed || fromAnApp ? null : messageTextRefusal(body.text);+ if (textRefused) return json(res, 400, { error: textRefused });const typed = pressed || fromAnApp ? "" : relayed ?? String(body.text ?? "").trim();if (!pressed && !fromAnApp && !typed) return json(res, 400, { error: "text required" });const bot = store.bot(m[1]);@@ -446,6 +449,8 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerconst bot = requestedTaskBot(m[1], body.threadId);const notYours = cloudThreadRefusal(auth, bot.threadId);if (notYours) return json(res, 403, { error: notYours });+ const textRefused = messageTextRefusal(body.text);+ if (textRefused) return json(res, 400, { error: textRefused });const text = String(body.text ?? "").trim();if (!text) return json(res, 400, { error: "text required" });const threadMessages = store.messagesFor(bot.threadId);diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.tsindex 77229628a8..356a55bd77 100644--- a/server/routes/bot-patch.ts+++ b/server/routes/bot-patch.ts@@ -94,7 +94,8 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {}const pairedDevice = req.headers["x-openmausbot-companion"] === "1";if ((auth.kind === "session" && !auth.scopes.includes("admin")) || pairedDevice) {- const field = clientBotPatchViolation(body, ownsDefaultBot(store.bot(m[1]), auth.kind === "session" ? auth.session.email : undefined));+ const session = auth.kind === "session" ? auth.session : undefined;+ const field = clientBotPatchViolation(body, ownsDefaultBot(store.bot(m[1]), session?.email), session?.membershipAuthority === "team");if (field) {return json(res, 403, {error: pairedDevicediff --git a/server/routes/channels.ts b/server/routes/channels.tsindex d327b0d8f1..9b8b5aaa44 100644--- a/server/routes/channels.ts+++ b/server/routes/channels.ts@@ -14,6 +14,7 @@ import {import { DATA_DIR, type AppConfig } from "../config.ts";import type { ProviderInstance, SteerOutcome } from "../contracts.ts";import { cancelledChatFollowup } from "../message-db.ts";+import { messageTextRefusal } from "../message-text.ts";import type { PhoneSecretSubmissionRegistry } from "../phone-secret.ts";import { promptWithReply, type PersonName } from "../replies.ts";import { clientGroupPatchViolation, requestSource, type RequestAuth } from "../request-auth.ts";@@ -65,6 +66,11 @@ export interface ChannelRouteDeps {readCursor(threadId: string): { lastReadMessageId?: string };/** A person opened this room (a Team Cloud's Needs you lines for them there are done). */threadRead?(auth: RequestAuth, threadId: string): void;+ /** A Team Cloud: marks the room read or unread for this person alone and answers the room as they see it; null where a+ * room is read once for everyone. */+ personMarkRoom?(auth: RequestAuth, room: GroupRecord, unread: boolean): WireGroup | null;+ /** A room as this person has read it (a Team Cloud); the room itself anywhere else. */+ groupFor?(auth: RequestAuth, group: WireGroup): WireGroup;pageSize(raw: string | null): number | null | undefined;messagePage(threadId: string, limit: number | undefined): MessagePage;resolveReplyTarget(threadId: string, value: unknown): Message | undefined;@@ -123,6 +129,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {return result;};return async ({ req, res, url, path, method, auth, json, readBody }) => {+ const own = (group: WireGroup) => deps.groupFor?.(auth, group) ?? group;let m: RegExpMatchArray | null = null;const routines = deps.routines();@@ -144,7 +151,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {if (!task) return json(res, 500, { error: "couldn't create that task" });// Who opened it decides who may answer its cards on a shared workspace.if (auth.kind === "session") threadStarters.set(task.threadId, actorKey(auth));- return json(res, 201, { group: groupWithThread(store.group(group.id)!), task });+ return json(res, 201, { group: own(groupWithThread(store.group(group.id)!)), task });}m = path.match(/^\/api\/groups\/([\w-]+)\/tasks\/delete$/);@@ -164,7 +171,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {if (allowed.length >= (group.tasks?.length ?? 1)) return json(res, 400, { error: "a channel keeps at least one task" });const result = deleteGroupTasks(group.id, allowed);if (!result) return json(res, 400, { error: "a channel keeps at least one task" });- return json(res, 200, { group: groupWithThread(result.group), deleted: result.deleted, refused });+ return json(res, 200, { group: own(groupWithThread(result.group)), deleted: result.deleted, refused });}m = path.match(/^\/api\/groups\/([\w-]+)\/tasks\/([\w-]+)$/);@@ -183,7 +190,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {if (!switched) return json(res, 404, { error: "no such channel task" });deps.threadRead?.(auth, switched.threadId);readThreadNotifications(switched.threadId, broadcast, auth);- const switchedSettings = publicGroupState(switched);+ const switchedSettings = own(publicGroupState(switched));// "0": settings only (no `messages` key); a positive page: that tail; omitted: the whole transcript.const responseGroup = requestedMessages === "0"? switchedSettings@@ -234,7 +241,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {if (refusal) return json(res, refusal.status, { error: refusal.error });const updated = deleteGroupTasks(group.id, [m[2]]);if (!updated?.deleted.length) return json(res, 400, { error: "a channel keeps at least one task" });- return json(res, 200, { group: groupWithThread(updated.group) });+ return json(res, 200, { group: own(groupWithThread(updated.group)) });}m = path.match(/^\/api\/groups\/([\w-]+)$/);@@ -250,8 +257,13 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {const notYours = cloudThreadRefusal(auth, renamed.threadId);if (notYours) return json(res, 403, { error: notYours });}+ if (deps.personMarkRoom && auth.kind === "session" && renamed && typeof body?.unread === "boolean") {+ const { unread, ...shared } = body;+ const group = Object.keys(shared).length ? updateChannel(m[1], shared) : renamed;+ return json(res, 200, { group: deps.personMarkRoom(auth, group, unread) ?? own(publicGroupState(group)) });+ }const group = updateChannel(m[1], body);- return json(res, 200, { group: publicGroupState(group) });+ return json(res, 200, { group: own(publicGroupState(group)) });}m = path.match(/^\/api\/groups\/([\w-]+)\/read$/);if (m && method === "POST") {@@ -259,10 +271,15 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {if (!room) return json(res, 404, { error: "no such room" });sawThread(room.threadId);deps.threadRead?.(auth, room.threadId);+ const personal = deps.personMarkRoom?.(auth, room, false);+ if (personal) {+ readThreadNotifications(room.threadId, broadcast, auth);+ return json(res, 200, { group: personal });+ }const group = store.patchGroup(room.id, { unread: false, ...readCursor(room.threadId) })!;readThreadNotifications(room.threadId, broadcast, auth);broadcast({ kind: "group", group: publicGroupState(group) });- return json(res, 200, { group: publicGroupState(group) });+ return json(res, 200, { group: own(publicGroupState(group)) });}m = path.match(/^\/api\/groups\/([\w-]+)$/);if (m && method === "DELETE") {@@ -292,6 +309,8 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {if (!body || typeof body !== "object" || Array.isArray(body)) {return json(res, 400, { error: "body must be a JSON object" });}+ const textRefused = messageTextRefusal(body.text);+ if (textRefused) return json(res, 400, { error: textRefused });const text = String(body.text ?? "").trim();if (!text) return json(res, 400, { error: "text required" });const group = store.group(m[1]);@@ -525,7 +544,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {}const visible = publicGroupState(store.group(group.id) ?? group);broadcast({ kind: "group", group: visible });- return json(res, 202, { ok: true, threadId: group.threadId, group: visible });+ return json(res, 202, { ok: true, threadId: group.threadId, group: own(visible) });}m = path.match(/^\/api\/groups\/([\w-]+)\/interrupt$/);if (m && method === "POST") {diff --git a/server/routes/cloud-signed.ts b/server/routes/cloud-signed.tsindex 607773523d..b39f9490af 100644--- a/server/routes/cloud-signed.ts+++ b/server/routes/cloud-signed.ts@@ -25,7 +25,7 @@ export const CLOUD_TEAM_MEMBER_LEFT_PATH = "/api/cloud/team/member-left";export function createCloudSignedRoutes(deps: {secret: string;- sessions: Pick<SessionRegistry, "openPairing" | "attemptAllowed" | "noteFailure" | "clearFailures">;+ sessions: Pick<SessionRegistry, "openPairing" | "revokeMember" | "attemptAllowed" | "noteFailure" | "clearFailures">;/** A Team Cloud: every pairing body must carry the Admin's member claim (cloud-team.ts). */team?: CloudTeam | null;health: Pick<CloudHealth, "report">;diff --git a/server/routes/groups.ts b/server/routes/groups.tsindex 4f3616582e..803aacb920 100644--- a/server/routes/groups.ts+++ b/server/routes/groups.ts@@ -15,6 +15,8 @@ export interface GroupRouteDeps {threadStarters: Pick<ThreadStarters, "set">;createChannel(value: unknown): GroupRecord;publicGroupState(record: GroupRecord): WireGroup;+ /** A room as this person has read it (a Team Cloud); the room itself anywhere else. */+ groupFor?(auth: RequestAuth, group: WireGroup): WireGroup;}/** A room's default responder from a request body; null when it is not one, or names a bot outside the room. */@@ -45,6 +47,7 @@ export function createGroupRoutes(deps: GroupRouteDeps): RouteHandler {return async ({ req, res, path, method, auth, json, readBody }) => {let m: RegExpMatchArray | null = null;const visible = deps.visibleFor(auth);+ const own = (group: WireGroup) => deps.groupFor?.(auth, group) ?? group;if (method === "POST" && path === "/api/groups") {const body = await readBody(req);const hiddenMember = Array.isArray(body?.memberIds) ? body.memberIds.find((id: unknown) => typeof id === "string" && store.bot(id) && !visible.bot(id)) : undefined;@@ -52,7 +55,7 @@ export function createGroupRoutes(deps: GroupRouteDeps): RouteHandler {const group = createChannel(body);// On a Cloud home whoever opens a room names it (cloudThreadRefusal).if (CLOUD_HOME && auth.kind === "session") threadStarters.set(group.threadId, actorKey(auth));- return json(res, 201, { group: { ...publicGroupState(group), messages: [] } });+ return json(res, 201, { group: { ...own(publicGroupState(group)), messages: [] } });}m = path.match(/^\/api\/groups\/([\w-]+)\/setup$/);if (m && method === "PATCH") {@@ -64,7 +67,7 @@ export function createGroupRoutes(deps: GroupRouteDeps): RouteHandler {return json(res, 400, { error: "action must be complete or skip" });}if (group.setupCompletedAt != null || group.setupSkippedAt != null) {- return json(res, 200, { group: publicGroupState(group) });+ return json(res, 200, { group: own(publicGroupState(group)) });}if (store.messagesFor(group.threadId).length > 0) {return json(res, 409, { error: "room setup must be finished before the first message" });@@ -87,7 +90,7 @@ export function createGroupRoutes(deps: GroupRouteDeps): RouteHandler {}const updated = store.patchGroup(m[1], patch);if (!updated) return json(res, 404, { error: "no such room" });- return json(res, 200, { group: publicGroupState(updated) });+ return json(res, 200, { group: own(publicGroupState(updated)) });}return PASS;};diff --git a/server/routes/room-holds.ts b/server/routes/room-holds.tsindex 3d351f1ffa..ab01b486f8 100644--- a/server/routes/room-holds.ts+++ b/server/routes/room-holds.ts@@ -1,18 +1,21 @@// POST /api/groups/<room>/holds {botId, held}: holding a member mid-turn ends that member's turn only.import { z } from "zod";import type { WireGroup } from "../../shared/wire.ts";+import type { RequestAuth } from "../request-auth.ts";import { PASS, type RouteHandler } from "./table.ts";export interface RoomHoldRouteDeps {group(id: string): { dm?: unknown; memberIds: readonly string[] } | undefined;setHold(groupId: string, botId: string, held: boolean): WireGroup | null;+ /** A room as this person has read it (a Team Cloud); the room itself anywhere else. */+ groupFor?(auth: RequestAuth, group: WireGroup): WireGroup;}const HOLDS = /^\/api\/groups\/([\w-]+)\/holds$/u;const BODY = z.object({ botId: z.string().regex(/^[\w-]+$/), held: z.boolean() }).strict();export function createRoomHoldRoutes(deps: RoomHoldRouteDeps): RouteHandler {- return async ({ req, res, path, method, json, readBody }) => {+ return async ({ req, res, path, method, auth, json, readBody }) => {const m = HOLDS.exec(path);if (!m || method !== "POST") return PASS;const parsed = BODY.safeParse(await readBody(req));@@ -23,6 +26,6 @@ export function createRoomHoldRoutes(deps: RoomHoldRouteDeps): RouteHandler {if (!group.memberIds.includes(parsed.data.botId)) return json(res, 404, { error: "that bot is not a member of this room" });const updated = deps.setHold(m[1]!, parsed.data.botId, parsed.data.held);if (!updated) return json(res, 404, { error: "no such room" });- return json(res, 200, { ok: true, group: updated });+ return json(res, 200, { ok: true, group: deps.groupFor?.(auth, updated) ?? updated });};}diff --git a/server/routes/threads.ts b/server/routes/threads.tsindex 1954d46f7f..7b45b2f245 100644--- a/server/routes/threads.ts+++ b/server/routes/threads.ts@@ -1,7 +1,9 @@+import { basename, join } from "node:path";+import type { WireBot, WireGroup } from "../../shared/wire.ts";import {- ATTACHMENTS_DIR, extensionForMime, FILE_MAX_BYTES, IMAGE_MAX_BYTES, parseAudioRange, readAttachment, saveFile, saveImageUpload,- validateAttachmentUploadId, type SavedAttachment,+ ATTACHMENTS_DIR, deleteAttachment, extensionForMime, FILE_MAX_BYTES, IMAGE_MAX_BYTES, parseAudioRange, readAttachment,+ saveFile, saveImageUpload, validateAttachmentUploadId, type SavedAttachment,} from "../attachments.ts";import { deliveredCopy } from "../bot-attachment.ts";import { memberBot, memberGroup, type Viewer, type VisibleSet } from "../bot-visibility.ts";@@ -21,6 +23,8 @@ import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";import { createJobRoutes } from "./jobs.ts";import { PASS, type RouteContext, type RouteHandler } from "./table.ts";+const UPLOADED_NAME = /^[A-Za-z0-9-]+\.[A-Za-z0-9]{1,10}$/;+export type MessagePage = { messages: Array<Message | Record<string, unknown>>; hasMore?: boolean; activeLeafId: string | null };export interface ThreadRouteDeps {@@ -51,9 +55,14 @@ export interface ThreadRouteDeps {botComputerControlSnapshot(botId: string): ReturnType<ComputerControl["snapshot"]>;messageFileRootsForThread(senderId: string, threadId: string): string[];viewerFor(auth: RequestAuth): Viewer;+ /** A room's unread mark as this person has read it (a Team Cloud); the room as it is anywhere else. */+ groupFor?(auth: RequestAuth, group: WireGroup): WireGroup;visibleTo(viewer: Viewer): VisibleSet;/** A Team Cloud: gives a member their own MausBot once, before their first list of bots. */memberDefaultBot?(email: string): unknown;+ /** Who uploaded each file: only its uploader discards it, and only while nothing uses it. */+ uploads: { note(auth: RequestAuth, name: string): void; owns(auth: RequestAuth, name: string): boolean };+ attachmentInUse(name: string): boolean;}export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {@@ -90,7 +99,8 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {botQueuedMessages: visible.everything ? queued : Object.fromEntries(Object.entries(queued).filter(([threadId]) => visible.thread(threadId))),sections: visible.sections(store.sections),groups: store.groups.filter((g) => visible.group(g.id)).map((g) => {- const room = { ...publicGroupState(g), ...messagePage(g.threadId, limit) };+ const group = publicGroupState(g);+ const room = { ...(deps.groupFor?.(auth, group) ?? group), ...messagePage(g.threadId, limit) };return visible.everything || !visible.member ? room : memberGroup(room);}),computerControl: Object.fromEntries(@@ -316,6 +326,7 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {});req.on("error", (e) => fail(400, e instanceof Error ? e.message : String(e)));});+ deps.uploads.note(auth, basename(saved.path));return json(res, 201, saved);}@@ -352,6 +363,7 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {// Returning must not destroy the socket: the caller still sends the 4xx when the byte count crosses the limit.const chunks = req.iterator({ destroyOnReturn: false }) as AsyncIterable<Buffer>;const saved = await saveFile(chunks, name, rawType ?? "", { uploadId, expectedBytes: declaredLength });+ deps.uploads.note(auth, basename(saved.path));return json(res, 201, saved);} catch (error) {req.resume();@@ -361,6 +373,13 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {// Name-locked to the attachments dir: readAttachment refuses anything but a bare generated filename.m = path.match(/^\/api\/attachments\/([\w.-]+)$/);+ if (m && method === "DELETE") {+ const name = m[1]!;+ if (!UPLOADED_NAME.test(name) || !deps.uploads.owns(auth, name)) return json(res, 404, { error: "no such attachment" });+ if (deps.attachmentInUse(name)) return json(res, 409, { error: "This file is already in a message, so it stays." });+ deleteAttachment(join(ATTACHMENTS_DIR, name));+ return json(res, 200, { ok: true });+ }if (m && method === "GET") {const attachment = readAttachment(m[1]!);if (!attachment) return json(res, 404, { error: "no such attachment" });diff --git a/server/sessions.test.ts b/server/sessions.test.tsindex 8cf4085fd0..13b40f56e2 100644--- a/server/sessions.test.ts+++ b/server/sessions.test.ts@@ -653,6 +653,22 @@ describe("a member's own phone on a Team Cloud", () => {expect(registry.authenticate(phone.token), "no check within the hour: removed from the team, the phone signs out").toBeNull();});+ it("ends every session of a removed member, one stored without a role too; a role change ends only the other roles", () => {+ const desktop = fromAdmin();+ registry.close();+ const stored = JSON.parse(readFileSync(file(), "utf8"));+ for (const session of stored.sessions) delete session.teamRole;+ writeFileSync(file(), JSON.stringify(stored));+ registry = new SessionRegistry({ file: file(), now: () => clock });+ expect(registry.revokeMember(ADA.email)).toBe(1);+ expect(registry.list().map((session) => session.id)).not.toContain(desktop.id);+ const member = fromAdmin();+ const admin = fromAdmin({ ...ADA, role: "admin" });+ expect(registry.revokeMember(ADA.email, "admin")).toBe(1);+ expect(registry.list().map((session) => session.id)).toEqual(expect.arrayContaining([admin.id]));+ expect(registry.list().map((session) => session.id)).not.toContain(member.id);+ });+it("never stretches a session the Admin opened itself", () => {const desktop = fromAdmin();clock += 30 * 60_000;diff --git a/server/sessions.ts b/server/sessions.tsindex 06b098cc88..6d5c288464 100644--- a/server/sessions.ts+++ b/server/sessions.ts@@ -590,11 +590,12 @@ export class SessionRegistry {}/** A person who left a Team Cloud: every session of theirs (app windows, phones) ends now, and no open code of theirs- * can open another. Returns how many sessions ended. */- revokeMember(email: string): number {+ * can open another. With `keepRole` (the Admin vouched for them at that role), only those at another role end. Returns+ * how many sessions ended. */+ revokeMember(email: string, keepRole?: TeamRole): number {const address = email.trim().toLowerCase();- this.pairings = this.pairings.filter((pairing) => pairing.member?.email.toLowerCase() !== address);- const ended = this.sessions.filter((session) => session.membershipAuthority === "team" && session.email?.toLowerCase() === address);+ this.pairings = this.pairings.filter((pairing) => pairing.member?.email.toLowerCase() !== address || pairing.member.role === keepRole);+ const ended = this.sessions.filter((session) => session.membershipAuthority === "team" && session.email?.toLowerCase() === address && (keepRole === undefined || session.teamRole !== keepRole));for (const session of ended) this.revoke(session.id);return ended.length;}diff --git a/src/App.tsx b/src/App.tsxindex 33a9b98526..447f030063 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -29,6 +29,7 @@ import { useNotificationFeed } from "@/lib/notification-preferences";import { UpdateBanner } from "@/components/UpdateBanner";import { AppNotices } from "@/components/AppNotices";import { CloudAsleepStrip } from "@/components/CloudAsleepStrip";+import { LiveConnectionStrip } from "@/components/LiveConnectionStrip";import { CloudSendStrip } from "@/components/CloudSendStrip";import { HomeLine } from "@/components/HomeLine";import { useTeamChats } from "@/state/team-chats";@@ -64,6 +65,8 @@ import { ChatNotice } from "@/components/ChatErrorBanner";import { loadingLine } from "@/lib/app-loading";import { useAiSwitchKeeper } from "@/lib/ai-switch";import { useChiefStepOpen } from "@/lib/default-bot";+import { SESSION_ENDED_REASON, useSessionEnded } from "@/lib/session-ended";+import { PairPage } from "./pair/PairPage";import { WebPanelPage } from "@/components/WebPanelPage";function Shell({ viewer }: { viewer: WelcomeViewer | null }) {@@ -303,6 +306,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {<div className="flex h-full flex-col"><UpdateBanner sidebarIndicator={!calendarFocus && (sidebarInline || drawerOpen)} /><CloudAsleepStrip />+ <LiveConnectionStrip connected={state.connected} hydrated={state.hydrated === true} /><CloudSendStrip cloudHome={state.config?.cloudHome === true} /><HomeLine /><AppNotices quiet={paletteOpen || drawerOpen || Boolean(localVmWorkspaceBotId)} viewer={viewer} />@@ -454,5 +458,7 @@ function Application() {}export default function App() {+ const ended = useSessionEnded();+ if (ended) return <PairPage initialCode={null} reason={SESSION_ENDED_REASON} />;return <WorkspaceBackupRecovery><Application /></WorkspaceBackupRecovery>;}diff --git a/src/components/AboutMeSettings.test.ts b/src/components/AboutMeSettings.test.tsnew file mode 100644index 0000000000..6e706dc25e--- /dev/null+++ b/src/components/AboutMeSettings.test.ts@@ -0,0 +1,61 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++import type { ConfigStatus } from "@/state/store";++const fixture = vi.hoisted(() => ({ config: null as Partial<ConfigStatus> | null, dispatch: vi.fn(), api: vi.fn() }));+vi.mock("@/state/store", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/state/store")>()),+ api: fixture.api,+ useStore: () => ({ state: { config: fixture.config }, dispatch: fixture.dispatch }),+}));+vi.mock("@/lib/own-profile", () => ({ saveTeamProfile: (patch: unknown) => fixture.api("/api/me", { method: "PUT", body: JSON.stringify(patch) }) }));++const { AboutMeSettings } = await import("./AboutMeSettings");++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+let host: HTMLDivElement;+let root: Root;++beforeEach(() => {+ fixture.dispatch = vi.fn();+ fixture.api.mockReset();+ fixture.api.mockImplementation(async (path: string) => path === "/api/profile/learned" ? { learned: [] } : { aboutMe: "Likes durian" });+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => {+ act(() => root.unmount());+ host.remove();+});++const type = async (text: string) => {+ const area = host.querySelector("textarea")!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(area, text);+ area.dispatchEvent(new Event("input", { bubbles: true }));+ });+ await act(async () => { area.dispatchEvent(new FocusEvent("focusout", { bubbles: true })); });+};++it("saves a Team Cloud person's About me to their own profile, also when Settings opened before the config arrived", async () => {+ fixture.config = null;+ await act(async () => root.render(createElement(AboutMeSettings)));+ fixture.config = { profile: { name: "Ada", email: "[email protected]", aboutMe: "" }, team: { id: "t1", name: "Acme" } };+ await act(async () => root.render(createElement(AboutMeSettings)));+ await type("Likes durian");+ const puts = fixture.api.mock.calls.filter(([, init]) => (init as RequestInit | undefined)?.method === "PUT").map(([path]) => path);+ expect(puts).toEqual(["/api/me"]);+});++it("saves the server's one profile with /api/config off a team", async () => {+ fixture.config = { profile: { name: "Ada", email: "", aboutMe: "" } };+ fixture.api.mockImplementation(async (path: string) => path === "/api/profile/learned" ? { learned: [] } : { profile: { aboutMe: "Likes durian" } });+ await act(async () => root.render(createElement(AboutMeSettings)));+ await type("Likes durian");+ const puts = fixture.api.mock.calls.filter(([, init]) => (init as RequestInit | undefined)?.method === "PUT").map(([path]) => path);+ expect(puts).toEqual(["/api/config"]);+});diff --git a/src/components/AdminOnly.tsx b/src/components/AdminOnly.tsxnew file mode 100644index 0000000000..82e1253083--- /dev/null+++ b/src/components/AdminOnly.tsx@@ -0,0 +1,11 @@+import type { ReactNode } from "react";++import { t } from "@/lib/i18n";+import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";+import type { LocaleKey } from "@/locales";++/** What only an admin may use: anyone else reads why instead of controls the server would refuse. */+export function AdminOnly({ children, note = "settings.adminOnly.change" }: { children: ReactNode; note?: LocaleKey }) {+ if (useOwnerOrAdmin() === false) return <p data-admin-only className="text-[13px] text-ink-secondary">{t(note)}</p>;+ return children;+}diff --git a/src/components/ApprovalCard.team-memory.test.ts b/src/components/ApprovalCard.team-memory.test.tsnew file mode 100644index 0000000000..349f3c8e9e--- /dev/null+++ b/src/components/ApprovalCard.team-memory.test.ts@@ -0,0 +1,33 @@+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { beforeEach, expect, it, vi } from "vitest";++import type { Message } from "@/state/store";++const fixture = vi.hoisted(() => ({ admin: false as boolean | null }));+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => fixture.admin }));++const { ApprovalCard } = await import("./ApprovalCard");++const saved: Message = {+ id: "applied-card", role: "bot", kind: "options", at: 1,+ card: {+ title: "Remember", subtitle: "Person: Ada Lovelace — Runs the payroll review.", options: [], answered: "allow", dismissed: true,+ autoApplied: true, requestId: "memory-request", tool: "propose_team_memory",+ teamMemoryRequest: { section: "", entryId: "e", kind: "person", revision: "v1" },+ },+};+const render = () => renderToStaticMarkup(createElement(ApprovalCard, { bot: { name: "Luna" }, message: saved, threadId: "thread-1" }));++beforeEach(() => { fixture.admin = false; });++it("offers no Undo on a department memory notice to a session that may not review team memory", () => {+ const html = render();+ expect(html).toContain("Luna saved to department memory: Person: Ada Lovelace");+ expect(html).not.toContain(">Undo<");+});++it("keeps Undo for an admin", () => {+ fixture.admin = true;+ expect(render()).toContain(">Undo<");+});diff --git a/src/components/ApprovalCard.tsx b/src/components/ApprovalCard.tsxindex bc68476e92..ff3e727e66 100644--- a/src/components/ApprovalCard.tsx+++ b/src/components/ApprovalCard.tsx@@ -13,6 +13,7 @@ import { PROFILE_REQUEST_FIELDS, type ProfileRequestField } from "../../shared/pimport type { RoutineRequestSchedule } from "../../shared/routine-request";import type { SkillShareRecord } from "../../shared/skill-request";import { cardAutomation } from "@/lib/automations";+import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";import { yourComputerAsk } from "@/lib/your-computer";import { TriggerCard } from "./TriggerCard";import { CardHint } from "./CardHint";@@ -215,6 +216,8 @@ function AppliedChangeLine({// Kept until the card's own patch arrives, so the Share button cannot come back in between.const [sharedNow, setSharedNow] = useState<{ requestId: string; shared: SkillShareRecord }>();const config = useContext(StoreContext)?.state.config ?? null;+ const reviewsTeamMemory = useOwnerOrAdmin() !== false;+ const canUndo = summary.canUndo && (!card.teamMemoryRequest || reviewsTeamMemory);const undone = card.undone === true;const cancels = summary.cancels === true;const skill = card.skillRequest;@@ -261,7 +264,7 @@ function AppliedChangeLine({)}{undone && !cancels && <span> · {t("approval.applied.undone")}</span>}</span>- {!undone && summary.canUndo && threadId && (+ {!undone && canUndo && threadId && (<buttontype="button"onClick={undo}diff --git a/src/components/AppsSection.tsx b/src/components/AppsSection.tsxnew file mode 100644index 0000000000..71a7743522--- /dev/null+++ b/src/components/AppsSection.tsx@@ -0,0 +1,31 @@+// One section of the Apps page (PluginsPanel.tsx): its title, a note beside it, View all, and its apps in a grid.+export function AppsSection({ id, title, note, viewAll, after, children }: {+ id: string;+ title: string;+ note?: string;+ viewAll?: { label: string; onClick: () => void };+ after?: React.ReactNode;+ children: React.ReactNode;+}) {+ return (+ <section aria-labelledby={id} data-apps-section={id}>+ <div className="mb-1.5 flex min-h-7 items-center justify-between gap-3 px-2">+ <h3 id={id} className="min-w-0 truncate text-[14px] font-semibold leading-5 text-ink">+ {title}+ {note && <span className="ms-2 text-[12px] font-normal text-ink-secondary">{note}</span>}+ </h3>+ {viewAll && (+ <button+ type="button"+ onClick={viewAll.onClick}+ className="shrink-0 rounded-full px-2 text-[13px] font-medium leading-5 text-ink-secondary transition-colors hover:text-ink"+ >+ {viewAll.label}+ </button>+ )}+ </div>+ <div className="grid grid-cols-1 items-start gap-x-6 gap-y-1 @xl:grid-cols-2">{children}</div>+ {after}+ </section>+ );+}diff --git a/src/components/BotContextMenu.member.test.ts b/src/components/BotContextMenu.member.test.tsnew file mode 100644index 0000000000..3aa4076163--- /dev/null+++ b/src/components/BotContextMenu.member.test.ts@@ -0,0 +1,61 @@+import { createElement, type ReactNode } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Bot } from "@/state/store";++const fixture = vi.hoisted(() => ({ advanced: true, admin: false as boolean | null }));+vi.mock("react", async (importOriginal) => ({ ...await importOriginal<typeof import("react")>(), useLayoutEffect: () => {} }));+vi.mock("react-dom", async (importOriginal) => ({ ...await importOriginal<typeof import("react-dom")>(), createPortal: (node: ReactNode) => node }));+vi.mock("./DesktopCapabilities", () => ({ useDesktopCapabilities: () => ({}) }));+vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => true }));+vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => fixture.advanced }));+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => fixture.admin }));+vi.mock("@/state/store", async (importOriginal) => {+ const original = await importOriginal<typeof import("@/state/store")>();+ return { ...original, useStore: () => ({ state: { ...original.initialState, bots: [chief, scout] }, dispatch: vi.fn() }) };+});++const { BotContextMenu } = await import("./Sidebar");+const base = { threadId: "thread", title: "", description: "", notifications: true, color: "green", unread: false, messages: [], modelSelection: { instanceId: "test", model: "test" } } as const;+const scout = { ...base, id: "scout", name: "Scout", tasks: [{ threadId: "thread", title: "a" }, { threadId: "t2", title: "b" }] } as unknown as Bot;+const chief = { ...base, id: "luna", name: "Luna", chiefOfStaff: true } as unknown as Bot;++beforeEach(() => {+ fixture.advanced = true;+ fixture.admin = false;+ vi.stubGlobal("document", { body: {} });+ vi.stubGlobal("window", { innerWidth: 1_000, innerHeight: 800, addEventListener: () => {}, removeEventListener: () => {} });+});+afterEach(() => vi.unstubAllGlobals());++const render = (bot: Bot) => renderToStaticMarkup(createElement(BotContextMenu, {+ menu: { botId: bot.id, x: 10, y: 10 }, onClose: vi.fn(), onArchive: vi.fn(), onDelete: vi.fn(),+ onMoveToSection: vi.fn(), onNewFolder: vi.fn(), onNewTaskFolder: vi.fn(),+}));++describe("a team bot's actions for a session without the admin scope", () => {+ it("offers nothing it would refuse and says why the crown is greyed", () => {+ const html = render(scout);+ for (const refused of [">Archive</button>", ">Delete</button>", "Duplicate", "Move to department", "Delete all threads"]) expect(html).not.toContain(refused);+ expect(html).toContain('title="Only an admin of this installation can choose the Chief of Staff."');+ expect(html).not.toContain("Choose Claude or an ACP model provider first");+ });++ it("does not offer to remove a Chief of Staff", () => {+ const html = render(chief);+ expect(html).toMatch(/<button[^>]*disabled=""[^>]*title="Only an admin of this installation can choose the Chief of Staff\."[^>]*>.*Remove Chief of Staff/);+ });++ it("leaves Archive, Delete and Move to department out of the simple menu", () => {+ fixture.advanced = false;+ const html = render(scout);+ for (const refused of [">Archive</button>", ">Delete</button>", "Move to department"]) expect(html).not.toContain(refused);+ });++ it("keeps every action for an admin", () => {+ fixture.admin = true;+ const html = render(scout);+ for (const offered of [">Archive</button>", ">Delete</button>", "Duplicate"]) expect(html).toContain(offered);+ expect(html).toContain("Choose Claude or an ACP model provider first");+ });+});diff --git a/src/components/BotPickerList.team.test.ts b/src/components/BotPickerList.team.test.tsnew file mode 100644index 0000000000..d72a20459a--- /dev/null+++ b/src/components/BotPickerList.team.test.ts@@ -0,0 +1,31 @@+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { afterEach, expect, it } from "vitest";++import type { Bot } from "@/state/store";+import { setTeamPeople, teamBotName } from "@/state/team-people";+import { BotPickerList } from "./BotPickerList";++const helper = (id: string, person: string) => ({ id, threadId: `t-${id}`, name: "MausBot", title: "", description: "", notifications: true, color: "green", unread: false,+ messages: [], modelSelection: { instanceId: "x", model: "x" }, defaultBot: { person } }) as unknown as Bot;+const bots = [helper("mine", "[email protected]"), helper("ada", "[email protected]"), helper("ben", "[email protected]")];+const olive = { email: "[email protected]", name: "Olive", role: "owner", you: true as const };+const team = { people: [olive, { email: "[email protected]", name: "Ada", role: "member" }, { email: "[email protected]", name: "Ben", role: "admin" }], me: olive, admin: true, needsYou: [] };++afterEach(() => setTeamPeople(null));++it("names each teammate's MausBot for its person in a picker, and the viewer's own as it is", () => {+ setTeamPeople(team);+ const html = renderToStaticMarkup(createElement(BotPickerList, { bots, picked: new Set<string>(), onToggle: () => {}, emptyHint: "" }));+ expect(html.match(/role="checkbox" aria-label="[^"]*"/g)?.map((match) => match.slice(match.indexOf("aria-label")))).toEqual(['aria-label="MausBot"', 'aria-label="MausBot · Ada"', 'aria-label="MausBot · Ben"']);+});++it("names a MausBot whose person is not in the list by their address", () => {+ expect(teamBotName(helper("x", "[email protected]"), team)).toBe("MausBot · Dan Smith");+ expect(teamBotName({ name: "Scout" }, team)).toBe("Scout");+});++it("leaves names alone off a team", () => {+ const html = renderToStaticMarkup(createElement(BotPickerList, { bots, picked: new Set<string>(), onToggle: () => {}, emptyHint: "" }));+ expect(html).not.toContain("·");+});diff --git a/src/components/BotPickerList.tsx b/src/components/BotPickerList.tsxindex b1d6569a32..a45bcb3666 100644--- a/src/components/BotPickerList.tsx+++ b/src/components/BotPickerList.tsx@@ -1,5 +1,6 @@import { Check } from "lucide-react";import type { Bot } from "@/state/store";+import { teamBotName, useTeamPeople } from "@/state/team-people";import { BotAvatar } from "./Avatar";import { cn } from "@/lib/cn";@@ -14,6 +15,7 @@ export function BotPickerList({onToggle: (id: string) => void;emptyHint: string;}) {+ const team = useTeamPeople();return (<div className="flex max-h-64 flex-col gap-0.5 overflow-y-auto">{bots.length === 0 && <div className="px-2 py-4 text-center text-[13px] text-ink-secondary">{emptyHint}</div>}@@ -22,12 +24,12 @@ export function BotPickerList({key={b.id}onClick={() => onToggle(b.id)}role="checkbox"- aria-label={b.name}+ aria-label={teamBotName(b, team)}aria-checked={picked.has(b.id)}className="flex items-center gap-2.5 rounded-lg px-2 py-1.5 text-left hover:bg-raised/50"><BotAvatar bot={b} state="happy" size={28} animated={false} />- <span className="min-w-0 flex-1 truncate text-[14px] text-ink">{b.name}</span>+ <span className="min-w-0 flex-1 truncate text-[14px] text-ink">{teamBotName(b, team)}</span><spanclassName={cn("flex size-[18px] shrink-0 items-center justify-center rounded-full border",diff --git a/src/components/BotSettingsDialog.simple.test.ts b/src/components/BotSettingsDialog.simple.test.tsindex ee96b6bca5..b61556879f 100644--- a/src/components/BotSettingsDialog.simple.test.ts+++ b/src/components/BotSettingsDialog.simple.test.ts@@ -36,7 +36,7 @@ const fixture = vi.hoisted(() => {refresh: (() => Promise.resolve()) as () => Promise<void>,putAssignments: (() => Promise.resolve()) as (name: string, remove?: boolean) => Promise<void>,},- memory: { doc: null as MemoryDoc | null, error: false, setDoc: (() => {}) as (doc: MemoryDoc) => void, reload: () => Promise.resolve() },+ memory: { docs: null as MemoryDoc[] | null, error: false, mine: false, setDoc: (() => {}) as (doc: MemoryDoc) => void, reload: () => Promise.resolve() },saveMemory: (() => Promise.resolve({ ok: true })) as (...args: unknown[]) => Promise<unknown>,openExternal: (() => Promise.resolve()) as (url: string) => Promise<void>,derived: {} as Record<string, unknown>,@@ -251,7 +251,7 @@ beforeEach(() => {skills: [], loading: false, working: "", error: "", reviewing: null, toggle: vi.fn(() => Promise.resolve()),setWorking: vi.fn(), setError: vi.fn(), refresh: vi.fn(() => Promise.resolve()), putAssignments: vi.fn(() => Promise.resolve()),};- fixture.memory = { doc: null, error: false, setDoc: vi.fn(), reload: vi.fn(() => Promise.resolve()) };+ fixture.memory = { docs: null, error: false, mine: false, setDoc: vi.fn(), reload: vi.fn(() => Promise.resolve()) };patch.mockReset();onOpen.mockReset();onClose.mockReset();@@ -788,14 +788,14 @@ describe("the Library tab", () => {it("values What it remembers by the notes in MEMORY.md, says Off when memory is off, and opens the memory page", () => {expect(rowValue(library(makeBot()), "memory")).toBeUndefined();- fixture.memory.doc = memoryDoc("# Notes\n- Likes short replies\n- Uses Resolve\n- Works nights\n");+ fixture.memory.docs = [memoryDoc("# Notes\n- Likes short replies\n- Uses Resolve\n- Works nights\n")];const rendered = library(makeBot());expect(rowValue(rendered, "memory")).toBe("3 notes");click(find(rendered, "data-panel-page", "memory"));expect(onOpen).toHaveBeenLastCalledWith("memory");- fixture.memory.doc = memoryDoc("- One thing\n");+ fixture.memory.docs = [memoryDoc("- One thing\n")];expect(rowValue(library(makeBot()), "memory")).toBe("1 note");- fixture.memory.doc = memoryDoc("# Empty\n");+ fixture.memory.docs = [memoryDoc("# Empty\n")];expect(rowValue(library(makeBot()), "memory")).toBe("Nothing yet");expect(rowValue(library(makeBot({ memoryEnabled: false })), "memory")).toBe("Off");});@@ -1016,7 +1016,7 @@ describe("the drill-in pages", () => {});it("lists what MEMORY.md remembers, forgets one line through the memory file route, and adds one", async () => {- fixture.memory.doc = memoryDoc("# Notes\n- Likes short replies\n\n- Uses Resolve Studio\n");+ fixture.memory.docs = [memoryDoc("# Notes\n- Likes short replies\n\n- Uses Resolve Studio\n")];const rendered = body("memory");expect(rendered.html).toContain("Likes short replies");expect(rendered.html).toContain("Uses Resolve Studio");@@ -1025,25 +1025,25 @@ describe("the drill-in pages", () => {for (const text of ["Tidy now", "Upkeep", "Obsidian", "Daily logs", "Journal"]) expect(rendered.html).not.toContain(text);click(rendered.nodes.filter((node) => node.props.label === "Forget")[0]!);await Promise.resolve();- expect(fixture.saveMemory).toHaveBeenLastCalledWith("scout", "MEMORY.md", "# Notes\n\n- Uses Resolve Studio\n", "h1");+ expect(fixture.saveMemory).toHaveBeenLastCalledWith("scout", "MEMORY.md", "# Notes\n\n- Uses Resolve Studio\n", "h1", false);await Promise.resolve();expect(fixture.memory.setDoc).toHaveBeenLastCalledWith(expect.objectContaining({ text: "# Notes\n\n- Uses Resolve Studio\n", hash: "h2" }));(find(body("memory"), "data-panel-form", "memory-add").props.onChange as (value: string) => void)(" Prefers the free version ");(find(body("memory"), "data-panel-form", "memory-add").props.onSubmit as () => void)();await Promise.resolve();- expect(fixture.saveMemory).toHaveBeenLastCalledWith("scout", "MEMORY.md", "# Notes\n- Likes short replies\n\n- Uses Resolve Studio\n- Prefers the free version\n", "h1");+ expect(fixture.saveMemory).toHaveBeenLastCalledWith("scout", "MEMORY.md", "# Notes\n- Likes short replies\n\n- Uses Resolve Studio\n- Prefers the free version\n", "h1", false);});it("says when memory is off, empty or unreadable, and re-reads on a conflict", async () => {expect(body("memory", makeBot({ memoryEnabled: false })).html).toContain("Memory is off for Scout.");expect(has(body("memory", makeBot({ memoryEnabled: false })), "data-panel-form", "memory-add")).toBe(false);- fixture.memory.doc = memoryDoc("");+ fixture.memory.docs = [memoryDoc("")];expect(body("memory").html).toContain("Nothing remembered yet.");- fixture.memory = { ...fixture.memory, doc: null, error: true };+ fixture.memory = { ...fixture.memory, docs: null, error: true };expect(body("memory").html).toContain("Couldn't read the memory file just now.");- fixture.memory = { ...fixture.memory, doc: memoryDoc("- Old\n"), error: false };+ fixture.memory = { ...fixture.memory, docs: [memoryDoc("- Old\n")], error: false };fixture.saveMemory = vi.fn(() => Promise.resolve({ ok: false, conflict: true, current: "- New\n", currentHash: "h3" }));click(find(body("memory"), "label", "Forget"));await Promise.resolve();diff --git a/src/components/ChatHeadPill.tsx b/src/components/ChatHeadPill.tsxindex 6242c6aa94..4ea67bf262 100644--- a/src/components/ChatHeadPill.tsx+++ b/src/components/ChatHeadPill.tsx@@ -1,4 +1,4 @@-import { ChevronRight, Lock, Users } from "lucide-react";+import { ChevronRight, Lock, UserRound, Users } from "lucide-react";import type { ComponentProps } from "react";import { cn } from "@/lib/cn";@@ -14,7 +14,18 @@ import { BOT_PANEL_ID } from "./bot-panel/side-panel";const UNTITLED = "New thread";const CHEVRON_MOTION = "duration-[140ms] ease-[cubic-bezier(.22,1,.36,1)]";-export type ChatHeadPrivacy = { kind: "private" } | { kind: "shared"; team: string } | null;+export type ChatHeadPrivacy = { kind: "private" } | { kind: "ownHelper" } | { kind: "shared"; team: string } | null;++const PRIVACY_ICONS = { private: Lock, ownHelper: UserRound, shared: Users } as const;++function privacyLabelOf(privacy: ChatHeadPrivacy): string | null {+ switch (privacy?.kind) {+ case "private": return t("team.privateHeader");+ case "ownHelper": return t("team.ownHelperHeader");+ case "shared": return t("team.sharedHeader", { team: privacy.team });+ default: return null;+ }+}/** Simple mode's whole chat header: the bot's face and name in one pill, which opens and closes the bot panel. Away from* the bot's main conversation it also names the one on screen. A dot says another of the bot's conversations needs a@@ -28,9 +39,8 @@ export function ChatHeadPill({ bot, avatar, privacy, onToggle }: {const { state } = useStore();const open = state.settingsOpen;const elsewhere = sidebarBotActivityTasks(bot, state.pendingQueued).filter((task) => task.threadId !== bot.threadId).length;- const privacyLabel = privacy?.kind === "private" ? t("team.privateHeader")- : privacy?.kind === "shared" ? t("team.sharedHeader", { team: privacy.team }) : null;- const PrivacyIcon = privacy?.kind === "private" ? Lock : Users;+ const privacyLabel = privacyLabelOf(privacy);+ const PrivacyIcon = privacy ? PRIVACY_ICONS[privacy.kind] : Users;const title = bot.tasks?.find((task) => task.threadId === bot.threadId)?.title;// Simple mode calls an untitled conversation what it is, never a "thread".const conversation = !awayFromMainThread(bot, false) ? nulldiff --git a/src/components/ChatMarkdown.test.ts b/src/components/ChatMarkdown.test.tsindex c48a4ec998..890f489b17 100644--- a/src/components/ChatMarkdown.test.ts+++ b/src/components/ChatMarkdown.test.ts@@ -59,6 +59,15 @@ vi.mock("shiki/engine/javascript", () => ({createJavaScriptRegexEngine: () => ({}),}));+describe("soft line breaks", () => {+ it("keeps a reply's single line breaks as line breaks, outside code", () => {+ const html = renderToStaticMarkup(createElement(ChatMarkdown, { text: "1\n2\n3\n\n`a`\nb\n\n```\nx\ny\n```" }));+ expect(html).toContain('<p dir="ltr">1<br/>\n2<br/>\n3</p>');+ expect(html).toMatch(/>a<\/code><br\/>\nb<\/p>/);+ expect(html).toContain(">x\ny</pre>");+ });+});+describe("mention highlighting", () => {const mentionPeers = [{ name: "Atlas" }, { name: "調査担当" }];it("carries bot colors into Markdown without coloring everyone as a bot", () => {diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsxindex fed07b8e5f..5ce193cb38 100644--- a/src/components/ChatMarkdown.tsx+++ b/src/components/ChatMarkdown.tsx@@ -91,6 +91,26 @@ const normalizationParseOptions: MarkdownParseOptions = {mdastExtensions: [...(gfmParseData.fromMarkdownExtensions ?? []), windowsPathDestinations],};+/** A single line break in a reply is a line break, as chat apps show it, not a space. */+function remarkSoftBreaks() {+ return (tree: { children?: any[] }) => {+ const visit = (node: { children?: any[] }) => {+ if (!node.children) return;+ node.children = node.children.flatMap((child) => {+ if (child?.type !== "text" || !child.value.includes("\n")) {+ visit(child);+ return [child];+ }+ return (child.value as string).split("\n").flatMap((value, index) => [+ ...(index ? [{ type: "break" }] : []),+ ...(value ? [{ type: "text", value }] : []),+ ]);+ });+ };+ visit(tree);+ };+}+function unwrapLinkedImages() {return (tree: { children?: any[] }) => {const visit = (node: { children?: any[] }) => {@@ -725,7 +745,7 @@ function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS,<MessageScopeContext.Provider value={{ message, imageOffsets, threads, currentBotId, delivered }}><div className="chat-md min-w-0 [&>*+*]:mt-2"><Markdown- remarkPlugins={[remarkGfm, remarkMath, remarkWindowsPathDestinations, unwrapLinkedImages, remarkGithubRefs, [remarkMentions, { peers: mentionPeers, everyone, person: mentionPerson }], remarkThreadRefs(threads, currentBotId)]}+ remarkPlugins={[remarkGfm, remarkMath, remarkWindowsPathDestinations, unwrapLinkedImages, remarkSoftBreaks, remarkGithubRefs, [remarkMentions, { peers: mentionPeers, everyone, person: mentionPerson }], remarkThreadRefs(threads, currentBotId)]}rehypePlugins={mathPlugin ? [mathPlugin] : []}urlTransform={chatUrlTransform}components={MARKDOWN_COMPONENTS}diff --git a/src/components/ChatView.missing-thread.test.ts b/src/components/ChatView.missing-thread.test.tsnew file mode 100644index 0000000000..19c136f41c--- /dev/null+++ b/src/components/ChatView.missing-thread.test.ts@@ -0,0 +1,65 @@+// @vitest-environment happy-dom+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import type { AppState, Bot, InstanceInfo } from "@/state/store";++vi.mock("./DesktopCapabilities", async (importOriginal) => ({+ ...await importOriginal<typeof import("./DesktopCapabilities")>(),+ useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "other" }, localComputer: { available: false } }, ready: true }),+}));+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));+vi.mock("@/lib/cloud-guest", () => ({ useCanWriteIn: () => true, useReactor: () => "user" }));+vi.mock("./ModelPicker", () => ({ ModelPicker: () => null }));++const { ChatView } = await import("./ChatView");+const { BotEditorStore, initialState, reducer } = await import("@/state/store");++let root: Root;+let container: HTMLDivElement;+beforeEach(() => {+ vi.stubGlobal("fetch", () => new Promise(() => {}));+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(() => {+ root.unmount();+ container.remove();+ vi.unstubAllGlobals();+});++const instances = [{ instanceId: "test", driverKind: "codex", displayName: "Test", snapshot: { state: "available" } } as InstanceInfo];+const draw = (state: AppState) => {+ const value = { state, dispatch: () => {}, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };+ flushSync(() => root.render(createElement(BotEditorStore, { value, children: createElement(ChatView, { bot: state.bots.find((bot) => bot.id === state.selectedId)! }) })));+};++it("opens a bot whose conversation the server did not name instead of going blank", () => {+ const scout = {+ id: "scout", name: "Scout", title: "", description: "", color: "green", notifications: true, unread: false,+ modelSelection: { instanceId: "test", model: "m" }, messages: [], tasks: [],+ } as unknown as Bot;+ expect(() => draw({ ...initialState, connected: true, selectedId: "scout", bots: [scout], instances, unreadDivider: null })).not.toThrow();+ expect(container.querySelector("[data-chathead-identity]")).not.toBeNull();+});++it("opens a bot that joined without a transcript", () => {+ const added = reducer({ ...initialState, instances }, {+ type: "botAdded",+ bot: { id: "mausbot", threadId: "own", name: "MausBot", title: "", description: "", color: "green", notifications: true, unread: false, modelSelection: { instanceId: "test", model: "m" } } as Bot,+ });+ expect(added.bots[0]!.messages).toEqual([]);+ expect(() => draw({ ...added, connected: true })).not.toThrow();+});++it("opens a member's first load when the server sent a bot without its transcript", () => {+ const hydrated = reducer({ ...initialState, instances }, {+ type: "hydrate",+ bots: [{ id: "pickle", name: "Pickle", title: "", description: "", color: "green", notifications: true, unread: false, modelSelection: { instanceId: "test", model: "m" }, tasks: [] } as unknown as Bot],+ groups: [], computerControl: {},+ } as Parameters<typeof reducer>[1]);+ expect(hydrated.bots[0]!.messages).toEqual([]);+ expect(() => draw({ ...hydrated, connected: true })).not.toThrow();+});diff --git a/src/components/ChatView.stopped.test.ts b/src/components/ChatView.stopped.test.tsnew file mode 100644index 0000000000..1014e1e561--- /dev/null+++ b/src/components/ChatView.stopped.test.ts@@ -0,0 +1,68 @@+// @vitest-environment happy-dom+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import type { AppState, Bot, InstanceInfo, Message } from "@/state/store";++vi.mock("./DesktopCapabilities", async (importOriginal) => ({+ ...await importOriginal<typeof import("./DesktopCapabilities")>(),+ useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "other" }, localComputer: { available: false } }, ready: true }),+}));+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));+vi.mock("@/lib/cloud-guest", () => ({ useCanWriteIn: () => true, useReactor: () => "user" }));+vi.mock("./ModelPicker", () => ({ ModelPicker: () => null }));++const { ChatView } = await import("./ChatView");+const { BotEditorStore, initialState } = await import("@/state/store");+const { forgetStops, sendStop } = await import("@/lib/stop-turn");+const { t } = await import("@/lib/i18n");++let root: Root;+let container: HTMLDivElement;+beforeEach(() => {+ forgetStops();+ vi.stubGlobal("fetch", () => new Promise(() => {}));+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(() => {+ root.unmount();+ container.remove();+ vi.unstubAllGlobals();+});++const instances = [{ instanceId: "test", driverKind: "codex", displayName: "Test", snapshot: { state: "available" } } as InstanceInfo];+const scout = (messages: Message[], busy: boolean): Bot => ({+ id: "scout", threadId: "t", name: "Scout", title: "", description: "", color: "green", notifications: true, unread: false,+ busy, messages, modelSelection: { instanceId: "test", model: "m" },+ tasks: [{ threadId: "t", title: "Poem", createdAt: 1, busy, activity: busy ? "working" : "idle", modelSelection: { instanceId: "test", model: "m" }, approvalMode: "ask" }],+});+const draw = (bot: Bot) => {+ const state: AppState = { ...initialState, connected: true, selectedId: bot.id, bots: [bot], instances };+ const value = { state, dispatch: () => {}, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };+ flushSync(() => root.render(createElement(BotEditorStore, { value, children: createElement(ChatView, { bot }) })));+};+const ask: Message = { id: "u1", role: "user", kind: "text", text: "Write a 250 word poem about cheese", at: Date.now() - 2_000 };++it("says the turn stopped after the person's Stop ended it before any answer", async () => {+ sendStop(async () => ({ ok: true }), { type: "interrupt", botId: "scout", threadId: "t" }, () => {});+ await Promise.resolve(); await Promise.resolve();+ draw(scout([ask], true));+ expect(container.textContent).not.toContain(t("chat.turnStoppedByYou"));+ draw(scout([ask], false));+ expect(container.textContent).toContain(t("chat.turnStoppedByYou"));+});++it("says nothing more once the server's own stopped row or an answer is there", async () => {+ sendStop(async () => ({ ok: true }), { type: "interrupt", botId: "scout", threadId: "t" }, () => {});+ await Promise.resolve(); await Promise.resolve();+ draw(scout([ask, { id: "b1", role: "bot", kind: "text", text: "Cheese, oh cheese", at: Date.now() }], false));+ expect(container.textContent).not.toContain(t("chat.turnStoppedByYou"));+});++it("says nothing for a turn nobody stopped here", () => {+ draw(scout([ask], false));+ expect(container.textContent).not.toContain(t("chat.turnStoppedByYou"));+});diff --git a/src/components/ChatView.team.test.ts b/src/components/ChatView.team.test.tsnew file mode 100644index 0000000000..7d1a6b3b8c--- /dev/null+++ b/src/components/ChatView.team.test.ts@@ -0,0 +1,67 @@+// @vitest-environment happy-dom+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import type { AppState, Bot, InstanceInfo, Message } from "@/state/store";++const viewer = vi.hoisted(() => ({ reactor: "p_ada" }));+vi.mock("./DesktopCapabilities", async (importOriginal) => ({+ ...await importOriginal<typeof import("./DesktopCapabilities")>(),+ useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "other" }, localComputer: { available: false } }, ready: true }),+}));+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));+vi.mock("@/lib/cloud-guest", () => ({ useCanWriteIn: () => true, useReactor: () => viewer.reactor }));+vi.mock("./ModelPicker", () => ({ ModelPicker: () => null }));++const { ChatView } = await import("./ChatView");+const { setColorUserBubbles } = await import("@/lib/user-bubble-preference");+const { BotEditorStore, initialState } = await import("@/state/store");+const { t } = await import("@/lib/i18n");++let root: Root;+let container: HTMLDivElement;+beforeEach(() => {+ vi.stubGlobal("fetch", () => new Promise(() => {}));+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(() => {+ root.unmount();+ container.remove();+ vi.unstubAllGlobals();+});++const instances = [{ instanceId: "test", driverKind: "codex", displayName: "Test", snapshot: { state: "available" } } as InstanceInfo];+const team = { id: "team-acme", name: "Acme" };+const line = (id: string, sender: { name: string; id: string }, text: string): Message => ({ id, role: "user", kind: "text", at: 1, text, sender });+const luna = (messages: Message[], extra: Partial<Bot> = {}): Bot => ({+ id: "luna", threadId: "main", name: "Luna", title: "", description: "", color: "green", notifications: true, unread: false,+ busy: false, messages, modelSelection: { instanceId: "test", model: "m" },+ tasks: [{ threadId: "main", title: "Main", createdAt: 1, busy: false, activity: "idle", modelSelection: { instanceId: "test", model: "m" }, approvalMode: "ask" }],+ ...extra,+});+const draw = (bot: Bot) => {+ const state: AppState = { ...initialState, connected: true, selectedId: bot.id, bots: [bot], instances, config: { team } as AppState["config"] };+ const value = { state, dispatch: () => {}, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };+ flushSync(() => root.render(createElement(BotEditorStore, { value, children: createElement(ChatView, { bot }) })));+};+const row = (text: string) => [...container.querySelectorAll<HTMLElement>("[data-message-row]")].find((element) => element.textContent?.includes(text))!;++it("shows a teammate's line in a shared chat as theirs, with their name, and only the viewer's own in their bubble", () => {+ setColorUserBubbles(true);+ draw(luna([line("o1", { name: "Olive", id: "p_olive" }, "plant is memory-Fernando"), line("a1", { name: "Ada", id: "p_ada" }, "noted")]));+ const olive = row("plant is memory-Fernando");+ expect(olive.textContent).toContain("Olive");+ expect(olive.querySelector("[data-chat-bubble]")!.className).not.toContain("user-bubble-colored");+ const own = row("noted");+ expect(own.textContent).not.toContain("Ada");+ expect(own.querySelector("[data-chat-bubble]")!.className).toContain("user-bubble-colored");+});++it("says a member's own MausBot is theirs, not everyone's", () => {+ draw(luna([], { defaultBot: { person: "[email protected]" } } as Partial<Bot>));+ expect(container.textContent).not.toContain(t("team.sharedHeader", { team: "Acme" }));+ expect(container.textContent).toContain(t("team.ownHelperHeader"));+});diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex b4e59df78b..dcd7824691 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -47,7 +47,8 @@ import { isPureLeakedSystemHarnessMessage, stripLeakedSystemHarnessMessages } frimport { ConversationalReply, QuickModelNote, isConversational, useReplySegments, useThreadOpenedAt } from "./ConversationalReply";import type { LocaleKey } from "@/locales";import { isProviderSafetyBlock, PROVIDER_SAFETY_GUIDANCE, PROVIDER_SAFETY_HELP_URL } from "../../shared/provider-safety";-import { isCancelledTranscriptRow } from "../../shared/client-cancel";+import { isCancelledTranscriptRow, PERSON_STOPPED_TURN_NAME } from "../../shared/client-cancel";+import { stopNoticeDue, useStoppedAt } from "@/lib/stop-turn";import { THIS_COMPUTER_NOT_READY } from "../../shared/your-computer";import { BotAvatar } from "./Avatar";import { TurnPresence } from "./TurnPresence";@@ -93,7 +94,7 @@ import { RenameTitle } from "./RenameTitle"; import { ChatHeadRole, chiefOfStaffimport { BotActivityPicker } from "./TaskPicker"; import { ChatHeadPill } from "./ChatHeadPill";import { ELEVATED_FLOAT, ELEVATED_HOVER } from "./elevated";import { ModelPicker } from "./ModelPicker";-import { ChatHeaderMenu, ChatMoreMenu } from "./ChatMoreMenu"; import { TeamPrivateFirstLine, TeamPrivateHeader, TeamSharedHeader } from "./TeamPrivateChatsLine";+import { ChatHeaderMenu, ChatMoreMenu } from "./ChatMoreMenu"; import { TeamOwnHelperHeader, TeamPrivateFirstLine, TeamPrivateHeader, TeamSharedHeader } from "./TeamPrivateChatsLine";import { useChatFindRequests } from "@/lib/chat-find";import { CitationSelectionToolbar, SentCitations } from "./CitationUI";import { SpeakButton } from "./SpeakButton";@@ -120,7 +121,7 @@ import { useUnreadDivider } from "@/hooks/use-unread-divider";import { NewMessagesDivider } from "./NewMessagesDivider";import { unreadMessageIds } from "@/lib/unread-divider";import { appendComposerDraft, appendDraftAttachments, useReplyDraft } from "@/lib/drafts";-import { dayLabel, localDay, transcriptLookups, type TranscriptLookups } from "@/lib/transcript-derivations";+import { localDay, transcriptLookups, type TranscriptLookups } from "@/lib/transcript-derivations"; import { DaySeparator } from "./DaySeparator";import { splitTranscriptCitations, type CitationAttachment } from "@/lib/citations";import { EmptyChat } from "./ChatEmptyState";import { PinnedBanner } from "./ChatPinnedBanner";@@ -172,14 +173,6 @@ function useDrawnBots(bots: readonly Bot[]): readonly Bot[] {return cache.current.bots;}-function DaySeparator({ at, today, simple = false }: { at: number; today: number; simple?: boolean }) {- return (- <div className={cn("text-center text-[13px] text-ink-secondary", simple ? "pt-5 pb-1 leading-[18px]" : "py-3")}>- {dayLabel(at, today)} {formatTime(at)}- </div>- );-}-export function ErrorRow({message,headline: plainHeadline,@@ -358,6 +351,7 @@ const Bubble = memo(function Bubble({const peer = peerLine(message) ?? peerRequest(message, botId);const user = message.role === "user" && !peer;const speaker = user ? otherSpeaker(message, speakerViewer ?? null) : null;+ const ownBubbleStyle = speaker ? undefined : bubbleStyle;const [expanded, setExpanded] = useState(false);const focusedSearch = focus?.messageId === message.id && Boolean(focus.matchText);const [viewRaw, setViewRaw] = useState(false);@@ -452,7 +446,7 @@ const Bubble = memo(function Bubble({...(simple ? replyAndCopy(() => onReply(message), visibleText) : []),...userMessageMenu({messageId: message.id,- onEdit: message.kind === "text" && !webhookView && !hasAttachments && !busy && !message.id.startsWith("optimistic-")+ onEdit: !speaker && message.kind === "text" && !webhookView && !hasAttachments && !busy && !message.id.startsWith("optimistic-")? () => onStartEdit(message.id) : undefined,pin: remoteClient ? undefined : { pinned, onToggle: togglePin },}),@@ -473,13 +467,13 @@ const Bubble = memo(function Bubble({: attachmentsOnly || split || tabled? cn("text-ink", simple && SIMPLE_BUBBLE_TEXT): user- ? cn("whitespace-pre-wrap text-ink", simple ? SIMPLE_USER_BUBBLE : "bg-bubble-user px-4 py-2.5", bubbleStyle && "user-bubble-colored", simple && bubbleStyle && "antialiased")+ ? cn("whitespace-pre-wrap text-ink", simple ? SIMPLE_USER_BUBBLE : "bg-bubble-user px-4 py-2.5", ownBubbleStyle && "user-bubble-colored", simple && ownBubbleStyle && "antialiased"): formatted? cn(formattedReplyWidth(text), "px-1 text-ink"): simple ? SIMPLE_BOT_BUBBLE : "bg-card px-4 py-2.5 text-ink",simple && join && !split && !attachmentsOnly && !tabled && joinedCorners(user ? "end" : "start", join),)}- style={user && !webhookView && !attachmentsOnly ? bubbleStyle : undefined}+ style={user && !webhookView && !attachmentsOnly ? ownBubbleStyle : undefined}title={workedFor === undefined ? new Date(message.at).toLocaleString() : `${workedLabel(workedFor)} · ${new Date(message.at).toLocaleString()}`}>{replyTarget && (@@ -908,6 +902,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {const localVoice = localSystemVoiceActive();const locale = activeLocale();const busy = Boolean(bot.busy);+ const stoppedAt = useStoppedAt(bot.threadId);const openedAt = useThreadOpenedAt(bot.threadId);const headerAnimated = busy || (mascotMotion?.kind ?? "none") !== "none";const branch = useRef(messages);@@ -923,7 +918,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {() => ({ botId: bot.id, threadId: bot.threadId, botName: bot.name, botColor: bot.color, voiceId: bot.voice, tts, localVoice, busy, liveTools, hasMore, bots, mentionPeers, mentionPerson: { profileName: state.config?.profile?.name }, focus, showToolCalls, locale, dispatch, onBranch, bubbleStyle, conversational: isConversational(bot.replyStyle), simple: !advanced, canReact: canWrite !== false, openedAt, speakerViewer }),[bot.id, bot.threadId, bot.name, bot.color, bot.voice, tts, localVoice, busy, liveTools, hasMore, bots, mentionPeers, state.config?.profile?.name, focus, showToolCalls, locale, dispatch, onBranch, bubbleStyle, bot.replyStyle, advanced, canWrite, openedAt, speakerViewer],);- const currentTask = bot.tasks?.find((task) => task.threadId === bot.threadId), place = effectivePlace(bot, currentTask), team = state.config?.team, privateChat = Boolean(team) && currentTask?.private === true, sharedChat = Boolean(team) && !privateChat;+ const currentTask = bot.tasks?.find((task) => task.threadId === bot.threadId), place = effectivePlace(bot, currentTask), team = state.config?.team, privateChat = Boolean(team) && currentTask?.private === true, ownHelper = Boolean(team) && !privateChat && Boolean(bot.defaultBot?.person), sharedChat = Boolean(team) && !privateChat && !ownHelper;const [editingId, setEditingId] = useState<string | null>(null);useEffect(() => setEditingId(null), [bot.id, bot.threadId]);@@ -1031,7 +1026,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {<ChatHeadPillbot={bot}avatar={{ state: stateForBot({ ...bot, messages }), motion: mascotMotion?.kind ?? "none", motionKey: mascotMotion?.nonce ?? 0, animated: headerAnimated }}- privacy={privateChat ? { kind: "private" } : sharedChat && team ? { kind: "shared", team: team.name } : null}+ privacy={privateChat ? { kind: "private" } : ownHelper ? { kind: "ownHelper" } : sharedChat && team ? { kind: "shared", team: team.name } : null}onToggle={() => dispatch({ type: "toggleSettings", open: !state.settingsOpen })}/>) : advanced ? (@@ -1087,7 +1082,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {<ChevronRight size={14} aria-hidden="true" className="-ml-2.5 w-0 shrink-0 text-ink-secondary opacity-0 transition-[width,margin,opacity] duration-150 group-hover:ml-0 group-hover:w-3.5 group-hover:opacity-100 group-focus-visible:ml-0 group-focus-visible:w-3.5 group-focus-visible:opacity-100" /></button>)}- {!phone && !simpleHead && <ChatHeadRole bot={bot} />}<span role="status" className="sr-only" data-chathead-status>{bot.busy ? t("sidebar.preview.working") : ""}</span>{!simpleHead && privateChat && <TeamPrivateHeader />}{!simpleHead && sharedChat && team && <TeamSharedHeader team={team} />}+ {!phone && !simpleHead && <ChatHeadRole bot={bot} />}<span role="status" className="sr-only" data-chathead-status>{bot.busy ? t("sidebar.preview.working") : ""}</span>{!simpleHead && privateChat && <TeamPrivateHeader />}{!simpleHead && ownHelper && <TeamOwnHelperHeader />}{!simpleHead && sharedChat && team && <TeamSharedHeader team={team} />}{!simpleHead && !bot.busy && bot.waitingForTeammates && <span className="truncate text-[12px] text-ink-secondary" role="status">Teammates working</span>}{(advanced || remoteClient) && awayFromMainThread(profile, showThreads) && (<button@@ -1216,6 +1211,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {onReply={selectReply}/></ChatRowsContext.Provider>+ {stopNoticeDue(messages, stoppedAt, busy) && <CancelledTurnRow name={PERSON_STOPPED_TURN_NAME} />}{laterCount > 0 && (<div className="flex justify-center"><buttondiff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex 18d3c4c4d5..3b03b46f6d 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -1,6 +1,6 @@import { directMessageSent, roomMessageSent } from "@/lib/product-events";import { useComposerDictation } from "@/lib/use-composer-dictation";-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type SetStateAction } from "react";+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type SetStateAction } from "react";import { ArrowUp, Clock, Mic, Paperclip, Square, X } from "lucide-react";import { useStore, visibleMessages, currentTaskBot, type Bot, type Group, type InstanceInfo, type Message } from "@/state/store";import { cn } from "@/lib/cn";@@ -36,7 +36,7 @@ import { ComposerAttachments, pathForFile } from "./ComposerAttachments";import { PointedChips } from "./app/PointedChips"; import { SetupRequestChip, setupRequestPlaceholder } from "./SetupOffer";import { takePointedChips } from "@/lib/pointed-chips";import { splitTranscriptCitations, type CitationAttachment } from "@/lib/citations";-import { PlaceChip, usePlaceMenuItem } from "./PlaceChip";+import { PlaceChip } from "./PlaceChip";import { ApprovalModeSelector } from "./ApprovalModeSelector";import { approvalModeFor } from "../../shared/approval-mode";import { useOnCall } from "@/lib/call";@@ -48,6 +48,7 @@ import {clipboardImageFiles,composeMessage,dataContextFor,+ discardUnsentUpload,composerShouldRefocus,composerTakesFocusOnOpen,imageAttachmentFromFile,@@ -66,6 +67,7 @@ import { PendingApprovalActions, PendingApprovalPanel, pendingApprovals } from "import { CallButton } from "./CallView";import { GroupCallButton } from "./GroupCallView";import { ApprovalChip, ComposerPlusMenu, GoalToggle } from "./ComposerPlusMenu";+import { PhonePlus } from "./PhonePlus";import { useThreadApproval } from "./thread-approval";import { useDesktopCapabilities } from "./DesktopCapabilities";import { ComposerReplyStrip } from "./ReplyQuote";@@ -99,18 +101,6 @@ interface ComposerDraftSnapshot extends ComposerSendSnapshot {reply: Message | null;}-type PhonePlusProps = Pick<ComponentProps<typeof ComposerPlusMenu>, "onAttach" | "goal" | "teach" | "approval" | "callBotId">;--function PhonePlusWithPlace({ place, ...rest }: PhonePlusProps & { place: Parameters<typeof usePlaceMenuItem>[0] }) {- const item = usePlaceMenuItem(place);- return <ComposerPlusMenu {...rest} extraItems={[item]} circle />;-}--/** The phone composer's round +: attach, Finish together, where the bot works, approval level and call mode. */-function PhonePlus({ place, ...rest }: PhonePlusProps & { place?: Parameters<typeof usePlaceMenuItem>[0] }) {- return place ? <PhonePlusWithPlace place={place} {...rest} /> : <ComposerPlusMenu {...rest} circle />;-}-export function Composer({bot: profile,group,@@ -207,6 +197,7 @@ export function Composer({(id: string) => {const removed = attachments.find((attachment) => attachment.id === id);if (removed?.kind === "image") releaseAttachmentImagePreview(removed);+ if (removed) discardUnsentUpload(removed);editAttachments((prev) => prev.filter((attachment) => attachment.id !== id));},[attachments, editAttachments],diff --git a/src/components/DaySeparator.tsx b/src/components/DaySeparator.tsxnew file mode 100644index 0000000000..2ef3511f82--- /dev/null+++ b/src/components/DaySeparator.tsx@@ -0,0 +1,12 @@+// The day and time line between a conversation's days (ChatView.tsx).+import { cn } from "@/lib/cn";+import { dayLabel } from "@/lib/transcript-derivations";+import { formatTime } from "@/state/store";++export function DaySeparator({ at, today, simple = false }: { at: number; today: number; simple?: boolean }) {+ return (+ <div className={cn("text-center text-[13px] text-ink-secondary", simple ? "pt-5 pb-1 leading-[18px]" : "py-3")}>+ {dayLabel(at, today)} {formatTime(at)}+ </div>+ );+}diff --git a/src/components/DesktopWorkspaceSwitcher.home.test.ts b/src/components/DesktopWorkspaceSwitcher.home.test.tsindex 62c68f7e71..6103916377 100644--- a/src/components/DesktopWorkspaceSwitcher.home.test.ts+++ b/src/components/DesktopWorkspaceSwitcher.home.test.ts@@ -53,3 +53,12 @@ it("says always on only when My Cloud's verified plan never sleeps, on its pagesexpect(label(), "no plan to read").toBe("My Cloud");}});++it("in a browser on a team's Cloud names the team, never My Cloud", async () => {+ delete window.ogb;+ for (const props of [{ cloudHome: true, place: "Acme Labs" }, { cloudHome: true, inline: true, pill: true, place: "Acme Labs" }]) {+ flushSync(() => root.render(createElement(DesktopWorkspaceSwitcher, props)));+ await vi.waitFor(() => expect(host.querySelector("[data-cloud-home-indicator]")?.textContent).toContain("Acme Labs"));+ expect(host.textContent, JSON.stringify(props)).not.toContain("My Cloud");+ }+});diff --git a/src/components/DesktopWorkspaceSwitcher.tsx b/src/components/DesktopWorkspaceSwitcher.tsxindex b62708e6a4..9e5272fb88 100644--- a/src/components/DesktopWorkspaceSwitcher.tsx+++ b/src/components/DesktopWorkspaceSwitcher.tsx@@ -78,8 +78,9 @@ export function useWorkspacePlace({ cloudHome = false, howTo = false, onMenuClosreturn { bridge, current, cloudHome, open, error, onLine, waking, openMenu, switchable: Boolean(bridge) && current?.home !== true };}+/** `place`: what this Cloud is called here, a team's name on a team's Cloud; My Cloud otherwise. */type SwitcherProps = {- compact?: boolean; inline?: boolean; pill?: boolean; rail?: boolean; cloudHome?: boolean; owner?: string | null; howTo?: boolean; onMenuClosed?: () => void;+ compact?: boolean; inline?: boolean; pill?: boolean; rail?: boolean; cloudHome?: boolean; owner?: string | null; howTo?: boolean; place?: string; onMenuClosed?: () => void;};/** The place on screen and the native Server menu; where a rail of places stands beside the page, the rail switches@@ -90,32 +91,33 @@ export function DesktopWorkspaceSwitcher(props: SwitcherProps) {return railShown(places) ? <div data-switcher-beside-rail className={places.beside ? "hidden" : "contents md:hidden"}>{switcher}</div> : switcher;}-function Switcher({ compact = false, inline = false, pill = false, rail = false, cloudHome = false, owner = null, howTo = false, onMenuClosed }: SwitcherProps) {+function Switcher({ compact = false, inline = false, pill = false, rail = false, cloudHome = false, owner = null, howTo = false, place, onMenuClosed }: SwitcherProps) {+ const cloudName = place || t("cloudSetup.myCloud");const { bridge, current, open, error, onLine, waking, openMenu } = useWorkspacePlace({ cloudHome, howTo, onMenuClosed });const withPower = (name: string) => (onLine ? `${name} · ${onLine}` : name);// This window's home is My Cloud: it opens nothing else, so there is nothing to switch.if (!bridge || current?.home === true) {if (!cloudHome && !current?.home) return null;const whose = owner ? t("sidebar.cloudOwner", { email: owner }) : "";- const label = `${withPower(t("cloudSetup.myCloud"))}${whose ? ` · ${whose}` : ""}`;+ const label = `${withPower(cloudName)}${whose ? ` · ${whose}` : ""}`;if (rail) return <div data-cloud-home-indicator data-workspace-switcher="rail" role="img" aria-label={label} title={label} className="flex size-9 items-center justify-center text-ink-secondary"><Cloud size={18} aria-hidden="true" /></div>;if (inline) return <div data-cloud-home-indicator data-workspace-switcher="inline" title={label}className={pill ? "flex h-8 min-w-0 items-center gap-1 rounded-full bg-raised/50 px-3 text-[13px] font-medium text-ink" : "flex min-w-0 items-center gap-1.5 px-1.5 text-[13px] font-medium text-ink"}><Cloud size={pill ? 15 : 14} aria-hidden="true" className={pill ? "hidden shrink-0 text-ink-secondary @max-[124px]/sidebar-top:block" : "shrink-0 text-ink-secondary"} />- <span className={pill ? "min-w-0 truncate @max-[124px]/sidebar-top:hidden" : "min-w-0 truncate"}>{t("cloudSetup.myCloud")}</span>+ <span className={pill ? "min-w-0 truncate @max-[124px]/sidebar-top:hidden" : "min-w-0 truncate"}>{cloudName}</span>{(onLine || whose) && <span className="sr-only">{onLine ? ` · ${onLine}` : ""}{whose ? ` · ${whose}` : ""}</span>}</div>;return <div data-cloud-home-indicator className={cn("py-1.5", compact ? "px-2" : "px-3")}><div title={label} className={cn("flex items-center gap-2 py-2 text-[13px] font-medium text-ink", compact ? "justify-center px-1" : "px-2")}><Cloud size={16} aria-hidden="true" className="shrink-0 text-ink-secondary" />- {compact ? <span className="sr-only">{label}</span> : <span className="min-w-0 flex-1 truncate">{t("cloudSetup.myCloud")}{onLine && <PowerLine text={onLine} />}+ {compact ? <span className="sr-only">{label}</span> : <span className="min-w-0 flex-1 truncate">{cloudName}{onLine && <PowerLine text={onLine} />}{whose && <span className="block truncate text-[12px] font-normal text-ink-secondary">{whose}</span>}</span>}</div></div>;}- const name = current?.name ?? (cloudHome ? t("cloudSetup.myCloud") : t("sidebar.servers"));+ const name = current?.name ?? (cloudHome ? cloudName : t("sidebar.servers"));const Icon = current?.local === false || (cloudHome && !current) ? Cloud : Laptop;const shown = cloudHome ? withPower(name) : name;const title = current?.origin ? `${shown} · ${current.origin}` : shown;diff --git a/src/components/LiveConnectionStrip.test.ts b/src/components/LiveConnectionStrip.test.tsnew file mode 100644index 0000000000..7144e1f9a4--- /dev/null+++ b/src/components/LiveConnectionStrip.test.ts@@ -0,0 +1,38 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { LiveConnectionStrip, RECONNECTING_AFTER_MS } from "./LiveConnectionStrip";+import { t } from "@/lib/i18n";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root;+let container: HTMLDivElement;+beforeEach(() => {+ vi.useFakeTimers();+ container = document.createElement("div");+ root = createRoot(container);+});+afterEach(() => {+ act(() => root.unmount());+ vi.useRealTimers();+});+const draw = (connected: boolean, hydrated = true) => act(() => root.render(createElement(LiveConnectionStrip, { connected, hydrated })));++it("says the app is reconnecting once the live stream has been down for a moment, and goes when it is back", async () => {+ draw(false);+ expect(container.textContent).toBe("");+ await act(async () => { await vi.advanceTimersByTimeAsync(RECONNECTING_AFTER_MS); });+ expect(container.textContent).toContain(t("liveConnection.reconnecting"));+ draw(true);+ expect(container.textContent).toBe("");+});++it("says the device is offline at once", () => {+ draw(true);+ act(() => { window.dispatchEvent(new Event("offline")); });+ expect(container.textContent).toContain(t("liveConnection.offline"));+ act(() => { window.dispatchEvent(new Event("online")); });+ expect(container.textContent).toBe("");+});diff --git a/src/components/LiveConnectionStrip.tsx b/src/components/LiveConnectionStrip.tsxnew file mode 100644index 0000000000..038634a30d--- /dev/null+++ b/src/components/LiveConnectionStrip.tsx@@ -0,0 +1,37 @@+import { useEffect, useState } from "react";+import { CloudOff, Loader2 } from "lucide-react";+import { cloudAsleep, onCloudPower } from "@/lib/cloud-power";+import { t } from "@/lib/i18n";++export const RECONNECTING_AFTER_MS = 4_000;++/** The live stream is down: replies and other people's messages wait until it is back. A blip shorter than a few+ * seconds says nothing; a Cloud asleep has its own strip. */+export function LiveConnectionStrip({ connected, hydrated }: { connected: boolean; hydrated: boolean }) {+ const [late, setLate] = useState(false);+ const [online, setOnline] = useState(() => typeof navigator === "undefined" || navigator.onLine !== false);+ const [asleep, setAsleep] = useState(cloudAsleep);+ useEffect(() => onCloudPower(setAsleep), []);+ useEffect(() => {+ const on = () => setOnline(true), off = () => setOnline(false);+ window.addEventListener("online", on);+ window.addEventListener("offline", off);+ return () => {+ window.removeEventListener("online", on);+ window.removeEventListener("offline", off);+ };+ }, []);+ useEffect(() => {+ setLate(false);+ if (connected) return;+ const timer = setTimeout(() => setLate(true), RECONNECTING_AFTER_MS);+ return () => clearTimeout(timer);+ }, [connected]);+ if (asleep || !hydrated) return null;+ const notice = !online ? "offline" : !connected && late ? "reconnecting" : null;+ if (!notice) return null;+ return <div role="status" data-live-connection={notice} className="flex items-center justify-center gap-2 border-b border-hairline/40 bg-panel px-3 py-1.5 text-[13px] text-ink-secondary">+ {notice === "offline" ? <CloudOff size={14} aria-hidden="true" /> : <Loader2 size={14} className="animate-spin" aria-hidden="true" />}+ <span>{t(notice === "offline" ? "liveConnection.offline" : "liveConnection.reconnecting")}</span>+ </div>;+}diff --git a/src/components/PhonePlus.tsx b/src/components/PhonePlus.tsxnew file mode 100644index 0000000000..e83b1682b6--- /dev/null+++ b/src/components/PhonePlus.tsx@@ -0,0 +1,17 @@+// The phone composer's round + (Composer.tsx): the + menu, with where the bot works when there is a choice.+import type { ComponentProps } from "react";++import { ComposerPlusMenu } from "./ComposerPlusMenu";+import { usePlaceMenuItem } from "./PlaceChip";++type PhonePlusProps = Pick<ComponentProps<typeof ComposerPlusMenu>, "onAttach" | "goal" | "teach" | "approval" | "callBotId">;++function PhonePlusWithPlace({ place, ...rest }: PhonePlusProps & { place: Parameters<typeof usePlaceMenuItem>[0] }) {+ const item = usePlaceMenuItem(place);+ return <ComposerPlusMenu {...rest} extraItems={[item]} circle />;+}++/** The phone composer's round +: attach, Finish together, where the bot works, approval level and call mode. */+export function PhonePlus({ place, ...rest }: PhonePlusProps & { place?: Parameters<typeof usePlaceMenuItem>[0] }) {+ return place ? <PhonePlusWithPlace place={place} {...rest} /> : <ComposerPlusMenu {...rest} circle />;+}diff --git a/src/components/PluginsPanel.member.test.ts b/src/components/PluginsPanel.member.test.tsnew file mode 100644index 0000000000..e3591ce568--- /dev/null+++ b/src/components/PluginsPanel.member.test.ts@@ -0,0 +1,31 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++const refused = Object.assign(new Error("forbidden: this session lacks the admin scope"), { status: 403 });+vi.mock("@/state/store", () => ({+ api: vi.fn(() => Promise.reject(refused)),+ useStore: () => ({ state: { pluginsSurface: "apps", bots: [], instances: [] }, dispatch: vi.fn() }),+}));+vi.mock("./McpServersPanel", () => ({ McpServersPanel: () => null }));+vi.mock("./HighLevelCard", () => ({ HighLevelCard: () => null }));+vi.mock("./XCard", () => ({ X_CARD_SEARCH: "x", XCard: () => null }));++const { PluginsPanel } = await import("./PluginsPanel");++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+let host: HTMLDivElement;+let root: Root;+beforeEach(() => { host = document.createElement("div"); document.body.append(host); root = createRoot(host); });+afterEach(() => { act(() => root.unmount()); host.remove(); });++it("tells a session without the admin scope why, and stops loading, instead of blaming this Mac's credential store", async () => {+ await act(async () => root.render(createElement(PluginsPanel)));+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });+ const text = host.textContent ?? "";+ expect(text).toContain("Only an admin of this installation can connect apps here.");+ expect(text).not.toContain("credential store");+ expect(text).not.toContain("Loading catalog");+ expect(text).not.toContain("lacks the admin scope");+});diff --git a/src/components/PluginsPanel.tsx b/src/components/PluginsPanel.tsxindex a957c151fc..775db60a98 100644--- a/src/components/PluginsPanel.tsx+++ b/src/components/PluginsPanel.tsx@@ -35,7 +35,8 @@ import { X_CARD_SEARCH, XCard } from "./XCard";import { mergeCompleteConnectorStatus, mergeCurrentConnectorStatus, onlyLatestConnectorResponses } from "@/lib/connector-status-merge";import { openBotSettings } from "./bot-panel/panel-link";import { openKeySettings } from "./keys/key-focus";-import { ServiceIcon, type ToolkitCard } from "./ServiceIcon";+import { lacksAdminScope, unlessRefused } from "@/lib/admin-scope";+import { ServiceIcon, type ToolkitCard } from "./ServiceIcon"; import { AppsSection } from "./AppsSection";export { ServiceIcon, type ToolkitCard } from "./ServiceIcon";let cachedConnectorStatus: Record<string, ConnectorStatus> | null = null;@@ -48,8 +49,12 @@ export interface ConnectorInventory {services: Record<string, ConnectorStatus>;/** false when the server could not read the credential store: nothing may be cleared on the strength of it. */authoritative: boolean;+ /** This session may not see the connected apps: its role, not the credential store. */+ refused?: true;}+const REFUSED_INVENTORY: ConnectorInventory = { services: {}, authoritative: true, refused: true };+export function preloadConnectedApps(force = false, background = false): Promise<ConnectorInventory> { // background: src/state/api.tsif (!force && cachedConnectorStatus !== null && Date.now() - cachedConnectorStatusAt < CONNECTOR_STATUS_CACHE_MS) {return Promise.resolve({@@ -58,8 +63,10 @@ export function preloadConnectedApps(force = false, background = false): Promise});}if (connectorStatusRequest) return connectorStatusRequest;- connectorStatusRequest = api("/api/connectors/connected", background ? { background: true } : undefined)- .then((response: { services?: Record<string, ConnectorStatus>; credentialStore?: string; inventoryComplete?: boolean }) => {+ type ConnectedAnswer = { services?: Record<string, ConnectorStatus>; credentialStore?: string; inventoryComplete?: boolean };+ connectorStatusRequest = unlessRefused<ConnectedAnswer | null>("/api/connectors/connected", () => api("/api/connectors/connected", background ? { background: true } : undefined), null)+ .then((response): ConnectorInventory => {+ if (!response) return REFUSED_INVENTORY;const services: Record<string, ConnectorStatus> = response.services ?? {};if (response.credentialStore === "unavailable" || response.inventoryComplete === false) {cachedConnectorStatusAuthoritative = false;@@ -229,8 +236,9 @@ export function PluginsPanel() {const requestGenerations = new Map(statusGenerations.current);setRefreshing(true);return preloadConnectedApps(force)- .then(({ services, authoritative }) => {+ .then(({ services, authoritative, refused }) => {setStale(!authoritative);+ if (refused) setError({ key: "connectors.adminOnly" });setStatus((current) => mergeCompleteConnectorStatus(current,services,@@ -289,7 +297,8 @@ export function PluginsPanel() {}).catch((e) => {if (!alive) return;- setError(e.message);+ setCards((current) => current ?? []);+ setError(lacksAdminScope(e) ? { key: "connectors.adminOnly" } : e.message);});return () => {alive = false;@@ -995,34 +1004,3 @@ export function PluginsPanel() {);}}--function AppsSection({ id, title, note, viewAll, after, children }: {- id: string;- title: string;- note?: string;- viewAll?: { label: string; onClick: () => void };- after?: React.ReactNode;- children: React.ReactNode;-}) {- return (- <section aria-labelledby={id} data-apps-section={id}>- <div className="mb-1.5 flex min-h-7 items-center justify-between gap-3 px-2">- <h3 id={id} className="min-w-0 truncate text-[14px] font-semibold leading-5 text-ink">- {title}- {note && <span className="ms-2 text-[12px] font-normal text-ink-secondary">{note}</span>}- </h3>- {viewAll && (- <button- type="button"- onClick={viewAll.onClick}- className="shrink-0 rounded-full px-2 text-[13px] font-medium leading-5 text-ink-secondary transition-colors hover:text-ink"- >- {viewAll.label}- </button>- )}- </div>- <div className="grid grid-cols-1 items-start gap-x-6 gap-y-1 @xl:grid-cols-2">{children}</div>- {after}- </section>- );-}diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsxindex 0793e9bc80..9b08818dc1 100644--- a/src/components/SettingsModal.tsx+++ b/src/components/SettingsModal.tsx@@ -4,6 +4,7 @@ import { useStore, type AppSettingsSection } from "@/state/store";import { skillsLibraryEnabled } from "@/lib/feature-flags";import { type LocaleKey } from "@/locales";import { t } from "@/lib/i18n";+import { AdminOnly } from "./AdminOnly";import { KeysPage } from "./keys/KeysPage";import { KEY_CATALOG, keyMatches, keySection, type KeyEntry } from "./keys/key-catalog";import { openKeySettings, useKeyFocus } from "./keys/key-focus";@@ -391,19 +392,19 @@ export function SettingsModal() {case "experimental":return <ExperimentalFeaturesRow />;case "connections":- return <KeysPage />;- case "decisionModel": return <DecisionModelSettings />;- case "engines": return <EnginesSettings />;- case "backups": return <><WorkspaceBackupSettings /><CompanyBackupSettings /></>;- case "import": return <ImportSettings />;+ return <AdminOnly><KeysPage /></AdminOnly>;+ case "decisionModel": return <AdminOnly><DecisionModelSettings /></AdminOnly>;+ case "engines": return <AdminOnly><EnginesSettings /></AdminOnly>;+ case "backups": return <AdminOnly><WorkspaceBackupSettings /><CompanyBackupSettings /></AdminOnly>;+ case "import": return <AdminOnly><ImportSettings /></AdminOnly>;case "companion":return <>{remoteAccess.client}{remoteAccess.domain}{remoteAccess.pairing}{remoteAccess.companion}</>;case "computer":- return <><BuiltInBrowserRow /><BrowserProfilesRow /><LocalComputerSection /></>;+ return <><BuiltInBrowserRow /><BrowserProfilesRow /><AdminOnly><LocalComputerSection /></AdminOnly></>;case "logins":return <LoginsSettings />;case "usage":- return <UsageSection />;+ return <AdminOnly note="settings.adminOnly.usage"><UsageSection /></AdminOnly>;case "skills":return skillsLibraryEnabled(state.config) ? <SkillsSection /> : null;case "people":diff --git a/src/components/SettingsSimplePages.member.test.ts b/src/components/SettingsSimplePages.member.test.tsnew file mode 100644index 0000000000..56cb42eabc--- /dev/null+++ b/src/components/SettingsSimplePages.member.test.ts@@ -0,0 +1,43 @@+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { beforeEach, expect, it, vi } from "vitest";++import type { Disclose } from "./SettingsSimplePages";++const fixture = vi.hoisted(() => ({ admin: false as boolean | null }));+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => fixture.admin }));+vi.mock("./EnginesSettings", () => ({ EnginesSettings: () => "AI ACCOUNTS" }));+vi.mock("./LocalComputerSection", () => ({ LocalComputerSection: () => "CLOUD DESKTOPS" }));+vi.mock("./UsageSection", () => ({ UsageSection: () => "USAGE TABLE" }));+vi.mock("./PlanUsage", () => ({ PlanUsageSummary: () => "PLAN USAGE" }));+vi.mock("./CloudUsageMeter", () => ({ useCloudUsageSettings: () => ({ usage: null, upgrade: null, dialog: null }), CloudUsageDetails: () => null, CloudUsageSummaryView: () => null }));+vi.mock("./ProIntroduction", () => ({ useCloudPlan: () => null, CloudPlanRow: () => null, CloudPlanFootnote: () => null }));+vi.mock("./BrowserSettingsRows", () => ({ BuiltInBrowserRow: () => null }));+vi.mock("./AppSettingsRows", async (original) => ({ ...await original<object>(), BrowserProfilesRow: () => null }));+vi.mock("./LoginsSettings", () => ({ LoginsSettings: () => null }));++const { SimpleAiPage, SimpleBillingPage, SimpleComputerPage } = await import("./SettingsSimplePages");++const has = () => true;+const disclose: Disclose = (id) => ({ id, open: true, onToggle: () => {} });+const remoteAccess = { client: null, domain: null, pairing: null, companion: null };+const pages = () => [+ renderToStaticMarkup(createElement(SimpleAiPage, { has, disclose, connections: "KEYS" })),+ renderToStaticMarkup(createElement(SimpleComputerPage, { has, disclose, remoteAccess, servers: null })),+ renderToStaticMarkup(createElement(SimpleBillingPage, { has, disclose, cloudAccount: null })),+].join("\n");++beforeEach(() => { fixture.admin = false; });++it("shows a session without the admin scope a plain sentence instead of the installation's AI, computers and usage", () => {+ const html = pages();+ for (const hidden of ["AI ACCOUNTS", "KEYS", "CLOUD DESKTOPS", "USAGE TABLE", "PLAN USAGE"]) expect(html).not.toContain(hidden);+ expect(html).toContain("Only an admin of this installation can change this.");+ expect(html).toContain("Only an admin of this installation can see usage.");+});++it("keeps them for an admin", () => {+ fixture.admin = true;+ const html = pages();+ for (const shown of ["AI ACCOUNTS", "KEYS", "CLOUD DESKTOPS", "USAGE TABLE", "PLAN USAGE"]) expect(html).toContain(shown);+});diff --git a/src/components/SettingsSimplePages.tsx b/src/components/SettingsSimplePages.tsxindex 7346156c77..b2079c9f7a 100644--- a/src/components/SettingsSimplePages.tsx+++ b/src/components/SettingsSimplePages.tsx@@ -31,6 +31,7 @@ import { NotificationRows } from "./NotificationSettingsRows";import { useServerUpdateItem } from "./SidebarProfileMenu";import { AdvancedModeRow, BrowserProfilesRow, ColorUserBubblesRow, LanguageRow, ReplayTourRow, SendKeyRow, UpdatesRow } from "./AppSettingsRows";import { ThemeRow } from "./ThemeRow";+import { AdminOnly } from "./AdminOnly";export type SimpleDisclosureId = "ai-more" | "ai-keys" | "computer-elsewhere" | "billing-limits";@@ -86,7 +87,7 @@ export function SimpleGeneralPage({ has, peopleOpen, onLooks }: { has: Has; peop</SettingsRows></SettingsGroup>)}- {has("import") && <SettingsGroup label={t("settings.section.import")} block="import"><ImportSettings /></SettingsGroup>}+ {has("import") && <SettingsGroup label={t("settings.section.import")} block="import"><AdminOnly><ImportSettings /></AdminOnly></SettingsGroup>}{has("organization") && <SettingsGroup label={t("settings.section.organization")} block="organization"><OrganizationSettings /></SettingsGroup>}{has("activity") && <SettingsGroup label={t("settings.section.activity")} block="activity"><ActivitySection /></SettingsGroup>}<div data-settings-block="advanced-mode" className="scroll-mt-4">@@ -108,11 +109,13 @@ export function SimpleLooksPage({ onBack }: { onBack: () => void }) {export function SimpleAiPage({ has, disclose, connections }: { has: Has; disclose: Disclose; connections: ReactNode }) {return (<>- {has("engines") && <div data-settings-block="engines" className="flex scroll-mt-4 flex-col gap-7"><EnginesSettings simple more={disclose("ai-more")} /></div>}+ {has("engines") && <div data-settings-block="engines" className="flex scroll-mt-4 flex-col gap-7"><AdminOnly><EnginesSettings simple more={disclose("ai-more")} /></AdminOnly></div>}{has("connections") && (- <SettingsDisclosureRow title={t("settings.simple.ai.keys")} block="connections" {...disclose("ai-keys")}>- {connections}- </SettingsDisclosureRow>+ <AdminOnly>+ <SettingsDisclosureRow title={t("settings.simple.ai.keys")} block="connections" {...disclose("ai-keys")}>+ {connections}+ </SettingsDisclosureRow>+ </AdminOnly>)}</>);@@ -123,7 +126,7 @@ export type RemoteAccessCards = Record<"client" | "domain" | "pairing" | "companexport function SimpleComputerPage({ has, remoteAccess, servers, disclose }: { has: Has; remoteAccess: RemoteAccessCards; servers: ReactNode; disclose: Disclose }) {return (<>- {has("computer") && <SettingsGroup label={t("settings.simple.computer.bots")} block="computer"><LocalComputerSection /></SettingsGroup>}+ {has("computer") && <SettingsGroup label={t("settings.simple.computer.bots")} block="computer"><AdminOnly><LocalComputerSection /></AdminOnly></SettingsGroup>}{has("companion") && (<SettingsGroup label={t("settings.simple.computer.devices")} block="companion">{remoteAccess.pairing}@@ -154,12 +157,12 @@ export function SimpleBillingPage({ has, disclose, cloudAccount }: { has: Has; dreturn (<><div data-settings-block="usage" className="scroll-mt-4">- {usage ? <CloudUsageSummaryView usage={usage} upgrade={upgrade}>{dialog}</CloudUsageSummaryView> : <PlanUsageSummary />}+ {usage ? <CloudUsageSummaryView usage={usage} upgrade={upgrade}>{dialog}</CloudUsageSummaryView> : <AdminOnly note="settings.adminOnly.usage"><PlanUsageSummary /></AdminOnly>}</div>{(usage || has("usage")) && (<SettingsDisclosureRow title={t("settings.simple.billing.limits")} {...disclose("billing-limits")}>{usage && <CloudUsageDetails usage={usage} upgrade={upgrade} />}- {has("usage") && <UsageSection />}+ {has("usage") && <AdminOnly note="settings.adminOnly.usage"><UsageSection /></AdminOnly>}</SettingsDisclosureRow>)}{has("cloudAccount") && (diff --git a/src/components/Sidebar.header-menus.test.ts b/src/components/Sidebar.header-menus.test.tsindex d177f16329..993c6274b5 100644--- a/src/components/Sidebar.header-menus.test.ts+++ b/src/components/Sidebar.header-menus.test.ts@@ -22,6 +22,7 @@ vi.mock("react", async (original) => ({useLayoutEffect: () => {},}));vi.mock("react-dom", () => ({ createPortal: (node: ReactNode) => node }));+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));vi.mock("./MenuMotion", () => ({useMenuMotion: (open: boolean) => ({ shown: open, closing: false, className: "", exitProps: {} }),useHeldMenuMotion: (value: unknown) => ({ shown: value !== null, value, closing: false, className: "", exitProps: {} }),diff --git a/src/components/Sidebar.header.test.ts b/src/components/Sidebar.header.test.tsindex 59c18764c7..7e6a4456a6 100644--- a/src/components/Sidebar.header.test.ts+++ b/src/components/Sidebar.header.test.ts@@ -186,11 +186,11 @@ describe("sidebar top row", () => {},);- it("keeps the browser build's placeholder lights 12px clear of the drag space and buttons", () => {+ it("draws no window buttons in a browser, where the browser has its own", () => {const row = topRow(render());- expect(row).toContain('<div class="flex shrink-0 items-center gap-2 mr-3"><span class="size-3 rounded-full bg-[#ff5f57]"></span>');+ expect(row).not.toContain("bg-[#ff5f57]");+ expect(row).not.toContain("data-traffic-light-space");const { spacer, buttons } = order(row);- expect(spacer).toBeGreaterThan(row.indexOf("bg-[#28c840]"));expect(buttons).toBeGreaterThan(spacer);});diff --git a/src/components/Sidebar.simple-layout.test.ts b/src/components/Sidebar.simple-layout.test.tsindex 9f037f5091..1017c25b53 100644--- a/src/components/Sidebar.simple-layout.test.ts+++ b/src/components/Sidebar.simple-layout.test.ts@@ -26,6 +26,7 @@ vi.mock("react", async (original) => ({useLayoutEffect: () => {},}));vi.mock("react-dom", () => ({ createPortal: (node: ReactNode) => node }));+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));vi.mock("./MenuMotion", () => ({useMenuMotion: (open: boolean) => ({ shown: open, closing: false, className: "", exitProps: {} }),useHeldMenuMotion: (value: unknown) => ({ shown: value !== null, value, closing: false, className: "", exitProps: {} }),diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex 421fa3161f..9c1413d9d0 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -1096,7 +1096,6 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {};const macInset = capabilities.windowChrome === "mac-inset", pageRail = usePlaces().places.length > 0;- const browser = capabilities.host.label === "Browser";const draggableChrome = macInset || capabilities.windowChrome === "win-caption";// SAFETY: Electron's -webkit-app-region is not in React's CSSProperties type; the renderer accepts it as an inline// style.@@ -1224,7 +1223,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {<Users size={16} className="text-ink-secondary" />{t("sidebar.newChannel.title")}</button>- {advanced && !remoteClient && <button+ {advanced && !remoteClient && teamSettingsAllowed !== false && <buttononClick={() => { setPlusOpen(false); setNewTeam(true); }}role="menuitem"className={plusItem}@@ -1303,12 +1302,6 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {) : macInset ? (// The macOS 26 traffic lights span 16-76px; nothing clickable starts before 88px, with the window's rail beside or not.<div aria-hidden="true" data-traffic-light-space className={density === "icons" ? "h-5 w-full" : pageRail ? "w-[72px] shrink-0 md:w-2" : "w-[72px] shrink-0 md:w-[calc(72px_-_var(--rail-beside,0px))]"} />- ) : browser ? (- <div className={cn("flex shrink-0 items-center gap-2", density !== "icons" && "mr-3", simpleDesk && "mt-1")}>- <span className="size-3 rounded-full bg-[#ff5f57]" />- <span className="size-3 rounded-full bg-[#febc2e]" />- <span className="size-3 rounded-full bg-[#28c840]" />- </div>) : null}{!phone && <ChromeRailToggle advanced={advanced} icons={density === "icons"} style={windowNoDragStyle} />}{rail && <div data-sidebar-rail-top className="flex flex-col items-center gap-2 pt-1" style={windowNoDragStyle}><button type="button" onClick={railSearch} aria-label={t("sidebar.searchAria")} title={t("sidebar.searchAria")} className={SIMPLE_TOP_BUTTON}>@@ -1320,7 +1313,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {<div data-sidebar-top-slot className={cn("@container/sidebar-top flex min-w-0 flex-1 items-center", simple && "justify-end")}>{!simple && <div data-sidebar-top-spacer className="min-w-0 flex-1 @min-[96px]/sidebar-top:min-w-6" />}<div data-sidebar-top-switcher className={simple ? "flex min-w-0 items-center" : "flex min-w-0 max-w-[140px] items-center"}>- <DesktopWorkspaceSwitcher inline pill={simple} cloudHome={state.config?.cloudHome === true} owner={cloudOwner} howTo={state.cloudHowTo} onMenuClosed={endHowTo} />+ <DesktopWorkspaceSwitcher inline pill={simple} cloudHome={state.config?.cloudHome === true} place={state.config?.team?.name} owner={cloudOwner} howTo={state.cloudHowTo} onMenuClosed={endHowTo} /></div></div>))}@@ -1403,7 +1396,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {</div>}</div>- {density === "icons" && !rail && <DesktopWorkspaceSwitcher compact cloudHome={state.config?.cloudHome === true} owner={cloudOwner} howTo={state.cloudHowTo} onMenuClosed={endHowTo} />}+ {density === "icons" && !rail && <DesktopWorkspaceSwitcher compact cloudHome={state.config?.cloudHome === true} place={state.config?.team?.name} owner={cloudOwner} howTo={state.cloudHowTo} onMenuClosed={endHowTo} />}<OrganizationIdentity compact={density === "icons"} />{phone ? null : simple ? searchShown && <SidebarSearchPill query={query} onQuery={setQuery} onClose={closeSearch} /> : <div className={cn("pt-1 pb-3", density === "icons" ? "hidden" : "px-3")}><div className={cn("flex h-8 items-center gap-2 rounded-full px-3 focus-within:ring-focus", ELEVATED_CONTROL)}>diff --git a/src/components/SidebarBotMenu.tsx b/src/components/SidebarBotMenu.tsxindex 42fdf2aab5..420d0df093 100644--- a/src/components/SidebarBotMenu.tsx+++ b/src/components/SidebarBotMenu.tsx@@ -66,7 +66,8 @@ export function BotContextMenu({const shown = motion.value;const { state, dispatch } = useStore();const showThreads = useShowThreads();- const canChooseFolder = useOwnerOrAdmin();+ const admin = useOwnerOrAdmin();+ const member = admin === false;const clearThreads = useDeleteAllThreads(simpleMenu), moveToTeam = useMoveToTeam({ blocked: (bot) => (bot.defaultBot ? t("teamMove.blockedDefault", { name: bot.name }) : bot.chiefOfStaff ? t("teamMove.blockedChief") : state.bots.filter((candidate) => !candidate.hidden).length <= 1 ? t("teamMove.blockedLast") : undefined) });const remoteClient = window.ogb?.remoteClient?.active === true;const bot = shown ? state.bots.find((b) => b.id === shown.botId) : undefined;@@ -156,6 +157,13 @@ export function BotContextMenu({: visibleBotCount <= 1? t("sidebar.bot.archiveBlockedLast"): undefined;+ const chiefItem = () => item(+ <Crown size={16} className={bot.chiefOfStaff ? "text-accent" : "text-ink-secondary"} />,+ bot.chiefOfStaff ? t("sidebar.bot.removeChief") : t("sidebar.bot.makeChief"),+ () => dispatch({ type: "updateBot", botId: bot.id, patch: { chiefOfStaff: !bot.chiefOfStaff } }),+ member ? { disabled: true, hint: t("sidebar.bot.chiefAdminOnly") }+ : { disabled: !bot.chiefOfStaff && !canCoordinate, hint: !bot.chiefOfStaff && !canCoordinate ? t("sidebar.bot.chiefNeedsEngine") : undefined },+ );const openForSettings = () => {if (state.selectedId === bot.id) dispatch({ type: "select", id: bot.id });else openBot(dispatch, bot, showThreads);@@ -228,14 +236,14 @@ export function BotContextMenu({<ChevronRight size={15} aria-hidden="true" className="text-ink-secondary rtl:-scale-x-100" /></button>);- const moveToSection = flyoutButton("move", moveRef, <FolderPlus size={16} className="text-ink-secondary" />, t("sidebar.bot.moveToSection"));+ const moveToSection = member ? null : flyoutButton("move", moveRef, <FolderPlus size={16} className="text-ink-secondary" />, t("sidebar.bot.moveToSection"));const rename = onRename && item(<SquarePen size={16} className="text-ink-secondary" />, t("sidebar.bot.rename"), () => onRename(bot.id));const editProfile = item(<Pencil size={16} className="text-ink-secondary" />, t("sidebar.bot.simple.editProfile"), () => {openForSettings();if (!state.settingsOpen) dispatch({ type: "toggleSettings", open: true });});const owner = team && mayChangeOwner(bot, team) ? item(<Users size={16} className="text-ink-secondary" />, ownerMenuLabel(bot, team), () => pickOwnerOf([bot], team, shown)) : null;- const deleteAll = allThreadRows(bot).length >= 2 ? [divider("more-threads"), item(<Trash2 size={16} />, t("task.deleteAllConversations"), () => clearThreads.ask(bot.id), { danger: true })] : [];+ const deleteAll = !member && allThreadRows(bot).length >= 2 ? [divider("more-threads"), item(<Trash2 size={16} />, t("task.deleteAllConversations"), () => clearThreads.ask(bot.id), { danger: true })] : [];const readState = readingBotId === bot.id || botUnreadThreadIds(bot).length > 0? item(readingBotId === bot.id ? <Loader2 size={16} className="animate-spin text-ink-secondary" /> : <CheckCheck size={16} className="text-ink-secondary" />,@@ -246,19 +254,14 @@ export function BotContextMenu({: item(<BellDot size={16} className="text-ink-secondary" />, t("sidebar.bot.simple.markUnread"), () => dispatch({ type: "markUnread", botId: bot.id }));const moreItems = remoteClient ? [editProfile, owner, ...deleteAll] : [editProfile,- item(- <Crown size={16} className={bot.chiefOfStaff ? "text-accent" : "text-ink-secondary"} />,- bot.chiefOfStaff ? t("sidebar.bot.removeChief") : t("sidebar.bot.makeChief"),- () => dispatch({ type: "updateBot", botId: bot.id, patch: { chiefOfStaff: !bot.chiefOfStaff } }),- { disabled: !bot.chiefOfStaff && !canCoordinate, hint: !bot.chiefOfStaff && !canCoordinate ? t("sidebar.bot.chiefNeedsEngine") : undefined },- ),- item(<Copy size={16} className="text-ink-secondary" />, t("sidebar.bot.duplicate"), () => dispatch({ type: "duplicateBot", botId: bot.id })),+ chiefItem(),+ member ? null : item(<Copy size={16} className="text-ink-secondary" />, t("sidebar.bot.duplicate"), () => dispatch({ type: "duplicateBot", botId: bot.id })),owner,...moveToTeam.items(bot, item),...deleteAll,];const moreRow = flyoutButton("more", moreRef, <MoreHorizontal size={16} className="text-ink-secondary" />, t("sidebar.bot.more"));- const leave = bot.defaultBot ? [<HideDefaultBotItem key="hide" bot={bot} onDone={onClose} className={MENU_ITEM} />] : [+ const leave = bot.defaultBot ? [<HideDefaultBotItem key="hide" bot={bot} onDone={onClose} className={MENU_ITEM} />] : member ? [] : [item(<Archive size={16} className="text-ink-secondary" />, t("sidebar.bot.archive"), () => onArchive(bot), { disabled: archiveBlocked, hint: archiveHint }),<BotDeleteMenuItem key="delete" deleting={deleting} className={MENU_ITEM} onClick={() => { onClose(); onDelete(bot); }} />,];@@ -301,8 +304,7 @@ export function BotContextMenu({divider("copy"),copyId,moreRow,- divider("leave"),- ...leave,+ ...(leave.length ? [divider("leave"), ...leave] : []),]}{readError?.botId === bot.id && <p role="alert" className="px-2 py-1.5 text-[12px] text-danger">{readError.message}</p>}</div>,@@ -352,14 +354,14 @@ export function BotContextMenu({>{showThreads && <>{item(<SquarePen size={16} className="text-ink-secondary" />, t("task.newShort"), () => dispatch({ type: "newTask", botId: bot.id }))}- {canChooseFolder && item(<FolderOpen size={16} className="shrink-0 text-ink-secondary" />, t("task.folder.new"), () => onNewTaskFolder(bot.id))}+ {admin && item(<FolderOpen size={16} className="shrink-0 text-ink-secondary" />, t("task.folder.new"), () => onNewTaskFolder(bot.id))}{item(<FolderPlus size={16} className="text-ink-secondary" />, t("folder.new"), () => onNewFolder(bot.id))}</>}- {item(<Trash2 size={16} />, t("task.deleteAll"), () => clearThreads.ask(bot.id), { danger: true })}+ {!member && item(<Trash2 size={16} />, t("task.deleteAll"), () => clearThreads.ask(bot.id), { danger: true })}{divider("threads")}{team && mayChangeOwner(bot, team) && item(<Users size={16} className="text-ink-secondary" />, ownerMenuLabel(bot, team), () => pickOwnerOf([bot], team, shown))}{remoteClient ? [- item(<FolderPlus size={16} className="text-ink-secondary" />, t("sidebar.bot.moveToSection"), () => {+ !member && item(<FolderPlus size={16} className="text-ink-secondary" />, t("sidebar.bot.moveToSection"), () => {onClose();onMoveToSection(bot.id);}),@@ -376,16 +378,8 @@ export function BotContextMenu({bot.pinned ? t("sidebar.bot.unpin") : t("sidebar.bot.pin"),() => dispatch({ type: "updateBot", botId: bot.id, patch: { pinned: !bot.pinned } }),),- item(- <Crown size={16} className={bot.chiefOfStaff ? "text-accent" : "text-ink-secondary"} />,- bot.chiefOfStaff ? t("sidebar.bot.removeChief") : t("sidebar.bot.makeChief"),- () => dispatch({ type: "updateBot", botId: bot.id, patch: { chiefOfStaff: !bot.chiefOfStaff } }),- {- disabled: !bot.chiefOfStaff && !canCoordinate,- hint: !bot.chiefOfStaff && !canCoordinate ? t("sidebar.bot.chiefNeedsEngine") : undefined,- },- ),- item(<FolderPlus size={16} className="text-ink-secondary" />, t("sidebar.bot.moveToSection"), () => {+ chiefItem(),+ !member && item(<FolderPlus size={16} className="text-ink-secondary" />, t("sidebar.bot.moveToSection"), () => {onClose();onMoveToSection(bot.id);}),@@ -403,7 +397,7 @@ export function BotContextMenu({openForSettings();if (!state.settingsOpen) dispatch({ type: "toggleSettings", open: true });}),- item(<Copy size={16} className="text-ink-secondary" />, t("sidebar.bot.duplicate"), () =>+ !member && item(<Copy size={16} className="text-ink-secondary" />, t("sidebar.bot.duplicate"), () =>dispatch({ type: "duplicateBot", botId: bot.id }),),divider("d2"),@@ -411,7 +405,7 @@ export function BotContextMenu({void copyText(bot.threadId);}),divider("d3"), ...moveToTeam.items(bot, item),- ...(bot.defaultBot ? [<HideDefaultBotItem key="hide" bot={bot} onDone={onClose} className={MENU_ITEM} />] : [+ ...(bot.defaultBot ? [<HideDefaultBotItem key="hide" bot={bot} onDone={onClose} className={MENU_ITEM} />] : member ? [] : [item(<Archive size={16} className="text-ink-secondary" />, t("sidebar.bot.archive"), () => onArchive(bot), { disabled: archiveBlocked, hint: archiveHint }),<BotDeleteMenuItem key="delete" deleting={deleting} className={MENU_ITEM} onClick={() => { onClose(); onDelete(bot); }} />,]),diff --git a/src/components/SidebarBotRead.test.ts b/src/components/SidebarBotRead.test.tsindex 817f389c2e..01a56ada0d 100644--- a/src/components/SidebarBotRead.test.ts+++ b/src/components/SidebarBotRead.test.ts@@ -7,6 +7,7 @@ import { BotEditorStore, initialState, reducer, type Action, type AppState, typeimport { BotContextMenu } from "./Sidebar";import { setLocale } from "@/lib/i18n";+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));vi.mock("./DesktopCapabilities", () => ({ useDesktopCapabilities: () => ({}) }));const mode = vi.hoisted(() => ({ advanced: true }));vi.mock("@/lib/interface-mode", async (original) => ({diff --git a/src/components/SidebarProfileMenu.test.ts b/src/components/SidebarProfileMenu.test.tsindex ccbf6c598a..4ab48d45bd 100644--- a/src/components/SidebarProfileMenu.test.ts+++ b/src/components/SidebarProfileMenu.test.ts@@ -580,6 +580,11 @@ describe("Simple mode's account menu", () => {expect(placeMenuItems(place({ bridge: undefined, switchable: false }), { owner: null, onCloudSettings })).toEqual([]);});+ it("names a team's Cloud by the team", () => {+ const team = placeMenuItems(place({ switchable: false, cloudHome: true, onLine: "" }), { owner: null, name: "Acme Labs", onCloudSettings: noop });+ expect(team.map((item) => item.label)).toEqual(["Acme Labs"]);+ });+it("shows one Get the phone app row, dotted while this computer's phone is connected", () => {expect(simplePhoneItems({ connected: true, onGetApp: noop }).map((item) => [item.key, Boolean(item.trailing)])).toEqual([["phone-app", true]]);expect(simplePhoneItems({ connected: false, onGetApp: noop })[0]!.trailing).toBeUndefined();diff --git a/src/components/SidebarProfileMenu.tsx b/src/components/SidebarProfileMenu.tsxindex 35664c7ff1..8fb3f96bf2 100644--- a/src/components/SidebarProfileMenu.tsx+++ b/src/components/SidebarProfileMenu.tsx@@ -367,8 +367,10 @@ export function accountDot({ automationsNeedYou, update, move }: { automationsNe}/** `besideRail`: the window's rail of places stands beside the page and switches places, so Switch to… isn't offered twice. */-export function placeMenuItems(place: Pick<WorkspacePlace, "bridge" | "current" | "cloudHome" | "onLine" | "openMenu" | "switchable">, { owner, onCloudSettings, besideRail = false }: {+export function placeMenuItems(place: Pick<WorkspacePlace, "bridge" | "current" | "cloudHome" | "onLine" | "openMenu" | "switchable">, { owner, name, onCloudSettings, besideRail = false }: {owner: string | null;+ /** A team's name on a team's Cloud. */+ name?: string;onCloudSettings: () => void;besideRail?: boolean;}): SidebarMenuItem[] {@@ -376,7 +378,7 @@ export function placeMenuItems(place: Pick<WorkspacePlace, "bridge" | "current"if (!place.switchable) {if (!place.cloudHome && !place.current?.home) return [];const subtitle = [place.onLine, owner ? t("sidebar.cloudOwner", { email: owner }) : ""].filter(Boolean).join(" · ");- return [{ key: "place", label: t("cloudSetup.myCloud"), ...(subtitle ? { subtitle } : {}), icon: <Cloud size={16} />, trailing: here, onSelect: onCloudSettings }];+ return [{ key: "place", label: name || t("cloudSetup.myCloud"), ...(subtitle ? { subtitle } : {}), icon: <Cloud size={16} />, trailing: here, onSelect: onCloudSettings }];}const current = place.current;const icon = cloudColor(current?.color) ? <CloudTile color={current?.color} size={16} />@@ -604,7 +606,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = faonFiles: filesReady ? () => dispatch({ type: "showFiles" }) : undefined,archived: account.archived,}),- places: placeMenuItems(account.place, { owner: account.owner, besideRail, onCloudSettings: openCloudAccount }),+ places: placeMenuItems(account.place, { owner: account.owner, name: state.config?.team?.name, besideRail, onCloudSettings: openCloudAccount }),} } : {}),onUsage: () => dispatch({ type: "toggleAppSettings", open: true, section: "usage" }),onSettings: () => dispatch({ type: "toggleAppSettings" }),diff --git a/src/components/TeamCanvas.tsx b/src/components/TeamCanvas.tsxindex dd8157e63a..6890813764 100644--- a/src/components/TeamCanvas.tsx+++ b/src/components/TeamCanvas.tsx@@ -1,6 +1,7 @@import { useCallback, useEffect, useMemo, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";import { ArrowRight, BookOpen, Brain, Crown, MessageCircle, Minus, Monitor, MoreHorizontal, Pencil, Plus, Trash2, Users } from "lucide-react";import { api, openBot, useStore, type Bot } from "@/state/store";+import { teamBotName, useTeamPeople } from "@/state/team-people";import { useShowThreads } from "@/lib/thread-preferences";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";@@ -41,12 +42,13 @@ function BotCard({ bot, selected, moving, connected, tagged = false, sent, onComconst { state, dispatch } = useStore();const showThreads = useShowThreads();const status = teamMapStatus(bot);+ const name = teamBotName(bot, useTeamPeople());const instance = state.instances.find((item) => item.instanceId === bot.modelSelection.instanceId);const model = instance?.models.options.find((item) => item.id === bot.modelSelection.model)?.label ?? bot.modelSelection.model;return <article className={cn("relative h-[126px] w-[236px] shrink-0 rounded-xl border bg-card shadow-sm transition-colors",selected ? "border-accent/60 ring-1 ring-accent/15" : connected ? "border-accent/40" : "border-hairline/50 hover:border-ink-secondary/40", tagged && "border-accent ring-4 ring-accent/25", moving && "opacity-35")}>{sent !== undefined && <span key={sent} data-sent-highlight aria-hidden className="pointer-events-none absolute -inset-px animate-sent-border rounded-xl border-2 border-accent" />}- <button data-bot-id={bot.id} aria-label={t("canvas.editBot", { name: bot.name })}+ <button data-bot-id={bot.id} aria-label={t("canvas.editBot", { name })}onClick={() => openBotSettings(dispatch, "identity", { botId: bot.id })}title={onArrange ? t("canvas.reorderHint") : undefined}onKeyDown={(event) => {@@ -57,7 +59,7 @@ function BotCard({ bot, selected, moving, connected, tagged = false, sent, onComclassName="flex h-[82px] w-full cursor-grab items-center gap-3 rounded-t-xl px-4 text-left active:cursor-grabbing focus-visible:outline-2 focus-visible:outline-accent"><BotAvatar bot={bot} size={38} motion="none" motionKey={0} animated={false} /><span className="min-w-0 flex-1">- <span className="flex items-center gap-1.5"><span className="truncate text-[14px] font-semibold">{bot.name}</span>+ <span className="flex items-center gap-1.5"><span className="truncate text-[14px] font-semibold">{name}</span>{bot.chiefOfStaff && <Crown size={12} className="shrink-0 text-warning" aria-label={t("chat.chiefOfStaff")} />}</span><span className="mt-1 block truncate text-[11px] text-ink-secondary">{bot.title || (bot.chiefOfStaff ? t("chat.chiefOfStaff") : t("canvas.bot"))}</span></span>diff --git a/src/components/TeamMapPage.tsx b/src/components/TeamMapPage.tsxindex 706df66deb..a6cd86ee6c 100644--- a/src/components/TeamMapPage.tsx+++ b/src/components/TeamMapPage.tsx@@ -25,6 +25,7 @@ import { t } from "@/lib/i18n";import { CanvasComputers } from "./CanvasComputers";import { useMapComputers, useShowComputers } from "@/lib/map-computers";import { MapComposer } from "./MapComposer";+import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";import { openBotSettings } from "./bot-panel/panel-link";import type { TeamComputer } from "../../shared/team-computer";@@ -270,6 +271,7 @@ export function TeamMapPage() {const { dragProps } = useCaptionChrome();const remoteClient = window.ogb?.remoteClient?.active === true;const teamPeople = useTeamPeople();+ const admin = useOwnerOrAdmin();const reportsChart = useMapMode() === "people" && teamPeople !== null;const [snapshot, setSnapshot] = useState<TeamMapSnapshot>(EMPTY_TEAM_MAP_SNAPSHOT);const [error, setError] = useState<string | null>(null);@@ -370,7 +372,7 @@ export function TeamMapPage() {{t("canvas.showComputers")}</button><button onClick={() => setComputersOpen((value) => !value)} aria-label={t("canvas.computers")} aria-expanded={computersOpen} className="rounded-lg p-2 text-ink-secondary hover:bg-control hover:text-ink"><Monitor size={17} /></button>- <details className="relative" onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget)) event.currentTarget.removeAttribute("open"); }} onKeyDown={(event) => {+ {admin !== false && <details className="relative" onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget)) event.currentTarget.removeAttribute("open"); }} onKeyDown={(event) => {if (event.key === "Escape") { event.currentTarget.removeAttribute("open"); event.currentTarget.querySelector("summary")?.focus(); }}}><summary aria-label={t("canvas.addToMap")} className="flex cursor-pointer list-none items-center gap-1.5 rounded-lg border border-hairline/60 bg-panel px-3 py-2 text-[12px] font-medium hover:bg-control [&::-webkit-details-marker]:hidden"><Plus size={14} /> {t("common.add")}</summary>@@ -381,7 +383,7 @@ export function TeamMapPage() {<button className="flex w-full items-center gap-2 rounded-lg px-3 py-2.5 text-left text-[12px] hover:bg-control" onClick={() => { setComputersOpen(true); setCreateComputerRequest((value) => value + 1); }}><Box size={14} />{t("canvas.cloudComputer")}</button>{placeOffered("vm", state.config) && <button className="flex w-full items-center gap-2 rounded-lg px-3 py-2.5 text-left text-[12px] hover:bg-control" onClick={() => dispatch({ type: "toggleAppSettings", section: "computer", open: true })}><Monitor size={14} />{t("canvas.localVm")}</button>}</div>- </details>+ </details>}</div>}</header>{(error || refreshError) && <div role="alert" className="flex shrink-0 items-center justify-between gap-3 border-b border-danger/20 bg-danger/10 px-6 py-2 text-[12px] text-danger">@@ -390,7 +392,7 @@ export function TeamMapPage() {</div>}<div className="relative flex min-h-0 flex-1"><div className="relative flex min-h-0 min-w-0 flex-1">- {reportsChart ? <TeamOrgChart bots={bots} /> : <TeamCanvas sections={sections} canManage={!remoteClient} onMove={requestMove} taggedBotIds={taggedBotIds} sent={sent} bottomInset={bots.length ? 96 : 0}+ {reportsChart ? <TeamOrgChart bots={bots} /> : <TeamCanvas sections={sections} canManage={!remoteClient && admin !== false} onMove={requestMove} taggedBotIds={taggedBotIds} sent={sent} bottomInset={bots.length ? 96 : 0}connectedBotIds={state.settingsOpen ? edges.flatMap((edge) => edge.sourceBotId === state.selectedId ? [edge.targetBotId] : edge.targetBotId === state.selectedId ? [edge.sourceBotId] : []) : []}onComputer={(bot) => openBotSettings(dispatch, "access", { botId: bot.id })}computers={showComputers && computersChoiceLoaded && !remoteClient ? mapComputers.computers : undefined} computerFrames={mapComputers.frames}diff --git a/src/components/TeamPrivateChatsLine.test.ts b/src/components/TeamPrivateChatsLine.test.tsindex 007ddfe9d7..e72154dbf3 100644--- a/src/components/TeamPrivateChatsLine.test.ts+++ b/src/components/TeamPrivateChatsLine.test.ts@@ -23,6 +23,14 @@ describe("who can see a team's private chat", () => {expect(renderToStaticMarkup(createElement(TeamSharedHeader, { team: { name: "Acme" } }))).toContain("Shared · everyone in Acme can see");});+ it("keeps the bot's name in view on a narrow header: the label gives way to its icon, never the name", () => {+ for (const html of [renderToStaticMarkup(createElement(TeamSharedHeader, { team: { name: "Acme" } })), renderToStaticMarkup(createElement(TeamPrivateHeader))]) {+ expect(html).not.toMatch(/^<span[^>]*\bshrink-0\b/);+ expect(html).toMatch(/^<span[^>]*title="[^"]+"[^>]*class="[^"]*\bmin-w-0\b/);+ expect(html).toMatch(/<span class="[^"]*@max-\[30rem\]\/chathead:sr-only[^"]*">/);+ }+ });+it("says the sentence in one private chat per team, then never again on this device", () => {const storage = memory();expect(teamPrivateChatsLineDue("acme", storage)).toBe(true);diff --git a/src/components/TeamPrivateChatsLine.tsx b/src/components/TeamPrivateChatsLine.tsxindex b3825f0160..68f887e8cf 100644--- a/src/components/TeamPrivateChatsLine.tsx+++ b/src/components/TeamPrivateChatsLine.tsx@@ -1,5 +1,5 @@-import { useState } from "react";-import { Lock, Users } from "lucide-react";+import { useState, type ReactNode } from "react";+import { Lock, UserRound, Users } from "lucide-react";import { t } from "@/lib/i18n";const SEEN_KEY = (teamId: string) => `omb.team-private-chats.${teamId}`;@@ -18,18 +18,26 @@ export function teamPrivateChatsLineDue(teamId: string, storage: Pick<Storage, "/** In every private chat with a team's bot, beside its name: who can see it. */export function TeamPrivateHeader() {- return <span data-chathead-private className="flex shrink-0 items-center gap-1 truncate text-[12px] text-ink-secondary">- <Lock size={12} aria-hidden="true" />{t("team.privateHeader")}- </span>;+ return <ChatHeadAudience icon={<Lock size={12} aria-hidden="true" className="shrink-0" />} label={t("team.privateHeader")} data-chathead-private="" />;}/** In a team bot's shared chats (its main chat, a routine's report): everyone in the team can read them. */export function TeamSharedHeader({ team }: { team: { name: string } }) {- return <span data-chathead-shared className="flex shrink-0 items-center gap-1 truncate text-[12px] text-ink-secondary">- <Users size={12} aria-hidden="true" />{t("team.sharedHeader", { team: team.name })}+ return <ChatHeadAudience icon={<Users size={12} aria-hidden="true" className="shrink-0" />} label={t("team.sharedHeader", { team: team.name })} data-chathead-shared="" />;+}++/** On a narrow header only the icon shows, so the bot's name keeps its room. */+function ChatHeadAudience({ icon, label, ...data }: { icon: ReactNode; label: string } & Record<`data-${string}`, string>) {+ return <span {...data} title={label} className="flex min-w-0 items-center gap-1 text-[12px] text-ink-secondary">+ {icon}<span className="truncate @max-[30rem]/chathead:sr-only">{label}</span></span>;}+/** In a member's own MausBot's chats: that member's helper, which other members never see. */+export function TeamOwnHelperHeader() {+ return <ChatHeadAudience icon={<UserRound size={12} aria-hidden="true" className="shrink-0" />} label={t("team.ownHelperHeader")} data-chathead-own-helper="" />;+}+/** Above the first private chat with any of the team's bots on this device, once: the same thing as a sentence. */export function TeamPrivateFirstLine({ team }: { team: { id: string; name: string } }) {const [due] = useState(() => teamPrivateChatsLineDue(team.id, typeof localStorage === "undefined" ? null : localStorage));diff --git a/src/components/bot-panel/LibraryTab.tsx b/src/components/bot-panel/LibraryTab.tsxindex 915c448f53..75aa2f98f2 100644--- a/src/components/bot-panel/LibraryTab.tsx+++ b/src/components/bot-panel/LibraryTab.tsx@@ -10,9 +10,9 @@ import { AttachedFileChip } from "../AttachmentPreview";import { recentChangedFiles, sharedFileReferences } from "../ComputerFilesPane";import { useDesktopCapabilities } from "../DesktopCapabilities";import { useManagedSkills } from "../bot-settings/SkillsSection";-import { memoryNotes } from "./memory-notes";import type { SimplePageId } from "./page-registry";import { Card, CardLabel, NavRow } from "./rows";+import { panelMemoryNotes } from "./memory-notes";import { useMemoryDoc } from "./use-memory-doc";export interface LibraryItems {@@ -62,7 +62,7 @@ export function LibraryTab({ bot, onOpen }: { bot: Bot; onOpen: (page: SimplePagif (phone) dispatch({ type: "toggleSettings", open: false });};const skillsOn = skills.skills.filter((skill) => skill.enabled).length;- const notes = memory.doc ? memoryNotes(memory.doc.text).length : null;+ const notes = memory.docs ? panelMemoryNotes(memory.docs).length : null;const memoryValue = bot.memoryEnabled === false ? t("botPanel.memory.off"): notes === null ? (memory.error ? t("botPanel.memory.nothingYet") : undefined): notes === 0 ? t("botPanel.memory.nothingYet")diff --git a/src/components/bot-panel/MemoryPage.team.test.ts b/src/components/bot-panel/MemoryPage.team.test.tsnew file mode 100644index 0000000000..9eeb3b265d--- /dev/null+++ b/src/components/bot-panel/MemoryPage.team.test.ts@@ -0,0 +1,71 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++import type { Bot } from "@/state/store";++const fixture = vi.hoisted(() => ({ team: true }));+vi.mock("@/state/store", async (importOriginal) => {+ const original = await importOriginal<typeof import("@/state/store")>();+ return { ...original, useStore: () => ({ state: { ...original.initialState, config: fixture.team ? { team: { id: "t", name: "Acme" } } : {} }, dispatch: vi.fn() }) };+});++const { MemoryPage } = await import("./pages");+const { LibraryTab } = await import("./LibraryTab");++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+const bot = { id: "scout", threadId: "t1", name: "Scout", title: "", description: "", notifications: true, color: "green", unread: false, messages: [],+ modelSelection: { instanceId: "x", model: "x" } } as unknown as Bot;+const files: Record<string, string> = {};+const calls: Array<[string, string]> = [];+const reply = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });+let host: HTMLDivElement;+let root: Root;++beforeEach(() => {+ fixture.team = true;+ calls.length = 0;+ Object.assign(files, { "MEMORY.md": "# Memory\n", "memory/food.md": "- Ada's favourite fruit is durian\n" });+ vi.stubGlobal("fetch", vi.fn(async (input: string, init?: RequestInit) => {+ const url = new URL(input, "http://x");+ const method = init?.method ?? "GET";+ calls.push([method, url.pathname]);+ if (!url.pathname.includes("/memory/mine")) return reply(403, { error: "forbidden: this session lacks the admin scope" });+ const path = url.searchParams.get("path") ?? (init?.body ? JSON.parse(String(init.body)).path : "MEMORY.md");+ if (url.pathname.endsWith("/mine")) return reply(200, { topics: Object.keys(files).filter((file) => file.startsWith("memory/")).map((file) => ({ path: file })) });+ if (method === "PUT") files[path] = JSON.parse(String(init!.body)).text;+ if (method === "DELETE") delete files[path];+ const text = files[path] ?? "";+ return reply(200, { path, text, hash: `h${text.length}`, exists: path in files, overview: {} });+ }));+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => {+ act(() => root.unmount());+ host.remove();+ vi.unstubAllGlobals();+});++const settle = () => act(async () => { for (let i = 0; i < 5; i += 1) await new Promise((resolve) => setTimeout(resolve, 0)); });++it("on a Team Cloud shows what the bot remembers about the person, from their own notes, and lets them forget it", async () => {+ await act(async () => root.render(createElement(MemoryPage, { bot, derived: {} as never })));+ await settle();+ expect(host.textContent).toContain("Ada's favourite fruit is durian");+ expect(host.textContent).not.toContain("Couldn't read the memory file");+ expect(calls.every(([, path]) => path.includes("/memory/mine"))).toBe(true);+ const forget = host.querySelector<HTMLButtonElement>("[data-memory-note] button")!;+ await act(async () => forget.click());+ await settle();+ expect(files["memory/food.md"]).toBe("");+ expect(host.textContent).not.toContain("durian");+});++it("counts those notes on the Library tab", async () => {+ await act(async () => root.render(createElement(LibraryTab, { bot, onOpen: () => {} })));+ await settle();+ expect(host.querySelector('[data-panel-page="memory"]')?.textContent).toContain("1 note");+});diff --git a/src/components/bot-panel/SettingsPage.tsx b/src/components/bot-panel/SettingsPage.tsxindex 72ab9909c8..f7ec5e6b3d 100644--- a/src/components/bot-panel/SettingsPage.tsx+++ b/src/components/bot-panel/SettingsPage.tsx@@ -37,7 +37,7 @@ export function SettingsPage({ bot, derived, onOpen, editingInstructions = falseeditingInstructions?: boolean;onEditInstructions?: (open: boolean) => void;}) {- const { dispatch } = useStore();+ const { dispatch, flushBotPatches } = useStore();const { capabilities, ready } = useDesktopCapabilities();const apps = useBotApps(bot);const approval = useThreadApproval(currentTaskBot(bot));@@ -93,7 +93,7 @@ export function SettingsPage({ bot, derived, onOpen, editingInstructions = false/>{editingInstructions && (<div className="flex justify-end">- <button type="button" data-panel-done="soul" onClick={() => onEditInstructions?.(false)} className={buttonCls}>+ <button type="button" data-panel-done="soul" onClick={() => { void flushBotPatches(bot.id); onEditInstructions?.(false); }} className={buttonCls}>{t("botSettings.simple.done")}</button></div>diff --git a/src/components/bot-panel/memory-notes.ts b/src/components/bot-panel/memory-notes.tsindex 4eaf491610..ba67e89964 100644--- a/src/components/bot-panel/memory-notes.ts+++ b/src/components/bot-panel/memory-notes.ts@@ -1,3 +1,5 @@+import { MEMORY_INDEX, type MemoryDoc } from "@/lib/memory";+/** The bullet lines of MEMORY.md, each with the line it sits on so one can be taken out again. */export interface MemoryNote {line: number;@@ -25,3 +27,19 @@ export function withMemoryNote(text: string, note: string): string {const bullet = `- ${note.trim().replace(/\s*\n\s*/g, " ")}`;return body ? `${body}\n${bullet}\n` : `${bullet}\n`;}++/** A note of one file: a bullet of it, or, for a topic file without bullets, the whole file (`line` null). */+export interface PanelMemoryNote {+ path: string;+ line: number | null;+ text: string;+}++export function panelMemoryNotes(docs: readonly MemoryDoc[]): PanelMemoryNote[] {+ return docs.flatMap((doc): PanelMemoryNote[] => {+ const bullets = memoryNotes(doc.text).map((note) => ({ path: doc.path, ...note }));+ if (bullets.length || doc.path === MEMORY_INDEX) return bullets;+ const text = doc.text.split("\n").map((line) => line.replace(/^#+\s*/, "").trim()).filter(Boolean).join(" ");+ return text ? [{ path: doc.path, line: null, text }] : [];+ });+}diff --git a/src/components/bot-panel/pages.tsx b/src/components/bot-panel/pages.tsxindex 2de9885874..1a6ddbfaba 100644--- a/src/components/bot-panel/pages.tsx+++ b/src/components/bot-panel/pages.tsx@@ -4,7 +4,7 @@ import { FolderOpen, Plus } from "lucide-react";import { appSwitchPatch } from "@/lib/bot-app-access";import { skillsLibraryEnabled } from "@/lib/feature-flags";import { t } from "@/lib/i18n";-import { MEMORY_INDEX, saveMemoryDoc } from "@/lib/memory";+import { deleteMemoryDoc, MEMORY_INDEX, saveMemoryDoc, type MemoryDoc } from "@/lib/memory";import { openExternalLink } from "@/lib/app-links";import type { Routine } from "@/lib/routines";import { shortPath } from "@/lib/short-path";@@ -21,7 +21,7 @@ import { RoutineList } from "../routines/RoutineList";import { BrowserLogins } from "./browser-logins";import { useOpenComputer, WherePage } from "./ComputerTab";import { SettingsPage } from "./SettingsPage";-import { memoryNotes, withMemoryNote, withoutMemoryNote } from "./memory-notes";+import { panelMemoryNotes, withMemoryNote, withoutMemoryNote, type PanelMemoryNote } from "./memory-notes";import type { SimplePageId } from "./page-registry";import { BotSwitch, buttonCls, Card, LinkRow, NoteRow, RadioRow, rowCls, SwitchRow, TextRow, TrashButton } from "./rows";import { useMemoryDoc } from "./use-memory-doc";@@ -126,29 +126,23 @@ export function RoutinesPage({ bot, derived }: PageContext) {);}-/** MEMORY.md's bullets. Every write goes through the memory file route with the hash it was read at, so a note the- * bot added meanwhile is never lost: a conflict re-reads and asks again. */+/** MEMORY.md's bullets, and on a Team Cloud the person's own notes. Every write goes through the memory file route with+ * the hash it was read at, so a note the bot added meanwhile is never lost: a conflict re-reads and asks again. */export function MemoryPage({ bot }: PageContext) {const memory = useMemoryDoc(bot);const [draft, setDraft] = useState("");const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);const memoryOn = bot.memoryEnabled !== false;- const notes = memory.doc ? memoryNotes(memory.doc.text) : null;+ const notes = memory.docs ? panelMemoryNotes(memory.docs) : null;+ const index = memory.docs?.find((doc) => doc.path === MEMORY_INDEX) ?? null;- const write = async (text: string) => {- if (!memory.doc || saving) return false;+ const change = async (save: () => Promise<boolean>) => {+ if (saving) return false;setSaving(true);setError(null);try {- const result = await saveMemoryDoc(bot.id, MEMORY_INDEX, text, memory.doc.exists ? memory.doc.hash : undefined);- if (result.ok) {- memory.setDoc(result.doc);- return true;- }- await memory.reload();- setError(t("memory.conflict.title", { name: bot.name }));- return false;+ return await save();} catch (cause) {setError(errorText(cause, t("botPanel.library.memoryError")));return false;@@ -156,10 +150,29 @@ export function MemoryPage({ bot }: PageContext) {setSaving(false);}};- const forget = (line: number) => { if (memory.doc) void write(withoutMemoryNote(memory.doc.text, line)); };+ const write = (doc: MemoryDoc, text: string) => change(async () => {+ const result = await saveMemoryDoc(bot.id, doc.path, text, doc.exists ? doc.hash : undefined, memory.mine);+ if (result.ok) {+ memory.setDoc(result.doc);+ return true;+ }+ await memory.reload();+ setError(t("memory.conflict.title", { name: bot.name }));+ return false;+ });+ const forget = (note: PanelMemoryNote) => {+ const doc = memory.docs?.find((candidate) => candidate.path === note.path);+ if (!doc) return;+ if (note.line !== null) void write(doc, withoutMemoryNote(doc.text, note.line));+ else void change(async () => {+ await deleteMemoryDoc(bot.id, doc.path, memory.mine);+ await memory.reload();+ return true;+ });+ };const add = async () => {- if (!memory.doc || !draft.trim()) return;- if (await write(withMemoryNote(memory.doc.text, draft))) setDraft("");+ if (!index || !draft.trim()) return;+ if (await write(index, withMemoryNote(index.text, draft))) setDraft("");};return (@@ -174,9 +187,9 @@ export function MemoryPage({ bot }: PageContext) {) : notes.length === 0 ? (<NoteRow>{t("botPanel.memory.empty")}</NoteRow>) : notes.map((note) => (- <div key={`${note.line}:${note.text}`} data-memory-note={note.line} className={rowCls}>+ <div key={`${note.path}:${note.line}:${note.text}`} data-memory-note={note.line ?? note.path} className={rowCls}><div className="min-w-0 flex-1 text-[13px] leading-[1.45] text-ink">{note.text}</div>- <TrashButton label={t("botPanel.memory.forget")} disabled={saving} onClick={() => forget(note.line)} />+ <TrashButton label={t("botPanel.memory.forget")} disabled={saving} onClick={() => forget(note)} /></div>))}{error && <NoteRow tone="warn">{error}</NoteRow>}@@ -189,7 +202,7 @@ export function MemoryPage({ bot }: PageContext) {placeholder={t("botPanel.memory.addPlaceholder", { name: bot.name })}label={t("botPanel.memory.addPlaceholder", { name: bot.name })}action={t("common.add")}- disabled={saving || memory.doc === null}+ disabled={saving || index === null}onChange={setDraft}onSubmit={() => void add()}/>diff --git a/src/components/bot-panel/use-memory-doc.ts b/src/components/bot-panel/use-memory-doc.tsindex 7c1a4517e3..77c500e2bc 100644--- a/src/components/bot-panel/use-memory-doc.ts+++ b/src/components/bot-panel/use-memory-doc.ts@@ -1,27 +1,37 @@import { useEffect, useState } from "react";-import { fetchMemoryDoc, MEMORY_INDEX, type MemoryDoc } from "@/lib/memory";-import type { Bot } from "@/state/store";+import { fetchMemoryDoc, fetchMemoryOverview, MEMORY_INDEX, type MemoryDoc } from "@/lib/memory";+import { useStore, type Bot } from "@/state/store";-export interface MemoryIndex {- doc: MemoryDoc | null;+export interface MemoryNotesState {+ /** MEMORY.md first; on a Team Cloud also the person's topic files. Null until read. */+ docs: MemoryDoc[] | null;error: boolean;+ /** On a Team Cloud the notes are the signed-in person's own layer. */+ mine: boolean;setDoc: (doc: MemoryDoc) => void;reload: () => Promise<void>;}-/** MEMORY.md for a bot whose memory is on; `doc` stays null until it has been read. It is read again as a turn starts and- * ends, so a note the bot just saved shows. */-export function useMemoryDoc(bot: Pick<Bot, "id" | "memoryEnabled" | "busy">): MemoryIndex {- const [state, setState] = useState<{ botId: string; doc: MemoryDoc | null; error: boolean }>({ botId: bot.id, doc: null, error: false });+async function readDocs(botId: string, mine: boolean): Promise<MemoryDoc[]> {+ if (!mine) return [await fetchMemoryDoc(botId, MEMORY_INDEX)];+ const overview = await fetchMemoryOverview(botId, true);+ return Promise.all([MEMORY_INDEX, ...overview.topics.map((topic) => topic.path)].map((path) => fetchMemoryDoc(botId, path, true)));+}++/** The notes the bot panel shows for a bot whose memory is on. They are read again as a turn starts and ends, so a note+ * the bot just saved shows. */+export function useMemoryDoc(bot: Pick<Bot, "id" | "memoryEnabled" | "busy">): MemoryNotesState {+ const mine = Boolean(useStore().state.config?.team);+ const [state, setState] = useState<{ botId: string; docs: MemoryDoc[] | null; error: boolean }>({ botId: bot.id, docs: null, error: false });const memoryOn = bot.memoryEnabled !== false;const read = async (botId: string, cancelled?: () => boolean) => {try {- const doc = await fetchMemoryDoc(botId, MEMORY_INDEX);- if (!cancelled?.()) setState({ botId, doc, error: false });+ const docs = await readDocs(botId, mine);+ if (!cancelled?.()) setState({ botId, docs, error: false });} catch {- if (!cancelled?.()) setState({ botId, doc: null, error: true });+ if (!cancelled?.()) setState({ botId, docs: null, error: true });}};@@ -31,13 +41,18 @@ export function useMemoryDoc(bot: Pick<Bot, "id" | "memoryEnabled" | "busy">): Mlet cancelled = false;void read(bot.id, () => cancelled);return () => { cancelled = true; };- }, [bot.id, memoryOn, busy]);+ }, [bot.id, memoryOn, busy, mine]);const own = state.botId === bot.id;return {- doc: own ? state.doc : null,+ docs: own ? state.docs : null,error: own && state.error,- setDoc: (doc) => setState({ botId: bot.id, doc, error: false }),+ mine,+ setDoc: (doc) => setState((current) => ({+ botId: bot.id,+ docs: (current.botId === bot.id ? current.docs ?? [] : []).map((existing) => existing.path === doc.path ? doc : existing),+ error: false,+ })),reload: () => read(bot.id),};}diff --git a/src/hooks/use-unread-divider.ts b/src/hooks/use-unread-divider.tsindex 5ddddb9572..86f0929a6a 100644--- a/src/hooks/use-unread-divider.ts+++ b/src/hooks/use-unread-divider.ts@@ -9,7 +9,8 @@ export function useUnreadDivider({ threadId, messages, following }: {following: boolean;}): { messageId: string | null; fading: boolean } {const { state, dispatch } = useStore();- const messageId = state.unreadDivider?.threadId === threadId ? state.unreadDivider.messageId : null;+ const divider = state.unreadDivider;+ const messageId = divider && divider.threadId === threadId ? divider.messageId : null;const newestOwnId = useMemo(() => {for (let i = messages.length - 1; i >= 0; i--) {if (messages[i]!.role === "user" && !peerLine(messages[i]!)) return messages[i]!.id;diff --git a/src/lib/admin-scope.test.ts b/src/lib/admin-scope.test.tsnew file mode 100644index 0000000000..c066b7818b--- /dev/null+++ b/src/lib/admin-scope.test.ts@@ -0,0 +1,46 @@+import { beforeEach, expect, it, vi } from "vitest";++const api = vi.hoisted(() => vi.fn());+vi.mock("@/state/store", async (importOriginal) => ({ ...await importOriginal<typeof import("@/state/store")>(), api }));++const refusal = () => Object.assign(new Error("forbidden: this session lacks the admin scope"), { status: 403 });++beforeEach(() => {+ vi.resetModules();+ api.mockReset();+});++it("stops asking for the engines' limits once the server says this session lacks the admin scope", async () => {+ api.mockRejectedValue(refusal());+ const { loadLimits } = await import("./limit-resets");+ await loadLimits();+ await loadLimits();+ await loadLimits(true);+ expect(api).toHaveBeenCalledTimes(1);+});++it("keeps asking after any other failure", async () => {+ api.mockRejectedValue(Object.assign(new Error("busy"), { status: 503 }));+ const { loadLimits } = await import("./limit-resets");+ await loadLimits();+ await loadLimits();+ expect(api).toHaveBeenCalledTimes(2);+});++it("asks for the connected apps once, and answers a refused session's later reads from that", async () => {+ api.mockRejectedValue(refusal());+ const { preloadConnectedApps } = await import("@/components/PluginsPanel");+ expect(await preloadConnectedApps()).toEqual({ services: {}, authoritative: true, refused: true });+ expect(await preloadConnectedApps(true)).toEqual({ services: {}, authoritative: true, refused: true });+ expect(api).toHaveBeenCalledTimes(1);+});++it("answers a refused route's later reads without asking, and leaves other routes alone", async () => {+ const { unlessRefused } = await import("./admin-scope");+ const request = vi.fn().mockRejectedValue(refusal());+ expect(await unlessRefused("/api/instances", request, null)).toBeNull();+ expect(await unlessRefused("/api/instances", request, null)).toBeNull();+ expect(request).toHaveBeenCalledTimes(1);+ expect(await unlessRefused("/api/live/call", async () => ({ call: null }), null)).toEqual({ call: null });+ await expect(unlessRefused("/api/live/call", async () => { throw new Error("offline"); }, null)).rejects.toThrow("offline");+});diff --git a/src/lib/admin-scope.ts b/src/lib/admin-scope.tsnew file mode 100644index 0000000000..3598f770ca--- /dev/null+++ b/src/lib/admin-scope.ts@@ -0,0 +1,19 @@+const refused = new Set<string>();++export function lacksAdminScope(cause: unknown): boolean {+ const error = Object(cause) as { status?: unknown; message?: unknown };+ return error.status === 403 && typeof error.message === "string" && error.message.includes("lacks the admin scope");+}++/** Asks for `route` until the server says this session lacks the admin scope; from then on answers `refusedAnswer`+ * without asking again. */+export async function unlessRefused<T>(route: string, request: () => Promise<T>, refusedAnswer: T): Promise<T> {+ if (refused.has(route)) return refusedAnswer;+ try {+ return await request();+ } catch (cause) {+ if (!lacksAdminScope(cause)) throw cause;+ refused.add(route);+ return refusedAnswer;+ }+}diff --git a/src/lib/composer-attachments.test.ts b/src/lib/composer-attachments.test.tsindex 2390d2a7d0..d7806acefc 100644--- a/src/lib/composer-attachments.test.ts+++ b/src/lib/composer-attachments.test.ts@@ -22,8 +22,24 @@ import {composerTakesFocusOnOpen,replyTargetTakesFocus,dataContextFor,+ discardUnsentUpload,} from "./composer-attachments";+describe("discardUnsentUpload", () => {+ it("asks the server to drop an uploaded file taken off the message, and nothing else", () => {+ const fetchMock = vi.fn(async () => new Response("{}"));+ vi.stubGlobal("fetch", fetchMock);+ try {+ discardUnsentUpload(fileAttachment("notes.txt", "/home/a/.openmausbot/attachments/0f1e2d3c-aaaa-4bbb-8ccc-123456789abc.txt", 3));+ discardUnsentUpload({ kind: "paste", id: "p", text: "hi", size: 2, lines: 1 });+ discardUnsentUpload({ kind: "image", id: "i", path: "", name: "x.png", size: 0, mime: "image/png", uploading: true });+ expect(fetchMock.mock.calls).toEqual([["/api/attachments/0f1e2d3c-aaaa-4bbb-8ccc-123456789abc.txt", { method: "DELETE" }]]);+ } finally {+ vi.unstubAllGlobals();+ }+ });+});+describe("the viewed Data result and the words", () => {it("rides as its own field of the send (shared/data-context.ts), so the transcript keeps every typed line", () => {expect(dataContextFor("Use last month", { botId: "pepper", threadId: "task", cardId: "c_1" }, { botId: "pepper", threadId: "task" })).toEqual({ cardId: "c_1" });diff --git a/src/lib/composer-attachments.ts b/src/lib/composer-attachments.tsindex 8fb557cad5..a44cae26c1 100644--- a/src/lib/composer-attachments.ts+++ b/src/lib/composer-attachments.ts@@ -647,6 +647,14 @@ export function splitAttachedImages(text: string): { display: string; images: streturn { display, images: images.map((image) => image.path) };}+/** A file uploaded for a message and taken off it before sending: the server keeps it only while a message uses it. */+export function discardUnsentUpload(attachment: Attachment): void {+ if ((attachment.kind !== "image" && attachment.kind !== "file") || !attachment.path) return;+ const name = attachmentBasename(attachment.path);+ if (!/^[A-Za-z0-9-]+\.[A-Za-z0-9]{1,10}$/.test(name)) return;+ void fetch(`/api/attachments/${encodeURIComponent(name)}`, { method: "DELETE" }).catch(() => undefined);+}+export function attachmentBasename(path: string): string {const parts = path.split(/[\\/]/);return parts[parts.length - 1] ?? "";diff --git a/src/lib/glass-surface.test.ts b/src/lib/glass-surface.test.tsindex e0bed1ab98..094f628a07 100644--- a/src/lib/glass-surface.test.ts+++ b/src/lib/glass-surface.test.ts@@ -95,7 +95,8 @@ describe("glass surface", () => {it("lets the Apps contents reflow inside the pop-up rather than overflow it", () => {const apps = readFileSync(join(src, "components", "PluginsPanel.tsx"), "utf8");expect(apps).toContain('data-apps-grid className="@container flex flex-col gap-7 pt-1"');- expect(apps).toContain("grid grid-cols-1 items-start gap-x-6 gap-y-1 @xl:grid-cols-2");+ const section = readFileSync(join(src, "components", "AppsSection.tsx"), "utf8");+ expect(section).toContain("grid grid-cols-1 items-start gap-x-6 gap-y-1 @xl:grid-cols-2");const mcp = readFileSync(join(src, "components", "McpServersPanel.tsx"), "utf8");expect(mcp).toContain('data-mcp-row className="flex flex-wrap items-center gap-3"');expect(mcp).toContain('data-mcp-row-actions className="ml-auto flex flex-wrap items-center justify-end gap-1"');diff --git a/src/lib/limit-resets.ts b/src/lib/limit-resets.tsindex c1f0075c0a..be55bdc7a9 100644--- a/src/lib/limit-resets.ts+++ b/src/lib/limit-resets.ts@@ -5,6 +5,7 @@ import { useEffect, useState } from "react";import { AFTER_RESET_MS, nearLimit, type EngineLimit, type EngineLimitsReport, type LimitResetSchedule } from "../../shared/limit-reset";import { t } from "@/lib/i18n";import type { Routine } from "@/lib/routines";+import { unlessRefused } from "@/lib/admin-scope";import { api } from "@/state/store";export { AFTER_RESET_MS, nearLimit, NEAR_LIMIT_PERCENT, isLimitResetSchedule, type EngineLimit, type LimitResetSchedule } from "../../shared/limit-reset";@@ -28,12 +29,15 @@ export function rememberLimits(next: Partial<EngineLimitsReport> | null | undefifor (const listener of listeners) listener(report);}+function readLimits(request: () => Promise<EngineLimitsReport>): Promise<void> {+ return unlessRefused("/api/limit-resets", request, null)+ .then((next) => { if (next) rememberLimits(next); }, () => undefined);+}+/** A person's refresh always asks again; a background read joins the one already on its way. */export function loadLimits(refresh = false): Promise<void> {- if (refresh) return api<EngineLimitsReport>("/api/limit-resets?refresh=1").then(rememberLimits, () => undefined);- loading ??= api<EngineLimitsReport>("/api/limit-resets", { background: true })- .then(rememberLimits, () => undefined)- .finally(() => { loading = null; });+ if (refresh) return readLimits(() => api<EngineLimitsReport>("/api/limit-resets?refresh=1"));+ loading ??= readLimits(() => api<EngineLimitsReport>("/api/limit-resets", { background: true })).finally(() => { loading = null; });return loading;}diff --git a/src/lib/memory.ts b/src/lib/memory.tsindex 5c8f9c7395..947559f5e1 100644--- a/src/lib/memory.ts+++ b/src/lib/memory.ts@@ -61,16 +61,19 @@ export type SaveResult =| { ok: true; doc: MemoryDoc; overview: MemoryOverview }| { ok: false; conflict: true; current: string; currentHash: string };-export function fetchMemoryOverview(botId: string): Promise<MemoryOverview> {- return api(`/api/bots/${botId}/memory`);+/** `mine`: on a Team Cloud, the signed-in person's own layer of the bot's memory rather than the team's. */+const memoryRoute = (botId: string, mine: boolean) => `/api/bots/${botId}/memory${mine ? "/mine" : ""}`;++export function fetchMemoryOverview(botId: string, mine = false): Promise<MemoryOverview> {+ return api(memoryRoute(botId, mine));}-export function fetchMemoryDoc(botId: string, path: string): Promise<MemoryDoc> {- return api(`/api/bots/${botId}/memory/file?path=${encodeURIComponent(path)}`);+export function fetchMemoryDoc(botId: string, path: string, mine = false): Promise<MemoryDoc> {+ return api(`${memoryRoute(botId, mine)}/file?path=${encodeURIComponent(path)}`);}-export async function saveMemoryDoc(botId: string, path: string, text: string, expectedHash: string | undefined): Promise<SaveResult> {- const response = await fetch(`/api/bots/${botId}/memory/file`, {+export async function saveMemoryDoc(botId: string, path: string, text: string, expectedHash: string | undefined, mine = false): Promise<SaveResult> {+ const response = await fetch(`${memoryRoute(botId, mine)}/file`, {method: "PUT",headers: { "content-type": "application/json" },body: JSON.stringify({ path, text, expectedHash }),@@ -84,8 +87,8 @@ export async function saveMemoryDoc(botId: string, path: string, text: string, ereturn { ok: true, doc: { path: saved.path, text: saved.text, hash: saved.hash, exists: saved.exists }, overview: saved.overview };}-export function deleteMemoryDoc(botId: string, path: string): Promise<{ overview: MemoryOverview }> {- return api(`/api/bots/${botId}/memory/file?path=${encodeURIComponent(path)}`, { method: "DELETE" });+export function deleteMemoryDoc(botId: string, path: string, mine = false): Promise<{ overview: MemoryOverview }> {+ return api(`${memoryRoute(botId, mine)}/file?path=${encodeURIComponent(path)}`, { method: "DELETE" });}export async function fetchMemoryJournal(botId: string, limit = 50): Promise<MemoryJournalRow[]> {diff --git a/src/lib/session-ended.test.ts b/src/lib/session-ended.test.tsnew file mode 100644index 0000000000..d244853438--- /dev/null+++ b/src/lib/session-ended.test.ts@@ -0,0 +1,32 @@+import { afterEach, expect, it, vi } from "vitest";++afterEach(() => { vi.unstubAllGlobals(); vi.resetModules(); });++async function refusedWith(sessionStatus: number) {+ vi.stubGlobal("window", {});+ vi.stubGlobal("fetch", vi.fn<typeof fetch>(async (path) => path === "/api/auth/session"+ ? new Response(JSON.stringify(sessionStatus === 200 ? { kind: "session", id: "s", scopes: ["client"] } : { error: "forbidden: this request came through a proxy (pair this device to use the server remotely)" }), { status: sessionStatus })+ : new Response(JSON.stringify({ error: "forbidden: this request came through a proxy (pair this device to use the server remotely)" }), { status: 403 })));+ const { api } = await import("@/state/api");+ const { sessionEnded, sessionCheck } = await import("./session-ended");+ await api("/api/notifications", { background: true }).catch(() => {});+ await sessionCheck();+ return sessionEnded();+}++it("learns that the session ended when the server refuses a request and no longer knows this device", async () => {+ expect(await refusedWith(403)).toBe(true);+});++it("stays signed in when only one request was refused", async () => {+ expect(await refusedWith(200)).toBe(false);+});++it("asks nothing when a request was refused only for lacking the admin scope", async () => {+ const requests = vi.fn<typeof fetch>(async () => new Response(JSON.stringify({ error: "forbidden: this session lacks the admin scope" }), { status: 403 }));+ vi.stubGlobal("window", {});+ vi.stubGlobal("fetch", requests);+ const { api } = await import("@/state/api");+ await api("/api/instances", { background: true }).catch(() => {});+ expect(requests.mock.calls.map(([path]) => path)).toEqual(["/api/instances"]);+});diff --git a/src/lib/session-ended.ts b/src/lib/session-ended.tsnew file mode 100644index 0000000000..26fdd30f44--- /dev/null+++ b/src/lib/session-ended.ts@@ -0,0 +1,45 @@+import { useSyncExternalStore } from "react";+import { readSessionState } from "./session";++export const SESSION_ENDED_REASON = "Your session ended. Pair this device again to keep using it.";+const ENDED_KEY = "omb.session-ended";++let ended = false;+let checking: Promise<void> | null = null;+const listeners = new Set<() => void>();++/** A request was refused (401/403): asks the server once whether this device is still signed in. */+export function noteRefusedRequest(): void {+ if (ended || checking) return;+ checking = readSessionState().then((state) => {+ if (state.kind !== "unauthenticated") return;+ ended = true;+ try { sessionStorage.setItem(ENDED_KEY, "1"); } catch { }+ for (const listener of listeners) listener();+ }).finally(() => { checking = null; });+}++/** The check a refused request started, if one is running. */+export function sessionCheck(): Promise<void> {+ return checking ?? Promise.resolve();+}++export function sessionEnded(): boolean {+ return ended;+}++export function useSessionEnded(): boolean {+ return useSyncExternalStore((listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ }, sessionEnded, sessionEnded);+}++/** This tab saw its session end before it reloaded: the pairing page says so. */+export function endedBeforeReload(): boolean {+ try { return sessionStorage.getItem(ENDED_KEY) === "1"; } catch { return false; }+}++export function forgetEndedSession(): void {+ try { sessionStorage.removeItem(ENDED_KEY); } catch { }+}diff --git a/src/lib/session.ts b/src/lib/session.tsindex 9eea70ccf4..5ff8b2ddc2 100644--- a/src/lib/session.ts+++ b/src/lib/session.ts@@ -3,7 +3,7 @@ export interface EnvironmentDescriptor {label: string;platform: string;version: string;- capabilities: { remoteSessions: true; selfUpdate: "desktop-managed" | "operator"; emailSignIn?: boolean; sharedComputers?: true; cloudHome?: true };+ capabilities: { remoteSessions: true; selfUpdate: "desktop-managed" | "operator"; emailSignIn?: boolean; sharedComputers?: true; cloudHome?: true; cloudTeam?: true };}/** A Team Cloud's session: the team and this person's role in it (owner, admin or member). */diff --git a/src/lib/stop-turn.ts b/src/lib/stop-turn.tsindex b606fb4c5e..b080350a3e 100644--- a/src/lib/stop-turn.ts+++ b/src/lib/stop-turn.ts@@ -5,12 +5,15 @@import { useSyncExternalStore } from "react";import type { RuntimeEvent } from "../../shared/runtime-events";+import { isCancelledTranscriptRow } from "../../shared/client-cancel";+import type { Message } from "@/state/store";export const STOP_REPEAT_MS = 1_000;const liveTurns = new Map<string, string>();const turnStarts = new Map<string, number>();const lastStops = new Map<string, number>();+const stopsHere = new Map<string, number>();const watchers = new Set<() => void>();const notify = () => { for (const watch of Array.from(watchers)) watch(); };const subscribe = (watch: () => void) => {@@ -50,6 +53,7 @@ export function useLiveTurn(threadId: string): string | undefined {export function forgetStops(): void {forgetLiveTurns();lastStops.clear();+ stopsHere.clear();turnStarts.clear();}@@ -69,6 +73,10 @@ export function sendStop(api: Api, action: StopAction, showError: (error: unknow}).then((result) => {// That turn was over: this client missed its end. Name none next time, so the next press reaches what runs.const over = (result as { outcome?: unknown } | null)?.outcome === "already-stopped";+ if (!over && action.threadId) {+ stopsHere.set(action.threadId, now);+ notify();+ }if (over && action.threadId && liveTurns.get(action.threadId) === turnId) {liveTurns.delete(action.threadId);notify();@@ -80,3 +88,17 @@ export function sendStop(api: Api, action: StopAction, showError: (error: unknowaction.onError?.();});}++/** When this client's Stop last reached a turn in the thread. */+export function useStoppedAt(threadId: string): number | undefined {+ return useSyncExternalStore(subscribe, () => stopsHere.get(threadId), () => undefined);+}++/** A Stop from here ended the turn on the newest message, and nothing came after it: not an answer, not the server's+ * own stopped row. */+export function stopNoticeDue(messages: readonly Message[], stoppedAt: number | undefined, busy: boolean): boolean {+ if (busy || stoppedAt === undefined) return false;+ const asked = messages.findLastIndex((message) => message.role === "user");+ if (asked < 0 || messages[asked]!.at > stoppedAt) return false;+ return !messages.slice(asked + 1).some((message) => message.kind === "text" || isCancelledTranscriptRow(message));+}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 3f1fc14c85..e36705e8e8 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -1679,6 +1679,7 @@"sidebar.bot.makeChief": "Make Chief of Staff","sidebar.bot.removeChief": "Remove Chief of Staff","sidebar.bot.chiefNeedsEngine": "Choose Claude or an ACP model provider first",+ "sidebar.bot.chiefAdminOnly": "Only an admin of this installation can choose the Chief of Staff.","sidebar.bot.chiefOfStaff": "Chief of Staff","sidebar.bot.modelBadge": "Model: {model} ({engine})","sidebar.bot.moveToSection": "Move to department",@@ -3097,6 +3098,8 @@"settings.profiles.newName": "New profile name","settings.profiles.create": "Create profile","settings.profiles.limit": "You can keep up to 20 shared profiles.",+ "settings.adminOnly.change": "Only an admin of this installation can change this.",+ "settings.adminOnly.usage": "Only an admin of this installation can see usage.","settings.profiles.ownerOnly": "Only an admin of this installation can manage browser profiles.","settings.profiles.refreshError": "Could not refresh browser profiles. Reload this page before trying again.","settings.profiles.removed": "This profile was removed. Choose another browser profile.",@@ -5001,6 +5004,7 @@"connectors.updateKey": "Update your connected apps key","connectors.featuredAfter": "for the full catalog.","connectors.loadingCatalog": "Loading catalog…",+ "connectors.adminOnly": "Only an admin of this installation can connect apps here.","connectors.section.yours": "Your connections","connectors.section.results": "Search results","connectors.section.available": "Available apps",@@ -6730,6 +6734,9 @@"team.privateChats": "Your chats in {team} are private. Only you can see them: not other members, not {team}'s admins.","team.privateHeader": "Private · only you","team.sharedHeader": "Shared · everyone in {team} can see",+ "liveConnection.reconnecting": "Reconnecting… New replies show up once the connection is back.",+ "liveConnection.offline": "You're offline. New replies show up once you're back online.",+ "team.ownHelperHeader": "Own helper · other members can't see it","chat.page.usage": "{pages} of {limit} pages","chat.page.copyLink": "Copy link","chat.page.copied": "Copied",diff --git a/src/main.tsx b/src/main.tsxindex 90f3ef816d..2621c72859 100644--- a/src/main.tsx+++ b/src/main.tsx@@ -12,6 +12,7 @@ import { settleAdvancedModeDefault } from "./lib/interface-mode";import { BrowserSignInPage } from "./pair/BrowserSignInPage";import { PairPage } from "./pair/PairPage";import { HomeScreen, SignedOutAtHome } from "./components/HomeScreen";+import { endedBeforeReload, forgetEndedSession, SESSION_ENDED_REASON } from "./lib/session-ended";import "./styles.css";// Before first paint; settleAdvancedModeDefault must run before applySkin writes omb-skin.@@ -39,9 +40,10 @@ async function chooseRoot(): Promise<React.ReactNode> {}const session = await readSessionState();if (session.kind === "unauthenticated") {- const pair = <PairPage initialCode={null} reason={session.error} />;+ const pair = <PairPage initialCode={null} reason={endedBeforeReload() ? SESSION_ENDED_REASON : session.error} />;return home ? <SignedOutAtHome bridge={home} fallback={pair} /> : pair;}+ forgetEndedSession();if (session.kind === "loopback" && session.trust === "service") return <PairPage initialCode={null} reason={SERVICE_TRUST_REASON} />;if (location.pathname === "/desktop-viewer") {const { DesktopViewer } = await import("./components/DesktopViewer");diff --git a/src/pair/PairPage.test.ts b/src/pair/PairPage.test.tsindex 5cd9787f45..b9af83d0fe 100644--- a/src/pair/PairPage.test.ts+++ b/src/pair/PairPage.test.ts@@ -6,7 +6,7 @@ const f = vi.hoisted(() => ({ effects: [] as EffectCallback[], pair: vi.fn() }))vi.mock("react", async original => ({ ...await original<typeof import("react")>(), useEffect: (effect: EffectCallback) => { f.effects.push(effect); } }));vi.mock("../lib/session", async original => ({ ...await original<typeof import("../lib/session")>(), pairWithCode: f.pair, readSessionState: vi.fn().mockResolvedValue({ kind: "unauthenticated", error: "" }) }));vi.mock("../components/DesktopWorkspaceSwitcher", () => ({ DesktopWorkspaceSwitcher: () => null }));-import { PairPage, pairIntro, pairsAutomatically } from "./PairPage";+import { PairPage, pairIntro, pairsAutomatically, pairTitle } from "./PairPage";import en from "../locales/en.json";const code = "ABCD-EFGH-JK23";@@ -60,3 +60,11 @@ it("My Cloud says where its connection starts, never 'the code shown on the servexpect(pairIntro({ mode: "code", sent: false, email: "", cloudHome: false })).toContain("shown on the server");expect(pairIntro({ mode: "email", sent: true, email: "[email protected]", cloudHome: false })).toContain("[email protected]");});++it("a team's Cloud is called by the team's name, a person's own Cloud My Cloud", () => {+ const descriptor = (capabilities: Record<string, unknown>) => ({ environmentId: "e", label: "Acme Labs", platform: "linux", version: "1", capabilities: { remoteSessions: true as const, selfUpdate: "operator" as const, ...capabilities } });+ expect(pairTitle(descriptor({ cloudHome: true, cloudTeam: true }), "code")).toBe("Acme Labs");+ expect(pairTitle(descriptor({ cloudHome: true }), "code")).toBe("My Cloud");+ expect(pairTitle(descriptor({}), "email")).toBe("Sign in to Acme Labs");+ expect(pairTitle(null, "code")).toBe("Connect to this MausBot");+});diff --git a/src/pair/PairPage.tsx b/src/pair/PairPage.tsxindex 7a9305ba48..6067df1b0e 100644--- a/src/pair/PairPage.tsx+++ b/src/pair/PairPage.tsx@@ -31,6 +31,12 @@ export function pairIntro({ mode, sent, email, cloudHome }: { mode: "email" | "creturn "Enter the pairing code shown on the server. Codes work once and expire after five minutes.";}+export function pairTitle(environment: EnvironmentDescriptor | null, mode: "email" | "code" | null): string {+ if (environment?.capabilities.cloudTeam) return environment.label;+ if (environment?.capabilities.cloudHome) return "My Cloud";+ return `${mode === "email" ? "Sign in to" : "Connect to"} ${environment?.label ?? `this ${productName()}`}`;+}+export function PairPage({ initialCode, initialEmail = null, reason }: { initialCode: string | null; initialEmail?: string | null; reason?: string }) {const [code, setCode] = useState(initialCode ?? "");const [label, setLabel] = useState(defaultDeviceLabel());@@ -118,7 +124,7 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initial{opening ? (<p role="status" className="text-[20px] font-semibold">{cloudHome ? "Opening the Cloud…" : `Connecting to ${environment?.label ?? `this ${productName()}`}…`}</p>) : <>- <h1 className="text-[20px] font-semibold">{cloudHome ? "My Cloud" : `${mode === "email" ? "Sign in to" : "Connect to"} ${environment?.label ?? `this ${productName()}`}`}</h1>+ <h1 className="text-[20px] font-semibold">{pairTitle(environment, mode)}</h1><p className="mt-1.5 text-[14px] leading-relaxed text-ink-secondary">{environment && !cloudHome ? `Version ${environment.version} on ${environment.platform}. ` : ""}{pairIntro({ mode, sent, email, cloudHome })}diff --git a/src/state/api.ts b/src/state/api.tsindex 9d734655ce..a667320a26 100644--- a/src/state/api.ts+++ b/src/state/api.ts@@ -1,6 +1,8 @@// The renderer's JSON request helper. A Cloud home that went to sleep is never woken by a background poll// (src/lib/cloud-power.ts), and a page out of sight sends none at all.import { asleepAnswer, BACKGROUND_HEADER, cloudAsleep, markCloudAsleep, markCloudAwake, pageHidden, pageShown } from "../lib/cloud-power";+import { lacksAdminScope } from "../lib/admin-scope";+import { noteRefusedRequest } from "../lib/session-ended";export class ApiError extends Error {readonly status: number;@@ -44,7 +46,9 @@ export async function api<T = any>(path: string, init?: ApiInit): Promise<T> {if (!res.ok) {const error = body?.error;const message = typeof error === "string" ? error : typeof error?.message === "string" ? error.message : `${res.status} ${res.statusText}`;- throw new ApiError(message, res.status, body);+ const refused = new ApiError(message, res.status, body);+ if (res.status === 401 || (res.status === 403 && !lacksAdminScope(refused))) noteRefusedRequest();+ throw refused;}return body;}diff --git a/src/state/bot-patch-queue.test.ts b/src/state/bot-patch-queue.test.tsindex 459f6d80e0..2e3c50c6f3 100644--- a/src/state/bot-patch-queue.test.ts+++ b/src/state/bot-patch-queue.test.ts@@ -53,6 +53,7 @@ describe("bot patch queue", () => {{ approvalMode: "ask" },expect.any(AbortSignal),expect.objectContaining({ approvalMode: "auto" }),+ false,);await queue.flush("bot-1");@@ -67,6 +68,7 @@ describe("bot patch queue", () => {{ modelSelection: { instanceId: "codex", model: "gpt-5.6-sol" } },expect.any(AbortSignal),expect.objectContaining({ id: "bot-1" }),+ false,);await queue.flush("bot-1");@@ -81,6 +83,7 @@ describe("bot patch queue", () => {{ connectorTools: { gmail: { tools: ["GMAIL_SEND_EMAIL"] } } },expect.any(AbortSignal),expect.objectContaining({ id: "bot-1" }),+ false,);});diff --git a/src/state/bot-patch-queue.ts b/src/state/bot-patch-queue.tsindex 77a456ef51..441c077a2f 100644--- a/src/state/bot-patch-queue.ts+++ b/src/state/bot-patch-queue.ts@@ -88,6 +88,7 @@ export interface BotPatchQueueOptions {patch: BotUpdatePatch,signal: AbortSignal,current: BotAnnouncement,+ leaving: boolean,) => Promise<BotAnnouncement>;reconcile: (botId: string, signal: AbortSignal) => Promise<BotAnnouncement | null>;onAuthoritative: (bot: BotAnnouncement, optimisticOverlay: BotStatePatch) => void;@@ -97,6 +98,8 @@ export interface BotPatchQueueOptions {export interface BotPatchQueue {enqueue: (botId: string, patch: BotUpdatePatch, fallback: BotAnnouncement) => void;flush: (botId: string) => Promise<BotAnnouncement | null>;+ /** Sends every edit still waiting out its pause now: the page is going away. */+ flushAll: () => void;overlayFor: (botId: string) => BotStatePatch;cancel: (botId: string) => void;/** Undo a dispose: StrictMode's dev mount probe runs the cleanup once against the same memoized queue. */@@ -148,7 +151,7 @@ export function createBotPatchQueue(options: BotPatchQueueOptions): BotPatchQueufor (const resolve of entry.idleWaiters.splice(0)) resolve(entry.fallback);};- const drain = async (entry: BotPatchQueueEntry): Promise<void> => {+ const drain = async (entry: BotPatchQueueEntry, leaving = false): Promise<void> => {if (disposed || entry.running || entry.timer !== null || !hasFields(entry.pending)) return;entry.running = true;const patch = entry.pending;@@ -158,7 +161,7 @@ export function createBotPatchQueue(options: BotPatchQueueOptions): BotPatchQueuentry.controller = controller;try {- const bot = await options.send(entry.botId, patch, controller.signal, entry.fallback);+ const bot = await options.send(entry.botId, patch, controller.signal, entry.fallback, leaving);if (disposed || entry.cancelled) return;entry.fallback = bot;options.onAuthoritative(bot, stateOverlay(entry.pending));@@ -253,6 +256,15 @@ export function createBotPatchQueue(options: BotPatchQueueOptions): BotPatchQueureturn idle;},+ flushAll() {+ for (const entry of entries.values()) {+ if (entry.timer === null) continue;+ clearTimeout(entry.timer);+ entry.timer = null;+ void drain(entry, true);+ }+ },+overlayFor(botId) {const entry = entries.get(botId);return entry ? stateOverlay({ ...entry.inFlight, ...entry.pending }) : {};@@ -284,3 +296,17 @@ export function createBotPatchQueue(options: BotPatchQueueOptions): BotPatchQueu},};}++/** Browsers cancel an ordinary request when the page reloads; a keepalive one still arrives, if its body is under 64 KiB. */+export const keepaliveFits = (body: string) => new TextEncoder().encode(body).length < 60_000;++/** Saves every edit still waiting at once (`flushAll`) when the page is left; returns the listeners' removal. */+export function flushWhenLeaving(queue: Pick<BotPatchQueue, "flushAll">, target: Pick<Window, "addEventListener" | "removeEventListener">): () => void {+ const leaving = () => queue.flushAll();+ target.addEventListener("pagehide", leaving);+ target.addEventListener("beforeunload", leaving);+ return () => {+ target.removeEventListener("pagehide", leaving);+ target.removeEventListener("beforeunload", leaving);+ };+}diff --git a/src/state/bot-patch-unload.test.ts b/src/state/bot-patch-unload.test.tsnew file mode 100644index 0000000000..77df0f4b9c--- /dev/null+++ b/src/state/bot-patch-unload.test.ts@@ -0,0 +1,53 @@+// @vitest-environment happy-dom+import { act, createElement, type Dispatch } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, expect, it, vi } from "vitest";+import { initialState, StoreProvider, useStore, type Action, type BotAnnouncement } from "./store";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const bot: BotAnnouncement = {+ id: "bot", threadId: "thread", name: "Chaos", title: "", description: "", notifications: true, unread: false, color: "green",+ modelSelection: { instanceId: "fake", model: "m" }, tasks: [],+};+afterEach(() => { initialState.bots = []; vi.useRealTimers(); vi.unstubAllGlobals(); });++it("saves an Instructions edit at once when the page is left before the save's pause ends", async () => {+ vi.useFakeTimers();+ initialState.bots = [{ ...bot, messages: [] }];+ const patches: string[] = [];+ vi.stubGlobal("fetch", vi.fn<typeof fetch>(async (path, init) => {+ if (path === "/api/bots/bot" && init?.method === "PATCH") patches.push(String(init.body));+ return new Response(JSON.stringify(path === "/api/bots/bot" ? { bot } : {}));+ }));+ let dispatch!: Dispatch<Action>;+ function Capture() { dispatch = useStore().dispatch; return null; }+ const root = createRoot(document.createElement("div"));+ await act(async () => root.render(createElement(StoreProvider, null, createElement(Capture))));+ act(() => dispatch({ type: "updateBot", botId: "bot", patch: { soul: "chaos instructions v3." } }));+ window.dispatchEvent(new Event("pagehide"));+ await act(async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); });+ expect(patches.map((body) => JSON.parse(body).soul)).toEqual(["chaos instructions v3."]);+ act(() => root.unmount());+});++it("sends only the leaving page's save as keepalive, so ordinary saves never use up the browser's keepalive budget", async () => {+ vi.useFakeTimers();+ initialState.bots = [{ ...bot, messages: [] }];+ const keepalive: Array<boolean | undefined> = [];+ vi.stubGlobal("fetch", vi.fn<typeof fetch>(async (path, init) => {+ if (path === "/api/bots/bot" && init?.method === "PATCH") keepalive.push(init.keepalive);+ return new Response(JSON.stringify(path === "/api/bots/bot" ? { bot } : {}));+ }));+ let dispatch!: Dispatch<Action>;+ function Capture() { dispatch = useStore().dispatch; return null; }+ const root = createRoot(document.createElement("div"));+ await act(async () => root.render(createElement(StoreProvider, null, createElement(Capture))));+ act(() => dispatch({ type: "updateBot", botId: "bot", patch: { soul: "v1" } }));+ await act(async () => { await vi.advanceTimersByTimeAsync(450); });+ act(() => dispatch({ type: "updateBot", botId: "bot", patch: { soul: "v2" } }));+ window.dispatchEvent(new Event("pagehide"));+ await act(async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); });+ expect(keepalive.map(Boolean)).toEqual([false, true]);+ act(() => root.unmount());+});diff --git a/src/state/live-call.ts b/src/state/live-call.tsnew file mode 100644index 0000000000..cb04ab5541--- /dev/null+++ b/src/state/live-call.ts@@ -0,0 +1,22 @@+// The live call line as the server reports it (GET /api/live/call and the stream's frames), and the order of the app's+// lookups of it (both re-exported by store.tsx).+import type { LiveCallState } from "../../shared/wire";++/** A missing `call` key is malformed, never "the line is free". */+export function liveCallFromFrame(frame: unknown): { call: LiveCallState | null } | null {+ if (!frame || typeof frame !== "object" || !Object.prototype.hasOwnProperty.call(frame, "call")) return null;+ const call: unknown = Reflect.get(frame, "call");+ if (call === null) return { call: null };+ if (!call || typeof call !== "object") return null;+ const record = call as Record<string, unknown>;+ if (typeof record.callId !== "string" || typeof record.botId !== "string" || typeof record.threadId !== "string" || typeof record.status !== "string") {+ return null;+ }+ return { call: call as LiveCallState };+}++let liveCallLookups = 0;+export function nextLiveCallLookup(): number {+ liveCallLookups += 1;+ return liveCallLookups;+}diff --git a/src/state/lost-send.test.ts b/src/state/lost-send.test.tsnew file mode 100644index 0000000000..443c1e02ad--- /dev/null+++ b/src/state/lost-send.test.ts@@ -0,0 +1,46 @@+import { createElement, type Dispatch } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { afterEach, expect, it, vi } from "vitest";+import { initialState, StoreProvider, useStore, type Action } from "./store";++const SEND = "/api/bots/bot/messages";+const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve(); };+const response = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status });++function mount(request: typeof fetch) {+ vi.useFakeTimers();+ vi.stubGlobal("fetch", request);+ vi.stubGlobal("window", {});+ let dispatch!: Dispatch<Action>;+ function Capture() { dispatch = useStore().dispatch; return null; }+ renderToStaticMarkup(createElement(StoreProvider, null, createElement(Capture)));+ return (onError: () => void) => dispatch({ type: "send", botId: "bot", threadId: "thread", text: "say ok6", sendId: "send-0123456789abcdef", onError });+}+afterEach(() => { initialState.bots = []; vi.clearAllTimers(); vi.useRealTimers(); vi.unstubAllGlobals(); });++it("asks again with the same sendId when a send's answer is lost, and never gives a delivered message back", async () => {+ const bodies: string[] = [];+ const requests = vi.fn<typeof fetch>(async (path, init) => {+ if (path !== SEND) return response({});+ bodies.push(String(init?.body));+ if (bodies.length === 1) throw new TypeError("Failed to fetch");+ return response({ threadId: "thread", message: { id: "m1", role: "user", kind: "text", text: "say ok6", at: 1, sendId: "send-0123456789abcdef" } }, 202);+ });+ const onError = vi.fn();+ mount(requests)(onError);+ await flush();+ await vi.advanceTimersByTimeAsync(5_000);+ await flush();+ expect(bodies).toHaveLength(2);+ expect(JSON.parse(bodies[1]!).sendId).toBe(JSON.parse(bodies[0]!).sendId);+ expect(onError).not.toHaveBeenCalled();+});++it("still gives the draft back when the server refuses the send", async () => {+ const requests = vi.fn<typeof fetch>(async (path) => path === SEND ? response({ error: "no" }, 409) : response({}));+ const onError = vi.fn();+ mount(requests)(onError);+ await flush();+ expect(requests.mock.calls.filter(([path]) => path === SEND)).toHaveLength(1);+ expect(onError).toHaveBeenCalledOnce();+});diff --git a/src/state/new-task-once.test.ts b/src/state/new-task-once.test.tsnew file mode 100644index 0000000000..4a2ea1dd2c--- /dev/null+++ b/src/state/new-task-once.test.ts@@ -0,0 +1,69 @@+import { createElement, type Dispatch } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { afterEach, expect, it, vi } from "vitest";+import { initialState, StoreProvider, useStore, type Action } from "./store";++const CREATE = "/api/bots/bot/tasks";+const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve(); };+afterEach(() => { initialState.bots = []; vi.unstubAllGlobals(); });++it("makes one conversation for a double or triple click on New conversation", async () => {+ let answer!: () => void;+ const requests = vi.fn<typeof fetch>(async (path) => {+ if (path !== CREATE) return new Response("{}");+ await new Promise<void>((resolve) => { answer = resolve; });+ return new Response(JSON.stringify({ bot: { id: "bot", threadId: "new" } }), { status: 201 });+ });+ vi.stubGlobal("fetch", requests);+ vi.stubGlobal("window", {});+ let dispatch!: Dispatch<Action>;+ function Capture() { dispatch = useStore().dispatch; return null; }+ renderToStaticMarkup(createElement(StoreProvider, null, createElement(Capture)));+ for (let click = 0; click < 3; click++) dispatch({ type: "newTask", botId: "bot" });+ await flush();+ expect(requests.mock.calls.filter(([path]) => path === CREATE)).toHaveLength(1);+ answer();+ await flush();+ dispatch({ type: "newTask", botId: "bot" });+ await flush();+ expect(requests.mock.calls.filter(([path]) => path === CREATE)).toHaveLength(2);+});++it("answers every click's callbacks with the one conversation's outcome", async () => {+ let fail!: () => void;+ vi.stubGlobal("fetch", vi.fn<typeof fetch>(async (path) => {+ if (path !== CREATE) return new Response("{}");+ await new Promise<void>((resolve) => { fail = resolve; });+ return new Response(JSON.stringify({ error: "no room for another" }), { status: 409 });+ }));+ vi.stubGlobal("window", {});+ let dispatch!: Dispatch<Action>;+ function Capture() { dispatch = useStore().dispatch; return null; }+ renderToStaticMarkup(createElement(StoreProvider, null, createElement(Capture)));+ const errors: string[] = [];+ for (let click = 0; click < 2; click++) dispatch({ type: "newTask", botId: "bot", cwd: "/work", onError: (message) => errors.push(message) });+ await flush();+ fail();+ await flush();+ expect(errors).toEqual(["no room for another", "no room for another"]);+});++it("tells a click that came while the conversation was being made that it was made", async () => {+ let answer!: () => void;+ vi.stubGlobal("fetch", vi.fn<typeof fetch>(async (path) => {+ if (path !== CREATE) return new Response("{}");+ await new Promise<void>((resolve) => { answer = resolve; });+ return new Response(JSON.stringify({ bot: { id: "bot", threadId: "new" } }), { status: 201 });+ }));+ vi.stubGlobal("window", {});+ let dispatch!: Dispatch<Action>;+ function Capture() { dispatch = useStore().dispatch; return null; }+ renderToStaticMarkup(createElement(StoreProvider, null, createElement(Capture)));+ const created = vi.fn();+ dispatch({ type: "newTask", botId: "bot", onCreated: created });+ dispatch({ type: "newTask", botId: "bot", onCreated: created });+ await flush();+ answer();+ await flush();+ expect(created).toHaveBeenCalledTimes(2);+});diff --git a/src/state/new-task-once.ts b/src/state/new-task-once.tsnew file mode 100644index 0000000000..dfb78559e6--- /dev/null+++ b/src/state/new-task-once.ts@@ -0,0 +1,26 @@+// New conversation makes one conversation per action (store.tsx): a click while one is being made for the same folder+// answers with that one's outcome, and a click for another folder waits for it, then runs.+type NewTask = { botId: string; projectId?: string; cwd?: string; onCreated?: () => void; onError?: (message: string) => void };++export function createNewTaskOnce() {+ const conversationsBeingMade = new Map<string, { projectId?: string; cwd?: string; outcome: Promise<string | null> }>();+ /** `settle`, for the caller to call with the failure (null once the conversation is made), or null when this click was+ * answered by the one being made, or will run again (`again`) once it is. */+ return (action: NewTask, again: () => void): ((failure: string | null) => void) | null => {+ const making = conversationsBeingMade.get(action.botId);+ if (making && making.projectId === action.projectId && making.cwd === action.cwd) {+ void making.outcome.then((failure) => failure === null ? action.onCreated?.() : action.onError?.(failure));+ return null;+ }+ if (making) {+ void making.outcome.then(() => again());+ return null;+ }+ let settle: (failure: string | null) => void = () => {};+ const outcome = new Promise<string | null>((resolve) => {+ settle = (failure) => { conversationsBeingMade.delete(action.botId); resolve(failure); };+ });+ conversationsBeingMade.set(action.botId, { projectId: action.projectId, cwd: action.cwd, outcome });+ return settle;+ };+}diff --git a/src/state/optimistic-send.ts b/src/state/optimistic-send.tsindex 5410293ac2..48894233fd 100644--- a/src/state/optimistic-send.ts+++ b/src/state/optimistic-send.ts@@ -1,4 +1,5 @@// A send shows at once as an optimistic user message; the server's copy, which carries the same sendId, replaces it.+import { ApiError } from "./api";import type { Message } from "./store";export const optimisticMessageId = (sendId: string): string => `optimistic-${sendId}`;@@ -22,3 +23,32 @@ export function optimisticUserMessage(channelMode,};}++/** Whether the server's copy of a send is in these messages. */+export function sendArrived(messages: readonly Message[] | undefined, sendId: string): boolean {+ return Boolean(messages?.some((message) => message.sendId === sendId && message.id !== optimisticMessageId(sendId)));+}++export const LOST_SEND_RETRY_MS = [1_000, 3_000] as const;++/** A send whose answer was lost may still have reached the server. It is asked again with the same sendId, which the+ * server never delivers twice, until it answers, refuses, or its copy arrives on the live stream. */+export async function sendReconciled<T>(+ post: () => Promise<T>,+ arrived: () => boolean,+ wait: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),+): Promise<{ body: T } | { arrived: true }> {+ for (let attempt = 0; ; attempt++) {+ try {+ return { body: await post() };+ } catch (error) {+ const lost = !(error instanceof ApiError) && (error as { name?: unknown } | null)?.name !== "AbortError";+ if (!lost) throw error;+ if (arrived()) return { arrived: true };+ const delay = LOST_SEND_RETRY_MS[attempt];+ if (delay === undefined) throw error;+ await wait(delay);+ if (arrived()) return { arrived: true };+ }+ }+}diff --git a/src/state/store.tsx b/src/state/store.tsxindex 5c3bfe4b51..50266a9403 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -22,7 +22,7 @@ import { bumpThreadUpdatedAt, mergeTaskStamps, rewindThreadUpdatedAt } from "./timport { botOpensTo, openBot, openNotificationTarget, visibleNotificationThread } from "./thread-navigation";import { patchGroupTask } from "./thread-edits";import type { EngineInstall } from "./engine-install";-import { optimisticMessageId, optimisticUserMessage } from "./optimistic-send";+import { optimisticMessageId, optimisticUserMessage, sendArrived, sendReconciled } from "./optimistic-send";import { patchedGroups, roomAnswers, snapshotPatch } from "./room-frames";import { savedStateAction, type SavedOwner, type SavedSnapshot } from "./saved-state";import { keepBotNavigation, keepGroupNavigation, navigatedSince, visibleMessages } from "./snapshot-navigation";@@ -64,9 +64,11 @@ import { showNotification } from "@/lib/notify";import { useShowThreads } from "@/lib/thread-preferences";import { speechOwner, spokenReplyStream } from "@/lib/spoken-reply-stream";import { t } from "@/lib/i18n";-import { createBotPatchQueue, type BotUpdatePatch } from "./bot-patch-queue";+import { createBotPatchQueue, flushWhenLeaving, keepaliveFits, type BotUpdatePatch } from "./bot-patch-queue"; import { createNewTaskOnce } from "./new-task-once";+import { liveCallFromFrame, nextLiveCallLookup } from "./live-call";import { useChatErrorClear } from "./chat-error";import { openLiveEvents, publishLiveFrame, publishMissedFrames } from "@/lib/live-events";+import { unlessRefused } from "@/lib/admin-scope";import { trimRoutineRuns } from "./routine-runs";import { reconcileSnapshotQueues, rememberConsumedQueueId, replaceBotQueues } from "./queue-receipts";@@ -914,7 +916,8 @@ export function reducer(state: AppState, action: Action): AppState {const selectedId = state.selectedId && known(state.selectedId) ? state.selectedId : resumed || (action.bots[0]?.id ?? "");const hydrated = {...state,- bots: action.bots.map((bot) => {+ bots: action.bots.map((sent) => {+ const bot = sent.messages ? sent : { ...sent, messages: [] };const previous = state.bots.find((candidate) => candidate.id === bot.id);return keepBotNavigation(previous, previous ? { ...bot, tasks: mergeTaskStamps(previous.tasks, bot.tasks) } : bot,action.preserveNavigation === true && navigatedSince(previous, action.navigationSince, state.transcriptGeneration), action.taskIdsAtStart);@@ -1149,7 +1152,7 @@ export function reducer(state: AppState, action: Action): AppState {return withMascotMotion({...state,// The HTTP response and its SSE broadcast race; fold both without showing the bot twice.- bots: [action.bot, ...state.bots.filter((bot) => bot.id !== action.bot.id)],+ bots: [action.bot.messages ? action.bot : { ...action.bot, messages: [] }, ...state.bots.filter((bot) => bot.id !== action.bot.id)],...(action.preserveSelection ? {} : { activeView: "chat" as const, selectedId: action.bot.id }),}, action.bot.id, "arrive");case "deleteBot": {@@ -1921,26 +1924,7 @@ export const initialState: AppState = {consumedQueueIds: {},};-/** A missing `call` key is malformed, never "the line is free". */-export function liveCallFromFrame(frame: unknown): { call: LiveCallState | null } | null {- if (!frame || typeof frame !== "object" || !Object.prototype.hasOwnProperty.call(frame, "call")) return null;- const call: unknown = Reflect.get(frame, "call");- if (call === null) return { call: null };- if (!call || typeof call !== "object") return null;- const record = call as Record<string, unknown>;- if (typeof record.callId !== "string" || typeof record.botId !== "string" || typeof record.threadId !== "string" || typeof record.status !== "string") {- return null;- }- return { call: call as LiveCallState };-}--let liveCallLookups = 0;-export function nextLiveCallLookup(): number {- liveCallLookups += 1;- return liveCallLookups;-}--export { api, ApiError };+export { api, ApiError, liveCallFromFrame, nextLiveCallLookup };/** Messages per snapshot thread and per scrollback page: the server's own page maximum. */export const MESSAGE_PAGE_SIZE = 200;@@ -1983,6 +1967,7 @@ export async function persistBotUpdate(request: (path: string, init?: RequestInit) => Promise<{ bot: BotAnnouncement }> = api,trustedApprovals: TrustedApprovalBridge | undefined = desktopApprovalBridge(),currentBot?: BotAnnouncement,+ leaving = false,): Promise<BotAnnouncement> {const {approvalMode,@@ -1996,17 +1981,14 @@ export async function persistBotUpdate((approvalMode === "full" && trustedApprovals !== undefined);if (!viaBridge) {- const result = await request(`/api/bots/${botId}`, {- method: "PATCH",- body: JSON.stringify(- approvalMode === undefined ? ordinaryPatch : {- ...ordinaryPatch,- approvalMode,- ...(applyToAllThreads ? { applyToAllThreads: true } : {}),- },- ),- signal,- });+ const body = JSON.stringify(+ approvalMode === undefined ? ordinaryPatch : {+ ...ordinaryPatch,+ approvalMode,+ ...(applyToAllThreads ? { applyToAllThreads: true } : {}),+ },+ );+ const result = await request(`/api/bots/${botId}`, { method: "PATCH", body, signal, keepalive: leaving && keepaliveFits(body) });return result.bot;}@@ -2153,8 +2135,8 @@ export function StoreProvider({ children }: { children: ReactNode }) {const botPatchQueue = useMemo(() =>createBotPatchQueue({- send: (botId, patch, signal, currentBot) =>- persistBotUpdate(botId, patch, signal, api, desktopApprovalBridge(), currentBot),+ send: (botId, patch, signal, currentBot, leaving) =>+ persistBotUpdate(botId, patch, signal, api, desktopApprovalBridge(), currentBot, leaving),reconcile: async (botId, signal) => {const result: { bots: BotAnnouncement[] } = await api(`/api/bots?messages=${MESSAGE_PAGE_SIZE}`, { signal });return result.bots.find((candidate) => candidate.id === botId) ?? null;@@ -2172,13 +2154,15 @@ export function StoreProvider({ children }: { children: ReactNode }) {useEffect(() => {// StrictMode runs this cleanup once against the same memoized queue; revive undoes it.botPatchQueue.revive();- return () => botPatchQueue.dispose();+ const stopFlushing = flushWhenLeaving(botPatchQueue, window);+ return () => { stopFlushing(); botPatchQueue.dispose(); };}, [botPatchQueue]);const dispatch = useMemo(() => {const navigation = new Map<string, number>();const roomAnswer = roomAnswers(() => stateRef.current, rawDispatch);const olderPagesInFlight = new Set<string>();+ const newTaskOnce = createNewTaskOnce();let creatingBot = false;const showError = (e: unknown) => {rawDispatch({ type: "error", message: e instanceof Error ? e.message : String(e) });@@ -2473,12 +2457,15 @@ export function StoreProvider({ children }: { children: ReactNode }) {const threadId =action.threadId ?? stateRef.current.bots.find((bot) => bot.id === action.botId)?.threadId;const sendId = action.sendId ?? crypto.randomUUID();+ const arrived = () => sendArrived(stateRef.current.bots.find((bot) => bot.id === action.botId && bot.threadId === threadId)?.messages, sendId);void waitForExecutionSettings(botBeforeSend ? [botBeforeSend] : [], threadId)- .then(() => api(`/api/bots/${action.botId}/messages`, {+ .then(() => sendReconciled(() => api(`/api/bots/${action.botId}/messages`, {method: "POST",body: JSON.stringify({ text: action.text, replyToId: action.replyToId, threadId, sendId, ...(action.dataContext ? { dataContext: action.dataContext } : {}), ...(action.pointed?.length ? { pointed: action.pointed } : {}), ...(action.mode === "goal" ? { mode: "goal" } : {}) }),- }))- .then((body) => {+ }), arrived))+ .then((sent) => {+ if (!("body" in sent)) return;+ const body = sent.body;if (body?.message && typeof body.threadId === "string") {rawDispatch({ type: "messageAdded", threadId: body.threadId, message: body.message });}@@ -2846,6 +2833,8 @@ export function StoreProvider({ children }: { children: ReactNode }) {break;case "newTask":case "switchTask": {+ const settle: ((failure: string | null) => void) | null = action.type === "newTask" ? newTaskOnce(action, () => dispatch(action)) : () => {};+ if (!settle) break;const revision = (navigation.get(action.botId) ?? 0) + 1;navigation.set(action.botId, revision);const selectedAtStart = selectionRevision.current;@@ -2856,7 +2845,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {? `/api/bots/${action.botId}/tasks`: `/api/bots/${action.botId}/tasks/${action.threadId}${action.whole ? "" : `?messages=${MESSAGE_PAGE_SIZE}`}`, { method: "POST", body: JSON.stringify(action.type === "newTask" ? { projectId: action.projectId, cwd: action.cwd } : {}) })).then((r) => {- if (action.type === "newTask") action.onCreated?.();+ if (action.type === "newTask") { settle(null); action.onCreated?.(); }if (!r?.bot || navigation.get(action.botId) !== revision) return;const selectsAfterCreation = action.type === "newTask" && action.cwd !== undefined;if (selectsAfterCreation && selectionRevision.current !== selectedAtStart) return;@@ -2867,7 +2856,9 @@ export function StoreProvider({ children }: { children: ReactNode }) {if (action.type === "switchTask" && navigation.get(action.botId) === revision) {rawDispatch({ type: "switchTaskFailed", botId: action.botId, threadId: action.threadId });}- if (action.type === "newTask" && action.onError) action.onError(error instanceof Error ? error.message : String(error));+ const message = error instanceof Error ? error.message : String(error);+ settle(message);+ if (action.type === "newTask" && action.onError) action.onError(message);else showError(error);});break;@@ -2985,8 +2976,8 @@ export function StoreProvider({ children }: { children: ReactNode }) {{key: "instances",request: async () => {- const { instances } = await api("/api/instances");- return () => rawDispatch({ type: "instances", instances });+ const answer = await unlessRefused<{ instances: InstanceInfo[] } | null>("/api/instances", () => api("/api/instances"), null);+ return () => { if (answer) rawDispatch({ type: "instances", instances: answer.instances }); };},},{@@ -3071,7 +3062,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {const taskIdsAtStart = new Set([...stateRef.current.bots, ...stateRef.current.groups].flatMap(owner => owner.tasks?.map(task => task.threadId) ?? []));const since = stateRef.current.liveCallVersion;const seq = nextLiveCallLookup();- void api<unknown>("/api/live/call")+ void unlessRefused<unknown>("/api/live/call", () => api<unknown>("/api/live/call"), null).then((body) => {const answer = liveCallFromFrame(body);if (alive && answer) flushSync(() => rawDispatch({ type: "liveCallLookup", call: answer.call, since, seq }));diff --git a/src/state/team-people.ts b/src/state/team-people.tsindex 53bd5bbf07..6703b2fa15 100644--- a/src/state/team-people.ts+++ b/src/state/team-people.ts@@ -65,6 +65,14 @@ export function departmentOwner(bots: ReadonlyArray<{ createdBy?: string; reportreturn first && owners.every((owner) => owner?.email === first.email) ? first : null;}+/** A teammate's MausBot named for its person ("MausBot · Ada"); any other bot, and the viewer's own MausBot, by its name. */+export function teamBotName(bot: { name: string; defaultBot?: { person?: string } }, team: Pick<TeamPeople, "people" | "me"> | null): string {+ const person = bot.defaultBot?.person?.trim().toLowerCase();+ if (!person || !team || team.me?.email.toLowerCase() === person) return bot.name;+ const owner = team.people.find((candidate) => candidate.email.toLowerCase() === person);+ return `${bot.name} · ${owner?.name || nameFromEmail(person)}`;+}+export function mayChangeOwner(bot: { createdBy?: string; reportsTo?: string; defaultBot?: { person?: string } }, team: TeamPeople | null): boolean {return Boolean(team && !bot.defaultBot?.person && (team.admin || (team.me && botOwner(bot) === team.me.email)));}