Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Team Cloud: share a private conversation and save a message to team memory (#5482)
Milind Soni752dcf966262
diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex f9a215c3e0..73419962fd 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -573,6 +573,43 @@ none, and the person can hide it.- With one side empty (nobody shared a bot with them yet, say) there is no switch and the sidebar lists everything.The first time the switch shows on a device, one line under it says what the two sides are.+## Sharing a conversation++A private conversation is shared only by the person it is private to, from its menu (the bot panel's This conversation+rows in Simple, the header's ⋯ in Advanced, and its row in a conversation list): **Share with the team** or **Share+with…** one teammate who can chat with that bot. A confirm step says who will read the whole conversation, everything+already in it and its files included, and that it can't be made private again (`POST+/api/bots/<bot>/tasks/<thread>/share { with: "team" | { email } }`, `GET` the same path for whom it can go to;+`server/routes/conversation-share.ts`). Nobody else, an admin included, can share it: to them it is no such conversation.++- **With the team** it becomes the team's (audience `team`): on the Team side for everyone who sees the bot, with the+ shared chat's label, its turns reading and writing the team's notes. Nobody gets an inbox line or a notification for it.+- **With one person** it gets an audience of its own, `member:<share key>`, the key made from the conversation and held by+ no session (`server/host/conversation-shares.ts`): its own memory layer, engine home and browser, so neither person's+ notes, About you or other chats reach it. Exactly its owner and that person read it, never an admin; both see it on+ the Team side, *"Shared · only you and Marta can see"* (`WireTask.shared`, `sharedWith`). Either of them writes in it and+ the bot keeps its context: the next turn opens a new engine session given the whole conversation so far. The person+ gets one inbox line and one notification linking it. From then on, what one of them writes, or the bot answers them,+ waits in the other's inbox while they don't have it open: one line per conversation, updated in place until they answer+ there. Its owner may still widen it to the team; nothing narrows it.+- **What stays.** Notifications from before the share stay with whoever they were for. A conversation a routine lives in+ is refused until the routine goes, and so is one the bot is working in. When one of the two people leaves the team the+ conversation becomes the other's private chat; one shared with the team stays the team's.+- **No way back.** It can't be made private again: nobody can un-read what was shared, and what others wrote in it, the+ notes its turns saved and the files they made would have no clear owner. Its owner can still delete it.++## Saving to team memory++**Save to team memory** on a message of a conversation with a team bot (not a group chat, not one's own MausBot) puts+that message into the bot's team notes (MEMORY.md in its own folder, which every conversation with it reads) in one+click, as one line saying who saved it and the day: *"We ship on 3 March (saved by Rui, 2026-11-11)"*. A message longer+than one note keeps its start and says *"shortened"*. Undo on the toast takes it out again (`POST`/`GET+/api/bots/<bot>/memory/team`, `DELETE /api/bots/<bot>/memory/team/<id>`; `server/host/team-memory-saves.ts`). It needs+Can chat on the bot and a conversation the person reads, so from a private chat only its own person saves. The line+names no conversation. Its author sees and removes it in the bot's What it remembers; an admin removes any line there+or in the notes; nobody else can remove or change it. Nothing is ever saved there on its own, and nothing from a+conversation that came in from outside.+## A bot's ownerEvery team bot has one **owner**, a member: `reportsTo` (an email) names them; without it the owner is `createdBy`, thediff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex f18d644c70..029b7f256a 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -65,6 +65,7 @@ export const VITEST_SUBSETS = {"scripts/testing/one-workspace-ui.e2e.test.ts","scripts/testing/rail-profile-ui.e2e.test.ts","scripts/testing/secret-card-descriptions.test.ts",+ "scripts/testing/team-conversation-share-ui.e2e.test.ts","scripts/testing/team-own-chat.e2e.test.ts","scripts/testing/team-side-switch-ui.e2e.test.ts","server/body-thread-guards.e2e.test.ts",@@ -86,6 +87,7 @@ export const VITEST_SUBSETS = {"server/cloud-team-away.e2e.test.ts","server/cloud-team-browser.e2e.test.ts","server/cloud-team-connections.e2e.test.ts",+ "server/cloud-team-conversation-share.e2e.test.ts","server/cloud-team-engine-homes.e2e.test.ts","server/cloud-team-gateway-mcp.e2e.test.ts","server/cloud-team-inbox.e2e.test.ts",@@ -166,6 +168,7 @@ export const VITEST_SUBSETS = {"server/host/wait-words.test.ts","server/place-inbox.e2e.test.ts","server/bot-api-team.e2e.test.ts",+ "server/cloud-team-conversation-share.e2e.test.ts","server/cloud-team-first-look.e2e.test.ts","server/cloud-team-mausbot-own-chat.e2e.test.ts","server/connector-stayed.e2e.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex da453bd9de..8c84c40814 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -205,6 +205,7 @@ describe("CI outputs", () => {"scripts/testing/one-workspace-ui.e2e.test.ts","scripts/testing/rail-profile-ui.e2e.test.ts","scripts/testing/secret-card-descriptions.test.ts",+ "scripts/testing/team-conversation-share-ui.e2e.test.ts","scripts/testing/team-own-chat.e2e.test.ts","scripts/testing/team-side-switch-ui.e2e.test.ts","server/body-thread-guards.e2e.test.ts",@@ -226,6 +227,7 @@ describe("CI outputs", () => {"server/cloud-team-away.e2e.test.ts","server/cloud-team-browser.e2e.test.ts","server/cloud-team-connections.e2e.test.ts",+ "server/cloud-team-conversation-share.e2e.test.ts","server/cloud-team-engine-homes.e2e.test.ts","server/cloud-team-gateway-mcp.e2e.test.ts","server/cloud-team-inbox.e2e.test.ts",@@ -306,6 +308,7 @@ describe("CI outputs", () => {"server/host/wait-words.test.ts","server/place-inbox.e2e.test.ts","server/bot-api-team.e2e.test.ts",+ "server/cloud-team-conversation-share.e2e.test.ts","server/cloud-team-first-look.e2e.test.ts","server/cloud-team-mausbot-own-chat.e2e.test.ts","server/connector-stayed.e2e.test.ts",diff --git a/scripts/testing/team-conversation-share-ui.e2e.test.ts b/scripts/testing/team-conversation-share-ui.e2e.test.tsnew file mode 100644index 0000000000..64b89a7f7e--- /dev/null+++ b/scripts/testing/team-conversation-share-ui.e2e.test.ts@@ -0,0 +1,247 @@+// Sharing a private conversation and saving to team memory, in the real app on a real Team Cloud (OMB_CLOUD_ROLE=team,+// each person paired with the Admin's signed claim) in headless Chrome: Rui hands a private chat to Marta, who finds it+// in her inbox and carries it on with the bot's whole context; it goes back and forth through their inboxes; Rui saves a+// decision to team memory in one click and Ana's new conversation with the bot uses it; the team's admin sees none of+// Rui's private chats. Run with OMB_UI_E2E=1; OMB_TEAM_SHARE_SHOTS=DIR keeps the screenshots there.+import { randomBytes } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";+import { join } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { WELCOME_VERSION } from "../../electron/onboarding-record.mjs";+import { hostTimeout } from "../../server/testing/host-timeout.ts";+import { SPOTLIGHTS } from "../../src/lib/first-conversation.ts";+import { TOUR_STEPS } from "../../src/lib/guided-tour.ts";+import { NOTICES } from "../../src/lib/notices.ts";+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "./cloud-send-fixture.ts";+import { agentBrowser, ensureUiBrowser, sessionEnv } from "./control-omb-ui.ts";+import { mountPreview, REPO_ROOT } from "./preview-fixture.ts";++const enabled = process.env.OMB_UI_E2E === "1";+if (!enabled) console.info("skipping the conversation sharing UI e2e: set OMB_UI_E2E=1");++const SHOTS = process.env.OMB_TEAM_SHARE_SHOTS || join(REPO_ROOT, ".omb-scratch", "team-conversation-share");+const ENGINE = `process.env.FAKE_CLAUDE_DUMP = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/dump.json";+process.env.FAKE_CLAUDE_EXIT_AFTER_TURN = "1";`;+const HANDOFF = "Kumquat launch: the supplier is Ortega, call before Friday";+const OTHER = "Rui's own salary questions";+const MARTA_LINE = "Picking this up: what did we agree with Ortega?";+const DECISION = "Decision: we ship the Kumquat launch on 3 March";+const DESKTOP = ["1280", "800"] as const, PHONE = ["390", "844"] as const;+const DISMISS = `(() => { [...document.querySelectorAll('[role="dialog"] button, dialog button')].find((button) => button.textContent.trim() === "Not now")?.click(); return true; })()`;++type Who = "olive" | "rui" | "marta" | "ana";+type Row = { text: string; tab: string; origin?: { threadId: string } };+type App = Awaited<ReturnType<typeof openAs>>;++let fx: CloudSendFixture, team: CloudTeamFixture;+let tools: { binary: string; chrome: string | null };+const tokens: Record<Who, string> = { olive: "", rui: "", marta: "", ana: "" };+const emails: Record<Who, string> = { olive: "[email protected]", rui: "[email protected]", marta: "[email protected]", ana: "[email protected]" };+let scout = "", handoff = "", other = "";+const apps: App[] = [];++const as = (who: Who, method: string, path: string, body?: unknown) => team.as(tokens[who], method, path, body);+const status = async (who: Who, threadId: string) => (await as(who, "GET", `/api/threads/${threadId}/messages?limit=50`)).status;+const idle = async () => ((await as("olive", "GET", "/api/bots")).body.bots as Array<{ activity?: string; busy?: boolean }>).every((bot) => bot.activity !== "working" && !bot.busy);+const openRows = async (who: Who, threadId: string) => (((await as(who, "GET", "/api/inbox")).body.rows ?? []) as Row[]).filter((row) => row.origin?.threadId === threadId && row.tab !== "done");+const dump = () => JSON.parse(readFileSync(join(team.home, "dump.json"), "utf8")) as { prompt: unknown; systemPrompt?: string };+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++async function openAs(who: Who, size: readonly [string, string]) {+ const preview = await mountPreview({ info: { url: team.base } }, { entry: "/scripts/testing/threads-preview.tsx", route: "/__threads.html", title: "Sharing",+ logLevel: "warn", proxyHeaders: { ...fx.edge, authorization: `Bearer ${tokens[who]}` } });+ const home = join(fx.root, `b${apps.length}`);+ mkdirSync(join(home, "tmp"), { recursive: true });+ const env = sessionEnv({ home, session: `s${apps.length}`, chrome: tools.chrome });+ const browser = (...args: string[]) => agentBrowser(tools.binary, env, args, 120_000);+ await browser("set", "viewport", ...size);+ const evaluate = async <T>(js: string) => (await browser("eval", js)).result as T;+ await browser("open", new URL("/package.json", preview.previewUrl).href);+ await evaluate(`(() => { for (const notice of ${JSON.stringify(NOTICES)}) localStorage.setItem(notice, "1"); return true; })()`);+ await browser("open", preview.previewUrl);+ const audience = () => evaluate<string | null>("(() => { const label = document.querySelector('[data-team-audience]'); return label ? label.dataset.teamAudience + ':' + label.textContent : null; })()");+ const clickText = (selector: string, text: string) => evaluate<boolean>(`(() => { const hit = [...document.querySelectorAll(${JSON.stringify(selector)})].find((each) => each.textContent.trim().includes(${JSON.stringify(text)})); hit?.click(); return Boolean(hit); })()`);+ const app = {+ who, evaluate, audience, clickText,+ words: () => evaluate<string>("document.body.innerText"),+ async shot(name: string) {+ await sleep(400);+ await browser("screenshot", join(SHOTS, `${name}.png`));+ },+ async openScout(on: "me" | "team") {+ await evaluate(DISMISS);+ await expect.poll(() => evaluate<boolean>(`(() => { const row = document.querySelector('[data-sidebar-bot-row="${scout}"]'); row?.click(); return Boolean(row); })()`), { timeout: 60_000, interval: 500 }).toBe(true);+ await expect.poll(async () => (await audience())?.split(":")[0], { timeout: 30_000 }).toBe(on);+ },+ async say(text: string) {+ await evaluate(`(() => { const field = document.querySelector('textarea[placeholder^="Message"]'); field.focus();+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value").set.call(field, ${JSON.stringify(text)});+ field.dispatchEvent(new Event("input", { bubbles: true })); return true; })()`);+ await browser("press", "Enter");+ await expect.poll(() => evaluate<string>("document.querySelector('main')?.innerText ?? ''"), { timeout: 30_000 }).toContain(text);+ await sleep(500);+ await expect.poll(idle, { timeout: 60_000, interval: 300 }).toBe(true);+ },+ /** The conversation's own actions: the bot panel's Conversation rows (Simple), else the header's ⋯. */+ async conversationAction(item: string) {+ await expect.poll(async () => {+ if (await clickText('[data-panel-card="conversation"] button', item)) return true;+ await evaluate(`(() => { if (!document.querySelector('[data-panel-card="conversation"]')) document.querySelector('[data-chathead-pill]')?.click(); return true; })()`);+ await evaluate(`(() => { const trigger = document.querySelector('[data-testid="chat-more"]'); (trigger?.closest('button') ?? trigger)?.click(); return true; })()`);+ return clickText('[role="menuitem"]', item);+ }, { timeout: 30_000, interval: 500 }).toBe(true);+ },+ async openInbox() {+ await evaluate(DISMISS);+ await expect.poll(() => evaluate<boolean>(`(() => { const row = document.querySelector('[data-sidebar-inbox]'); (row?.closest('button') ?? row)?.click(); return Boolean(row); })()`), { timeout: 60_000, interval: 500 }).toBe(true);+ await expect.poll(() => evaluate<boolean>("Boolean(document.querySelector('[data-inbox-panel]'))"), { timeout: 30_000 }).toBe(true);+ },+ async openInboxLine(text: string) {+ await expect.poll(() => clickText("[data-inbox-row] button", text), { timeout: 30_000, interval: 500 }).toBe(true);+ await expect.poll(() => evaluate<boolean>(`(() => { const open = document.querySelector('[data-inbox-action="open"]'); open?.click(); return Boolean(open); })()`), { timeout: 30_000 }).toBe(true);+ },+ async close() {+ await browser("close").catch(() => {});+ await preview.close();+ },+ };+ apps.push(app);+ return app;+}++(enabled ? describe : describe.skip)("sharing a conversation and saving to team memory on a Team Cloud, in the real app", () => {+ beforeAll(async () => {+ mkdirSync(SHOTS, { recursive: true });+ tools = await ensureUiBrowser(process.env);+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-share-${randomBytes(8).toString("hex")}`,+ team: { id: "team-acme-share-ui", name: "Acme", engine: ENGINE, env: { OMB_TEAM_PRESENCE_GRACE_MS: "1000" } } });+ team = fx.team!;+ for (const [who, role] of [["olive", "owner"], ["rui", "member"], ["marta", "member"], ["ana", "member"]] as const) tokens[who] = (await team.pair({ email: emails[who], role })).token!;+ const onboarding = { completedAt: new Date().toISOString(), version: WELCOME_VERSION, hintsSeen: [...TOUR_STEPS.map((step) => step.id), ...SPOTLIGHTS, "cloud-welcome-done", "cloud-setup-hidden"] };+ expect((await as("olive", "PATCH", "/api/config", { onboarding, language: "en" })).status).toBe(200);+ for (const who of ["rui", "marta", "ana"] as const) {+ expect((await as(who, "PUT", "/api/me/welcome", { welcomed: true })).status).toBe(200);+ expect((await as(who, "PUT", "/api/me", { name: who[0]!.toUpperCase() + who.slice(1) })).status).toBe(200);+ }+ for (const who of ["olive", "rui", "marta", "ana"] as const) {+ const own = ((await as(who, "GET", "/api/bots?messages=0")).body.bots as Array<{ id: string; defaultBot?: { person?: string } }>).find((bot) => bot.defaultBot?.person === emails[who])!;+ expect((await as(who, "PATCH", `/api/bots/${own.id}`, { welcomed: true, sidebarHidden: false, pinned: true })).status).toBe(200);+ }+ const created = await as("olive", "POST", "/api/bots", { name: "Scout" });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ scout = created.body.bot.id;+ }, hostTimeout(300_000));+ afterAll(async () => {+ for (const app of apps) await app.close().catch(() => {});+ await fx?.close();+ }, hostTimeout(120_000));++ it("Rui shares a private chat with Marta from the conversation's menu, after a confirm step that says who will read all of it", async () => {+ const rui = await openAs("rui", DESKTOP);+ await rui.openScout("me");+ expect(await rui.audience()).toBe("me:Private · only you");+ await rui.say(HANDOFF);+ const tasks = ((await as("rui", "GET", "/api/bots?messages=0")).body.bots as Array<{ id: string; tasks: Array<{ threadId: string; private?: true }> }>).find((bot) => bot.id === scout)!.tasks;+ handoff = tasks.find((task) => task.private)!.threadId;+ await rui.shot("00-rui-private-chat-desktop");+ await rui.conversationAction("Share with…");+ await expect.poll(() => rui.evaluate<string>("document.querySelector('[role=alertdialog]')?.innerText ?? ''"), { timeout: 30_000 }).toContain("Nobody else can see it, admins included.");+ await rui.evaluate(`(() => { const select = document.querySelector('[role=alertdialog] select'); select.value = ${JSON.stringify(emails.marta)}; select.dispatchEvent(new Event("change", { bubbles: true })); return true; })()`);+ await expect.poll(() => rui.evaluate<string>("document.querySelector('[role=alertdialog]')?.innerText ?? ''"), { timeout: 10_000 })+ .toContain("Marta will be able to read this whole conversation, including everything already in it and its files, and carry it on with Scout.");+ await rui.shot("01-rui-share-with-confirm-desktop");+ expect(await status("marta", handoff), "nothing moves before he confirms").toBe(404);+ await rui.clickText("[role=alertdialog] button", "Share with Marta");+ await expect.poll(rui.audience, { timeout: 30_000 }).toBe("team:Shared · only you and Marta can see");+ await rui.shot("02-rui-shared-label-desktop");+ expect(await status("marta", handoff)).toBe(200);+ for (const who of ["ana", "olive"] as const) expect(await status(who, handoff), who).toBe(404);+ await rui.close();+ const made = await as("rui", "POST", `/api/bots/${scout}/tasks`, { title: "Salary" });+ other = made.body.task.threadId;+ expect((await as("rui", "POST", `/api/bots/${scout}/messages`, { text: OTHER, threadId: other })).status).toBe(202);+ await expect.poll(idle, { timeout: 60_000, interval: 300 }).toBe(true);++ }, hostTimeout(300_000));++ it("Marta finds it in her inbox, opens it, and the bot carries on with the whole conversation", async () => {+ await sleep(2_500);+ const marta = await openAs("marta", DESKTOP);+ await marta.openInbox();+ await expect.poll(marta.words, { timeout: 30_000 }).toContain("Rui shared");+ await marta.shot("03-marta-inbox-desktop");+ await marta.openInboxLine("Rui shared");+ await expect.poll(marta.audience, { timeout: 30_000 }).toBe("team:Shared · only you and Rui can see");+ expect(await marta.evaluate<string>("document.querySelector('main')?.innerText ?? ''"), "everything already in it").toContain(HANDOFF);+ rmSync(join(team.home, "dump.json"), { force: true });+ await marta.say(MARTA_LINE);+ await expect.poll(() => existsSync(join(team.home, "dump.json")), { timeout: 30_000 }).toBe(true);+ expect(JSON.stringify(dump().prompt), "the bot has the conversation so far").toContain(HANDOFF);+ expect(JSON.stringify(dump()), "and none of Rui's other private chat").not.toContain(OTHER);+ await marta.shot("04-marta-carries-on-desktop");+ await marta.close();+ }, hostTimeout(300_000));++ it("and back: Rui's inbox holds one line for it, he answers there, and it waits in Marta's inbox in turn", async () => {+ await sleep(2_500);+ expect((await openRows("rui", handoff)).length, "one line, updated in place by the bot's answer").toBe(1);+ const rui = await openAs("rui", DESKTOP);+ await rui.openInbox();+ await expect.poll(rui.words, { timeout: 30_000 }).toContain("answered Marta");+ await rui.shot("05-rui-inbox-back-desktop");+ await rui.openInboxLine("answered Marta");+ await expect.poll(rui.audience, { timeout: 30_000 }).toBe("team:Shared · only you and Marta can see");+ expect(await rui.evaluate<string>("document.querySelector('main')?.innerText ?? ''")).toContain(MARTA_LINE);+ await rui.say(DECISION);+ expect(await openRows("rui", handoff), "he answered, so nothing waits on him").toEqual([]);+ expect((await openRows("marta", handoff)).length, "now it waits on Marta").toBe(1);++ await rui.evaluate(`(() => { const row = [...document.querySelectorAll('[data-message-row]')].find((each) => each.innerText.includes(${JSON.stringify(DECISION)})); row.querySelector('button[aria-label="Message actions"]').click(); return true; })()`);+ await expect.poll(() => rui.clickText('[role="menuitem"]', "Save to team memory"), { timeout: 10_000 }).toBe(true);+ await expect.poll(() => rui.evaluate<string>("document.querySelector('[data-access-toast]')?.innerText ?? ''"), { timeout: 10_000 }).toContain("Saved to Scout's team memory");+ await rui.shot("06-rui-saved-to-team-memory-desktop");+ expect(readFileSync(join(team.home, ".openmausbot", "workspaces", scout, "MEMORY.md"), "utf8")).toMatch(/Decision: we ship the Kumquat launch on 3 March \(saved by Rui, \d{4}-\d{2}-\d{2}\)/);+ await rui.close();+ }, hostTimeout(300_000));++ it("Marta at phone width: the line waiting on her, and the conversation's label", async () => {+ await sleep(2_500);+ const marta = await openAs("marta", PHONE);+ await marta.openInbox();+ await expect.poll(marta.words, { timeout: 30_000 }).toContain("answered Rui");+ await marta.shot("07-marta-inbox-phone");+ await marta.openInboxLine("answered Rui");+ await expect.poll(marta.audience, { timeout: 30_000 }).toBe("team:Shared · only you and Rui can see");+ await marta.evaluate(`(() => { document.querySelector('[data-inbox-panel] button[aria-label="Close inbox"]')?.click(); return true; })()`);+ await expect.poll(() => marta.evaluate<boolean>("!document.querySelector('[data-inbox-panel]')"), { timeout: 10_000 }).toBe(true);+ await marta.shot("08-marta-shared-chat-phone");+ expect(await marta.evaluate<number>("document.scrollingElement.scrollWidth - window.innerWidth"), "no sideways scroll").toBeLessThanOrEqual(1);+ await marta.close();+ }, hostTimeout(300_000));++ it("Ana's new conversation with Scout reads the decision Rui saved", async () => {+ const ana = await openAs("ana", DESKTOP);+ await ana.openScout("me");+ rmSync(join(team.home, "dump.json"), { force: true });+ await ana.say("When do we ship the Kumquat launch?");+ await expect.poll(() => existsSync(join(team.home, "dump.json")), { timeout: 30_000 }).toBe(true);+ expect(`${JSON.stringify(dump().prompt)}\n${dump().systemPrompt ?? ""}`).toContain(DECISION);+ expect(await ana.words(), "nothing of the handoff on her screen").not.toContain(HANDOFF);+ await ana.shot("09-ana-new-chat-desktop");+ await ana.close();+ }, hostTimeout(300_000));++ it("the team's admin sees none of Rui's private chats, nor the one he handed to Marta", async () => {+ for (const threadId of [other, handoff]) expect(await status("olive", threadId)).toBe(404);+ const olive = await openAs("olive", DESKTOP);+ await olive.openScout("me");+ expect(await olive.words()).not.toContain(OTHER);+ expect(await olive.words()).not.toContain(HANDOFF);+ await olive.evaluate(`document.querySelector('[data-team-side-option="team"]')?.click(); true`);+ await sleep(1_000);+ expect(await olive.words(), "nor on the Team side").not.toContain(HANDOFF);+ await olive.shot("10-admin-desktop");+ await olive.close();+ }, hostTimeout(300_000));+});diff --git a/server/bot-visibility.ts b/server/bot-visibility.tsindex 59303a2233..80b1a34f92 100644--- a/server/bot-visibility.ts+++ b/server/bot-visibility.ts@@ -22,6 +22,8 @@ export interface ThreadAudiences {ownTask?<T extends { threadId: string; unread?: boolean; lastReadMessageId?: string }>(task: T): T;/** The person whose private chat a routine lives in (routine-home.ts), else null. */routineHome?(routine: RoutineRef): string | null;+ /** The two people a conversation shared with one person is read by (host/conversation-shares.ts), else null. */+ readers?(threadId: string): readonly string[] | null;}export type RoutineRef = { botId?: unknown; groupId?: unknown; name?: unknown; sourceThreadId?: unknown; resultsThreadId?: unknown };@@ -280,7 +282,10 @@ export class VisibleSet {private audienceShows(threadId: string): boolean {const audience = this.audiences?.of(threadId);- return audience === undefined || audienceIncludes(audience, { admin: this.viewer.kind === "all", person: this.audiences!.person, seesRoom: (groupId) => this.group(groupId) });+ if (audience === undefined) return true;+ const person = this.audiences!.person;+ return audienceIncludes(audience, { admin: this.viewer.kind === "all", person, seesRoom: (groupId) => this.group(groupId) })+ || (person !== null && this.audiences!.readers?.(threadId)?.includes(person) === true);}private indexedOwner(threadId: string): ThreadOwner | undefined {diff --git a/server/cloud-team-conversation-share.e2e.test.ts b/server/cloud-team-conversation-share.e2e.test.tsnew file mode 100644index 0000000000..e7146cdb05--- /dev/null+++ b/server/cloud-team-conversation-share.e2e.test.ts@@ -0,0 +1,274 @@+// Sharing a private conversation and saving to team memory on a real Team Cloud, as its owner and as hostile callers:+// only the conversation's own person shares it or saves from it, nobody else (another member, an admin) reaches it+// before or after, a conversation shared with one person is read by those two alone and carries the bot's context+// without either person's private notes, and a line saved to team memory reaches the next conversation with that bot.+import { randomBytes } from "node:crypto";+import { existsSync, readFileSync, rmSync } from "node:fs";+import { join } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const ENGINE = `process.env.FAKE_CLAUDE_DUMP = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/dump.json";+process.env.FAKE_CLAUDE_EXIT_AFTER_TURN = "1";`;+const OLIVE = { email: "[email protected]", role: "owner" as const };+const RUI = { email: "[email protected]", role: "member" as const };+const MARTA = { email: "[email protected]", role: "member" as const };+const ANA = { email: "[email protected]", role: "member" as const };+const BEN = { email: "[email protected]", role: "member" as const };+const HANDOFF = "Kumquat launch: the supplier is Ortega, call before Friday";+const OTHER = "Rui's other private chat about his salary";+const RUI_NOTE = "Rui prefers to be called Ruizinho";+const DECISION = "We ship the Kumquat launch on 3 March";++type Task = { threadId: string; title?: string; private?: true; shared?: true; sharedWith?: { name: string; byYou?: true } };+type Bot = { id: string; mainThreadId: string; tasks: Task[] };+type Dump = { env: Record<string, string>; prompt: unknown; systemPrompt?: string };+const said = (dump: Dump) => `${JSON.stringify(dump.prompt)}\n${dump.systemPrompt ?? ""}`;++let fx: CloudSendFixture, team: CloudTeamFixture;+const tokens = { olive: "", rui: "", marta: "", ana: "", ben: "" };+type Who = keyof typeof tokens;+let scout = "", vault = "", handoff = "", other = "";++const as = (who: Who, method: string, path: string, body?: unknown) => team.as(tokens[who], method, path, body);+const messages = async (who: Who, threadId: string) => as(who, "GET", `/api/threads/${threadId}/messages?limit=200`);+const scoutOf = async (who: Who) => ((await as(who, "GET", "/api/bots?messages=0")).body.bots as Bot[]).find((bot) => bot.id === scout)!;+const taskOf = async (who: Who, threadId: string) => (await scoutOf(who)).tasks.find((task) => task.threadId === threadId);+const idle = async (who: Who) => ((await as(who, "GET", "/api/bots")).body.bots as Array<{ activity?: string; busy?: boolean }>).every((bot) => bot.activity !== "working" && !bot.busy);+const inboxLines = async (who: Who) => JSON.stringify((await as(who, "GET", "/api/inbox")).body.rows ?? []);+type Row = { id: string; text: string; tab: string; origin?: { threadId: string } };+const openRows = async (who: Who, threadId: string) => (((await as(who, "GET", "/api/inbox")).body.rows ?? []) as Row[]).filter((row) => row.origin?.threadId === threadId && row.tab !== "done");+const notifications = async (who: Who) => JSON.stringify((await as(who, "GET", "/api/notifications")).body);++/** expect.poll, usable in beforeAll too. */+async function until(done: () => Promise<boolean>, timeoutMs = 60_000): Promise<void> {+ const end = Date.now() + timeoutMs;+ while (!(await done())) {+ if (Date.now() > end) throw new Error("timed out waiting");+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+}+async function turn(who: Who, botId: string, threadId: string, text: string): Promise<Dump> {+ rmSync(join(team.home, "dump.json"), { force: true });+ const before = ((await messages(who, threadId)).body.messages as unknown[]).length;+ const sent = await as(who, "POST", `/api/bots/${botId}/messages`, { text, threadId });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ await until(async () => await idle(who) && ((await messages(who, threadId)).body.messages as unknown[]).length >= before + 2 && existsSync(join(team.home, "dump.json")));+ return JSON.parse(readFileSync(join(team.home, "dump.json"), "utf8")) as Dump;+}+const opened = async (who: Who, botId: string, title: string) => {+ const made = await as(who, "POST", `/api/bots/${botId}/tasks`, { title });+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ return made.body.task.threadId as string;+};+const lastLine = async (who: Who, threadId: string) => ((await messages(who, threadId)).body.messages as Array<{ id: string; role: string }>).at(-1)!.id;++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-share-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-share", name: "Acme", engine: ENGINE } });+ team = fx.team!;+ for (const [who, person] of [["olive", OLIVE], ["rui", RUI], ["marta", MARTA], ["ana", ANA], ["ben", BEN]] as const) tokens[who] = (await team.pair(person)).token!;+ const created = await as("olive", "POST", "/api/bots", { name: "Scout" });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ scout = created.body.bot.id;+ const locked = await as("olive", "POST", "/api/bots", { name: "Vault" });+ vault = locked.body.bot.id;+ expect((await as("olive", "PUT", `/api/bots/${vault}/access`, { everyone: "none", people: { [RUI.email]: "chat" } })).status).toBe(200);+ expect((await as("rui", "PUT", `/api/bots/${scout}/memory/mine/file`, { path: "MEMORY.md", text: `- ${RUI_NOTE}\n` })).status).toBe(200);+ handoff = await opened("rui", scout, "Kumquat launch");+ await turn("rui", scout, handoff, HANDOFF);+ other = await opened("rui", scout, "Salary");+ await turn("rui", scout, other, OTHER);+}, hostTimeout(240_000));++afterAll(async () => {+ await fx?.close();+});++describe("sharing a private conversation", () => {+ it("is refused to anyone but its person, and changes nothing for them: another member and an admin get no such conversation", async () => {+ for (const who of ["ben", "olive", "marta"] as const) {+ expect((await as(who, "GET", `/api/bots/${scout}/tasks/${handoff}/share`)).status, `${who}: reading its sharing`).toBe(404);+ expect((await as(who, "POST", `/api/bots/${scout}/tasks/${handoff}/share`, { with: "team" })).status, `${who}: sharing it with the team`).toBe(404);+ expect((await as(who, "POST", `/api/bots/${scout}/tasks/${handoff}/share`, { with: { email: `${who}@acme.test` } })).status, `${who}: sharing it with themselves`).toBe(404);+ expect((await messages(who, handoff)).status, `${who}: reading it`).toBe(404);+ }+ expect((await taskOf("rui", handoff))?.private).toBe(true);+ expect((await taskOf("rui", handoff))?.shared).toBeUndefined();+ }, hostTimeout(60_000));++ it("offers its person the teammates who can chat with the bot, and refuses one who can't", async () => {+ const offered = await as("rui", "GET", `/api/bots/${scout}/tasks/${handoff}/share`);+ expect(offered.status).toBe(200);+ expect(offered.body.shared).toBeNull();+ expect((offered.body.people as Array<{ email: string }>).map((person) => person.email).sort()).toEqual([ANA.email, BEN.email, MARTA.email, OLIVE.email].sort());+ const locked = await opened("rui", vault, "Vault notes");+ expect((await as("rui", "GET", `/api/bots/${vault}/tasks/${locked}/share`)).body.people).toEqual([expect.objectContaining({ email: OLIVE.email })]);+ const refused = await as("rui", "POST", `/api/bots/${vault}/tasks/${locked}/share`, { with: { email: MARTA.email } });+ expect(refused.status).toBe(409);+ expect(refused.body.errorKey).toBe("serverError.share.cantUse");+ expect((await as("rui", "POST", `/api/bots/${scout}/tasks/${handoff}/share`, { with: { email: "[email protected]" } })).body.errorKey).toBe("serverError.share.notTeammate");+ expect((await as("rui", "POST", `/api/bots/${scout}/tasks/${handoff}/share`, { with: "private" })).status, "there is no way back").toBe(400);+ }, hostTimeout(60_000));++ it("with one person: only Rui and Marta read it, all of it, and Marta alone hears of it, once, in her inbox", async () => {+ const before = { ana: await inboxLines("ana"), ben: await inboxLines("ben"), olive: await inboxLines("olive") };+ const shared = await as("rui", "POST", `/api/bots/${scout}/tasks/${handoff}/share`, { with: { email: MARTA.email } });+ expect(shared.status, JSON.stringify(shared.body)).toBe(200);+ expect(shared.body.shared).toEqual({ email: MARTA.email, name: expect.any(String) });++ const page = await messages("marta", handoff);+ expect(page.status).toBe(200);+ expect(JSON.stringify(page.body), "everything already in it").toContain(HANDOFF);+ expect(await taskOf("marta", handoff)).toMatchObject({ shared: true, sharedWith: { name: expect.any(String) } });+ expect((await taskOf("marta", handoff))?.private).toBeUndefined();+ expect((await taskOf("marta", handoff))?.sharedWith?.byYou).toBeUndefined();+ expect(await taskOf("rui", handoff)).toMatchObject({ shared: true, sharedWith: { byYou: true } });+ expect((await taskOf("rui", handoff))?.private, "no longer says only you").toBeUndefined();+ expect((await as("rui", "GET", "/api/auth/session")).body.openedThreads, "nor is it counted among his private chats").not.toContain(handoff);++ for (const who of ["ben", "olive", "ana"] as const) {+ expect((await messages(who, handoff)).status, `${who}: reading it`).toBe(404);+ expect(await taskOf(who, handoff), `${who}: listed`).toBeUndefined();+ expect(await notifications(who), `${who}: notified`).not.toContain(handoff);+ expect(await inboxLines(who), `${who}: inbox`).toBe(before[who]);+ }+ expect((await messages("marta", other)).status, "Rui's other private chat stays his").toBe(404);+ await expect.poll(() => inboxLines("marta"), { timeout: 10_000 }).toContain("shared");+ expect(await inboxLines("marta")).toContain(handoff);+ const theirs = JSON.parse(await notifications("marta")) as { notifications?: Array<{ threadId: string; title: string }> } | Array<{ threadId: string; title: string }>;+ const list = Array.isArray(theirs) ? theirs : theirs.notifications ?? [];+ expect(list.filter((entry) => entry.threadId === handoff).length, "one notification, linking the conversation").toBe(1);+ }, hostTimeout(90_000));++ it("Marta carries it on: the bot gets the whole conversation so far, in a home of its own, without either person's private notes", async () => {+ const dump = await turn("marta", scout, handoff, "What did Rui say about the supplier?");+ expect(JSON.stringify(dump.prompt), "the conversation so far").toContain(HANDOFF);+ expect(said(dump), "Rui's own notes about him stay his").not.toContain(RUI_NOTE);+ expect(said(dump), "his other private chat too").not.toContain(OTHER);+ const ruiHome = (await turn("rui", scout, other, "Another private line")).env.HOME;+ expect(dump.env.HOME, "not Rui's own engine home").not.toBe(ruiHome);+ expect((await messages("rui", handoff)).status).toBe(200);+ expect(JSON.stringify((await messages("rui", handoff)).body), "Rui reads what Marta wrote").toContain("What did Rui say about the supplier?");+ }, hostTimeout(120_000));++ it("goes back and forth: what one of them writes, or the bot answers them, waits in the other's inbox as one line", async () => {+ const forRui = await openRows("rui", handoff);+ expect(forRui.length, "Marta wrote and the bot answered her: one line for Rui").toBe(1);+ expect(forRui[0]!.text).toContain("answered");+ const mentions = (list: string) => (JSON.parse(list).notifications as Array<{ threadId: string; kind: string; forPerson?: string }>).filter((entry) => entry.threadId === handoff && entry.kind === "mention");+ expect(mentions(await notifications("rui")).length, "one notification for the one line").toBe(1);+ expect((await openRows("marta", handoff)).length, "her own line was settled when she wrote").toBe(0);++ await turn("rui", scout, handoff, "Ortega confirmed, thanks Marta");+ expect(await openRows("rui", handoff), "Rui answered there, so nothing waits on him").toEqual([]);+ const forMarta = await openRows("marta", handoff);+ expect(forMarta.length, "one line for Marta, updated in place by the bot's answer").toBe(1);+ expect(forMarta[0]!.text).toContain("answered");+ await turn("marta", scout, handoff, "Great, I'll book the call");+ expect(await openRows("marta", handoff)).toEqual([]);+ expect((await openRows("rui", handoff)).length).toBe(1);+ for (const who of ["ben", "olive", "ana"] as const) expect(await openRows(who, handoff), `${who}: nothing`).toEqual([]);+ }, hostTimeout(120_000));++ it("is shared once: Marta can't pass it on, Rui can't hand it to a third person, and only widening to the team stays", async () => {+ expect((await as("marta", "POST", `/api/bots/${scout}/tasks/${handoff}/share`, { with: "team" })).body.errorKey).toBe("serverError.share.notYours");+ expect((await as("rui", "POST", `/api/bots/${scout}/tasks/${handoff}/share`, { with: { email: ANA.email } })).body.errorKey).toBe("serverError.share.alreadyWith");+ expect((await as("rui", "POST", `/api/bots/${scout}/tasks/${handoff}/share`, { with: { email: MARTA.email } })).status, "the same person again changes nothing").toBe(200);+ }, hostTimeout(60_000));++ it("with the team: everyone who can use the bot reads it, nobody gets an inbox line or a notification for it, and it can't be shared again", async () => {+ const before = { ana: await inboxLines("ana"), ben: await inboxLines("ben"), olive: await inboxLines("olive"), marta: await inboxLines("marta") };+ const notifiedBefore = { ana: await notifications("ana"), ben: await notifications("ben"), olive: await notifications("olive") };+ const widened = await as("rui", "POST", `/api/bots/${scout}/tasks/${handoff}/share`, { with: "team" });+ expect(widened.status, JSON.stringify(widened.body)).toBe(200);+ expect(widened.body.shared).toBe("team");+ for (const who of ["ana", "ben", "olive", "marta"] as const) {+ expect((await messages(who, handoff)).status, `${who}: reading it`).toBe(200);+ expect(await taskOf(who, handoff), `${who}: on the Team side`).toMatchObject({ shared: true });+ expect((await taskOf(who, handoff))?.sharedWith).toBeUndefined();+ expect(await inboxLines(who), `${who}: no inbox line`).toBe(before[who]);+ }+ for (const who of ["ana", "ben", "olive"] as const) expect(await notifications(who), `${who}: no notification`).toBe(notifiedBefore[who]);+ expect((await as("rui", "POST", `/api/bots/${scout}/tasks/${handoff}/share`, { with: { email: ANA.email } })).body.errorKey).toBe("serverError.share.alreadyTeam");+ for (const who of ["ben", "olive", "marta"] as const) expect((await messages(who, other)).status, `${who}: Rui's other private chat`).toBe(404);+ }, hostTimeout(90_000));++ it("a private conversation shared straight to the team: an admin can't do it for its person", async () => {+ const own = await opened("ana", scout, "Ana's own");+ await turn("ana", scout, own, "Ana's private line");+ expect((await as("olive", "POST", `/api/bots/${scout}/tasks/${own}/share`, { with: "team" })).status).toBe(404);+ expect((await as("ana", "POST", `/api/bots/${scout}/tasks/${own}/share`, { with: "team" })).status).toBe(200);+ expect((await messages("olive", own)).status).toBe(200);+ }, hostTimeout(90_000));+});++describe("saving to team memory", () => {+ let ruiEntry = "", benEntry = "";++ it("is refused from someone else's private conversation, for a member and an admin alike", async () => {+ const line = await lastLine("rui", other);+ for (const who of ["ben", "olive"] as const) {+ const refused = await as(who, "POST", `/api/bots/${scout}/memory/team`, { threadId: other, messageId: line, text: OTHER });+ expect(refused.status, `${who}: ${JSON.stringify(refused.body)}`).toBe(404);+ }+ expect(readFileSync(join(team.home, ".openmausbot", "workspaces", scout, "MEMORY.md"), "utf8")).not.toContain(OTHER);+ }, hostTimeout(60_000));++ it("from a person's own private conversation and from a shared one, saying who and when, and the next conversation with the bot reads it", async () => {+ const inboxBefore = { rui: await inboxLines("rui"), ben: await inboxLines("ben"), ana: await inboxLines("ana") };+ const saved = await as("rui", "POST", `/api/bots/${scout}/memory/team`, { threadId: other, messageId: await lastLine("rui", other), text: DECISION });+ expect(saved.status, JSON.stringify(saved.body)).toBe(201);+ ruiEntry = saved.body.entry.id;+ expect(saved.body.entry.text).toMatch(new RegExp(`^${DECISION} \\(saved by .+, \\d{4}-\\d{2}-\\d{2}\\)$`));+ const fromShared = await as("ben", "POST", `/api/bots/${scout}/memory/team`, { threadId: handoff, messageId: await lastLine("ben", handoff), text: "Ortega's number is in the CRM" });+ expect(fromShared.status, JSON.stringify(fromShared.body)).toBe(201);+ benEntry = fromShared.body.entry.id;+ const notes = readFileSync(join(team.home, ".openmausbot", "workspaces", scout, "MEMORY.md"), "utf8");+ expect(notes).toContain(DECISION);+ expect(notes, "nothing else of the private chat").not.toContain(OTHER);+ for (const who of ["rui", "ben", "ana"] as const) expect(await inboxLines(who), `${who}: no inbox line`).toBe(inboxBefore[who]);++ const fresh = await opened("ana", scout, "Launch questions");+ const dump = await turn("ana", scout, fresh, "When do we ship?");+ expect(said(dump)).toContain(DECISION);+ }, hostTimeout(120_000));++ it("keeps one note's worth of a very long message, saying it was shortened, rather than refusing it", async () => {+ const long = Array.from({ length: 600 }, (_, index) => `word${index}`).join(" ");+ const saved = await as("rui", "POST", `/api/bots/${scout}/memory/team`, { threadId: other, messageId: await lastLine("rui", other), text: long });+ expect(saved.status, JSON.stringify(saved.body)).toBe(201);+ expect(saved.body.entry.text).toMatch(/^word0 word1 .*… \(shortened; saved by .+, \d{4}-\d{2}-\d{2}\)$/);+ expect(saved.body.entry.text.length).toBeLessThan(1_100);+ expect((await as("rui", "DELETE", `/api/bots/${scout}/memory/team/${saved.body.entry.id}`)).status, "Undo").toBe(200);+ expect(readFileSync(join(team.home, ".openmausbot", "workspaces", scout, "MEMORY.md"), "utf8")).not.toContain("word0 word1 word2");+ }, hostTimeout(60_000));++ it("lists each person their own lines and an admin every line; only the author or an admin removes one", async () => {+ const mine = await as("rui", "GET", `/api/bots/${scout}/memory/team`);+ expect(mine.body.entries).toEqual([expect.objectContaining({ id: ruiEntry, yours: true })]);+ expect((await as("ana", "GET", `/api/bots/${scout}/memory/team`)).body.entries).toEqual([]);+ expect(((await as("olive", "GET", `/api/bots/${scout}/memory/team`)).body.entries as Array<{ id: string }>).map((entry) => entry.id).sort()).toEqual([ruiEntry, benEntry].sort());+ expect((await as("ben", "DELETE", `/api/bots/${scout}/memory/team/${ruiEntry}`)).status).toBe(403);+ expect((await as("ben", "PUT", `/api/bots/${scout}/memory/file`, { path: "MEMORY.md", text: "" })).status, "nor edit the notes").toBe(403);+ expect(readFileSync(join(team.home, ".openmausbot", "workspaces", scout, "MEMORY.md"), "utf8")).toContain(DECISION);+ expect((await as("rui", "DELETE", `/api/bots/${scout}/memory/team/${ruiEntry}`)).status).toBe(200);+ expect((await as("olive", "DELETE", `/api/bots/${scout}/memory/team/${benEntry}`)).status).toBe(200);+ const notes = readFileSync(join(team.home, ".openmausbot", "workspaces", scout, "MEMORY.md"), "utf8");+ expect(notes).not.toContain(DECISION);+ expect(notes).not.toContain("Ortega's number");+ }, hostTimeout(60_000));+});++describe("someone leaving", () => {+ it("hands a conversation shared with one person to the one who stays, as their own private chat", async () => {+ const plan = await opened("ben", scout, "Ben's plan");+ await turn("ben", scout, plan, "Ben's handover notes");+ expect((await as("ben", "POST", `/api/bots/${scout}/tasks/${plan}/share`, { with: { email: ANA.email } })).status).toBe(200);+ expect((await team.signed("POST", "/api/cloud/team/member-left", { email: BEN.email })).status).toBeLessThan(300);+ await expect.poll(async () => (await taskOf("ana", plan))?.private, { timeout: 10_000 }).toBe(true);+ expect(JSON.stringify((await messages("ana", plan)).body)).toContain("Ben's handover notes");+ expect((await messages("olive", plan)).status, "and nobody else's").toBe(404);+ }, hostTimeout(90_000));+});diff --git a/server/host/cloud-team-host.ts b/server/host/cloud-team-host.tsindex 6bc027aacf..60f665e025 100644--- a/server/host/cloud-team-host.ts+++ b/server/host/cloud-team-host.ts@@ -10,6 +10,7 @@ import { personKey } from "../person-key.ts";import { ensureWorkspace, loadMemory, workspaceDir } from "../workspace.ts";import type { EngineHomes } from "../engine-homes/engine-homes.ts";import { storeThreads, type StoreBotThreads } from "../engine-homes/migrate.ts";+import type { ConversationShares } from "./conversation-shares.ts";export interface CloudTeamHostDeps {team: CloudTeam | null;@@ -18,6 +19,8 @@ export interface CloudTeamHostDeps {starters: { get(threadId: string): string | undefined };/** Keys that name no person (nobody, outside). */markers: ReadonlySet<string>;+ /** Conversations their people shared (host/conversation-shares.ts). */+ shares?: Pick<ConversationShares, "audienceOf" | "readers" | "isShareKey">;language?: () => string | undefined;/** config.json's one profile. On a team it is nobody's: it is handed to the member whose address it names, then* cleared. */@@ -40,8 +43,13 @@ type MemberSession = { id: string; email?: string };export function createCloudTeamHost(deps: CloudTeamHostDeps) {const team = deps.team;const people: PeopleAbout = createPeopleAbout(deps.dataDir);- const audienceOf = (threadId: string): Audience =>- threadAudienceFrom({ room: deps.store.groupByThread(threadId)?.id, starter: deps.starters.get(threadId), markers: deps.markers });+ const audienceOf = (threadId: string): Audience => (team ? deps.shares?.audienceOf(threadId) : null)+ ?? threadAudienceFrom({ room: deps.store.groupByThread(threadId)?.id, starter: deps.starters.get(threadId), markers: deps.markers });+ /** The person an audience is private to; a conversation shared with one person is nobody's own. */+ const ownPerson = (audience: Audience): string | null => {+ const person = audienceMember(audience);+ return person && !deps.shares?.isShareKey(person) ? person : null;+ };if (team) deps.engineHomes?.start({ dataDir: deps.dataDir, audienceOf, threads: () => storeThreads(deps.store.bots ?? []) });/** The layer a turn in this conversation writes into: the bot's own folder off a team or for the team's conversations,* a sibling folder for a room's or a member's. The folder exists before the turn starts, so the box can bind it. */@@ -103,7 +111,7 @@ export function createCloudTeamHost(deps: CloudTeamHostDeps) {},/** Captured facts about the person, into that person's own "About you"; nothing for the team's or a room's layer. */learnAbout(layerOrBotId: string, plan: (current: string) => { next: string; count: number } | null): number {- const person = team ? audienceMember(layerAudience(layerOrBotId)) : null;+ const person = team ? ownPerson(layerAudience(layerOrBotId)) : null;if (!person) return 0;const planned = plan(people.read(person));if (!planned) return 0;@@ -127,7 +135,7 @@ export function createCloudTeamHost(deps: CloudTeamHostDeps) {* server's profile otherwise. */profileFor<T extends { aboutMe?: string }>(threadId: string, serverProfile: T | undefined): T | { aboutMe: string; person?: string } | undefined {if (!team) return serverProfile;- const person = audienceMember(audienceOf(threadId));+ const person = ownPerson(audienceOf(threadId));if (!person) return undefined;const name = personName(person);return { aboutMe: people.read(person), ...(name ? { person: name } : {}) };@@ -172,11 +180,11 @@ export function createCloudTeamHost(deps: CloudTeamHostDeps) {},/** The person whose "About you" a layer's captured facts belong to; null for the team's and a room's. */aboutPerson(layerOrBotId: string): string | null {- return team ? audienceMember(layerAudience(layerOrBotId)) : null;+ return team ? ownPerson(layerAudience(layerOrBotId)) : null;},/** A turn's captured facts are the member's own when the conversation is theirs. */ownTurn(threadId: string): boolean {- return team !== null && audienceMember(audienceOf(threadId)) !== null;+ return team !== null && ownPerson(audienceOf(threadId)) !== null;},people,baseBotId,@@ -184,7 +192,7 @@ export function createCloudTeamHost(deps: CloudTeamHostDeps) {* key, so another person's private chat is never theirs to see. Only the server itself (no address) sees everything. */audiencesFor(viewer: { kind: "all"; email?: string } | { kind: "member"; email?: string }): ThreadAudiences | undefined {if (!team || (viewer.kind === "all" && viewer.email === undefined)) return undefined;- return { of: audienceOf, person: viewer.email ? personKey({ id: "", email: viewer.email }) : null };+ return { of: audienceOf, person: viewer.email ? personKey({ id: "", email: viewer.email }) : null, ...(deps.shares ? { readers: deps.shares.readers } : {}) };},/** Whose browser a conversation's turns use: on a team its audience's (the member's, the group chat's or the team's),* the bot's own elsewhere. */@@ -203,7 +211,9 @@ export function createCloudTeamHost(deps: CloudTeamHostDeps) {return team && session.teamRole ? { id: team.id, name: team.name, role: session.teamRole } : null;},/** The person a conversation is private to on a team (theirs alone, audience.ts); null for the team's, a room's and- * anywhere off a team. */+ * anywhere off a team. Security invariant: a conversation shared with one person answers its share key, which no+ * session holds, so whatever follows this alone (a routine's home, an ask's person) reaches nobody rather than either+ * of its two readers. */privateTo(threadId: string): string | null {return team ? audienceMember(audienceOf(threadId)) : null;},diff --git a/server/host/conversation-shares.test.ts b/server/host/conversation-shares.test.tsnew file mode 100644index 0000000000..3b9c3315e6--- /dev/null+++ b/server/host/conversation-shares.test.ts@@ -0,0 +1,84 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { personKey } from "../person-key.ts";+import { createConversationShares, shareKey } from "./conversation-shares.ts";+import { teamMemoryLine, TEAM_MEMORY_TEXT_MAX } from "./team-memory-saves.ts";++const rui = personKey({ id: "", email: "[email protected]" });+const marta = personKey({ id: "", email: "[email protected]" });+const ana = personKey({ id: "", email: "[email protected]" });+let dir = "";++beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "team-share-shares-")); });+afterEach(() => { rmSync(dir, { recursive: true, force: true }); });++describe("conversation shares", () => {+ it("gives a conversation shared with one person an audience of its own that names no person, read by those two", () => {+ const shares = createConversationShares({ dataDir: dir, team: true });+ shares.share("t1", rui, marta, 100);+ expect(shares.audienceOf("t1")).toBe(`member:${shareKey("t1")}`);+ expect(shareKey("t1")).not.toBe(rui);+ expect(shares.readers("t1")).toEqual([rui, marta]);+ expect(shares.isShareKey(shareKey("t1"))).toBe(true);+ expect(shares.isShareKey(rui)).toBe(false);+ expect(shares.audienceOf("t2"), "never shared").toBeNull();+ shares.share("t1", rui, "team", 200);+ expect(shares.audienceOf("t1")).toBe("team");+ expect(shares.readers("t1")).toBeNull();+ expect(createConversationShares({ dataDir: dir, team: true }).audienceOf("t1"), "kept across a restart").toBe("team");+ });++ it("is nothing off a team", () => {+ createConversationShares({ dataDir: dir, team: true }).share("t1", rui, marta);+ const off = createConversationShares({ dataDir: dir, team: false });+ expect(off.audienceOf("t1")).toBeNull();+ expect(off.readers("t1")).toBeNull();+ });++ it("keeps what was said before a share with its owner, and what was said while shared with one person with those two", () => {+ const shares = createConversationShares({ dataDir: dir, team: true });+ shares.share("t1", rui, marta, 100);+ expect(shares.reaches({ threadId: "t1", at: 50 }, marta)).toBe(false);+ expect(shares.reaches({ threadId: "t1", at: 50 }, rui)).toBe(true);+ expect(shares.reaches({ threadId: "t1", at: 150 }, marta)).toBe(true);+ shares.share("t1", rui, "team", 200);+ expect(shares.reaches({ threadId: "t1", at: 150 }, marta)).toBe(true);+ expect(shares.reaches({ threadId: "t1", at: 150 }, ana)).toBe(false);+ expect(shares.reaches({ threadId: "t1", at: 50 }, marta)).toBe(false);+ expect(shares.reaches({ threadId: "t1", at: 250 }, ana)).toBe(true);+ });++ it("dissolves a share with one person when either leaves, into the other's own; the team's stays", () => {+ const shares = createConversationShares({ dataDir: dir, team: true });+ shares.share("handed", rui, marta);+ shares.share("received", ana, rui);+ shares.share("team", rui, "team");+ expect(shares.personLeft(rui)).toEqual([{ threadId: "handed", to: marta }, { threadId: "received", to: ana }]);+ expect(shares.audienceOf("handed")).toBeNull();+ expect(shares.audienceOf("team")).toBe("team");+ });++ it("marks each person's copy: shared, and who the other reader is", () => {+ const shares = createConversationShares({ dataDir: dir, team: true });+ shares.share("t1", rui, marta);+ const names = (key: string) => (key === rui ? "Rui" : "Marta");+ expect(shares.forViewer({ threadId: "t1" }, rui, names)).toEqual({ threadId: "t1", shared: true, sharedWith: { name: "Marta", byYou: true } });+ expect(shares.forViewer({ threadId: "t1" }, marta, names)).toEqual({ threadId: "t1", shared: true, sharedWith: { name: "Rui" } });+ expect(shares.forViewer({ threadId: "t9" }, rui, names)).toEqual({ threadId: "t9" });+ });+});++describe("a team memory line", () => {+ it("says who saved it and when", () => {+ expect(teamMemoryLine(" We ship\non 3 March ", "Rui", Date.UTC(2026, 10, 11))).toBe("We ship on 3 March (saved by Rui, 2026-11-11)");+ });++ it("keeps one note's worth of a long message, cut at a word, and says it was shortened", () => {+ const line = teamMemoryLine(Array.from({ length: 400 }, () => "word").join(" "), "Rui", Date.UTC(2026, 10, 11));+ expect(line).toMatch(/^word( word)*… \(shortened; saved by Rui, 2026-11-11\)$/);+ expect(line.length).toBeLessThanOrEqual(TEAM_MEMORY_TEXT_MAX + 50);+ });+});diff --git a/server/host/conversation-shares.ts b/server/host/conversation-shares.tsnew file mode 100644index 0000000000..55e4d85244--- /dev/null+++ b/server/host/conversation-shares.ts@@ -0,0 +1,115 @@+// On a Team Cloud a private conversation is shared only by the person it is private to: with the team, when it becomes+// the team's (audience `team`), or with one teammate. A conversation shared with one person has an audience of its own,+// `member:<share key>`, the key made from the conversation and held by no session: its memory layer, engine home and+// browser are its own, so neither person's private notes reach it, and nobody but its two readers (never an admin) sees+// it. Security invariant: a share is never undone into a narrower audience by anyone's request; only someone leaving the+// team dissolves one with one reader, into a private chat of the reader who stays.+import { createHash } from "node:crypto";+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { z } from "zod";++import { writeFileAtomic } from "../atomic.ts";+import { memberAudience, type Audience } from "../audience.ts";++export const CONVERSATION_SHARES_FILE = "conversation-shares.json";+const MAX_SHARES = 50_000;++const person = z.string().regex(/^p_[\w-]{22}$/);+const shareSchema = z.object({ owner: person, with: z.union([z.literal("team"), person]), at: z.number(), before: z.object({ with: person, at: z.number() }).optional() });+const fileSchema = z.record(z.string().regex(/^[\w-]{1,128}$/), shareSchema);++export type ConversationShare = z.infer<typeof shareSchema>;++export function shareKey(threadId: string): string {+ return `p_${createHash("sha256").update(`conversation:${threadId}`).digest("base64url").slice(0, 22)}`;+}++/** What someone leaving did to a share with one reader: the conversation is now `to`'s private chat. */+export interface DissolvedShare { threadId: string; to: string }++export function createConversationShares(deps: { dataDir: string; team: boolean }) {+ const file = join(deps.dataDir, CONVERSATION_SHARES_FILE);+ let shares: Record<string, ConversationShare> = {};+ if (deps.team) {+ try {+ const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));+ if (parsed.success) shares = parsed.data;+ else console.warn(`conversation shares: ${file} is not a shares file; nothing is shared`);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.warn(`conversation shares: ${file} is unreadable; nothing is shared`);+ }+ }+ const keys = () => new Set(Object.entries(shares).filter(([, share]) => share.with !== "team").map(([threadId]) => shareKey(threadId)));+ let shareKeys = keys();+ const save = () => {+ const entries = Object.entries(shares);+ if (entries.length > MAX_SHARES) shares = Object.fromEntries(entries.slice(-MAX_SHARES));+ shareKeys = keys();+ writeFileAtomic(file, `${JSON.stringify(shares)}\n`, { mode: 0o600 });+ };++ return {+ get(threadId: string): ConversationShare | undefined {+ return deps.team ? shares[threadId] : undefined;+ },+ /** The audience sharing gave the conversation; null when it was never shared. */+ audienceOf(threadId: string): Audience | null {+ const share = deps.team ? shares[threadId] : undefined;+ if (!share) return null;+ return share.with === "team" ? "team" : memberAudience(shareKey(threadId));+ },+ /** Who reads a conversation shared with one person: its owner and that person. Null for any other conversation. */+ readers(threadId: string): readonly string[] | null {+ const share = deps.team ? shares[threadId] : undefined;+ return share && share.with !== "team" ? [share.owner, share.with] : null;+ },+ /** A share key names a conversation, never a person: no About you, no inbox, no own connections. */+ isShareKey(key: string): boolean {+ return shareKeys.has(key);+ },+ /** A task as one person is sent it: marked shared, and when shared with one person, who the other reader is. */+ forViewer<T extends { threadId: string }>(task: T, viewer: string, nameOf: (person: string) => string | undefined): T {+ const share = deps.team ? shares[task.threadId] : undefined;+ if (!share) return task;+ if (share.with === "team") return { ...task, shared: true };+ const byYou = share.owner === viewer;+ const other = byYou ? share.with : share.owner;+ return { ...task, shared: true, sharedWith: { name: nameOf(other) ?? "", ...(byYou ? { byYou: true } : {}) } };+ },+ /** Whether a notification about the conversation reaches this person: one from before it was shared with them was+ * its owner's alone, and stays so. */+ reaches(entry: { threadId?: string; at: number }, person: string | null): boolean {+ const share = deps.team && entry.threadId ? shares[entry.threadId] : undefined;+ if (!share || entry.at >= share.at || person === share.owner) return true;+ return Boolean(share.before && person === share.before.with && entry.at >= share.before.at);+ },+ share(threadId: string, owner: string, to: "team" | string, at = Date.now()): ConversationShare {+ const earlier = shares[threadId];+ const before = earlier && earlier.with !== "team" ? { with: earlier.with, at: earlier.at } : undefined;+ const share = shareSchema.parse({ owner, with: to, at, ...(before ? { before } : {}) });+ shares[threadId] = share;+ save();+ return share;+ },+ /** Someone left: a conversation they shared with one person becomes that person's, one shared with them becomes its+ * owner's again. What was shared with the team stays the team's. */+ personLeft(key: string): DissolvedShare[] {+ const dissolved: DissolvedShare[] = [];+ for (const [threadId, share] of Object.entries(shares)) {+ if (share.with === "team" || (share.owner !== key && share.with !== key)) continue;+ dissolved.push({ threadId, to: share.owner === key ? share.with : share.owner });+ delete shares[threadId];+ }+ if (dissolved.length) save();+ return dissolved;+ },+ forget(threadIds: readonly string[]): void {+ const known = threadIds.filter((threadId) => Object.hasOwn(shares, threadId));+ for (const threadId of known) delete shares[threadId];+ if (known.length) save();+ },+ };+}++export type ConversationShares = ReturnType<typeof createConversationShares>;diff --git a/server/host/person-inbox.ts b/server/host/person-inbox.tsindex bced48b721..e6df53d96c 100644--- a/server/host/person-inbox.ts+++ b/server/host/person-inbox.ts@@ -442,6 +442,23 @@ export function createPersonInbox(deps: PersonInboxDeps) {route,answeredIn,answer: answerItem,+ /** One line per conversation that waits on this person: while their line about it is not answered or done, a newer+ * one takes its words and its place at the top instead of adding another. `created` when it is a new line. */+ keepOne(to: string, delivery: Delivery & { origin: Origin }): { item: Item; created: boolean } | null {+ const open = items.findLast((item) => item.person === to && item.kind === delivery.kind && item.origin?.threadId === delivery.origin.threadId && !item.done && !settled(item));+ const posted = open && line(open);+ if (!open || !posted) {+ const item = deliver(to, { ...delivery, quiet: true });+ return item ? { item, created: true } : null;+ }+ store.patchMessage(open.threadId, open.id, { text: delivery.text, ...(posted.inbox ? { inbox: { ...posted.inbox, from: delivery.from, ...(posted.inbox.origin ? { origin: { ...posted.inbox.origin, ...delivery.origin } } : {}) } } : {}) });+ Object.assign(open, { text: oneLine(delivery.text, 400), from: delivery.from.name.slice(0, 200), origin: delivery.origin, at: now(), seen: false });+ if (delivery.from.email) open.fromEmail = delivery.from.email; else delete open.fromEmail;+ save();+ touch(open.threadId);+ store.patchTask(open.botId, open.threadId, { unread: true });+ return { item: open, created: false };+ },/** The line in this inbox that `messageId` is, when it waits on an answer. */replyable(threadId: string, messageId: string): Item | undefined {return items.find((item) => item.threadId === threadId && item.id === messageId && item.to !== undefined);diff --git a/server/host/team-member-left.ts b/server/host/team-member-left.tsindex c7bc13bb1b..04be809850 100644--- a/server/host/team-member-left.ts+++ b/server/host/team-member-left.ts@@ -47,6 +47,8 @@ export interface TeamMemberLeftDeps {openedBy(person: string): string[];/** The person a conversation is private to (audience.ts), else null. */privateTo(threadId: string): string | null;+ /** Their conversations shared with one person become that person's own, before their private chats go. */+ sharesLeft?(person: string): void;/** Ends every session and open pairing code of this address; how many sessions ended. */revokeSessions(email: string): number;busy(botId: string, threadId: string): boolean;@@ -103,6 +105,7 @@ export function createTeamMemberLeft(deps: TeamMemberLeftDeps): (email: string)deps.record({ category: "bot", action: "routine.handover", target: { kind: "routine", id: routine.id, name: routine.name }, after: { owner: to } });}for (const routine of ownRoutines) deps.deleteRoutine(routine.id);+ deps.sharesLeft?.(person);const mine = new Set(deps.openedBy(person).filter((threadId) => deps.privateTo(threadId) === person));let chats = 0;const files = new Set<string>([...memberUploads(deps.dataDir, person), ...ownRoutines.flatMap((routine) => routine.files)]);diff --git a/server/host/team-memory-saves.ts b/server/host/team-memory-saves.tsnew file mode 100644index 0000000000..743987c5c8--- /dev/null+++ b/server/host/team-memory-saves.ts@@ -0,0 +1,111 @@+// "Save to team memory" on a Team Cloud: a line a person chose from a conversation they read goes into the bot's team+// notes (MEMORY.md in the bot's own folder, which every conversation with it reads), saying who added it and when.+// Security invariant: only a person's own request adds one, and only its author or an admin takes one out; the line+// names no conversation, so nothing records where a private one came from.+import { randomUUID } from "node:crypto";+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { z } from "zod";++import { writeFileAtomic } from "../atomic.ts";+import { journalMemoryWrite } from "../memory-journal.ts";+import { MEMORY_INDEX, MemoryStoreError, readMemoryDoc } from "../memory-store.ts";++export const TEAM_MEMORY_SAVES_FILE = "team-memory-saves.json";+export const TEAM_MEMORY_TEXT_MAX = 1_000;+const MAX_ENTRIES = 5_000;+const WRITE_TRIES = 3;++const entrySchema = z.object({+ id: z.string().regex(/^[\w-]{1,64}$/), botId: z.string().regex(/^[\w-]{1,128}$/), person: z.string().regex(/^p_[\w-]{22}$/),+ line: z.string().max(TEAM_MEMORY_TEXT_MAX + 300), at: z.number(),+});+export type TeamMemoryEntry = z.infer<typeof entrySchema>;++/** One bullet: the words on one line, then who saved them and the day. Words past what one note holds are cut at a word+ * and the note says it was shortened. */+export function teamMemoryLine(text: string, name: string, at: number): string {+ const all = text.replace(/\s+/g, " ").trim();+ const cut = all.length > TEAM_MEMORY_TEXT_MAX ? all.slice(0, TEAM_MEMORY_TEXT_MAX).replace(/\s+\S*$/, "") : all;+ const who = name.replace(/\s+/g, " ").trim().slice(0, 80) || "a teammate";+ const day = new Date(at).toISOString().slice(0, 10);+ return cut === all ? `${all} (saved by ${who}, ${day})` : `${cut}… (shortened; saved by ${who}, ${day})`;+}++const bullets = (text: string): string[] => text.split("\n").map((line) => /^\s*[-*]\s+(.+?)\s*$/.exec(line)?.[1]).filter((line): line is string => Boolean(line));++export function createTeamMemorySaves(deps: { dataDir: string; now?: () => number }) {+ const file = join(deps.dataDir, TEAM_MEMORY_SAVES_FILE);+ const now = deps.now ?? Date.now;+ let entries: TeamMemoryEntry[] = [];+ try {+ const parsed = z.array(entrySchema).safeParse(JSON.parse(readFileSync(file, "utf8")));+ if (parsed.success) entries = parsed.data;+ } catch {}+ const save = () => {+ entries = entries.slice(-MAX_ENTRIES);+ writeFileAtomic(file, `${JSON.stringify(entries)}\n`, { mode: 0o600 });+ };+ /** MEMORY.md written against the hash it was read at, so a note the bot writes meanwhile is kept. */+ const rewrite = (botId: string, change: (text: string) => string | null): boolean => {+ for (let attempt = 0; attempt < WRITE_TRIES; attempt++) {+ const doc = readMemoryDoc(botId, MEMORY_INDEX);+ const next = change(doc.text);+ if (next === null) return false;+ try {+ journalMemoryWrite(botId, MEMORY_INDEX, next, { actor: "person", via: "team-save", expectedHash: doc.hash });+ return true;+ } catch (error) {+ if (!(error instanceof MemoryStoreError) || error.code !== "conflict") throw error;+ }+ }+ throw new MemoryStoreError("conflict", 409, "The team's notes kept changing. Try again.");+ };+ /** An entry whose line an admin edited or took out of MEMORY.md is gone. */+ const present = (botId: string): TeamMemoryEntry[] => {+ const lines = new Set(bullets(readMemoryDoc(botId, MEMORY_INDEX).text));+ return entries.filter((entry) => entry.botId === botId && lines.has(entry.line));+ };++ return {+ add(input: { botId: string; person: string; name: string; text: string }): TeamMemoryEntry {+ const at = now();+ const line = teamMemoryLine(input.text, input.name, at);+ rewrite(input.botId, (text) => {+ const body = text.replace(/\s+$/, "");+ return body ? `${body}\n- ${line}\n` : `- ${line}\n`;+ });+ const entry: TeamMemoryEntry = { id: randomUUID(), botId: input.botId, person: input.person, line, at };+ entries.push(entry);+ save();+ return entry;+ },+ /** A member's own entries; every entry for an admin. */+ list(botId: string, viewer: { person: string; admin: boolean }): TeamMemoryEntry[] {+ return present(botId).filter((entry) => viewer.admin || entry.person === viewer.person);+ },+ remove(botId: string, id: string, by: { person: string; admin: boolean }): "removed" | "gone" | "not-yours" {+ const entry = entries.find((candidate) => candidate.botId === botId && candidate.id === id);+ if (!entry) return "gone";+ if (!by.admin && entry.person !== by.person) return "not-yours";+ rewrite(botId, (text) => {+ const lines = text.split("\n");+ const at = lines.findIndex((line) => /^\s*[-*]\s+(.+?)\s*$/.exec(line)?.[1] === entry.line);+ if (at < 0) return null;+ lines.splice(at, 1);+ return lines.join("\n");+ });+ entries = entries.filter((candidate) => candidate !== entry);+ save();+ return "removed";+ },+ /** A person left: the lines they saved stay in the team's notes, as anything else they did for the team. */+ personLeft(person: string): void {+ if (!entries.some((entry) => entry.person === person)) return;+ entries = entries.filter((entry) => entry.person !== person);+ save();+ },+ };+}++export type TeamMemorySaves = ReturnType<typeof createTeamMemorySaves>;diff --git a/server/host/team-presence-host.ts b/server/host/team-presence-host.tsindex 0ae91dcfc9..bc81ec4a23 100644--- a/server/host/team-presence-host.ts+++ b/server/host/team-presence-host.ts@@ -26,6 +26,8 @@ export interface TeamPresenceHostDeps {/** A frame every team stream gets, replayed to one that reconnects (`team.people`). */broadcast(payload: Record<string, unknown>): void;audienceOf(threadId: string): Audience;+ /** A conversation its person shared with one other person (host/conversation-shares.ts): read by those two. */+ sharedWithOne?(threadId: string): boolean;store(): Pick<Store, "botByThread" | "groupByThread" | "bot">;visibleTo(viewer: Viewer): Pick<VisibleSet, "thread">;clock?: PresenceClock;@@ -56,7 +58,7 @@ export function createTeamPresenceHost<Stream extends PresenceStream>(deps: Team/** More than one person can read it: never a conversation that is someone's own, nor one with someone's own bot. */function shared(threadId: string): boolean {- if (audienceMember(deps.audienceOf(threadId)) !== null) return false;+ if (audienceMember(deps.audienceOf(threadId)) !== null && !deps.sharedWithOne?.(threadId)) return false;const store = deps.store();const group = store.groupByThread(threadId);const bots = group ? group.memberIds.map((id) => store.bot(id)) : [store.botByThread(threadId)];@@ -125,6 +127,10 @@ export function createTeamPresenceHost<Stream extends PresenceStream>(deps: Teamstreams,/** What the people list says of someone: whether they are here now. Undefined off a team. */of: presence ? (email: string): PersonPresence => ({ here: presence.here(email) }) : undefined,+ /** Whether this person has the conversation open in a window now. */+ looking(email: string, threadId: string): boolean {+ return presence?.viewers(threadId).includes(email) === true;+ },close(): void {presence?.close();peopleTimer?.cancel();diff --git a/server/index.ts b/server/index.tsindex de367b877b..bce96a5db6 100644--- a/server/index.ts+++ b/server/index.ts@@ -544,7 +544,7 @@ import {sessionCookieName, ownerOrAdmin, acceptLegacyOrigins,} from "./request-auth.ts";import { cookieMaxAgeSeconds, formatPairingCode, pairingRequest, SessionRegistry, type SessionRecord } from "./sessions.ts";-import { ThreadStarters } from "./thread-starters.ts";+import { ThreadStarters } from "./thread-starters.ts"; import { createConversationShares } from "./host/conversation-shares.ts"; import { createTeamMemorySaves } from "./host/team-memory-saves.ts"; import { createConversationSharing } from "./routes/conversation-share.ts";import { startPhoneRelay } from "./phone-relay.ts";import {appendAdminAction,@@ -730,7 +730,7 @@ await startBotBoxAtBoot({ dataDir: DATA_DIR, port: PORT }); // The bot box (servif (CLOUD_HOME && Object.keys(CLOUD_SECRETS).length === 0) {console.warn("cloud home: its secrets came in this process's environment, which anything running as the same user can read in /proc; start it with cloud-home-start");}-const threadStarters = new ThreadStarters(join(DATA_DIR, "thread-starters.json"));+const threadStarters = new ThreadStarters(join(DATA_DIR, "thread-starters.json")); const conversationShares = createConversationShares({ dataDir: DATA_DIR, team: Boolean(CLOUD_TEAM) });const commandAllowlist = new CommandAllowlistStore(join(DATA_DIR, "command-allowlist.json"));// Every value saved in the Vault is scrubbed from whatever a bot or a transcript can read.const logins = new VaultStore({ dataDir: DATA_DIR, secretChanged: (item) => mcpServersHost.keyChanged(item) });@@ -955,10 +955,10 @@ const CLOUD_OWNER_KEY = CLOUD_PERSONAL ? `p_${createHash("sha256").update(`cloud/** Settled at boot once routines load (settleCloudHome); only `proven` feeds lending and memory. */let cloudEarlierOwners: Pick<CloudOwnership, "adopted" | "proven"> = { adopted: new Set(), proven: new Set() };/** Until it is settled, a Cloud home counts as shared. */-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,+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, shares: conversationShares, 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 vaultReaders = createVaultReaders({ team: CLOUD_TEAM !== null, audienceOf: (threadId) => teamHost.audienceOf(threadId), personOf: actorKey });const teamOwners = createTeamOwners({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store: () => store, audienceOf: (threadId) => teamHost.audienceOf(threadId), starters: threadStarters }); const mausbotOwnChat = createMausBotOwnChat({ bots: () => store.bots, starters: threadStarters, personKey: (email) => personKey({ id: "", email }), moveNotes: (from, to, person) => moveMemoryLayer(from, to, personLanguages.forLine(person)) });-const personRooms = createPersonRooms({ reads: CLOUD_TEAM ? createRoomReads(DATA_DIR, (person) => { botOrders?.forgetPerson(person); forgetNotificationReader(person); }) : null, store: () => store, newestMessageId: (threadId) => readCursor(threadId).lastReadMessageId, publicGroupState, broadcast, shared: (threadId) => teamHost.privateTo(threadId) === null, wireBot: (botId) => { const bot = store.bot(botId); return bot ? wireBot(bot) : null; } });+const personRooms = createPersonRooms({ reads: CLOUD_TEAM ? createRoomReads(DATA_DIR, (person) => { botOrders?.forgetPerson(person); forgetNotificationReader(person); }) : null, store: () => store, newestMessageId: (threadId) => readCursor(threadId).lastReadMessageId, publicGroupState, broadcast, shared: (threadId) => teamHost.privateTo(threadId) === null || conversationShares.readers(threadId) !== null, wireBot: (botId) => { const bot = store.bot(botId); return bot ? wireBot(bot) : null; } });const botOrders = CLOUD_TEAM ? createPersonBotOrder(DATA_DIR) : null; const teamRoutines = createTeamRoutines({ team: Boolean(CLOUD_TEAM), privateTo: teamHost.privateTo, task: (botId, threadId) => store.taskByThread(botId, threadId), routines: () => routines, authors: cloudRoutineAuthors, withWriter: withRoutineWriter, ownBot: (botId) => { const person = store.bot(botId)?.defaultBot?.person; return person ? personKey({ id: "", email: person }) : null; }, tasks: (botId) => store.tasks(botId), threadRefusal: cloudThreadRefusal, openChat: (botId, title, person) => { const threadId = store.createTask(botId, title, false)?.threadId; if (threadId) threadStarters.set(threadId, person); return threadId; } });function actorKey(auth: RequestAuth & { kind: "session" }): string {@@ -1140,7 +1140,7 @@ async function answeringCardAs(auth: RequestAuth, threadId: string, requestId: s}const { viewerFor, threadOwner, visibleTo, forgetVisibility, threadShown, subjectVisible, hiddenRoutineTarget, roomFeedsBot, settleRoomFloor } = createVisibilityHost({ store: () => store, routines: () => routines,- team: Boolean(CLOUD_TEAM), audiencesFor: (viewer) => { const audiences = teamHost.audiencesFor(viewer), person = audiences?.person; return audiences && person ? { ...audiences, routineHome: teamRoutines.home, ownTask: (task) => personRooms.taskForPerson(task, person) } : audiences && { ...audiences, routineHome: teamRoutines.home }; }, threadsReferencing }); if (CLOUD_TEAM) hideOthersSyncFolders(() => store.bots, threadShown); const notificationListed = notificationListedFor(threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined, CLOUD_TEAM ? (auth) => (auth.kind === "session" ? personKey(auth.session) : null) : undefined); const botAccess = createBotAccessHost({ visibleFor: (auth) => visibleTo(viewerFor(auth)), store: () => store, routines: () => routines, threadOwner, routineWriter: (id) => cloudRoutineAuthors?.writer(id) }), { levelOf } = botAccess; const accessRequests = createAccessRequests({ team: CLOUD_TEAM, store: () => store, people: () => teamOwners.people?.list() ?? [], profileName: (email) => teamHost.people.profile(personKey({ id: "", email })).name, inbox: () => teamMessages.inbox, visibleTo, levelOf, writeAccess: (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access), record: (row, by) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: by, email: by } }) });+ team: Boolean(CLOUD_TEAM), audiencesFor: (viewer) => { const audiences = teamHost.audiencesFor(viewer), person = audiences?.person; return audiences && person ? { ...audiences, routineHome: teamRoutines.home, ownTask: (task) => conversationShares.forViewer(personRooms.taskForPerson(task, person), person, teamHost.personName) } : audiences && { ...audiences, routineHome: teamRoutines.home }; }, threadsReferencing }); if (CLOUD_TEAM) hideOthersSyncFolders(() => store.bots, threadShown); const notificationListed = notificationListedFor(threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) && conversationShares.reaches(entry, auth.kind === "session" ? personKey(auth.session) : null) : undefined, CLOUD_TEAM ? (auth) => (auth.kind === "session" ? personKey(auth.session) : null) : undefined); const botAccess = createBotAccessHost({ visibleFor: (auth) => visibleTo(viewerFor(auth)), store: () => store, routines: () => routines, threadOwner, routineWriter: (id) => cloudRoutineAuthors?.writer(id) }), { levelOf } = botAccess; const accessRequests = createAccessRequests({ team: CLOUD_TEAM, store: () => store, people: () => teamOwners.people?.list() ?? [], profileName: (email) => teamHost.people.profile(personKey({ id: "", email })).name, inbox: () => teamMessages.inbox, visibleTo, levelOf, writeAccess: (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access), record: (row, by) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: by, email: by } }) });function recentWorkFilter(threadId: string): { include?: (threadId: string) => boolean; privateThread?: (threadId: string) => boolean } {const include = CLOUD_TEAM ? (id: string) => teamHost.readableFrom(threadId)(id) && outsideLineage.mayReach(id, threadId) : CLOUD_HOME ? cloudOwnerOnlyThread : () => true; return { include: (id) => !botApiThread(id) && include(id), ...(CLOUD_TEAM ? { privateThread: (id: string) => teamHost.privateTo(id) !== null } : {}) };@@ -4625,7 +4625,7 @@ interface SseClient {/** Stops the heartbeat and leaves `sseClients` before ending the response; every way a stream ends goes through it. */close: () => void;}-const { streams: sseClients, ...teamPresence } = createTeamPresenceHost<SseClient>({ people: teamOwners.people, broadcast, audienceOf: (threadId) => teamHost.audienceOf(threadId), store: () => store, visibleTo });+const { streams: sseClients, ...teamPresence } = createTeamPresenceHost<SseClient>({ people: teamOwners.people, broadcast, audienceOf: (threadId) => teamHost.audienceOf(threadId), sharedWithOne: (threadId) => conversationShares.readers(threadId) !== null, store: () => store, visibleTo });let audienceChangedAt = 0;function audienceChanged(): void {@@ -12199,7 +12199,7 @@ ROUTES.push(createBotMemoryRoutes({broadcast({ kind: "config", ...configStatus() });},}));-const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL || DESKTOP_MANAGED ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: Boolean(botMoves) })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes(updateRouteDeps({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE), dataDir: DATA_DIR, activeTurns: () => liveTurnByThread.size, actor: adminActorFor })), createSeatsRoutes({ signInList: signInAllowList, sessions: () => sessions.list() }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));+const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL || DESKTOP_MANAGED ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: Boolean(botMoves) })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes(updateRouteDeps({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE), dataDir: DATA_DIR, activeTurns: () => liveTurnByThread.size, actor: adminActorFor })), createSeatsRoutes({ signInList: signInAllowList, sessions: () => sessions.list() }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages)); const conversationSharing = createConversationSharing({ team: CLOUD_TEAM, store: () => store, shares: conversationShares, saves: createTeamMemorySaves({ dataDir: DATA_DIR }), starter: (threadId) => threadStarters.get(threadId), audienceOf: teamHost.audienceOf, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), levelOf, levelFor: (person, botId) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }).level(botId), people: () => teamOwners.people?.list() ?? [], nameOf: (email) => teamHost.personName(personKey({ id: "", email })) ?? email, language: (person) => personLanguages.forLine(person), busy: threadBusy, routinesIn: (threadId) => (routines?.listRoutines() ?? []).filter((routine) => routine.sourceThreadId === threadId || routine.resultsThreadId === threadId).length, outside: cloudGuestDriven, audienceChanged: (botId, threadId) => { store.patchTask(botId, threadId, { rewound: true, resumeCursors: {} }); }, changed: (botId) => { const bot = store.bot(botId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, inbox: () => teamMessages.inbox, looking: (email, threadId) => teamPresence.looking(email, threadId), notify, botOf: (threadId) => store.botByThread(threadId)?.id, handTo: (threadId, person) => threadStarters.handTo(threadId, person) }); ROUTES.push(conversationSharing.routes);if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));ROUTES.push(teamPresence.routes, createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) })); const appSuggestions = createAppSuggestions({ dataDir: DATA_DIR, store, configured: () => composio.configured(cfg), catalog: () => composio.listToolkits(cfg), services: () => composio.connectedServices(cfg), offerable: (slug) => !managedPolicy.appRefusal(slug) && !managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) && !teamConnections.personApps().includes(slug), pickAvailable: () => appPickAvailable(cfg), decider }); ROUTES.push(createAppSuggestionRoutes(appSuggestions));@@ -12298,7 +12298,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, 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) => { connectionHealth.forgetPerson(person); personRooms.reads?.forgetPerson(person); return teamConnections.forgetPerson(person); }, forgetSecrets: (person) => { logins.forgetPerson(person); }, ...teamRoutines.leaving, forgetOnBots: (email) => forgetMember(store, email, (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access)).length, ownerOf: (botId) => { const bot = store.bot(botId); return bot ? botOwner(bot) : null; }, record: (row) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: "MausBot Cloud" } }) }) : null;+}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, sharesLeft: conversationSharing.personLeft, 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) => { connectionHealth.forgetPerson(person); personRooms.reads?.forgetPerson(person); return teamConnections.forgetPerson(person); }, forgetSecrets: (person) => { logins.forgetPerson(person); }, ...teamRoutines.leaving, forgetOnBots: (email) => forgetMember(store, email, (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access)).length, ownerOf: (botId) => { const bot = store.bot(botId); return bot ? botOwner(bot) : null; }, record: (row) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: "MausBot Cloud" } }) }) : null;ROUTES.push(createTeamRoutes({store,cfg,@@ -12743,7 +12743,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {...(auth.session.email ? { email: auth.session.email } : {}),...(auth.session.owner ? { owner: auth.session.owner } : {}),...(HOSTED_WORKSPACE ? { hosted: true } : {}),- ...(CLOUD_HOME ? { cloudHome: true } : {}), ...teamSignInFor(CLOUD_HOME, auth.session), ...(ownHome.owner(auth) ? { own: true, ...(ownerLends() ? { lending: OWNER_LENDING } : {}) } : {}), ...(teamHost.sessionInfo(auth.session) ? { team: teamHost.sessionInfo(auth.session), openedThreads: threadStarters.threadsOf(actorKey(auth), 2_000) } : {}),+ ...(CLOUD_HOME ? { cloudHome: true } : {}), ...teamSignInFor(CLOUD_HOME, auth.session), ...(ownHome.owner(auth) ? { own: true, ...(ownerLends() ? { lending: OWNER_LENDING } : {}) } : {}), ...(teamHost.sessionInfo(auth.session) ? { team: teamHost.sessionInfo(auth.session), openedThreads: threadStarters.threadsOf(actorKey(auth), 2_000).filter((threadId) => !conversationShares.get(threadId)) } : {}),...(CLOUD_PERSONAL && !cloudOwnerSession(auth) ? { cloudGuest: true, openedThreads: threadStarters.threadsOf(actorKey(auth), 2_000) } : {}),...(reactorFor(auth).by !== "user" ? { reactor: reactorFor(auth).by } : {}),},diff --git a/server/request-auth.ts b/server/request-auth.tsindex a55bed6622..e3b0ad4e8f 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -431,6 +431,11 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg// 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 member sharing their own private conversation, and saving a line to a bot's team memory: the handler+ // lets only the conversation's person share it and only its author or an admin remove a line (routes/conversation-share.ts)+ { methods: ["GET", "POST"], path: /^\/api\/bots\/[\w-]+\/tasks\/[\w-]+\/share$/ },+ { methods: ["GET", "POST"], path: /^\/api\/bots\/[\w-]+\/memory\/team$/ },+ { methods: ["DELETE"], path: /^\/api\/bots\/[\w-]+\/memory\/team\/[\w-]+$/ },// 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 backdiff --git a/server/routes/conversation-share.test.ts b/server/routes/conversation-share.test.tsnew file mode 100644index 0000000000..1f942c8160--- /dev/null+++ b/server/routes/conversation-share.test.ts@@ -0,0 +1,60 @@+// The routes refuse anything but a team member's own signed-in session: the server itself (a bot's loopback call, a+// service), a session the team's Admin never signed and any server that is not a team's reach nothing here.+import { describe, expect, it, vi } from "vitest";++import type { RequestAuth } from "../request-auth.ts";+import type { SessionRecord } from "../sessions.ts";+import { createConversationSharing, type ConversationShareDeps } from "./conversation-share.ts";+import { PASS, type RouteContext } from "./table.ts";++const share = vi.fn(), add = vi.fn();+const deps = (team: boolean): ConversationShareDeps => ({+ team: team ? { id: "acme", name: "Acme" } : null,+ store: () => ({ bot: () => ({ id: "scout", name: "Scout" }), taskByThread: () => ({ threadId: "t1", title: "Plan" }), messagesFor: () => [{ id: "m1" }], onChange: () => () => {} }) as never,+ shares: { get: () => undefined, share, readers: () => null, personLeft: () => [] } as never,+ saves: { add, list: () => [], remove: () => "gone", personLeft: () => {} } as never,+ starter: () => undefined, audienceOf: () => "team", sees: () => true, levelOf: () => "edit", levelFor: () => "edit",+ people: () => [], nameOf: (email) => email, language: () => undefined, busy: () => false, routinesIn: () => 0, outside: () => false,+ audienceChanged: vi.fn(), changed: vi.fn(), inbox: () => ({ keepOne: () => null }), looking: () => false, notify: vi.fn(),+ botOf: () => "scout", handTo: vi.fn(),+});++async function call(team: boolean, auth: RequestAuth, method: string, path: string, body: unknown = {}) {+ let status = 0;+ const answered = await createConversationSharing(deps(team)).routes({+ req: {} as never, res: {} as never, url: new URL(`http://x${path}`), path, method, auth,+ json: ((_res: unknown, code: number) => { status = code; }) as never, readBody: (async () => body) as never,+ } as RouteContext);+ return answered === PASS ? "pass" : status;+}++const member = (extra: Partial<SessionRecord> = {}): RequestAuth => ({ kind: "session", via: "bearer", scopes: ["client"],+ session: { id: "s1", email: "[email protected]", membershipAuthority: "team", ...extra } as SessionRecord });++describe("who reaches sharing and team memory", () => {+ const routes: Array<[string, string, unknown]> = [+ ["POST", "/api/bots/scout/tasks/t1/share", { with: "team" }],+ ["GET", "/api/bots/scout/tasks/t1/share", undefined],+ ["POST", "/api/bots/scout/memory/team", { threadId: "t1", messageId: "m1", text: "x" }],+ ["DELETE", "/api/bots/scout/memory/team/e1", undefined],+ ];++ it("refuses the server itself, as a bot's own call would come, with every scope", async () => {+ for (const [method, path, body] of routes) expect(await call(true, { kind: "loopback", scopes: ["admin", "client"] }, method, path, body), `${method} ${path}`).toBe(404);+ expect(share).not.toHaveBeenCalled();+ expect(add).not.toHaveBeenCalled();+ });++ it("refuses a session no team membership vouches for, and everything off a team", async () => {+ for (const [method, path, body] of routes) {+ expect(await call(true, member({ membershipAuthority: undefined }), method, path, body)).toBe(404);+ expect(await call(false, member(), method, path, body)).toBe(404);+ }+ expect(share).not.toHaveBeenCalled();+ expect(add).not.toHaveBeenCalled();+ });++ it("leaves every other path to the routes after it", async () => {+ expect(await call(true, member(), "GET", "/api/bots/scout/memory/mine", undefined)).toBe("pass");+ });+});diff --git a/server/routes/conversation-share.ts b/server/routes/conversation-share.tsnew file mode 100644index 0000000000..2297edaa39--- /dev/null+++ b/server/routes/conversation-share.ts@@ -0,0 +1,206 @@+// Sharing a private conversation and saving a line to a bot's team memory, on a Team Cloud only.+// Security invariant: only a signed-in person acts here, never a bot, a script without a person or the server itself.+// Sharing is the conversation's own person's act alone (an admin can't, and can't see it); saving needs only to read the+// conversation, which for a private one is again its person alone. The visibility and access gates have already+// answered 404 for a conversation the caller can't see and 403 for a bot they can't chat with; each check is repeated+// here so a route never depends on a gate it can't see.+import { z } from "zod";++import { atLeast, type BotAccessLevel } from "../../shared/bot-access.ts";+import { memberAudience, type Audience } from "../audience.ts";+import type { CloudTeam, TeamRole } from "../cloud-team.ts";+import type { PersonInbox } from "../host/person-inbox.ts";+import { NO_SUCH_CONVERSATION } from "../host/team-private.ts";+import type { ConversationShare, ConversationShares } from "../host/conversation-shares.ts";+import type { TeamMemorySaves } from "../host/team-memory-saves.ts";+import type { Notification } from "../../shared/notification.ts";+import { personKey } from "../person-key.ts";+import type { RequestAuth } from "../request-auth.ts";+import { serverLine, type ServerLineKey } from "../server-lines.ts";+import type { BotRecord, Message, Store } from "../store.ts";+import { userError } from "../user-errors.ts";+import { PASS, type RouteHandler } from "./table.ts";++/** Longer words are cut to one note (team-memory-saves.ts); this only bounds what a request may carry. */+const TEAM_MEMORY_BODY_MAX = 100_000;+const SHARE = /^\/api\/bots\/([\w-]{1,128})\/tasks\/([\w-]{1,128})\/share$/;+const TEAM_MEMORY = /^\/api\/bots\/([\w-]{1,128})\/memory\/team(?:\/([\w-]{1,64}))?$/;++const shareBody = z.object({ with: z.union([z.literal("team"), z.object({ email: z.string().email().max(320) })]) });+const saveBody = z.object({ threadId: z.string().regex(/^[\w-]{1,128}$/), messageId: z.string().regex(/^[\w-]{1,128}$/), text: z.string().max(TEAM_MEMORY_BODY_MAX) });++export interface ConversationShareDeps {+ team: CloudTeam | null;+ store(): Pick<Store, "bot" | "taskByThread" | "messagesFor" | "onChange">;+ shares: ConversationShares;+ saves: TeamMemorySaves;+ starter(threadId: string): string | undefined;+ audienceOf(threadId: string): Audience;+ /** Whether this session may read the conversation (VisibleSet.thread). */+ sees(auth: RequestAuth, threadId: string): boolean;+ levelOf(auth: RequestAuth, botId: string): BotAccessLevel;+ /** A teammate's level on a bot, as their own session would have it. */+ levelFor(person: { email: string; role: TeamRole }, botId: string): BotAccessLevel;+ /** The team's current members. */+ people(): ReadonlyArray<{ email: string; role: TeamRole }>;+ /** What a person is called: the name they chose, else their address. */+ nameOf(email: string): string;+ /** The language a person reads the server's lines in. */+ language(person: string): string | undefined;+ busy(botId: string, threadId: string): boolean;+ /** Routines whose home is this conversation (routine-home.ts). */+ routinesIn(threadId: string): number;+ /** The conversation came in from outside (host/outside-lineage.ts). */+ outside(threadId: string): boolean;+ /** The conversation now runs in another audience: its next turn opens a new engine session with the whole history. */+ audienceChanged(botId: string, threadId: string): void;+ /** Each person's copy of the bot goes out again. */+ changed(botId: string): void;+ inbox(): Pick<PersonInbox, "keepOne">;+ /** Whether this person has the conversation open in a window now (host/team-presence-host.ts). */+ looking(email: string, threadId: string): boolean;+ notify(notification: Notification): void;+ /** The bot a conversation belongs to. */+ botOf(threadId: string): string | undefined;+ /** The conversation becomes this person's own (thread-starters.ts handTo). */+ handTo(threadId: string, person: string): void;+}++type Me = { email: string; person: string; admin: boolean };++function signedIn(auth: RequestAuth): Me | null {+ if (auth.kind !== "session" || auth.session.membershipAuthority !== "team" || !auth.session.email) return null;+ return { email: auth.session.email.trim().toLowerCase(), person: personKey(auth.session), admin: auth.scopes.includes("admin") };+}++export function createConversationSharing(deps: ConversationShareDeps): { routes: RouteHandler; personLeft(person: string): void } {+ const sharedAs = (share: ConversationShare | undefined) => {+ if (!share) return null;+ if (share.with === "team") return "team" as const;+ const email = deps.people().find((person) => personKey({ id: "", email: person.email }) === share.with)?.email;+ return email ? { email, name: deps.nameOf(email) } : null;+ };+ const nameOfShare = (share: ConversationShare) => {+ const as = sharedAs(share);+ return as && as !== "team" ? as.name : "someone";+ };+ const canChat = (person: { email: string; role: TeamRole }, botId: string) => atLeast(deps.levelFor(person, botId), "chat");++ const routes: RouteHandler = async ({ req, res, path, method, auth, json, readBody }) => {+ const share = SHARE.exec(path);+ const memory = share ? null : TEAM_MEMORY.exec(path);+ if (!share && !memory) return PASS;+ const me = deps.team ? signedIn(auth) : null;+ if (!me) return json(res, 404, { error: "not found" });+ const store = deps.store();+ const bot = store.bot((share ?? memory)![1]!);+ if (!bot) return json(res, 404, userError("serverError.bot.missing"));++ if (share) {+ if (method !== "GET" && method !== "POST") return PASS;+ const threadId = share[2]!;+ const task = store.taskByThread(bot.id, threadId);+ if (!task || !deps.sees(auth, threadId)) return json(res, 404, { error: NO_SUCH_CONVERSATION });+ if (bot.defaultBot) return json(res, 409, userError("serverError.share.ownBot"));+ const current = deps.shares.get(threadId);+ if (current?.with === "team") return json(res, 409, userError("serverError.share.alreadyTeam"));+ const mine = deps.starter(threadId) === me.person && (current ? current.owner === me.person : deps.audienceOf(threadId) === memberAudience(me.person));+ if (!mine) return json(res, 403, userError("serverError.share.notYours"));+ const eligible = () => deps.people().filter((person) => person.email !== me.email && canChat(person, bot.id))+ .map((person) => ({ email: person.email, name: deps.nameOf(person.email) })).sort((a, b) => a.name.localeCompare(b.name));+ if (method === "GET") return json(res, 200, { shared: sharedAs(current), people: eligible() });++ const parsed = shareBody.safeParse(await readBody(req));+ if (!parsed.success) return json(res, 400, { error: "with must be \"team\" or { email }" });+ const wanted = parsed.data.with;+ const recipient = wanted === "team" ? null : deps.people().find((person) => person.email === wanted.email.trim().toLowerCase());+ if (wanted !== "team") {+ if (!recipient || recipient.email === me.email) return json(res, 409, userError("serverError.share.notTeammate", { name: wanted.email }));+ if (current) {+ return current.with === personKey({ id: "", email: recipient.email }) ? json(res, 200, { shared: sharedAs(current) })+ : json(res, 409, userError("serverError.share.alreadyWith", { name: nameOfShare(current) }));+ }+ if (!canChat(recipient, bot.id)) return json(res, 409, userError("serverError.share.cantUse", { name: deps.nameOf(recipient.email), bot: bot.name }));+ }+ if (deps.busy(bot.id, threadId)) return json(res, 409, userError("serverError.share.busy", { bot: bot.name }));+ if (deps.routinesIn(threadId) > 0) return json(res, 409, userError("serverError.share.routine"));++ const to = recipient ? personKey({ id: "", email: recipient.email }) : "team";+ const saved = deps.shares.share(threadId, me.person, to);+ deps.audienceChanged(bot.id, threadId);+ deps.changed(bot.id);+ if (recipient) tell(to, bot, threadId, "server.share.withYouTitle", "server.share.withYou", { name: deps.nameOf(me.email), title: task.title || bot.name, bot: bot.name }, { name: deps.nameOf(me.email), email: me.email });+ return json(res, 200, { shared: sharedAs(saved) });+ }++ const entryId = memory![2];+ if (method === "GET" && !entryId) {+ const entries = deps.saves.list(bot.id, me).map((entry) => ({ id: entry.id, text: entry.line, at: entry.at, ...(entry.person === me.person ? { yours: true } : {}) }));+ return json(res, 200, { entries });+ }+ if (method === "DELETE" && entryId) {+ const removed = deps.saves.remove(bot.id, entryId, me);+ if (removed === "not-yours") return json(res, 403, userError("serverError.teamMemory.notYours"));+ return json(res, 200, { ok: true, removed: removed === "removed" });+ }+ if (method !== "POST" || entryId) return PASS;+ const parsed = saveBody.safeParse(await readBody(req));+ if (!parsed.success) return json(res, 400, { error: "threadId, messageId and text are required" });+ const { threadId, messageId } = parsed.data;+ if (!store.taskByThread(bot.id, threadId) || !deps.sees(auth, threadId)) return json(res, 404, { error: NO_SUCH_CONVERSATION });+ if (bot.defaultBot) return json(res, 409, userError("serverError.share.ownBot"));+ if (!atLeast(deps.levelOf(auth, bot.id), "chat")) return json(res, 403, userError("serverError.bot.viewOnly", { bot: bot.name }));+ if (!store.messagesFor(threadId).some((message) => message.id === messageId)) return json(res, 404, { error: "no such message" });+ if (deps.outside(threadId)) return json(res, 409, userError("serverError.teamMemory.outside"));+ const text = parsed.data.text.replace(/\s+/g, " ").trim();+ if (!text) return json(res, 400, userError("serverError.teamMemory.empty"));+ const entry = deps.saves.add({ botId: bot.id, person: me.person, name: deps.nameOf(me.email), text });+ return json(res, 201, { entry: { id: entry.id, text: entry.line, at: entry.at, yours: true } });+ };++ /** Someone left the team: a conversation shared between them and one other person becomes the other's own, and the+ * lines they saved to team memory stay without them. */+ function personLeft(person: string): void {+ for (const { threadId, to } of deps.shares.personLeft(person)) {+ deps.handTo(threadId, to);+ const botId = deps.botOf(threadId);+ if (botId) deps.audienceChanged(botId, threadId);+ }+ deps.saves.personLeft(person);+ }++ if (deps.team) deps.store().onChange((change) => { if (change.type === "message") handedBackAndForth(change.threadId, change.message); });+ return { routes, personLeft };++ /** The one line in `to`'s inbox about this conversation, and one notification linking it when the line is new. */+ function tell(to: string, bot: BotRecord, threadId: string, titleKey: ServerLineKey, textKey: ServerLineKey, params: Record<string, string>, from: { name: string; email?: string; botId?: string }): void {+ const language = deps.language(to);+ const heading = serverLine(language, titleKey, params);+ const kept = deps.inbox().keepOne(to, {+ kind: "message", from, origin: { botId: bot.id, threadId },+ text: serverLine(language, textKey, params), title: heading, notify: "mention",+ });+ if (kept?.created) deps.notify({ kind: "mention", botId: bot.id, botName: bot.name, threadId, title: heading, body: params.title ?? "", forPerson: to, ...(bot.avatarUrl ? { avatarUrl: bot.avatarUrl } : {}) });+ }++ /** A conversation shared with one person goes back and forth: what one of the two writes, or the bot answers them,+ * waits in the other's inbox while they don't have it open. */+ function handedBackAndForth(threadId: string, message: Message): void {+ const readers = deps.shares.readers(threadId);+ const botId = readers && deps.botOf(threadId);+ const bot = botId ? deps.store().bot(botId) : undefined;+ const task = bot && deps.store().taskByThread(bot.id, threadId);+ if (!readers || !bot || !task) return;+ const personLine = (line: Message) => line.role === "user" && !line.peerAsk && !line.relay && readers.includes(line.sender?.id ?? "");+ const writer = personLine(message) ? message.sender!.id : message.role === "bot" && message.kind === "text" && !message.inbox+ ? deps.store().messagesFor(threadId).findLast(personLine)?.sender?.id : undefined;+ const to = writer && readers.find((person) => person !== writer);+ const people = deps.people();+ const email = (key: string) => people.find((person) => personKey({ id: "", email: person.email }) === key)?.email;+ const toEmail = to ? email(to) : undefined, writerEmail = writer ? email(writer) : undefined;+ if (!to || !toEmail || !writerEmail || deps.looking(toEmail, threadId)) return;+ const params = { name: deps.nameOf(writerEmail), title: task.title || bot.name, bot: bot.name };+ if (message.role === "user") tell(to, bot, threadId, "server.share.wroteTitle", "server.share.wrote", params, { name: params.name, email: writerEmail });+ else tell(to, bot, threadId, "server.share.answeredTitle", "server.share.answered", params, { name: bot.name, botId: bot.id });+ }+}diff --git a/server/thread-starters.ts b/server/thread-starters.tsindex ca3fa0be07..10565528a8 100644--- a/server/thread-starters.ts+++ b/server/thread-starters.ts@@ -55,6 +55,13 @@ export class ThreadStarters {return moved;}+ /** A conversation whose person left the team, handed to the one it was shared with. */+ handTo(threadId: string, person: string): void {+ if (!KEY.test(person) || !this.starters.has(threadId)) return;+ this.starters.set(threadId, person);+ writeFileAtomic(this.file, JSON.stringify(Object.fromEntries(this.starters)) + "\n", { mode: 0o600 });+ }+/** Record once; a thread keeps the person it was first opened for. */set(threadId: string, person: string | undefined): void {if (!person || !KEY.test(person) || !THREAD.test(threadId) || this.starters.has(threadId)) return;diff --git a/server/user-errors.ts b/server/user-errors.tsindex 1db6a862fa..31e7aa0993 100644--- a/server/user-errors.ts+++ b/server/user-errors.ts@@ -198,6 +198,17 @@ export const USER_ERROR = {"serverError.attachment.alreadyInMessage": "This file is already in a message, so it stays.","serverError.engine.signedOut": "{name} is signed out.","serverError.bot.viewOnly": "You can view {bot}, not chat with it.",+ "serverError.share.ownBot": "Chats with your own MausBot stay yours, so they can't be shared.",+ "serverError.share.alreadyTeam": "This conversation is already shared with the team.",+ "serverError.share.notYours": "Only the person this conversation belongs to can share it.",+ "serverError.share.notTeammate": "{name} isn't on this team.",+ "serverError.share.alreadyWith": "This conversation is already shared with {name}.",+ "serverError.share.cantUse": "{name} can't chat with {bot}, so you can't share this with them.",+ "serverError.share.busy": "{bot} is still working here. Share it once it's done.",+ "serverError.share.routine": "A routine is tied to this conversation. Delete the routine first, then share.",+ "serverError.teamMemory.outside": "This conversation came in from outside the team, so nothing from it goes into team memory.",+ "serverError.teamMemory.empty": "Write what to save first.",+ "serverError.teamMemory.notYours": "Only the person who saved this, or an admin, can remove it.","serverError.secret.mailboxAlreadyConnected": "this mailbox was already connected","serverError.secret.emailAndPassword": "Enter your email address and its password.","serverError.secret.emailUnavailable": "Email can't be connected here.",diff --git a/shared/wire.ts b/shared/wire.tsindex f89223c280..768b134c48 100644--- a/shared/wire.ts+++ b/shared/wire.ts@@ -155,6 +155,9 @@ export interface WireTask extends InboxTask {/** Set when a bot, not a person, opened this thread. */ openedBy?: TaskOpenedBy;/** On a team's server: one person's conversation, seen by them alone (never by another member or an admin). */private?: true;+ /** On a team's server: a private conversation its person shared, never private again. `sharedWith`: shared with one person,+ * the other reader as this viewer sees them (`byYou` to the one who shared it); nobody else, an admin included, is sent it. */+ shared?: true; sharedWith?: { name: string; byYou?: true };/** Team Cloud, where several people write, while it works: whose request runs (they or an Owner or Admin stop it). */ askedBy?: ResolvedSender;/** Set by close_thread; absent while the thread is open. */closedBy?: TaskClosedBy;diff --git a/src/App.tsx b/src/App.tsxindex 916f826b01..67de49f3bb 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -56,6 +56,7 @@ import { cloudIntentDue, cloudIntentShown, useCloudIntent } from "@/lib/cloud-inimport { CloudSetup } from "@/components/CloudSetup";import { CloudWelcome } from "@/components/cloud-welcome/CloudWelcome";import { TeamWelcome } from "@/components/TeamWelcome";+import { ConversationShareDialogs } from "@/components/conversation-share/ConversationShareDialogs";import { invitedToTeam, teamWelcomeDue, useTeamWelcomeRecord } from "@/lib/team-welcome";import { WelcomeKeeper } from "@/components/cloud-welcome/WelcomeKeeper";import { EmptyChatShell } from "@/components/onboarding/EmptyChatShell";@@ -335,6 +336,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {<div className={cn("flex h-full flex-col", framed && "bg-frame")}><WindowFrameBar notifications={notificationTray} /><BotLimitPopup />+ <ConversationShareDialogs />{!framed && strips}<div className="relative flex min-h-0 flex-1">{!calendarFocus && <buttondiff --git a/src/components/ChatHeadPill.tsx b/src/components/ChatHeadPill.tsxindex 9925c79ed6..2973678ca2 100644--- a/src/components/ChatHeadPill.tsx+++ b/src/components/ChatHeadPill.tsx@@ -16,7 +16,7 @@ import { sharedChatAudience } from "./TeamPrivateChatsLine";const UNTITLED = "New thread";const CHEVRON_MOTION = "duration-[140ms] ease-[cubic-bezier(.22,1,.36,1)]";-export type ChatHeadPrivacy = { kind: "private" } | { kind: "ownHelper" } | { kind: "shared"; team: string; onlyPeopleAdded?: boolean } | null;+export type ChatHeadPrivacy = { kind: "private" } | { kind: "ownHelper" } | { kind: "shared"; team: string; onlyPeopleAdded?: boolean; sharedWith?: string } | null;const PRIVACY_ICONS = { private: Lock, ownHelper: UserRound, shared: Users } as const;@@ -24,7 +24,7 @@ function privacyLabelOf(privacy: ChatHeadPrivacy): string | null {switch (privacy?.kind) {case "private": return t("team.privateHeader");case "ownHelper": return t("team.ownHelperHeader");- case "shared": return sharedChatAudience(privacy.team, privacy.onlyPeopleAdded);+ case "shared": return sharedChatAudience(privacy.team, privacy.onlyPeopleAdded, privacy.sharedWith);default: return null;}}diff --git a/src/components/ChatMoreMenu.test.ts b/src/components/ChatMoreMenu.test.tsindex b52156130d..e14b6fbe34 100644--- a/src/components/ChatMoreMenu.test.ts+++ b/src/components/ChatMoreMenu.test.ts@@ -14,12 +14,18 @@ const fixture = vi.hoisted(() => {run: vi.fn(),inspectorOpen: false,find: vi.fn(),+ team: false,+ open: vi.fn(),};});vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();- return { ...original, useStore: () => ({ state: { ...original.initialState, inspectorOpen: fixture.inspectorOpen }, dispatch: fixture.dispatch }) };+ return { ...original, useStore: () => ({ state: { ...original.initialState, inspectorOpen: fixture.inspectorOpen, ...(fixture.team ? { config: { ...original.initialState.config, team: { id: "acme", name: "Acme" } } } : {}) }, dispatch: fixture.dispatch }) };});+vi.mock("./conversation-share/conversation-share", async (importOriginal) => ({+ ...await importOriginal<typeof import("./conversation-share/conversation-share")>(),+ openConversationDialog: fixture.open,+}));vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => fixture.advanced, setAdvancedMode: vi.fn() }));vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => fixture.advanced && fixture.threadsChosen }));vi.mock("@/lib/chat-find", async (importOriginal) => ({@@ -66,6 +72,8 @@ beforeEach(() => {fixture.advanced = false;fixture.threadsChosen = true;fixture.inspectorOpen = false;+ fixture.team = false;+ fixture.open.mockClear();fixture.dispatch.mockClear();fixture.find.mockClear();});@@ -191,3 +199,31 @@ describe("ChatHeaderMenu, Advanced mode's header ⋯", () => {expect(items.find((item) => item.key === "threads")!.submenu).toHaveLength(3);});});++describe("sharing the conversation on screen, on a team", () => {+ const withSide = (extra: Partial<Task>): Bot => ({ ...bot, tasks: bot.tasks!.map((each) => (each.threadId === "side" ? { ...each, ...extra } : each)) });+ const shareKeys = (item: Bot) => keys(menuOf(createElement(ChatHeaderMenu, { bot: item })).items).filter((key) => key.startsWith("share-"));++ it("offers its own person both shares of a private conversation, each opening its confirm step", () => {+ fixture.team = true;+ const items = menuOf(createElement(ChatHeaderMenu, { bot: withSide({ private: true }) })).items;+ expect(items.filter((item) => item.key.startsWith("share-")).map((item) => item.label)).toEqual(["Share with the team", "Share with…"]);+ items.find((item) => item.key === "share-team")!.onSelect();+ expect(fixture.open).toHaveBeenLastCalledWith({ kind: "team", botId: "pepper", threadId: "side" });+ items.find((item) => item.key === "share-person")!.onSelect();+ expect(fixture.open).toHaveBeenLastCalledWith({ kind: "person", botId: "pepper", threadId: "side" });+ });++ it("only widens to the team what its person shared with one person, and offers nothing to the person it was shared with", () => {+ fixture.team = true;+ expect(shareKeys(withSide({ shared: true, sharedWith: { name: "Marta", byYou: true } }))).toEqual(["share-team"]);+ expect(shareKeys(withSide({ shared: true, sharedWith: { name: "Rui" } }))).toEqual([]);+ expect(shareKeys(withSide({ shared: true }))).toEqual([]);+ expect(shareKeys(withSide({}))).toEqual([]);+ expect(shareKeys({ ...withSide({ private: true }), defaultBot: { person: "[email protected]" } } as Bot), "a chat with their own MausBot").toEqual([]);+ });++ it("is not offered off a team", () => {+ expect(shareKeys(withSide({ private: true }))).toEqual([]);+ });+});diff --git a/src/components/ChatMoreMenu.tsx b/src/components/ChatMoreMenu.tsxindex 1ced2f05a3..72b4a373b0 100644--- a/src/components/ChatMoreMenu.tsx+++ b/src/components/ChatMoreMenu.tsx@@ -1,5 +1,5 @@import { useMemo, useState, type JSX } from "react";-import { Bug, Copy, Cpu, Download, Gauge, ListChecks, MessagesSquare, Monitor, MoreHorizontal, RotateCcw, Search, Share, SquarePen, UserRound } from "lucide-react";+import { Bug, Copy, Cpu, Download, Gauge, ListChecks, MessagesSquare, Monitor, MoreHorizontal, RotateCcw, Search, Share, SquarePen, UserPlus, UserRound, Users } from "lucide-react";import { currentTaskBot, openBotThread, useStore, visibleMessages, type Bot } from "@/state/store";import { useAdvancedMode } from "@/lib/interface-mode";import { useShowThreads } from "@/lib/thread-preferences";@@ -24,6 +24,7 @@ import { ShareBotButton, useTeamName } from "./bot-access/ShareBotButton";import { UsageBars } from "./EngineUsage";import { useConversationSide } from "./TeamSideSwitch";import { tasksOfSide } from "@/state/team-side";+import { openConversationDialog, shareChoices } from "./conversation-share/conversation-share";/** One item list for the chat's ⋯ menu wherever it sits; it lists the threads whenever the sidebar hides them. The* Simple bot panel draws the same items as rows, and its Share button holds the two that export. */@@ -43,6 +44,13 @@ export function useChatMoreItems(profile: Bot, phoneHeader = false): { items: Siconst transcript = () => formatTranscriptMarkdown({ title: bot.name, messages, botName: bot.name, isGroup: false });const side = useConversationSide(profile);const threads = showThreads ? [] : orderedThreadList((side ? tasksOfSide(profile, side) : profile.tasks ?? []).filter((task) => !task.routineRunId));+ const sharing = shareChoices(profile, profile.tasks?.find((task) => task.threadId === bot.threadId), Boolean(useTeamName()));+ const shareItems: SidebarMenuItem[] = [+ ...(sharing.team ? [{ key: "share-team", label: t("conversationShare.withTeam"), icon: <Users size={16} />,+ onSelect: () => openConversationDialog({ kind: "team", botId: profile.id, threadId: bot.threadId }) }] : []),+ ...(sharing.person ? [{ key: "share-person", label: t("conversationShare.withPerson"), icon: <UserPlus size={16} />,+ onSelect: () => openConversationDialog({ kind: "person", botId: profile.id, threadId: bot.threadId }) }] : []),+ ].map((item, index) => (index === 0 ? { ...item, separatorBefore: true } : item));const selection = profile.modelSelection;const modelName = phoneHeader && selection? state.instances.find((candidate) => candidate.instanceId === selection.instanceId)?.models.options.find((option) => option.id === selection.model)?.label ?? selection.model@@ -115,6 +123,7 @@ export function useChatMoreItems(profile: Bot, phoneHeader = false): { items: Sititle: t(bot.busy ? "contextWarning.busy" : "chat.startFresh.hint"),onSelect: () => contextAction.run(`/api/bots/${profile.id}/start-fresh`, { threadId: bot.threadId }),},+ ...shareItems,{key: "copy",heading: t("chat.export.heading"),diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex d595e1bbf7..84e6279a5d 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -8,7 +8,7 @@ import { WorkingDots } from "@/components/WorkingIndicator";import { ACTION_ICON, ChatBusyContext, CopyButton, MESSAGE_ROW, MessageActions, messageActionClass, ReplyAction, type MessageMenuItem } from "@/components/MessageActions";import { copyText } from "@/lib/copy-text";import { ReactAction, ReactionChips } from "@/components/Reactions";-import { useBotMessageMenu, userMessageMenu } from "@/components/message-menu";+import { useBotMessageMenu, userMessageMenu } from "@/components/message-menu"; import { savesToTeamMemory, TEAM_MEMORY_ITEM, TeamMemorySavesContext } from "@/components/conversation-share/conversation-share";import { useSpeech } from "@/lib/tts/useSpeech";import { localSystemVoiceActive } from "@/lib/local-voice";import { computerStartLine, useScreensWhile } from "@/lib/computer-start";@@ -356,7 +356,7 @@ const Bubble = memo(function Bubble({const text = user ? rawText : stripLeakedSystemHarnessMessages(rawText);const botMenu = useBotMessageMenu({text,- botId,+ botId, threadId,messageId: message.id,voiceId,tts,@@ -440,7 +440,7 @@ const Bubble = memo(function Bubble({menu={[...(simple ? replyAndCopy(() => onReply(message), visibleText) : []),...userMessageMenu({- messageId: message.id,+ messageId: message.id, save: botMenu.filter((item) => item.key === TEAM_MEMORY_ITEM),onEdit: !speaker && message.kind === "text" && !webhookView && !hasAttachments && !message.id.startsWith("optimistic-")? () => onStartEdit(message.id) : undefined,pin: remoteClient ? undefined : { pinned, onToggle: togglePin },@@ -913,7 +913,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, 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, 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 || ownChatStarted(bot.threadId)), ownHelper = Boolean(team) && !privateChat && Boolean(bot.defaultBot?.person), sharedChat = Boolean(team) && !privateChat && !ownHelper;+ const currentTask = bot.tasks?.find((task) => task.threadId === bot.threadId), place = effectivePlace(bot, currentTask), team = state.config?.team, privateChat = Boolean(team) && (currentTask?.private === true || (ownChatStarted(bot.threadId) && !currentTask?.shared)), 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]);@@ -1023,7 +1023,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" } : ownHelper ? { kind: "ownHelper" } : sharedChat && team ? { kind: "shared", team: team.name, onlyPeopleAdded: bot.onlyPeopleAdded } : null}+ privacy={privateChat ? { kind: "private" } : ownHelper ? { kind: "ownHelper" } : sharedChat && team ? { kind: "shared", team: team.name, onlyPeopleAdded: bot.onlyPeopleAdded, sharedWith: currentTask?.sharedWith?.name } : null}onToggle={() => dispatch({ type: "toggleSettings", open: !state.settingsOpen })}/>) : advanced ? (@@ -1079,7 +1079,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 && ownHelper && <TeamOwnHelperHeader />}{!simpleHead && sharedChat && team && <TeamSharedHeader team={team} onlyPeopleAdded={bot.onlyPeopleAdded} />}+ {!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} onlyPeopleAdded={bot.onlyPeopleAdded} sharedWith={currentTask?.sharedWith?.name} />}{!simpleHead && !bot.busy && bot.waitingForTeammates && <span className="truncate text-[12px] text-ink-secondary" role="status">{t("chat.teammatesWorking")}</span>}{(advanced || remoteClient) && awayFromMainThread(profile, showThreads) && (<button@@ -1185,7 +1185,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {<div ref={topSentinelRef} className="h-2 w-full pointer-events-none" aria-hidden="true" />) : null}{windowedMessages.length === 0 && !bot.busy && <EmptyChat bot={bot} />}- <ChatRowsContext.Provider value={rows}><LiveToolsContext value={liveTools}><ChatBusyContext value={busy}><PagePaneContext value={pagePane}>+ <ChatRowsContext.Provider value={rows}><TeamMemorySavesContext value={savesToTeamMemory(bot, Boolean(team))}><LiveToolsContext value={liveTools}><ChatBusyContext value={busy}><PagePaneContext value={pagePane}><MessagesListmessages={windowedMessages}transcript={messages}@@ -1206,7 +1206,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {onRegenerate={regenerate}onReply={selectReply}/>- </PagePaneContext></ChatBusyContext></LiveToolsContext></ChatRowsContext.Provider>+ </PagePaneContext></ChatBusyContext></LiveToolsContext></TeamMemorySavesContext></ChatRowsContext.Provider>{stopNoticeDue(messages, stoppedAt, busy) && <CancelledTurnRow name={PERSON_STOPPED_TURN_NAME} />}{laterCount > 0 && (<div className="flex justify-center">diff --git a/src/components/ConfirmDialog.tsx b/src/components/ConfirmDialog.tsxindex d09691f05f..9c498026c5 100644--- a/src/components/ConfirmDialog.tsx+++ b/src/components/ConfirmDialog.tsx@@ -21,6 +21,8 @@ export interface ConfirmDialogProps {/** A gentler way to the same end, offered beside the confirm button ("Archive instead"). */alternative?: { label: string; onClick: () => void };pending?: boolean;+ /** The confirm button waits for a choice the body asks for. */+ confirmDisabled?: boolean;returnFocusRef?: RefObject<HTMLElement | null>;/** Where it sits among open dialogs, when another one above the usual layer asked it. */layer?: string;@@ -47,7 +49,7 @@ export function ConfirmDialog(props: ConfirmDialogProps) {return;}if (event.key === "Tab") {- const controls = dialogRef.current?.querySelectorAll<HTMLElement>("button:not([disabled])");+ const controls = dialogRef.current?.querySelectorAll<HTMLElement>("button:not([disabled]), select:not([disabled]), textarea:not([disabled])");if (!controls?.length) { event.preventDefault(); dialogRef.current?.focus(); return; }const first = controls[0]!;const last = controls[controls.length - 1]!;@@ -101,6 +103,7 @@ export function ConfirmDialogCard({onConfirm,alternative,pending = false,+ confirmDisabled = false,}: ConfirmDialogProps & {ref?: React.Ref<HTMLDivElement>;cancelRef?: React.Ref<HTMLButtonElement>;@@ -148,7 +151,7 @@ export function ConfirmDialogCard({<buttontype="button"onClick={onConfirm}- disabled={pending}+ disabled={pending || confirmDisabled}className={cn("rounded-xl px-4 py-2 text-[13px] font-medium",danger ? "bg-danger text-white hover:brightness-110" : "bg-accent text-white hover:brightness-110",diff --git a/src/components/SidebarThreadRow.tsx b/src/components/SidebarThreadRow.tsxindex 820ea68726..774497deab 100644--- a/src/components/SidebarThreadRow.tsx+++ b/src/components/SidebarThreadRow.tsx@@ -17,10 +17,11 @@ import { Select } from "./Select";import { WorkingTimer } from "./WorkingIndicator";import { useHeldText } from "./SidebarWorkingStep";import { localizedTaskTitle } from "@/lib/task-title";+import { ShareRowItems } from "./conversation-share/ShareRowItems";export { isSnoozed, orderedThreadList };-type ThreadRowTask = Pick<Task, "threadId" | "title" | "sharedChat" | "projectId" | "busy" | "activity" | "unread" | "openedBy" | "closedBy" | "archivedAt" | "snoozedUntil" | "waitingForTeammates" | "link" | "turnStartedAt"> & {+type ThreadRowTask = Pick<Task, "threadId" | "title" | "sharedChat" | "private" | "shared" | "sharedWith" | "projectId" | "busy" | "activity" | "unread" | "openedBy" | "closedBy" | "archivedAt" | "snoozedUntil" | "waitingForTeammates" | "link" | "turnStartedAt"> & {queued?: boolean;pinned?: boolean;createdAt?: number;@@ -359,6 +360,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow({ task, ownerId,onKeyDown={(event) => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); setMenu(null); actionRef.current?.focus(); } }}><button type="button" onClick={copyLink} className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[14px] leading-[18px] text-ink hover:bg-menu-hover"><Link2 size={16} />{t("task.copyLink")}</button>{!task.sharedChat && <button type="button" onClick={startRename} className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[14px] leading-[18px] text-ink hover:bg-menu-hover"><Pencil size={16} />{t("task.renameAria")}</button>}+ <ShareRowItems botId={ownerId} task={task} onPicked={() => setMenu(null)} />{onRegenerateTitle && !task.sharedChat && <button type="button" disabled={regenerating} aria-busy={regenerating} onClick={regenerateTitle} className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[14px] leading-[18px] text-ink hover:bg-menu-hover disabled:opacity-40">{regenerating ? <Loader2 size={16} className="animate-spin" /> : <RefreshCw size={16} />}{regenerating ? t("task.regeneratingTitle") : t("task.regenerateTitle")}</button>}{onMove && Boolean(folders?.length) && <label className="block rounded-md px-2 py-1.5 text-[13px] text-ink"><span className="mb-1 flex items-center gap-2 text-ink-secondary"><FolderInput size={16} />{t("folder.move")}</span><Select size="sm" className="w-full" aria-label={t("folder.moveNamed", { title: task.title })} value={folders?.some((folder) => folder.id === task.projectId) ? task.projectId : ""}diff --git a/src/components/TeamPrivateChatsLine.tsx b/src/components/TeamPrivateChatsLine.tsxindex ea4f00ef3c..630319d2f8 100644--- a/src/components/TeamPrivateChatsLine.tsx+++ b/src/components/TeamPrivateChatsLine.tsx@@ -26,13 +26,15 @@ export function TeamPrivateHeader() {return <ChatHeadAudience icon={<Lock size={12} aria-hidden="true" className="shrink-0" />} label={t("team.privateHeader")} data-chathead-private="" />;}-/** Who can read a team bot's shared chats (its main chat, a routine's report). */-export function sharedChatAudience(team: string, onlyPeopleAdded?: boolean): string {+/** Who can read a team bot's shared chats (its main chat, a routine's report, a conversation its person shared); `sharedWith`+ * the one other person a conversation shared with one person is read by. */+export function sharedChatAudience(team: string, onlyPeopleAdded?: boolean, sharedWith?: string): string {+ if (sharedWith !== undefined) return t("teamSide.sharedWith", { name: sharedWith });return onlyPeopleAdded ? t("team.sharedHeaderPeople") : t("team.sharedHeader", { team });}-export function TeamSharedHeader({ team, onlyPeopleAdded }: { team: { name: string }; onlyPeopleAdded?: boolean }) {- return <ChatHeadAudience icon={<Users size={12} aria-hidden="true" className="shrink-0" />} label={sharedChatAudience(team.name, onlyPeopleAdded)} data-chathead-shared="" />;+export function TeamSharedHeader({ team, onlyPeopleAdded, sharedWith }: { team: { name: string }; onlyPeopleAdded?: boolean; sharedWith?: string }) {+ return <ChatHeadAudience icon={<Users size={12} aria-hidden="true" className="shrink-0" />} label={sharedChatAudience(team.name, onlyPeopleAdded, sharedWith)} data-chathead-shared="" />;}/** On a narrow header only the icon shows, so the bot's name keeps its room. */diff --git a/src/components/TeamSideSwitch.dom.test.ts b/src/components/TeamSideSwitch.dom.test.tsindex e25d9c98a0..95692917eb 100644--- a/src/components/TeamSideSwitch.dom.test.ts+++ b/src/components/TeamSideSwitch.dom.test.ts@@ -190,6 +190,14 @@ describe("who can see it, by the message box", () => {expect(label()?.textContent, "the person's own MausBot").toBe("Private · only you");});+ it("names the one other reader of a conversation shared with one person, and says a conversation shared with the team is the team's", () => {+ box(acme(), { bot: bot({ threadId: "handed", tasks: [MAIN, task("handed", "Kumquat launch", { shared: true, sharedWith: { name: "Marta", byYou: true } })] }) });+ expect(label()?.getAttribute("data-team-audience")).toBe("team");+ expect(label()?.textContent).toBe("Shared · only you and Marta can see");+ box(acme(), { bot: bot({ threadId: "widened", tasks: [MAIN, task("widened", "Launch", { shared: true })] }) });+ expect(label()?.textContent).toBe("Shared · everyone in Acme can see");+ });+it("never follows the switch: with Just me chosen, a shared chat on screen still says Shared", () => {setTeamSide("me");forgetShownConversations();diff --git a/src/components/TeamSideSwitch.tsx b/src/components/TeamSideSwitch.tsxindex 5869b74746..2a2b111384 100644--- a/src/components/TeamSideSwitch.tsx+++ b/src/components/TeamSideSwitch.tsx@@ -150,7 +150,8 @@ export function TeamAudienceLabel({ bot, group }: { bot?: Bot; group?: Group })}, [team?.teamId, person, shown, side, bot?.switchingTo]);if (!side || !teamName) return null;const Icon = side === "me" ? Lock : Users;- const label = side === "me" ? t("team.privateHeader") : group ? t("teamSide.groupAudience") : sharedChatAudience(teamName, bot?.onlyPeopleAdded);+ const sharedWith = bot?.tasks?.find((task) => task.threadId === bot.threadId)?.sharedWith?.name;+ const label = side === "me" ? t("team.privateHeader") : group ? t("teamSide.groupAudience") : sharedChatAudience(teamName, bot?.onlyPeopleAdded, sharedWith);return (<div role="note" data-team-audience={side} className="relative z-[1] flex items-center gap-1 px-2 pb-1 text-[12px] leading-4 text-ink-secondary"><Icon size={12} aria-hidden="true" className="shrink-0" /><span className="truncate">{label}</span>diff --git a/src/components/bot-panel/DetailsTab.tsx b/src/components/bot-panel/DetailsTab.tsxindex 67e22d38d7..742e823029 100644--- a/src/components/bot-panel/DetailsTab.tsx+++ b/src/components/bot-panel/DetailsTab.tsx@@ -14,7 +14,7 @@ import { Card, CardLabel, LabelAction, panelActionCls, NavRow, RowIcon, rowCls,type Derived = ReturnType<typeof useBotSettingsDerived>;-export const CONVERSATION_ITEMS = ["find", "start-fresh", "usage", "activity", "inspector"];+export const CONVERSATION_ITEMS = ["find", "start-fresh", "share-team", "share-person", "usage", "activity", "inspector"];/** A ⋯ menu item drawn as a panel row: the same label, icon, value and handler. */export function ItemRow({ item }: { item: SidebarMenuItem }) {diff --git a/src/components/bot-panel/MemoryPage.team.test.ts b/src/components/bot-panel/MemoryPage.team.test.tsindex 9eeb3b265d..a378c64b44 100644--- a/src/components/bot-panel/MemoryPage.team.test.ts+++ b/src/components/bot-panel/MemoryPage.team.test.ts@@ -19,6 +19,7 @@ const bot = { id: "scout", threadId: "t1", name: "Scout", title: "", descriptionmodelSelection: { instanceId: "x", model: "x" } } as unknown as Bot;const files: Record<string, string> = {};const calls: Array<[string, string]> = [];+let teamLines: Array<{ id: string; text: string; at: number; yours?: true }> = [];const reply = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });let host: HTMLDivElement;let root: Root;@@ -26,11 +27,17 @@ let root: Root;beforeEach(() => {fixture.team = true;calls.length = 0;+ teamLines = [];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.endsWith("/memory/team")) return reply(200, { entries: teamLines });+ if (url.pathname.includes("/memory/team/") && method === "DELETE") {+ teamLines = teamLines.filter((line) => !url.pathname.endsWith(`/${line.id}`));+ return reply(200, { ok: true, removed: true });+ }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 })) });@@ -56,7 +63,7 @@ it("on a Team Cloud shows what the bot remembers about the person, from their owawait 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);+ expect(calls.every(([, path]) => path.includes("/memory/mine") || path.includes("/memory/team")), "never the bot's own notes file").toBe(true);const forget = host.querySelector<HTMLButtonElement>("[data-memory-note] button")!;await act(async () => forget.click());await settle();@@ -69,3 +76,17 @@ it("counts those notes on the Library tab", async () => {await settle();expect(host.querySelector('[data-panel-page="memory"]')?.textContent).toContain("1 note");});++it("lists the lines the person saved to the team's memory beside their own notes, and takes one out through the team route", async () => {+ teamLines = [{ id: "l1", text: "We ship on 3 March (saved by Rui, 2026-11-11)", at: 1, yours: true }];+ await act(async () => root.render(createElement(MemoryPage, { bot, derived: {} as never })));+ await settle();+ const row = host.querySelector<HTMLElement>('[data-team-memory-entry="l1"]')!;+ expect(row.textContent).toContain("We ship on 3 March (saved by Rui, 2026-11-11)");+ expect(row.textContent).toContain("In team memory · added by you");+ await act(async () => row.querySelector<HTMLButtonElement>("button")!.click());+ await settle();+ expect(calls).toContainEqual(["DELETE", "/api/bots/scout/memory/team/l1"]);+ expect(host.querySelector('[data-team-memory-entry="l1"]')).toBeNull();+ expect(calls.some(([method, path]) => method !== "GET" && path.endsWith("/memory/file"))).toBe(false);+});diff --git a/src/components/bot-panel/pages.tsx b/src/components/bot-panel/pages.tsxindex 332d92989f..9fee32310b 100644--- a/src/components/bot-panel/pages.tsx+++ b/src/components/bot-panel/pages.tsx@@ -35,6 +35,7 @@ import type { SimplePageId } from "./page-registry";import { BotSwitch, buttonCls, Card, ColRow, LinkRow, NoteRow, RadioRow, RowIcon, rowCls, RowText, SwitchRow, TextRow, TrashButton } from "./rows";import { MemoryUpkeepCards } from "./MemoryUpkeepCards";import { useMemoryDoc } from "./use-memory-doc";+import { useTeamMemoryEntries } from "../conversation-share/conversation-share";type Derived = ReturnType<typeof useBotSettingsDerived>;@@ -168,6 +169,7 @@ export function RoutinesPage({ bot, derived }: PageContext) {* 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 teamSaved = useTeamMemoryEntries(bot.id, memory.mine && bot.memoryEnabled !== false && !bot.defaultBot?.person, memory.docs);const [draft, setDraft] = useState("");const [asText, setAsText] = useState<{ botId: string; doc: MemoryDoc } | null>(null);const [saving, setSaving] = useState(false);@@ -239,7 +241,7 @@ export function MemoryPage({ bot }: PageContext) {<NoteRow tone="warn">{t("botPanel.library.memoryError")}</NoteRow>) : notes === null ? (<NoteRow>{t("common.checking")}</NoteRow>- ) : notes.length === 0 ? (+ ) : notes.length === 0 && teamSaved.entries.length === 0 ? (<NoteRow>{t("botPanel.memory.empty")}</NoteRow>) : notes.map((note) => (<div key={`${note.path}:${note.line}:${note.text}`} data-memory-note={note.line ?? note.path} className={rowCls}>@@ -247,6 +249,15 @@ export function MemoryPage({ bot }: PageContext) {<TrashButton label={t("botPanel.memory.forget")} disabled={saving} onClick={() => forget(note)} /></div>))}+ {memoryOn && !memory.error && notes !== null && teamSaved.entries.map((entry) => (+ <div key={entry.id} data-team-memory-entry={entry.id} className={rowCls}>+ <div className="min-w-0 flex-1 text-[13px] leading-[1.45] text-ink">+ {entry.text}+ {entry.yours && <span className="block text-[12px] text-ink-secondary">{t("teamMemorySave.yours")}</span>}+ </div>+ <TrashButton label={t("botPanel.memory.forget")} disabled={saving} onClick={() => void change(async () => { await teamSaved.remove(entry.id); return true; })} />+ </div>+ ))}{error && <NoteRow tone="warn">{error}</NoteRow>}</Card>{memoryOn && (diff --git a/src/components/conversation-share/ConversationShareDialogs.dom.test.ts b/src/components/conversation-share/ConversationShareDialogs.dom.test.tsnew file mode 100644index 0000000000..5e710d8197--- /dev/null+++ b/src/components/conversation-share/ConversationShareDialogs.dom.test.ts@@ -0,0 +1,138 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@/state/store", async (importOriginal) => {+ const original = await importOriginal<typeof import("@/state/store")>();+ const state = { ...original.initialState, config: { ...original.initialState.config, team: { id: "acme", name: "Acme" } },+ bots: [{ id: "scout", name: "Scout", threadId: "t1", tasks: [] }] };+ return { ...original, useStore: () => ({ state, dispatch: vi.fn() }) };+});++const { ConversationShareDialogs } = await import("./ConversationShareDialogs");+const { closeConversationDialog, openConversationDialog, savesToTeamMemory, shareChoices } = await import("./conversation-share");++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+const reply = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });+let sent: Array<{ method: string; path: string; body: unknown }> = [];+let answer: (method: string, path: string) => Response;+let host: HTMLDivElement;+let root: Root;++beforeEach(() => {+ sent = [];+ answer = (method) => (method === "GET" ? reply(200, { shared: null, people: [{ email: "[email protected]", name: "Ana" }, { email: "[email protected]", name: "Marta" }] }) : reply(200, { shared: "team" }));+ vi.stubGlobal("fetch", vi.fn(async (input: string, init?: RequestInit) => {+ const method = init?.method ?? "GET";+ const path = new URL(input, "http://x").pathname;+ sent.push({ method, path, body: init?.body ? JSON.parse(String(init.body)) : undefined });+ return answer(method, path);+ }));+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => {+ act(() => closeConversationDialog());+ 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)); });+const dialog = () => document.querySelector<HTMLElement>('[role="alertdialog"]');+const button = (label: string) => [...document.querySelectorAll<HTMLButtonElement>('[role="alertdialog"] button')].find((each) => each.textContent === label)!;+async function show(next: Parameters<typeof openConversationDialog>[0]) {+ await act(async () => root.render(createElement(ConversationShareDialogs)));+ await act(async () => openConversationDialog(next));+ await settle();+}++describe("which actions a conversation offers", () => {+ it("shares a private one either way, widens one shared with one person, and nothing else", () => {+ const bot = {};+ expect(shareChoices(bot, { private: true }, true)).toEqual({ team: true, person: true });+ expect(shareChoices(bot, { shared: true, sharedWith: { name: "Marta", byYou: true } }, true)).toEqual({ team: true, person: false });+ expect(shareChoices(bot, { shared: true, sharedWith: { name: "Rui" } }, true)).toEqual({ team: false, person: false });+ expect(shareChoices(bot, { shared: true }, true)).toEqual({ team: false, person: false });+ expect(shareChoices(bot, {}, true), "a team conversation").toEqual({ team: false, person: false });+ expect(shareChoices(bot, { private: true, sharedChat: true }, true)).toEqual({ team: false, person: false });+ expect(shareChoices({ defaultBot: { person: "[email protected]" } }, { private: true }, true), "their own MausBot").toEqual({ team: false, person: false });+ expect(shareChoices(bot, { private: true }, false), "off a team").toEqual({ team: false, person: false });+ });++ it("saves to team memory for a team bot the person can chat with, never their own MausBot", () => {+ expect(savesToTeamMemory({ yourAccess: "chat" }, true)).toBe(true);+ expect(savesToTeamMemory({ yourAccess: "view" }, true)).toBe(false);+ expect(savesToTeamMemory({ defaultBot: { person: "[email protected]" } }, true)).toBe(false);+ expect(savesToTeamMemory({ yourAccess: "chat" }, false)).toBe(false);+ });+});++describe("the confirm step", () => {+ it("says who will read the whole conversation when it goes to the team, and that it can't be made private again", async () => {+ await show({ kind: "team", botId: "scout", threadId: "t9" });+ expect(dialog()?.textContent).toContain("Share with the team?");+ expect(dialog()?.textContent).toContain("Everyone in Acme who can use Scout will be able to read this whole conversation, including everything already in it and its files, and write in it. It moves to the Team side. It can't be made private again.");+ expect(sent, "nothing is sent before the person confirms").toEqual([]);+ await act(async () => button("Share with the team").click());+ await settle();+ expect(sent).toEqual([{ method: "POST", path: "/api/bots/scout/tasks/t9/share", body: { with: "team" } }]);+ expect(dialog()).toBeNull();+ });++ it("names the one person who will read it, admins kept out, and shares with the one chosen", async () => {+ await show({ kind: "person", botId: "scout", threadId: "t9" });+ expect(sent).toEqual([{ method: "GET", path: "/api/bots/scout/tasks/t9/share", body: undefined }]);+ expect(dialog()?.textContent).toContain("Ana will be able to read this whole conversation, including everything already in it and its files, and carry it on with Scout. Nobody else can see it, admins included. It can't be made private again.");+ const select = dialog()!.querySelector("select")!;+ expect([...select.options].map((option) => option.textContent)).toEqual(["Ana", "Marta"]);+ await act(async () => { select.value = "[email protected]"; select.dispatchEvent(new Event("change", { bubbles: true })); });+ expect(dialog()?.textContent).toContain("Marta will be able to read this whole conversation");+ await act(async () => button("Share with Marta").click());+ await settle();+ expect(sent.at(-1)).toEqual({ method: "POST", path: "/api/bots/scout/tasks/t9/share", body: { with: { email: "[email protected]" } } });+ expect(dialog()).toBeNull();+ });++ it("says so when nobody else can chat with the bot, and has nothing to confirm", async () => {+ answer = () => reply(200, { shared: null, people: [] });+ await show({ kind: "person", botId: "scout", threadId: "t9" });+ expect(dialog()?.textContent).toContain("Nobody else on the team can chat with Scout yet.");+ expect(button("Share with…").disabled).toBe(true);+ });++ it("keeps the dialog open with the server's words when it refuses", async () => {+ answer = (method) => (method === "GET" ? reply(200, { shared: null, people: [] }) : reply(409, { error: "Scout is still working here. Share it once it's done.", errorKey: "serverError.share.busy", errorParams: { bot: "Scout" } }));+ await show({ kind: "team", botId: "scout", threadId: "t9" });+ await act(async () => button("Share with the team").click());+ await settle();+ expect(dialog()?.querySelector('[role="alert"]')?.textContent).toBe("Scout is still working here. Share it once it's done.");+ });++ it("saves a message to team memory in one click, with Undo taking it out again", async () => {+ answer = (method) => (method === "POST" ? reply(201, { entry: { id: "e1", text: "x", at: 1, yours: true } }) : reply(200, { ok: true, removed: true }));+ await show({ kind: "memory", botId: "scout", threadId: "t9", messageId: "m1", text: "We ship the launch\non 3 March" });+ expect(dialog(), "no dialog, no editing first").toBeNull();+ expect(sent).toEqual([{ method: "POST", path: "/api/bots/scout/memory/team", body: { threadId: "t9", messageId: "m1", text: "We ship the launch\non 3 March" } }]);+ const toast = document.querySelector<HTMLElement>("[data-access-toast]")!;+ expect(toast.textContent).toContain("Saved to Scout's team memory");+ await act(async () => [...toast.querySelectorAll("button")].find((each) => each.textContent === "Undo")!.click());+ await settle();+ expect(sent.at(-1)).toEqual({ method: "DELETE", path: "/api/bots/scout/memory/team/e1", body: undefined });+ expect(document.querySelector("[data-access-toast]")).toBeNull();+ });++ it("says why a save was refused and tries again when asked", async () => {+ let tries = 0;+ answer = () => (++tries === 1 ? reply(409, { error: "This conversation came in from outside the team, so nothing from it goes into team memory." }) : reply(201, { entry: { id: "e2", text: "x", at: 1 } }));+ await show({ kind: "memory", botId: "scout", threadId: "t9", messageId: "m1", text: "Launch: 3 March" });+ const toast = () => document.querySelector<HTMLElement>("[data-access-toast]");+ expect(toast()?.textContent).toContain("This conversation came in from outside the team");+ await act(async () => [...toast()!.querySelectorAll("button")].find((each) => each.textContent === "Try again")!.click());+ await settle();+ expect(sent.filter((each) => each.method === "POST").length).toBe(2);+ expect(toast()?.textContent).toContain("Saved to Scout's team memory");+ });+});diff --git a/src/components/conversation-share/ConversationShareDialogs.tsx b/src/components/conversation-share/ConversationShareDialogs.tsxnew file mode 100644index 0000000000..73d07b487f--- /dev/null+++ b/src/components/conversation-share/ConversationShareDialogs.tsx@@ -0,0 +1,115 @@+import { useEffect, useId, useRef, useState } from "react";+import { UserPlus, Users } from "lucide-react";++import { t } from "@/lib/i18n";+import { useStore } from "@/state/store";+import { teamChats } from "@/state/team-chats";+import { setTeamSide } from "@/state/team-side";+import { ConfirmDialog } from "../ConfirmDialog";+import { Select } from "../Select";+import { UndoToast, useTeamName } from "../bot-access/ShareBotButton";+import {+ closeConversationDialog, removeTeamMemoryEntry, saveToTeamMemory, shareConversation, sharingOf, useConversationDialog,+ type ConversationDialog, type Sharing,+} from "./conversation-share";++/** The server keeps one note's worth and says it was shortened; this only keeps a very long message off the wire. */+const MEMORY_TEXT_SENT = 20_000;++/** The confirm step of sharing a conversation and of saving a message to team memory, wherever either was chosen. */+export function ConversationShareDialogs() {+ const dialog = useConversationDialog();+ const teamName = useTeamName();+ const { state } = useStore();+ const bot = dialog ? state.bots.find((candidate) => candidate.id === dialog.botId) : undefined;+ if (!dialog || !teamName || !bot) return null;+ const key = `${dialog.kind}:${dialog.threadId}:${dialog.kind === "memory" ? dialog.messageId : ""}`;+ if (dialog.kind === "memory") return <SaveToTeamMemory key={key} dialog={dialog} botName={bot.name} />;+ return <ShareConversation key={key} dialog={dialog} botName={bot.name} teamName={teamName} />;+}++function useSubmit() {+ const [pending, setPending] = useState(false);+ const [error, setError] = useState("");+ const run = (work: () => Promise<void>) => {+ if (pending) return;+ setPending(true);+ setError("");+ void work().then(closeConversationDialog, (cause: unknown) => {+ setError(cause instanceof Error ? cause.message : String(cause));+ setPending(false);+ });+ };+ return { pending, error, run };+}++function ShareConversation({ dialog, botName, teamName }: { dialog: ConversationDialog & { kind: "team" | "person" }; botName: string; teamName: string }) {+ const { pending, error, run } = useSubmit();+ const [sharing, setSharing] = useState<Sharing | null>(null);+ const [email, setEmail] = useState("");+ const fieldId = useId();+ useEffect(() => {+ if (dialog.kind !== "person") return;+ let live = true;+ void sharingOf(dialog).then((answer) => {+ if (!live) return;+ setSharing(answer);+ setEmail(answer.people[0]?.email ?? "");+ }, () => { if (live) setSharing({ shared: null, people: [] }); });+ return () => { live = false; };+ }, [dialog.kind, dialog.botId, dialog.threadId]);+ const share = (to: "team" | { email: string }) => run(async () => {+ await shareConversation(dialog, to);+ setTeamSide("team", teamChats());+ });+ const failed = error && <span role="alert" className="mt-3 block text-danger">{error}</span>;++ if (dialog.kind === "team") {+ return (+ <ConfirmDialog open tone="neutral" icon={<Users size={18} />} title={t("conversationShare.teamTitle")}+ body={<span data-conversation-share="team">{t("conversationShare.teamBody", { team: teamName, bot: botName })}{failed}</span>}+ confirmLabel={t("conversationShare.withTeam")} pending={pending} onCancel={closeConversationDialog} onConfirm={() => share("team")} />+ );+ }+ const person = sharing?.people.find((candidate) => candidate.email === email) ?? null;+ return (+ <ConfirmDialog open tone="neutral" icon={<UserPlus size={18} />} title={t("conversationShare.personTitle")}+ body={<span data-conversation-share="person">+ {sharing === null ? t("common.checking") : sharing.people.length === 0 ? t("conversationShare.nobody", { bot: botName }) : <>+ <label htmlFor={fieldId} className="block text-[12px] font-medium text-ink">{t("conversationShare.personField")}</label>+ <Select id={fieldId} className="mt-1 w-full" value={email} disabled={pending} onChange={(event) => setEmail(event.target.value)}>+ {sharing.people.map((candidate) => <option key={candidate.email} value={candidate.email}>{candidate.name}</option>)}+ </Select>+ {person && <span className="mt-3 block">{t("conversationShare.personBody", { name: person.name, bot: botName })}</span>}+ </>}+ {failed}+ </span>}+ confirmLabel={person ? t("conversationShare.personConfirm", { name: person.name }) : t("conversationShare.withPerson")}+ confirmDisabled={!person} pending={pending} onCancel={closeConversationDialog} onConfirm={() => { if (person) share({ email: person.email }); }} />+ );+}++/** One click saves the message as it is; the toast's Undo takes it out again. Changing or removing it later is the bot's+ * memory view. */+function SaveToTeamMemory({ dialog, botName }: { dialog: ConversationDialog & { kind: "memory" }; botName: string }) {+ const [state, setState] = useState<{ saved: string } | { error: string } | null>(null);+ const [attempt, setAttempt] = useState(0);+ const started = useRef(-1);+ const retrying = useRef(false);+ useEffect(() => {+ if (started.current === attempt) return;+ started.current = attempt;+ void saveToTeamMemory({ ...dialog, text: dialog.text.slice(0, MEMORY_TEXT_SENT) }).then(+ (answer) => setState({ saved: answer.entry.id }),+ (cause: unknown) => setState({ error: cause instanceof Error ? cause.message : String(cause) }),+ );+ }, [attempt]);+ if (!state) return null;+ if ("error" in state) {+ const retry = async () => { retrying.current = true; setState(null); setAttempt((count) => count + 1); };+ const done = () => { if (retrying.current) retrying.current = false; else closeConversationDialog(); };+ return <UndoToast text={state.error} actionLabel={t("common.tryAgain")} onDone={done} onUndo={retry} />;+ }+ return <UndoToast text={t("teamMemorySave.saved", { bot: botName })} onDone={closeConversationDialog}+ onUndo={() => removeTeamMemoryEntry(dialog.botId, state.saved)} />;+}diff --git a/src/components/conversation-share/ShareRowItems.tsx b/src/components/conversation-share/ShareRowItems.tsxnew file mode 100644index 0000000000..17f6c22a68--- /dev/null+++ b/src/components/conversation-share/ShareRowItems.tsx@@ -0,0 +1,20 @@+import { UserPlus, Users } from "lucide-react";++import { t } from "@/lib/i18n";+import type { Task } from "@/state/store";+import { useOptionalStoreRef } from "@/state/store-ref";+import { openConversationDialog, shareChoices } from "./conversation-share";++const ROW = "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[14px] leading-[18px] text-ink hover:bg-menu-hover";++/** "Share with the team" and "Share with…" in a conversation's row menu, for the person it is private to. */+export function ShareRowItems({ botId, task, onPicked }: { botId: string; task: Pick<Task, "threadId" | "private" | "shared" | "sharedWith" | "sharedChat">; onPicked: () => void }) {+ const state = useOptionalStoreRef()?.state();+ const bot = state?.bots.find((candidate) => candidate.id === botId);+ const choices = bot ? shareChoices(bot, task, Boolean(state?.config?.team)) : { team: false, person: false };+ const open = (kind: "team" | "person") => { onPicked(); openConversationDialog({ kind, botId, threadId: task.threadId }); };+ return <>+ {choices.team && <button type="button" data-share-conversation="team" onClick={() => open("team")} className={ROW}><Users size={16} />{t("conversationShare.withTeam")}</button>}+ {choices.person && <button type="button" data-share-conversation="person" onClick={() => open("person")} className={ROW}><UserPlus size={16} />{t("conversationShare.withPerson")}</button>}+ </>;+}diff --git a/src/components/conversation-share/conversation-share.ts b/src/components/conversation-share/conversation-share.tsnew file mode 100644index 0000000000..a93c06f455--- /dev/null+++ b/src/components/conversation-share/conversation-share.ts@@ -0,0 +1,84 @@+// A Team Cloud's conversation actions: sharing a private conversation (with the team, or with one person) and saving a+// message to a bot's team memory. Which actions show follows the server's answer on the task; the server refuses+// anything else in any case.+import { createContext, useEffect, useState, useSyncExternalStore } from "react";++import { api, type Bot, type Task } from "@/state/store";++export interface ConversationTarget { botId: string; threadId: string }+export type ConversationDialog =+ | (ConversationTarget & { kind: "team" | "person" })+ | (ConversationTarget & { kind: "memory"; messageId: string; text: string });++export interface Sharing { shared: "team" | { email: string; name: string } | null; people: Array<{ email: string; name: string }> }+export interface TeamMemoryEntry { id: string; text: string; at: number; yours?: true }++export const TEAM_MEMORY_ITEM = "team-memory";+/** Whether the messages drawn below offer "Save to team memory": set once by the conversation, so a row never reads the+ * store to know. */+export const TeamMemorySavesContext = createContext(false);++let dialog: ConversationDialog | null = null;+const listeners = new Set<() => void>();+const changed = () => { for (const listener of listeners) listener(); };++export function openConversationDialog(next: ConversationDialog): void {+ dialog = next;+ changed();+}++export function closeConversationDialog(): void {+ dialog = null;+ changed();+}++export function useConversationDialog(): ConversationDialog | null {+ return useSyncExternalStore((listener) => { listeners.add(listener); return () => { listeners.delete(listener); }; }, () => dialog, () => dialog);+}++/** What this person can do with a conversation's sharing: its own person shares a private one either way, and widens one+ * they shared with one person to the team. Never a bot's shared chat or a chat with their own MausBot. */+export function shareChoices(bot: Pick<Bot, "defaultBot">, task: Pick<Task, "private" | "shared" | "sharedWith" | "sharedChat"> | undefined, onTeam: boolean): { team: boolean; person: boolean } {+ if (!onTeam || !task || bot.defaultBot?.person || task.sharedChat) return { team: false, person: false };+ if (task.private === true && !task.shared) return { team: true, person: true };+ return { team: task.sharedWith?.byYou === true, person: false };+}++/** Saving a message to the bot's team memory: on a team, for a bot the person can chat with that isn't their own MausBot. */+export function savesToTeamMemory(bot: Pick<Bot, "defaultBot" | "yourAccess"> | undefined, onTeam: boolean): boolean {+ return onTeam && Boolean(bot) && !bot!.defaultBot?.person && bot!.yourAccess !== "view";+}++const sharePath = ({ botId, threadId }: ConversationTarget) => `/api/bots/${encodeURIComponent(botId)}/tasks/${encodeURIComponent(threadId)}/share`;++export const sharingOf = (target: ConversationTarget) => api<Sharing>(sharePath(target));++export const shareConversation = (target: ConversationTarget, to: "team" | { email: string }) =>+ api<{ shared: Sharing["shared"] }>(sharePath(target), { method: "POST", body: JSON.stringify({ with: to }) });++export const saveToTeamMemory = (target: ConversationTarget & { messageId: string; text: string }) =>+ api<{ entry: TeamMemoryEntry }>(`/api/bots/${encodeURIComponent(target.botId)}/memory/team`, {+ method: "POST", body: JSON.stringify({ threadId: target.threadId, messageId: target.messageId, text: target.text }),+ });++export const teamMemoryEntries = (botId: string) => api<{ entries: TeamMemoryEntry[] }>(`/api/bots/${encodeURIComponent(botId)}/memory/team`);++export const removeTeamMemoryEntry = (botId: string, id: string) =>+ api(`/api/bots/${encodeURIComponent(botId)}/memory/team/${encodeURIComponent(id)}`, { method: "DELETE" });++/** The lines saved to a bot's team memory that this person may take out: their own, or every line for an admin. Read+ * again whenever `version` changes. */+export function useTeamMemoryEntries(botId: string, on: boolean, version: unknown): { entries: TeamMemoryEntry[]; remove(id: string): Promise<void> } {+ const [state, setState] = useState<{ botId: string; entries: TeamMemoryEntry[] }>({ botId, entries: [] });+ const read = (cancelled?: () => boolean) => teamMemoryEntries(botId).then((answer) => { if (!cancelled?.()) setState({ botId, entries: answer.entries }); }, () => {});+ useEffect(() => {+ if (!on) return;+ let cancelled = false;+ void read(() => cancelled);+ return () => { cancelled = true; };+ }, [botId, on, version]);+ return {+ entries: on && state.botId === botId ? state.entries : [],+ remove: async (id) => { await removeTeamMemoryEntry(botId, id); await read(); },+ };+}diff --git a/src/components/message-menu.tsx b/src/components/message-menu.tsxindex c65facc95b..f5308aa48a 100644--- a/src/components/message-menu.tsx+++ b/src/components/message-menu.tsx@@ -1,9 +1,11 @@-import { Code, Copy, Eye, Pencil, Pin, PinOff, RefreshCw, Square, Volume2 } from "lucide-react";+import { BookmarkPlus, Code, Copy, Eye, Pencil, Pin, PinOff, RefreshCw, Square, Volume2 } from "lucide-react";import { copyText } from "@/lib/copy-text";import { t } from "@/lib/i18n";+import { useContext } from "react";import type { ConfigStatus, Group, Message, useStore } from "@/state/store";import { ACTION_ICON, type MessageMenuItem } from "@/components/MessageActions";import { useSpeakAction } from "@/components/SpeakButton";+import { openConversationDialog, TEAM_MEMORY_ITEM, TeamMemorySavesContext } from "@/components/conversation-share/conversation-share";export type PinAction = { pinned: boolean; onToggle: () => void; hint?: string };@@ -32,9 +34,18 @@ function idItem(messageId: string): MessageMenuItem {return { key: "copy-id", icon: <Copy {...ACTION_ICON} />, label: t("chat.copyMessageId"), onSelect: () => { void copyText(messageId); } };}+/** "Save to team memory" on a message of a team bot's conversation; nothing in a group chat or off a team. */+function useTeamMemoryItem(text: string, messageId: string, botId?: string, threadId?: string): MessageMenuItem[] {+ const offered = useContext(TeamMemorySavesContext);+ if (!offered || !botId || !threadId || !text.trim() || messageId.startsWith("optimistic-")) return [];+ return [{ key: TEAM_MEMORY_ITEM, icon: <BookmarkPlus {...ACTION_ICON} />, label: t("teamMemorySave.menu"),+ onSelect: () => openConversationDialog({ kind: "memory", botId, threadId, messageId, text }) }];+}+export function useBotMessageMenu({text,botId,+ threadId,messageId,voiceId,tts,@@ -47,6 +58,8 @@ export function useBotMessageMenu({}: {text: string;botId?: string;+ /** The bot's conversation the message is in; a group chat names none. */+ threadId?: string;messageId: string;voiceId?: string;tts: ConfigStatus["tts"];@@ -58,6 +71,7 @@ export function useBotMessageMenu({pin?: PinAction;}): MessageMenuItem[] {const speak = useSpeakAction({ text, botId, messageId, voiceId, tts, localVoice });+ const teamMemory = useTeamMemoryItem(text, messageId, botId, threadId);const items: MessageMenuItem[] = [];if (canSpeak && text) {items.push({@@ -78,13 +92,15 @@ export function useBotMessageMenu({});}if (onRegenerate) items.push({ key: "regenerate", icon: <RefreshCw {...ACTION_ICON} />, label: t("chat.regenerate"), onSelect: onRegenerate });- items.push(...pinItem(pin), idItem(messageId));+ items.push(...teamMemory, ...pinItem(pin), idItem(messageId));return items;}-export function userMessageMenu({ messageId, onEdit, pin }: { messageId: string; onEdit?: () => void; pin?: PinAction }): MessageMenuItem[] {+/** `save`: the message's "Save to team memory", as the bot menu's hook made it. */+export function userMessageMenu({ messageId, onEdit, pin, save = [] }: { messageId: string; onEdit?: () => void; pin?: PinAction; save?: MessageMenuItem[] }): MessageMenuItem[] {return [...(onEdit ? [{ key: "edit", icon: <Pencil {...ACTION_ICON} />, label: t("chat.editMessage"), onSelect: onEdit, idleOnly: true }] : []),+ ...save,...pinItem(pin),idItem(messageId),];diff --git a/src/locales/de.json b/src/locales/de.jsonindex 74896deacd..711036ea4e 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -312,6 +312,12 @@"server.teammates.answerPassed": "Antwort an die wartende Arbeit weitergegeben","server.teammates.answeredForPerson": "Frage von {name} für die Person beantwortet","server.teammates.personReplied": "{name} hat geantwortet",+ "server.share.withYouTitle": "{name} hat „{title}“ mit dir geteilt",+ "server.share.withYou": "{name} hat „{title}“ mit dir geteilt. Öffne die Unterhaltung, um mit {bot} weiterzumachen.",+ "server.share.wroteTitle": "{name} hat in „{title}“ geschrieben",+ "server.share.wrote": "{name} hat in „{title}“ geschrieben. Öffne die Unterhaltung, um zu antworten.",+ "server.share.answeredTitle": "{bot} hat {name} in „{title}“ geantwortet",+ "server.share.answered": "{bot} hat {name} in „{title}“ geantwortet. Öffne die Unterhaltung, um weiterzumachen.","server.teammates.personAssistantAnswered": "Die Assistenz von {name} hat geantwortet","server.teammates.told": "{name} Bescheid gegeben","server.noAi.member": "{owner} muss eine KI verbinden, bevor Bots antworten können. Ich habe Bescheid gegeben.",diff --git a/src/locales/en.json b/src/locales/en.jsonindex f11fc7447e..69411a8498 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -447,6 +447,12 @@"server.teammates.answerPassed": "Answer passed to the waiting work","server.teammates.answeredForPerson": "Answered {name}'s question for the person","server.teammates.personReplied": "{name} replied",+ "server.share.withYouTitle": "{name} shared “{title}” with you",+ "server.share.withYou": "{name} shared “{title}” with you. Open it to carry on with {bot}.",+ "server.share.wroteTitle": "{name} wrote in “{title}”",+ "server.share.wrote": "{name} wrote in “{title}”. Open it to answer.",+ "server.share.answeredTitle": "{bot} answered {name} in “{title}”",+ "server.share.answered": "{bot} answered {name} in “{title}”. Open it to carry on.","server.teammates.personAssistantAnswered": "{name}'s assistant answered","server.teammates.told": "Told {name}","server.noAi.member": "{owner} needs to connect an AI before bots can answer. I've told them.",@@ -7657,6 +7663,19 @@"teamSide.team": "Team","teamSide.hint": "Just me is private, even from admins. Team is shared.","teamSide.groupAudience": "Shared · everyone in this group chat can see",+ "teamSide.sharedWith": "Shared · only you and {name} can see",+ "conversationShare.withTeam": "Share with the team",+ "conversationShare.withPerson": "Share with…",+ "conversationShare.teamTitle": "Share with the team?",+ "conversationShare.teamBody": "Everyone in {team} who can use {bot} will be able to read this whole conversation, including everything already in it and its files, and write in it. It moves to the Team side. It can't be made private again.",+ "conversationShare.personTitle": "Share with one person?",+ "conversationShare.personField": "Share with",+ "conversationShare.personBody": "{name} will be able to read this whole conversation, including everything already in it and its files, and carry it on with {bot}. Nobody else can see it, admins included. It can't be made private again.",+ "conversationShare.personConfirm": "Share with {name}",+ "conversationShare.nobody": "Nobody else on the team can chat with {bot} yet.",+ "teamMemorySave.menu": "Save to team memory",+ "teamMemorySave.saved": "Saved to {bot}'s team memory",+ "teamMemorySave.yours": "In team memory · added by you","chat.page.usage": "{pages} of {limit} pages","chat.page.copyLink": "Copy link","chat.page.copied": "Copied",@@ -9932,6 +9951,17 @@"time.invalid": "Invalid Date","shortcuts.send-follow-up": "While a bot works: queue instead of steering, or the other way round","serverError.bot.viewOnly": "You can view {bot}, not chat with it.",+ "serverError.share.ownBot": "Chats with your own MausBot stay yours, so they can't be shared.",+ "serverError.share.alreadyTeam": "This conversation is already shared with the team.",+ "serverError.share.notYours": "Only the person this conversation belongs to can share it.",+ "serverError.share.notTeammate": "{name} isn't on this team.",+ "serverError.share.alreadyWith": "This conversation is already shared with {name}.",+ "serverError.share.cantUse": "{name} can't chat with {bot}, so you can't share this with them.",+ "serverError.share.busy": "{bot} is still working here. Share it once it's done.",+ "serverError.share.routine": "A routine is tied to this conversation. Delete the routine first, then share.",+ "serverError.teamMemory.outside": "This conversation came in from outside the team, so nothing from it goes into team memory.",+ "serverError.teamMemory.empty": "Write what to save first.",+ "serverError.teamMemory.notYours": "Only the person who saved this, or an admin, can remove it.","native.teamMove.sessionLabel": "Move to a team","native.teamMove.homeNoAnswer": "My Cloud did not answer.","native.teamMove.openTeam": "Open the team you're moving a bot into.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex d5d66fbc4b..6bac22ed81 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -430,6 +430,12 @@"server.teammates.answerPassed": "Resposta entregue à tarefa em espera","server.teammates.answeredForPerson": "Respondeu à pergunta de {name} em nome da pessoa","server.teammates.personReplied": "{name} respondeu",+ "server.share.withYouTitle": "{name} compartilhou “{title}” com você",+ "server.share.withYou": "{name} compartilhou “{title}” com você. Abra a conversa para continuar com {bot}.",+ "server.share.wroteTitle": "{name} escreveu em “{title}”",+ "server.share.wrote": "{name} escreveu em “{title}”. Abra a conversa para responder.",+ "server.share.answeredTitle": "{bot} respondeu a {name} em “{title}”",+ "server.share.answered": "{bot} respondeu a {name} em “{title}”. Abra a conversa para continuar.","server.teammates.personAssistantAnswered": "O assistente de {name} respondeu","server.teammates.told": "Avisou {name}","server.noAi.member": "{owner} precisa conectar uma IA para os bots poderem responder. Já avisei.",@@ -7467,6 +7473,19 @@"teamSide.team": "Equipe","teamSide.hint": "Só eu é privado, até para os administradores. Equipe é compartilhado.","teamSide.groupAudience": "Compartilhado · todos neste chat em grupo podem ver",+ "teamSide.sharedWith": "Compartilhada · só você e {name} podem ver",+ "conversationShare.withTeam": "Compartilhar com a equipe",+ "conversationShare.withPerson": "Compartilhar com…",+ "conversationShare.teamTitle": "Compartilhar com a equipe?",+ "conversationShare.teamBody": "Todos em {team} que podem usar {bot} vão poder ler esta conversa inteira, incluindo tudo o que já está nela e os arquivos, e escrever nela. Ela passa para o lado Equipe. Não será possível torná-la privada de novo.",+ "conversationShare.personTitle": "Compartilhar com uma pessoa?",+ "conversationShare.personField": "Compartilhar com",+ "conversationShare.personBody": "{name} vai poder ler esta conversa inteira, incluindo tudo o que já está nela e os arquivos, e continuá-la com {bot}. Mais ninguém pode vê-la, nem os administradores. Não será possível torná-la privada de novo.",+ "conversationShare.personConfirm": "Compartilhar com {name}",+ "conversationShare.nobody": "Ninguém mais na equipe pode conversar com {bot} ainda.",+ "teamMemorySave.menu": "Salvar na memória da equipe",+ "teamMemorySave.saved": "Salvo na memória da equipe de {bot}",+ "teamMemorySave.yours": "Na memória da equipe · adicionado por você","chat.page.usage": "Páginas: {pages} de {limit}","chat.page.copyLink": "Copiar link","chat.page.copied": "Copiado",@@ -9885,6 +9904,17 @@"time.invalid": "Data inválida","shortcuts.send-follow-up": "Enquanto um bot trabalha: colocar na fila em vez de enviar agora, ou o contrário","serverError.bot.viewOnly": "Você pode ver {bot}, mas não conversar com ele.",+ "serverError.share.ownBot": "As conversas com o seu próprio MausBot são só suas, então não podem ser compartilhadas.",+ "serverError.share.alreadyTeam": "Esta conversa já está compartilhada com a equipe.",+ "serverError.share.notYours": "Só a pessoa dona desta conversa pode compartilhá-la.",+ "serverError.share.notTeammate": "{name} não faz parte desta equipe.",+ "serverError.share.alreadyWith": "Esta conversa já está compartilhada com {name}.",+ "serverError.share.cantUse": "{name} não pode conversar com {bot}, então não é possível compartilhar esta conversa com essa pessoa.",+ "serverError.share.busy": "{bot} ainda está trabalhando aqui. Compartilhe quando terminar.",+ "serverError.share.routine": "Há uma rotina ligada a esta conversa. Exclua a rotina primeiro e depois compartilhe.",+ "serverError.teamMemory.outside": "Esta conversa veio de fora da equipe, então nada dela vai para a memória da equipe.",+ "serverError.teamMemory.empty": "Escreva primeiro o que salvar.",+ "serverError.teamMemory.notYours": "Só quem salvou isto, ou um administrador, pode removê-lo.","native.teamMove.sessionLabel": "Mover para uma equipe","native.teamMove.homeNoAnswer": "O Cloud não respondeu.","native.teamMove.openTeam": "Abra a equipe para a qual você quer mover o bot.",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex 390690502f..628959a527 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -3427,6 +3427,12 @@"phoneUpdate.bodyMany": "9eaa5a5fee2496ba55ce8bc2032ca7a32b6fb7c9740909fb2ee98579c83e935d","phoneUpdate.open": "4997e0ba6a79fe84efb5c17a9025aa917c736232b40d1f765e43443d1a99b51e","remote.devices.pairAgain": "b0545ee3486b14f40b7b0a853bb1626a6f62ef7df6d6099faa39ff305d6d8f98",+ "server.share.withYouTitle": "f5e11ae6e88e03c36b5f005704b15a4ad4718a3e779b53ea53962ad05844f3a3",+ "server.share.withYou": "181fcc73d27760500dace56ff4c5c17950c1f6b189d02a966790dc7af744a72a",+ "server.share.wroteTitle": "6833cfe3d9a3332e194d13ea970d6a8b98310a175957b6e208972b1de6837163",+ "server.share.wrote": "7672ad3a723e9f3a97a7570db7c388644185cfd1c78a5582743d1900fd50ccf1",+ "server.share.answeredTitle": "475334e117f72b6000a657501681debdd73d31128177856fda6a5c48999c94ef",+ "server.share.answered": "b9baf8feb4ac3ea7b8277d116c8c5ea89fe86cbb997143892121ca28259581ec","settings.learnMore": "1445799c033a2d17e2bad5d8610879e71ff0d73a8a3c2b932b43ad0449dac3a1","phone.pair.installLine": "c38bd5e91a296019b3909f24bed64290e6adbef39480d48eb1af18e5f8fa90ea","phone.code.notCamera": "94977df418d83e1fd94e4d9ed0b8452bcf97bfc9a6a88a42576855f3c32e7481",@@ -34224,6 +34230,36 @@"phoneUpdate.bodyMany": "9eaa5a5fee2496ba55ce8bc2032ca7a32b6fb7c9740909fb2ee98579c83e935d","phoneUpdate.open": "4997e0ba6a79fe84efb5c17a9025aa917c736232b40d1f765e43443d1a99b51e","remote.devices.pairAgain": "b0545ee3486b14f40b7b0a853bb1626a6f62ef7df6d6099faa39ff305d6d8f98",+ "serverError.share.ownBot": "4b8ac64954f41e33c7cbb6c2ce8c769ca66240ae78167ad74eadec52ec15786f",+ "serverError.share.alreadyTeam": "2c1bcaac2f0f8388e8185742b0846cd6fe574c0f01e8fe6a3f6815520eda47f6",+ "serverError.share.notYours": "a50f065b3cb93d8299bdf009def479f971da8d1fbf9295d6ffd8814eac0926d6",+ "serverError.share.notTeammate": "a052364621479919f42bed138fe06d527596e3d8a33f45de7867e81befdb2e36",+ "serverError.share.alreadyWith": "f3a16dacf260cdb0f4106be9068cc5b0395c53a45309aa22058a5e2d07288ab2",+ "serverError.share.cantUse": "8b065884fb61dd08d396d5725fa9e496534f936918bffeea1f59794f1408a06e",+ "serverError.share.busy": "836170b954f4c5ec99759a268669c5f5e799b15b7d42d310bfce679773289493",+ "serverError.share.routine": "a0a4587710949461145281ce2da9f1b3c40a870768bd315f61a2b1b0d018849c",+ "serverError.teamMemory.outside": "a951e9011251518086f200d69b4eb4d593bdf2bf89a982e820088461716539d6",+ "serverError.teamMemory.empty": "52bca2141e0692aec0b74a64af9af399c3eec7c795c9d0578dcbf8d4497132fe",+ "serverError.teamMemory.notYours": "a01de62ce77defc1c8ebe00d0d015100ab9758289dab8536997a6e32f953b0d7",+ "server.share.withYouTitle": "f5e11ae6e88e03c36b5f005704b15a4ad4718a3e779b53ea53962ad05844f3a3",+ "server.share.withYou": "181fcc73d27760500dace56ff4c5c17950c1f6b189d02a966790dc7af744a72a",+ "teamSide.sharedWith": "73187751302a92c2e4835e720e07a1159e1c02a776786528e7fc5c7a02a42c4a",+ "conversationShare.withTeam": "2051920cb6f192a67ee628f17ea9372e551795ef4c0c6725bbcc56ce027010b1",+ "conversationShare.withPerson": "3cdb003d49ac8846d497285ffba4c1f61bca62dd8d27675d1288a9a8e4089551",+ "conversationShare.teamTitle": "030121b0cf7d19fc98d4f84878f664a4e94aca51bc438ec90bbdc1de240e5e20",+ "conversationShare.teamBody": "588260a5cd3d44781dcc04429fc2f45b856cc6dd9b83914df4c7bf9d966de64a",+ "conversationShare.personTitle": "44e9a9a8554f25bfe551c59efd1b389c14329e25e34b3df1a8d8e4dba5f092c1",+ "conversationShare.personField": "2d9182ea72cfa1696c00c5cdf09fc2637681295795aa0a7fef4e0aca920f5671",+ "conversationShare.personBody": "a95717d322004f99c2484531cd0acc6f5b21ed90e39ad488e7735ff890e6816c",+ "conversationShare.personConfirm": "b457031b91f4e9050e701e2a7ea0cb5e8f94c3a927b6feaed59b18009b12db0b",+ "conversationShare.nobody": "16488af60125467ed2dd079accf565aa31f5f206fe313d27b7a75cf89406fdda",+ "teamMemorySave.menu": "c197e789f4ad58c69617482e7c5527594b3fdb110cfa2459a57e2e8d23fd162b",+ "teamMemorySave.yours": "a8d84f9a1ae2c3bb10f9345de6abc6f372629bb8853c99554ea40365d28b553c",+ "server.share.wroteTitle": "6833cfe3d9a3332e194d13ea970d6a8b98310a175957b6e208972b1de6837163",+ "server.share.wrote": "7672ad3a723e9f3a97a7570db7c388644185cfd1c78a5582743d1900fd50ccf1",+ "server.share.answeredTitle": "475334e117f72b6000a657501681debdd73d31128177856fda6a5c48999c94ef",+ "server.share.answered": "b9baf8feb4ac3ea7b8277d116c8c5ea89fe86cbb997143892121ca28259581ec",+ "teamMemorySave.saved": "16dcefaa40a168bc07ccea0eb693f0d461e06c3f4204c36418aca8f06b4eb04e","settings.learnMore": "1445799c033a2d17e2bad5d8610879e71ff0d73a8a3c2b932b43ad0449dac3a1","phone.pair.installLine": "c38bd5e91a296019b3909f24bed64290e6adbef39480d48eb1af18e5f8fa90ea","phone.code.notCamera": "94977df418d83e1fd94e4d9ed0b8452bcf97bfc9a6a88a42576855f3c32e7481",diff --git a/src/state/store.tsx b/src/state/store.tsxindex eae2f4c5a8..10ac313636 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -215,7 +215,7 @@ export interface ModelSelection {variant?: string;}-export interface Task extends Pick<WireTask, "private" | "setupRequest" | "inbox" | "openAsks" | "askedBy"> {+export interface Task extends Pick<WireTask, "private" | "shared" | "sharedWith" | "setupRequest" | "inbox" | "openAsks" | "askedBy"> {waitingForTeammates?: boolean; sharedChat?: true;threadId: string;routineRunId?: string;diff --git a/src/state/team-side.test.ts b/src/state/team-side.test.tsindex 2d9e70e309..ca45750f59 100644--- a/src/state/team-side.test.ts+++ b/src/state/team-side.test.ts@@ -52,6 +52,13 @@ describe("the side of a conversation is the server's answer", () => {expect(teamThreadOf(mausbot()), "a person's own MausBot has none").toBeNull();});+ it("moves a conversation its person shared to Team at once, even on a page whose session still lists it as theirs", () => {+ setTeamChats({ ...ADA, opened: ["handed", "widened"] });+ const bot = scout([{ threadId: "handed", shared: true, sharedWith: { name: "Marta", byYou: true }, createdAt: 2 }, { threadId: "widened", shared: true, createdAt: 3 }]);+ expect(sideOfThread(bot, "handed"), "shared with one person").toBe("team");+ expect(sideOfThread(bot, "widened"), "shared with the team").toBe("team");+ });+it("does not move with the switch: the same conversation is the same side whichever side the sidebar shows", () => {setTeamChats(ADA);const bot = scout([{ threadId: "ada-own", private: true, createdAt: 2 }]);diff --git a/src/state/team-side.ts b/src/state/team-side.tsindex a5c28c0dce..916c6c7c96 100644--- a/src/state/team-side.ts+++ b/src/state/team-side.ts@@ -6,7 +6,7 @@ import { onTeamChats, ownChatOf, ownChatStarted, teamChats, type TeamChats } froexport type TeamSide = "me" | "team";-type SideTask = { threadId: string; private?: unknown; sharedChat?: unknown; unread?: boolean; routineRunId?: unknown; archivedAt?: unknown };+type SideTask = { threadId: string; private?: unknown; shared?: unknown; sharedChat?: unknown; unread?: boolean; routineRunId?: unknown; archivedAt?: unknown };type SideBot = { id: string; threadId: string; tasks?: SideTask[]; yourAccess?: string; defaultBot?: { person?: unknown }; hidden?: boolean; messages?: unknown[] };type SideGroup = { id: string; unread?: boolean };@@ -19,7 +19,7 @@ type SideGroup = { id: string; unread?: boolean };export function sideOfThread(bot: Pick<SideBot, "tasks" | "defaultBot">, threadId: string): TeamSide {if (bot.defaultBot?.person) return "me";const task = bot.tasks?.find((candidate) => candidate.threadId === threadId);- return task?.sharedChat !== true && (task?.private === true || ownChatStarted(threadId)) ? "me" : "team";+ return task?.sharedChat !== true && (task?.private === true || (ownChatStarted(threadId) && task?.shared !== true)) ? "me" : "team";}/** The bot's shared chat, as the server names it; null for a bot that has none (a person's own MausBot). */