Skip to content

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

Team Clouds: one "Just me / Team" switch in the sidebar, and who can see it by the message box (#5340)

Milind Soni5fa30928eee7
diff --git a/docs/team-cloud.md b/docs/team-cloud.md
index c910f9d2b7..743ded5701 100644
--- a/docs/team-cloud.md
+++ b/docs/team-cloud.md
@@ -498,8 +498,44 @@ routine from anyone else (404 *no such bot*).
## The shared chat's name
A team bot's main chat is called *"Shared chat"* on every person's copy (`WireTask.sharedChat`), whatever its stored title,
-so nobody takes it for one of their own, and it can't be renamed. A member's own MausBot has none. Clicking a bot still
-opens the person's own private chat.
+so nobody takes it for one of their own, and it can't be renamed. A member's own MausBot has none.
+
+## Just me and Team
+
+At the top of a team's sidebar sits one switch, **Just me / Team** (`src/state/team-side.ts`, `TeamSideSwitch`). It is in
+the sidebar in each of its shapes: full width, the rail of icons (two icon buttons) and the phone's bot list. It is not
+in the window's rail of Clouds, which is the desktop window's own chrome: a browser and a phone have none, one place has
+none, and the person can hide it.
+
+- **Just me** lists the bots the person can chat with privately (their own MausBot among them), each with their own
+ conversations with it, and no group chat. A bot opens the person's own chat with it, made through `POST
+ /api/bots/<id>/tasks` the first time.
+- **Team** lists the bots that have a shared chat, each with its shared conversations only, and the group chats. A bot
+ opens its shared chat. A bot with no shared chat (a person's own MausBot) is not listed there. No new conversation is
+ offered beside a shared chat: a conversation a person opens is always private, so New conversation is under Just me.
+- **Which side a conversation is on is the server's answer**, never the switch: `private: true` on the task (or a
+ conversation this page just made through that route, or the person's own MausBot) is Just me; everything else, a
+ conversation the page knows nothing of included, is Team. Neither side's list shows a conversation, an unread mark or a
+ preview line of the other's.
+- **By the message box**, every conversation on a team says who can read it, from that same answer: *"Private · only
+ you"*, *"Shared · everyone in Acme can see"*, *"Shared · only people added and admins can see"* or, in a group chat,
+ *"Shared · everyone in this group chat can see"* (`TeamAudienceLabel`).
+- **The switch follows a conversation the person asked for**: another bot or group chat, a conversation opened by
+ name (a notification, a link, search, a list), one they just made. That, and pressing the switch, are the only things
+ that keep a side as their choice (`localStorage`, `omb.team-side.<team>.<address>`, per person and team on the
+ device; Just me until they choose Team).
+- **A conversation that came on screen unasked is never kept.** The first conversation a page shows, one the app opened
+ as it started (before it knew this is a team's Cloud), or the bot's own pick changing because a teammate opened
+ another: when it is of the other side, the page goes back to the side the person chose, to their own conversation
+ with that bot when it is listed there. So a reload with Just me chosen opens their private chat, never the shared one.
+ With nowhere to go on that side the switch shows the side on screen for that page only.
+- **A draft stays with its conversation.** What is typed and not sent is kept per conversation, so it is never in the
+ message box of the other side; on a team the older per-bot draft is not read.
+- **Unread.** The side not shown carries a dot when the person has something unread there (their own marks: a private
+ chat's, or their own read line of a shared chat or a group chat). A bot's row carries only its side's marks: no
+ unread mark, working line or preview from the other side's conversations.
+- 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.
## Who looks after a bot
@@ -776,8 +812,8 @@ listed), two of that name, the person the bot is already talking with, a person
inbox here, and more than 10 passes an hour from one conversation (answers from an inbox included).
**People.** The composer's @ list offers the teammates after the bots, with their picture and a "Person" tag; the
-sidebar lists the team's people with their pictures: your own row opens your inbox, a teammate's puts their @name in
-the composer on screen. Each person is tagged by their whole name, and by their first name when no other teammate shares
+sidebar shows the team's people as a row of faces above the bots, never as rows of their own: your own face opens your
+inbox, a teammate's puts their @name in the composer on screen. Each person is tagged by their whole name, and by their first name when no other teammate shares
it (`shared/person-mention.ts`). A tag a bot shares is the person's: "@Ben" reaches Ben even with a bot called Ben, and
that bot is not told it was named; only a longer bot name ("@Ben Bot") reaches a bot. A bot made or renamed with a
person's name says so once in its own chat, and the Chief's `create_bot` result warns (`server/host/bot-name-clash.ts`).
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs
index 26a753ae05..e31912b7e6 100644
--- a/scripts/ci-scope.mjs
+++ b/scripts/ci-scope.mjs
@@ -62,6 +62,7 @@ export const VITEST_SUBSETS = {
"scripts/testing/rail-profile-ui.e2e.test.ts",
"scripts/testing/secret-card-descriptions.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",
"server/client-notifications.e2e.test.ts",
"server/cloud-connections.e2e.test.ts",
diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.ts
index fa507406c6..c367a43278 100644
--- a/scripts/ci-scope.test.ts
+++ b/scripts/ci-scope.test.ts
@@ -199,6 +199,7 @@ describe("CI outputs", () => {
"scripts/testing/rail-profile-ui.e2e.test.ts",
"scripts/testing/secret-card-descriptions.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",
"server/client-notifications.e2e.test.ts",
"server/cloud-connections.e2e.test.ts",
diff --git a/scripts/testing/team-side-switch-ui.e2e.test.ts b/scripts/testing/team-side-switch-ui.e2e.test.ts
new file mode 100644
index 0000000000..6fc82dabf1
--- /dev/null
+++ b/scripts/testing/team-side-switch-ui.e2e.test.ts
@@ -0,0 +1,277 @@
+// "Just me / Team" at the top of a team's sidebar and the audience label by the message box, 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: what one member types under Just me reaches no other member and no
+// admin, on screen or through the API, and what they type under Team reaches both. Run with OMB_UI_E2E=1;
+// OMB_TEAM_SWITCH_SHOTS=DIR keeps the screenshots there.
+import { randomBytes } from "node:crypto";
+import { mkdirSync } 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 Just me / Team UI e2e: set OMB_UI_E2E=1");
+
+const SHOTS = process.env.OMB_TEAM_SWITCH_SHOTS || join(REPO_ROOT, ".omb-scratch", "team-side-switch");
+const PRIVATE = "Kumquat salary plan for March";
+const SHARED = "Team lunch is on Friday";
+const DESKTOP = ["1280", "800"] as const, PHONE = ["390", "844"] as const;
+
+/** A new member is offered their own MausBot in a dialog over the app; this run leaves it for later. */
+const DISMISS = `(() => { [...document.querySelectorAll('[role="dialog"] button, dialog button')].find((button) => button.textContent.trim() === "Not now")?.click(); return true; })()`;
+
+type Task = { threadId: string; private?: true; sharedChat?: true; unread?: boolean };
+type Bot = { id: string; threadId: string; mainThreadId: string; tasks: Task[] };
+type App = Awaited<ReturnType<typeof openAs>>;
+
+let fx: CloudSendFixture, team: CloudTeamFixture;
+let tools: { binary: string; chrome: string | null };
+const tokens: Record<"olive" | "ada" | "ben", string> = { olive: "", ada: "", ben: "" };
+let scout = "", main = "";
+const apps: App[] = [];
+
+const scoutAs = async (who: keyof typeof tokens) => ((await team.as(tokens[who], "GET", "/api/bots?messages=0")).body.bots as Bot[]).find((bot) => bot.id === scout)!;
+const wordsIn = async (who: keyof typeof tokens, threadId: string) => {
+ const page = await team.as(tokens[who], "GET", `/api/threads/${threadId}/messages?limit=50`);
+ return { status: page.status, text: JSON.stringify(page.body) };
+};
+
+/** The real renderer on the team's Cloud, signed in as one person, and what they do with it. */
+async function openAs(who: keyof typeof tokens, size: readonly [string, string]) {
+ const preview = await mountPreview({ info: { url: team.base } }, { entry: "/scripts/testing/threads-preview.tsx", route: "/__threads.html", title: "Just me / Team",
+ logLevel: "warn", proxyHeaders: { ...fx.edge, authorization: `Bearer ${tokens[who]}` } });
+ // agent-browser 0.37 refuses a socket path over 103 bytes, and it lives under this home.
+ const home = join(fx.root, `b${apps.length}`);
+ mkdirSync(join(home, "tmp"), { recursive: true });
+ const env = sessionEnv({ home, session: `t${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;
+ // Once-per-person cards (a sponsor's offer, say) sit over the message box: this browser has seen them before the app starts.
+ 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 side = () => evaluate<string | null>("document.querySelector('[data-team-side]')?.dataset.teamSide ?? null");
+ const audience = () => evaluate<string | null>("(() => { const label = document.querySelector('[data-team-audience]'); return label ? label.dataset.teamAudience + ':' + label.textContent : null; })()");
+ const app = {
+ who, evaluate, side, audience,
+ listed: () => evaluate<string[]>("[...document.querySelectorAll('[data-sidebar-bot-row]')].map((row) => row.dataset.sidebarBotRow)"),
+ words: () => evaluate<string>("document.body.innerText"),
+ async shot(name: string) {
+ await new Promise((resolve) => setTimeout(resolve, 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 evaluate<string>("document.querySelector('textarea')?.getAttribute('placeholder') ?? ''")} ${(await audience())?.split(":")[0]}`, { timeout: 30_000 }).toBe(`Message Scout ${on}`);
+ },
+ async openList() {
+ await evaluate(DISMISS);
+ await expect.poll(audience, { timeout: 60_000, interval: 500 }).not.toBeNull();
+ await evaluate(`document.querySelector('button[aria-label="Open bot list"]')?.click(); true`);
+ await expect.poll(() => evaluate<boolean>(`Boolean(document.querySelector('button[aria-label="Open bot list"][aria-expanded="true"]') && document.querySelector('[data-team-side]'))`), { timeout: 30_000 }).toBe(true);
+ },
+ async choose(next: "me" | "team") {
+ await evaluate(`document.querySelector('[data-team-side-option="${next}"]').click(); true`);
+ await expect.poll(side, { timeout: 30_000 }).toBe(next);
+ await expect.poll(async () => (await audience())?.split(":")[0] ?? null, { timeout: 30_000 }).toBe(next);
+ },
+ 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);
+ },
+ /** Types without sending. */
+ async draft(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 new Promise((resolve) => setTimeout(resolve, 600));
+ },
+ typed: () => evaluate<string>(`document.querySelector('textarea[placeholder^="Message"]')?.value ?? ""`),
+ saved: () => evaluate<string | null>(`localStorage.getItem("omb.team-side.team-acme-switch." + ${JSON.stringify(`${who}@acme.test`)})`),
+ async reload() {
+ await evaluate("location.reload(); true");
+ await expect.poll(() => evaluate<boolean>(`Boolean(document.querySelector('[data-sidebar-bot-row="${scout}"]'))`), { timeout: 60_000, interval: 500 }).toBe(true);
+ },
+ async close() {
+ await browser("close").catch(() => {});
+ await preview.close();
+ },
+ };
+ apps.push(app);
+ return app;
+}
+
+(enabled ? describe : describe.skip)("Just me / Team 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-switch-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-switch", name: "Acme" } });
+ team = fx.team!;
+ tokens.olive = (await team.pair({ email: "[email protected]", role: "owner" })).token!;
+ tokens.ada = (await team.pair({ email: "[email protected]", role: "member" })).token!;
+ tokens.ben = (await team.pair({ email: "[email protected]", role: "member" })).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 team.as(tokens.olive, "PATCH", "/api/config", { onboarding, language: "en" })).status).toBe(200);
+ for (const who of ["ada", "ben"] as const) expect((await team.as(tokens[who], "PUT", "/api/me/welcome", { welcomed: true })).status).toBe(200);
+ // Each person said yes to "Add MausBot", as its card saves it: their own helper sits at the top of their sidebar.
+ for (const who of ["olive", "ada", "ben"] as const) {
+ const own = ((await team.as(tokens[who], "GET", "/api/bots?messages=0")).body.bots as Array<{ id: string; defaultBot?: { person?: string } }>).find((bot) => bot.defaultBot?.person === `${who}@acme.test`)!;
+ const added = await team.as(tokens[who], "PATCH", `/api/bots/${own.id}`, { welcomed: true, sidebarHidden: false, pinned: true });
+ expect(added.status, JSON.stringify(added.body)).toBe(200);
+ }
+ const created = await team.as(tokens.olive, "POST", "/api/bots", { name: "Scout" });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ scout = created.body.bot.id; main = created.body.bot.mainThreadId;
+ }, hostTimeout(300_000));
+ afterAll(async () => {
+ for (const app of apps) await app.close().catch(() => {});
+ await fx?.close();
+ }, hostTimeout(120_000));
+
+ let adaOwn = "", mine = "";
+
+ it("a member's Just me chat is hers alone and her Team message is the team's, each sent to the conversation the label names", async () => {
+ const ada = await openAs("ada", DESKTOP);
+ await expect.poll(ada.side, { timeout: 60_000, interval: 500 }).toBe("me");
+ expect(await ada.evaluate<string | null>("document.querySelector('[data-team-side-hint]')?.textContent ?? null"), "said once, the first time").toBe("Just me is private, even from admins. Team is shared.");
+ expect(await ada.evaluate<string[]>("[...document.querySelectorAll('[data-team-side] [role=radio]')].map((radio) => radio.textContent.trim() + ':' + radio.getAttribute('aria-checked'))")).toEqual(["Just me:true", "Team:false"]);
+ await ada.openScout("me");
+ expect(await ada.audience(), "by the message box").toBe("me:Private · only you");
+ await ada.say(PRIVATE);
+ await ada.shot("01-ada-just-me-desktop");
+
+ const bots = (await team.as(tokens.ada, "GET", "/api/bots?messages=0")).body.bots as Array<Bot & { defaultBot?: { person?: string } }>;
+ mine = bots.find((bot) => bot.defaultBot?.person === "[email protected]")!.id;
+ expect(await ada.listed(), "Just me lists her own MausBot and the bots she can chat with").toEqual(expect.arrayContaining([scout, mine]));
+ const own = (await scoutAs("ada")).tasks.filter((task) => task.private === true);
+ expect(own.length, "one private conversation, made by the click").toBe(1);
+ adaOwn = own[0]!.threadId;
+ expect(adaOwn).not.toBe(main);
+ expect((await wordsIn("ada", adaOwn)).text).toContain(PRIVATE);
+ expect((await wordsIn("ada", main)).text, "nothing typed under Just me reaches the shared chat").not.toContain(PRIVATE);
+
+ await ada.choose("team");
+ expect(await ada.audience()).toBe("team:Shared · everyone in Acme can see");
+ expect(await ada.listed(), "a private-only bot is not on the Team side").not.toContain(mine);
+ expect(await ada.listed()).toContain(scout);
+ expect(await ada.words(), "nothing of the private chat on the Team side: not the transcript, not the sidebar").not.toContain(PRIVATE);
+ await ada.say(SHARED);
+ await ada.shot("02-ada-team-desktop");
+ expect((await wordsIn("ada", main)).text).toContain(SHARED);
+ expect((await wordsIn("ada", main)).text).not.toContain(PRIVATE);
+ expect((await wordsIn("ada", adaOwn)).text, "nothing typed under Team lands in her private chat").not.toContain(SHARED);
+
+ await ada.reload();
+ await expect.poll(ada.side, { timeout: 60_000, interval: 500 }).toBe("team");
+ await expect.poll(async () => (await ada.audience())?.split(":")[0] ?? null, { timeout: 30_000 }).toBe("team");
+ await ada.choose("me");
+ expect(await ada.audience()).toBe("me:Private · only you");
+ expect(await ada.evaluate<string>("document.querySelector('main').innerText")).toContain(PRIVATE);
+ expect(await ada.words(), "and nothing of the shared chat under Just me").not.toContain(SHARED);
+ expect((await scoutAs("ada")).tasks.filter((task) => task.private === true).length, "going back opens her chat, it makes no second one").toBe(1);
+ await ada.close();
+ }, hostTimeout(300_000));
+
+ it("a reload keeps a member in her private chat and keeps her choice, whatever conversation the server would show first", async () => {
+ const ada = await openAs("ada", DESKTOP);
+ await ada.openScout("me");
+ await ada.choose("team");
+ await ada.choose("me");
+ expect(await ada.saved(), "she pressed Just me").toBe("me");
+ for (let round = 0; round < 2; round++) {
+ // A teammate opens the bot's shared chat meanwhile, so the bot's own pick of a conversation is the shared one.
+ expect((await team.as(tokens.ben, "POST", `/api/bots/${scout}/tasks/${main}`, {})).status).toBe(200);
+ expect((await scoutAs("ada")).threadId, "what her page is sent first").toBe(main);
+ await ada.reload();
+ await expect.poll(async () => `${await ada.side()} ${await ada.audience()}`, { timeout: 60_000, interval: 500 }).toBe("me me:Private · only you");
+ await new Promise((resolve) => setTimeout(resolve, 1_500));
+ expect(`${await ada.side()} ${await ada.audience()}`, "and it stays there").toBe("me me:Private · only you");
+ expect(await ada.saved(), "a reload never rewrites what she chose").toBe("me");
+ expect(await ada.evaluate<string>("document.querySelector('main').innerText"), "her own conversation, the one she was in").toContain(PRIVATE);
+ // The same teammate opening the shared chat again while her page is open moves nothing under her.
+ expect((await team.as(tokens.ben, "POST", `/api/bots/${scout}/tasks/${main}`, {})).status).toBe(200);
+ await new Promise((resolve) => setTimeout(resolve, 1_500));
+ expect(`${await ada.side()} ${await ada.audience()} ${await ada.saved()}`).toBe("me me:Private · only you me");
+ }
+ expect((await scoutAs("ada")).tasks.filter((task) => task.private === true).map((task) => task.threadId), "no second private chat is made").toEqual([adaOwn]);
+
+ const AFTER = "Typed after the reload, for me alone";
+ await ada.say(AFTER);
+ expect((await wordsIn("ada", adaOwn)).text).toContain(AFTER);
+ expect((await wordsIn("ada", main)).text, "what she types after a reload never reaches the shared chat").not.toContain(AFTER);
+
+ const DRAFT = "A private thought not sent yet";
+ await ada.draft(DRAFT);
+ await ada.choose("team");
+ expect(await ada.typed(), "a draft typed under Just me is not in the Team message box").toBe("");
+ await ada.reload();
+ await expect.poll(ada.audience, { timeout: 60_000, interval: 500 }).toBe("team:Shared · everyone in Acme can see");
+ expect(await ada.typed(), "nor after a reload").toBe("");
+ expect(await ada.saved(), "she pressed Team").toBe("team");
+ await ada.choose("me");
+ expect(await ada.typed(), "it waits where it was typed").toBe(DRAFT);
+ expect((await wordsIn("ada", main)).text).not.toContain(DRAFT);
+ await ada.draft("");
+ await ada.close();
+ }, hostTimeout(300_000));
+
+ it("the switch stays reachable and the label visible at phone width", async () => {
+ const ada = await openAs("ada", PHONE);
+ await ada.openList();
+ const fits = (selector: string) => ada.evaluate<boolean>(`(() => { const box = document.querySelector(${JSON.stringify(selector)})?.getBoundingClientRect(); return Boolean(box && box.width > 0 && box.left >= 0 && box.right <= window.innerWidth && box.top >= 0 && box.bottom <= window.innerHeight); })()`);
+ await ada.shot("03-ada-list-just-me-phone");
+ expect(await fits("[data-team-side] [role=radiogroup]"), "the whole switch is on screen in the bot list").toBe(true);
+ await ada.evaluate(`document.querySelector('[data-team-side-option="team"]').click(); true`);
+ await expect.poll(ada.side, { timeout: 30_000 }).toBe("team");
+ expect(await ada.listed(), "the list changed and stayed open").toContain(scout);
+ expect(await ada.listed()).not.toContain(mine);
+ await ada.shot("04-ada-list-team-phone");
+ await ada.openScout("team");
+ await expect.poll(ada.audience, { timeout: 30_000 }).toBe("team:Shared · everyone in Acme can see");
+ expect(await fits("[data-team-audience]"), "the label is on screen by the message box").toBe(true);
+ await ada.shot("05-ada-team-chat-phone");
+ await ada.openList();
+ await ada.evaluate(`document.querySelector('[data-team-side-option="me"]').click(); true`);
+ await expect.poll(ada.side, { timeout: 30_000 }).toBe("me");
+ await ada.openScout("me");
+ await expect.poll(ada.audience, { timeout: 30_000 }).toBe("me:Private · only you");
+ expect(await fits("[data-team-audience]")).toBe(true);
+ await ada.shot("06-ada-just-me-chat-phone");
+ expect(await ada.evaluate<number>("document.scrollingElement.scrollWidth - window.innerWidth"), "no sideways scroll").toBeLessThanOrEqual(1);
+ expect((await scoutAs("ada")).tasks.filter((task) => task.private === true).map((task) => task.threadId), "another device opens her chat, it makes no second one").toEqual([adaOwn]);
+ await ada.close();
+ }, hostTimeout(300_000));
+
+ for (const [who, role] of [["ben", "another member"], ["olive", "the team's owner, an admin"]] as const) {
+ it(`${role} reads the Team message and never the Just me chat`, async () => {
+ const listed = await scoutAs(who);
+ expect(listed.tasks.some((task) => task.threadId === adaOwn), "not in their list of conversations").toBe(false);
+ expect(JSON.stringify((await team.as(tokens[who], "GET", "/api/bots")).body), "nor its words in anything listed").not.toContain(PRIVATE);
+ expect((await wordsIn(who, adaOwn)).status, "opening it by id: no such conversation").toBe(404);
+
+ const app = await openAs(who, DESKTOP);
+ await expect.poll(app.side, { timeout: 60_000, interval: 500 }).toBe("me");
+ await app.openScout("me");
+ expect(await app.audience()).toBe("me:Private · only you");
+ expect(await app.words(), "their own Just me has none of hers").not.toContain(PRIVATE);
+ expect((await scoutAs(who)).tasks.filter((task) => task.private === true).map((task) => task.threadId), "their own private chat, not hers").not.toContain(adaOwn);
+ await app.choose("team");
+ await expect.poll(() => app.evaluate<string>("document.querySelector('main').innerText"), { timeout: 30_000 }).toContain(SHARED);
+ expect(await app.words(), "nowhere on the Team side, sidebar included").not.toContain(PRIVATE);
+ await app.shot(who === "ben" ? "07-ben-team-desktop" : "08-admin-team-desktop");
+ await app.close();
+ }, hostTimeout(300_000));
+ }
+});
diff --git a/src/components/ChatMoreMenu.tsx b/src/components/ChatMoreMenu.tsx
index 8f6af11c96..1ced2f05a3 100644
--- a/src/components/ChatMoreMenu.tsx
+++ b/src/components/ChatMoreMenu.tsx
@@ -22,6 +22,8 @@ import { orderedThreadList } from "./SidebarThreadRow";
import { openBotSettings } from "./bot-panel/panel-link";
import { ShareBotButton, useTeamName } from "./bot-access/ShareBotButton";
import { UsageBars } from "./EngineUsage";
+import { useConversationSide } from "./TeamSideSwitch";
+import { tasksOfSide } from "@/state/team-side";
/** 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. */
@@ -39,7 +41,8 @@ export function useChatMoreItems(profile: Bot, phoneHeader = false): { items: Si
const contextAction = useContextAction();
const atFreshStart = messages.at(-1)?.compaction?.fresh === true;
const transcript = () => formatTranscriptMarkdown({ title: bot.name, messages, botName: bot.name, isGroup: false });
- const threads = showThreads ? [] : orderedThreadList((profile.tasks ?? []).filter((task) => !task.routineRunId));
+ const side = useConversationSide(profile);
+ const threads = showThreads ? [] : orderedThreadList((side ? tasksOfSide(profile, side) : profile.tasks ?? []).filter((task) => !task.routineRunId));
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
@@ -81,7 +84,7 @@ export function useChatMoreItems(profile: Bot, phoneHeader = false): { items: Si
onSelect: () => requestChatFind(bot.threadId),
},
...phoneScreen,
- ...(showThreads ? [] : [{
+ ...(showThreads || side === "team" ? [] : [{
key: "new-thread",
heading: t("task.list"),
separatorBefore: true,
@@ -92,6 +95,7 @@ export function useChatMoreItems(profile: Bot, phoneHeader = false): { items: Si
// With one thread there is nothing to switch to.
...(threads.length < 2 ? [] : [{
key: "threads",
+ ...(side === "team" ? { heading: t("task.list"), separatorBefore: true } : {}),
label: t("task.switch"),
icon: <MessagesSquare size={16} />,
value: String(threads.length),
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
index 3218b03e3a..5254e2bb6a 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -1,4 +1,5 @@
import { directMessageSent, roomMessageSent } from "@/lib/product-events";
+import { TeamAudienceLabel } from "./TeamSideSwitch";
import { useComposerDictation } from "@/lib/use-composer-dictation";
import { useCallback, useEffect, useMemo, useRef, useState, type SetStateAction } from "react";
import { Mic, Paperclip, Square, X } from "lucide-react";
@@ -164,7 +165,7 @@ export function Composer({
: `bot:${bot?.id ?? ""}:${bot?.threadId ?? ""}`;
const [text, setText, attachments, setAttachments] = useComposerDraft(
draftId,
- !group && bot ? `bot:${bot.id}` : undefined,
+ !group && bot && !state.config?.team ? `bot:${bot.id}` : undefined,
);
const attachmentPending = useDraftAttachmentPending(draftId);
const failedSends = useFailedComposerSends(draftId); const picks = mentionPicksFor(draftId);
@@ -756,7 +757,7 @@ export function Composer({
else if (bot) dispatch({ type: "cancelQueued", botId: bot.id, threadId, queueId });
}}
onEdit={locked ? undefined : editQueued}
- />
+ /><TeamAudienceLabel bot={bot} group={group} />
<div className="relative">
{/* Plain canvas behind the composer and the strip below it, so the transcript ends at the composer
with no fade. Simple mode starts it at the composer's top edge, Advanced at its middle. */}
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index 1fa42b9df3..59748b6424 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -74,7 +74,7 @@ import { GlassBar, GlassScrollFrame, GlassScroller } from "./GlassScrollFrame";
import { DesktopWorkspaceSwitcher, endCloudHowTo } from "./DesktopWorkspaceSwitcher"; import { PlaceTint } from "./PlaceTint"; import { ChromeRailToggle } from "./ChromeRailToggle";
import { useCloudOwner } from "./CloudOwner";
import { SidebarSectionHeader } from "./SidebarSectionHeader";
-import { NeedsYouButton, OwnerPickerHost, pickOwnerOf } from "./TeamOwner"; import { SidebarPeople } from "./SidebarPeople"; import { SidebarInboxRow } from "./SidebarInboxRow"; import { SidebarActiveThreads } from "./SidebarActiveThreads"; import { setAttentionPinned, useAttentionPinned } from "./inbox/attention-pinned"; import { useInboxSupport } from "@/state/inbox";
+import { NeedsYouButton, OwnerPickerHost, pickOwnerOf } from "./TeamOwner"; import { SidebarPeople } from "./SidebarPeople"; import { SidebarInboxRow } from "./SidebarInboxRow"; import { TeamSideSwitch, useTeamSideLists } from "./TeamSideSwitch"; import { SidebarActiveThreads } from "./SidebarActiveThreads"; import { setAttentionPinned, useAttentionPinned } from "./inbox/attention-pinned"; import { useInboxSupport } from "@/state/inbox";
import { showWhoReportsToWhom, TeamMenuItems } from "./SidebarTeamMenu";
import { MENU_ITEM, MENU_ITEM_SEPARATOR, MENU_SHEET } from "./menu-recipe";
import { ELEVATED_CONTROL } from "./elevated";
@@ -1088,7 +1088,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {
const botDrag = useSidebarBotDrag({ dispatch, announce: sections.announce, onNamed: sections.focusHeader, onRenamed: sections.renamed,
onError: (text) => setTeamFeedback({ error: true, text }), onCancelled: () => sidebarRef.current?.focus() });
- const matchingBots = state.bots
+ const sideLists = useTeamSideLists(state), matchingBots = sideLists.bots
.filter((b) => !b.hidden)
.filter(
(b) =>
@@ -1099,7 +1099,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {
b.tasks?.some((task) => !task.routineRunId && task.title.toLowerCase().includes(q)) ||
b.projects?.some((folder) => folder.name.toLowerCase().includes(q)),
);
- const visibleGroups = state.groups.filter((g) => !q || g.name.toLowerCase().includes(q) || g.tasks?.some((task) => task.title.toLowerCase().includes(q)));
+ const visibleGroups = sideLists.groups.filter((g) => !q || g.name.toLowerCase().includes(q) || g.tasks?.some((task) => task.title.toLowerCase().includes(q)));
const viewerEmail = useViewerEmail();
const parts = partitionSidebarBots(botDrag.preview(matchingBots), { universalPins, viewerEmail, welcoming: useWelcomingBot(), searching: Boolean(q) });
const saved = simpleDesk ? withPrimaryTile(parts, myDefaultBot(state.bots, viewerEmail)?.id) : { ...parts, primary: null };
@@ -1326,7 +1326,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {
/>
</div>
</div>}
- {!q && <SidebarInboxRow icons={density === "icons"} large={!advanced} running={attentionHasRunningWork(attention)} onOpened={phone ? onClose : undefined} />}
+ {!q && <TeamSideSwitch compact={density === "icons"} listOnly={phone} />}{!q && <SidebarInboxRow icons={density === "icons"} large={!advanced} running={attentionHasRunningWork(attention)} onOpened={phone ? onClose : undefined} />}
{universalPins && pinnedBots.length > 0 && !simpleDesk && (
<div
data-sidebar-universal-pins=""
diff --git a/src/components/SidebarPeople.test.ts b/src/components/SidebarPeople.test.ts
index 20a9357a19..c1ebcad6e7 100644
--- a/src/components/SidebarPeople.test.ts
+++ b/src/components/SidebarPeople.test.ts
@@ -24,16 +24,24 @@ const line = (inbox: Message["inbox"], extra: Partial<Message> = {}): Message =>
afterEach(() => setTeamPeople(null));
describe("the team's people in the sidebar", () => {
- it("lists everyone with their face, you first, and says what a click does", () => {
+ it("shows everyone as a row of faces, you first, and says what a click does", () => {
setTeamPeople(asBen);
const markup = render(createElement(SidebarPeople, { compact: false }));
- expect(markup).toContain(">People<");
+ expect(markup).toContain('aria-label="People"');
expect(markup.indexOf("[email protected]")).toBeLessThan(markup.indexOf("[email protected]"));
expect(markup).toMatch(/aria-label="Your inbox: everything sent to you"[^>]*data-person="[email protected]"/);
- expect(markup).toContain("Ben (you)");
expect(markup).toMatch(/aria-label="Write to Cleo"[^>]*data-person="[email protected]"/);
});
+ it("is faces only: no row per person that reads as a chat with them, and no heading", () => {
+ setTeamPeople(asBen);
+ const markup = render(createElement(SidebarPeople, { compact: false }));
+ expect(markup).not.toContain(">People<");
+ expect(markup).not.toContain(">Cleo<");
+ expect(markup).not.toMatch(/>Ben[^<]*</);
+ expect(markup).toContain("flex-wrap");
+ });
+
it("shows nothing off a team, or for a team of one", () => {
expect(render(createElement(SidebarPeople, { compact: false }))).toBe("");
setTeamPeople({ ...asBen, people: [BEN] });
@@ -47,11 +55,11 @@ describe("the team's people in the sidebar", () => {
setTeamPeople({ ...asBen, admin: true });
const listed = render(createElement(SidebarPeople, { compact: false }), { config });
expect(listed).toContain(invite);
- expect(listed).toContain("Invite someone</span>");
+ expect(listed).toContain('aria-label="Invite someone"');
expect(listed.indexOf("[email protected]")).toBeLessThan(listed.indexOf(invite));
setTeamPeople({ ...asBen, people: [BEN], admin: true });
const alone = render(createElement(SidebarPeople, { compact: false }), { config });
- expect(alone).toContain(">People<");
+ expect(alone).toContain('aria-label="People"');
expect(alone).toContain(invite);
const rail = render(createElement(SidebarPeople, { compact: true }), { config });
expect(rail).toContain(invite);
diff --git a/src/components/SidebarPeople.tsx b/src/components/SidebarPeople.tsx
index 9dea655d1c..d0730adefb 100644
--- a/src/components/SidebarPeople.tsx
+++ b/src/components/SidebarPeople.tsx
@@ -1,8 +1,7 @@
-// On a Team Cloud: the team's people, with their pictures, and, when the server says who is here, a dot on whoever is
-// here now, listed first. Your own row opens your inbox, your chat with your Chief where
-// everything sent to you arrives, with the inbox's list beside it, and counts the asks waiting on you there. Anyone
-// else's puts @their name in the composer, which reaches their inbox once sent. For the team's admins, one more row opens
-// the team's People page, where invitations are sent, so someone alone on a new team still has a way to bring people in.
+// On a Team Cloud: the team's people as a row of faces above the bots, you first, with a dot on whoever is here now when
+// the server says so. People are who you share with and who you mention, never a chat of their own: your own face opens
+// your inbox, a teammate's puts @their name in the composer on screen. For the team's admins, one more opens the team's
+// People page, where invitations are sent, so someone alone on a new team still has a way to bring people in.
import { UserPlus } from "lucide-react";
import { botOwner } from "../../shared/bot-owner";
import { openAsksOf } from "@/lib/bot-unread";
@@ -98,10 +97,10 @@ export function SidebarPeople({ compact, onOpened }: { compact: boolean; onOpene
} else if (inbox) openBot(dispatch, inbox, showThreads);
focusComposer();
};
+ const face = compact ? 22 : 26;
return (
- <section aria-label={t("sidebar.people.title")} data-sidebar-people className={cn(compact ? "px-1" : "px-2 pb-1")}>
- {!compact && <div className="px-2 pb-0.5 pt-1 text-[11px] font-medium text-ink-tertiary">{t("sidebar.people.title")}</div>}
- <ul className={cn("flex", compact ? "flex-col items-center gap-1" : "flex-col")}>
+ <section aria-label={t("sidebar.people.title")} data-sidebar-people className={cn(compact ? "px-1" : "px-2 pb-1.5 pt-0.5")}>
+ <ul className={cn("flex items-center gap-1", compact ? "flex-col" : "flex-wrap")}>
{people.map((person) => {
const label = !person.you ? teammateLabel(person, presence)
: waiting ? t("sidebar.people.yourInboxWaiting", { count: waiting }) : t("sidebar.people.yourInbox");
@@ -109,15 +108,14 @@ export function SidebarPeople({ compact, onOpened }: { compact: boolean; onOpene
return (
<li key={person.email}>
<button type="button" onClick={() => open(person)} aria-label={label} title={label} data-person={person.email}
- className={cn("relative flex w-full min-w-0 items-center gap-2 rounded-lg text-left text-[13px] text-ink hover:bg-raised/60", compact ? "p-1" : "px-2 py-1")}>
+ className="relative flex rounded-full p-1 hover:bg-raised/60">
<span className="relative inline-flex shrink-0" data-person-here={here || undefined}>
- <PersonFace person={person} size={compact ? 22 : 18} />
- {here && <HereDot size={compact ? 22 : 18} />}
+ <PersonFace person={person} size={face} />
+ {here && <HereDot size={face} />}
</span>
- {!compact && <span className="min-w-0 flex-1 truncate">{person.you ? t("sidebar.people.you", { name: person.name }) : person.name}</span>}
{person.you && waiting > 0 && (
<span aria-hidden="true" data-inbox-waiting={waiting}
- className={cn("rounded-full bg-warning px-1.5 text-[11px] font-semibold tabular-nums text-panel", compact && "absolute -right-0.5 -top-0.5 px-1 text-[10px]")}>{waiting}</span>
+ className="absolute -right-0.5 -top-0.5 rounded-full bg-warning px-1 text-[10px] font-semibold tabular-nums text-panel">{waiting}</span>
)}
</button>
</li>
@@ -126,9 +124,10 @@ export function SidebarPeople({ compact, onOpened }: { compact: boolean; onOpene
{invite && (
<li>
<a href={invite} target="_blank" rel="noreferrer" aria-label={t("sidebar.people.invite")} title={t("sidebar.people.invite")} data-people-invite
- className={cn("flex w-full min-w-0 items-center gap-2 rounded-lg text-left text-[13px] text-ink-secondary hover:bg-raised/60 hover:text-ink", compact ? "justify-center p-1" : "px-2 py-1")}>
- <UserPlus aria-hidden="true" size={compact ? 18 : 15} strokeWidth={1.75} className="shrink-0" />
- {!compact && <span className="min-w-0 flex-1 truncate">{t("sidebar.people.invite")}</span>}
+ className="flex items-center justify-center rounded-full p-1 text-ink-secondary hover:bg-raised/60 hover:text-ink">
+ <span className="flex items-center justify-center rounded-full border border-dashed border-hairline" style={{ width: face, height: face }}>
+ <UserPlus aria-hidden="true" size={compact ? 13 : 14} strokeWidth={1.75} className="shrink-0" />
+ </span>
</a>
</li>
)}
diff --git a/src/components/TeamSideSwitch.dom.test.ts b/src/components/TeamSideSwitch.dom.test.ts
new file mode 100644
index 0000000000..e25d9c98a0
--- /dev/null
+++ b/src/components/TeamSideSwitch.dom.test.ts
@@ -0,0 +1,367 @@
+// @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";
+import type { AppState, Bot, Group, Task } from "@/state/store";
+
+const fixture = vi.hoisted(() => ({
+ dispatch: vi.fn(),
+ state: null as unknown,
+ calls: [] as Array<[string, RequestInit | undefined]>,
+ answer: null as unknown,
+}));
+const api = vi.hoisted(() => async (path: string, init?: RequestInit) => { fixture.calls.push([path, init]); return fixture.answer; });
+vi.mock("@/state/api", () => ({ api }));
+vi.mock("@/state/store", async (importOriginal) => {
+ const original = await importOriginal<typeof import("@/state/store")>();
+ return { ...original, api, useStore: () => ({ state: fixture.state ?? original.initialState, dispatch: fixture.dispatch }) };
+});
+vi.mock("@/lib/use-media-query", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/use-media-query")>(), useMediaQuery: () => true }));
+
+const { initialState } = await import("@/state/store");
+const { setTeamChats } = await import("@/state/team-chats");
+const { savedTeamSide, setTeamSide, teamSide, teamSideView } = await import("@/state/team-side");
+const { botShowsUnread } = await import("@/lib/bot-unread");
+const { forgetShownConversations, TeamAudienceLabel, TeamSideSwitch } = await import("./TeamSideSwitch");
+const { BotConversations, forgetConversationLines } = await import("./bot-panel/Conversations");
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const ADA = { teamId: "team-acme", member: true, opened: [] as string[], person: "[email protected]" };
+const now = Date.now();
+const task = (threadId: string, title: string, extra: Partial<Task> = {}): Task => ({ threadId, title, createdAt: now - 60_000, updatedAt: now - 30_000, ...extra });
+const MAIN = task("scout-main", "Shared chat", { sharedChat: true });
+const OWN = task("ada-own", "Pricing notes", { private: true });
+const bot = (overrides: Partial<Bot> = {}): Bot => ({
+ id: "scout", threadId: "scout-main", mainThreadId: "scout-main", name: "Scout", title: "", description: "", notifications: true, color: "green", unread: false,
+ modelSelection: { instanceId: "claude", model: "test" }, messages: [], tasks: [MAIN, OWN], ...overrides,
+} as Bot);
+const MINE = bot({ id: "mine", name: "MausBot", threadId: "mine-main", mainThreadId: "mine-main", defaultBot: { person: "[email protected]" } as never, tasks: [task("mine-main", "Inbox")] });
+const ROOM = { id: "room-1", name: "Relaunch", threadId: "room-thread", unread: false, members: [], messages: [] } as unknown as Group;
+const acme = (extra: Partial<AppState> = {}): AppState =>
+ ({ ...initialState, config: { team: { id: "team-acme", name: "Acme" } }, bots: [bot(), MINE], groups: [ROOM], selectedId: "scout", activeView: "chat", ...extra }) as unknown as AppState;
+
+let root: Root;
+let host: HTMLElement;
+const draw = (state: AppState, ...children: ReturnType<typeof createElement>[]) => {
+ fixture.state = state;
+ act(() => root.render(createElement("div", null, ...children)));
+};
+const sidebar = (state: AppState = acme(), compact = false) => draw(state, createElement(TeamSideSwitch, { compact }));
+const option = (side: "me" | "team") => host.querySelector<HTMLButtonElement>(`[data-team-side-option="${side}"]`);
+const checked = () => host.querySelector('[role="radio"][aria-checked="true"]')?.getAttribute("data-team-side-option");
+const settle = () => act(() => new Promise<void>((resolve) => setTimeout(resolve, 0)));
+
+const stored = new Map<string, string>();
+beforeEach(() => {
+ stored.clear();
+ vi.stubGlobal("localStorage", { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => { stored.set(key, value); } });
+ fixture.dispatch.mockReset();
+ fixture.calls.length = 0;
+ fixture.answer = null;
+ forgetShownConversations();
+ setTeamChats(ADA);
+ host = document.body.appendChild(document.createElement("div"));
+ root = createRoot(host);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ host.remove();
+ setTeamChats(null);
+ forgetConversationLines();
+ vi.unstubAllGlobals();
+});
+
+describe("the Just me / Team switch at the top of a team's sidebar", () => {
+ it("shows on a team's Cloud only", () => {
+ sidebar();
+ expect(host.querySelector('[role="radiogroup"]')?.getAttribute("aria-label")).toBe("Whose chats to show");
+ expect([...host.querySelectorAll('[role="radio"]')].map((radio) => radio.textContent)).toEqual(["Just me", "Team"]);
+ expect(checked(), "Just me until the person chooses").toBe("me");
+ setTeamChats(null);
+ sidebar({ ...initialState, bots: [bot()] } as AppState);
+ expect(host.innerHTML, "a personal install and My Cloud").toBe("<div></div>");
+ });
+
+ it("shows no switch, never a disabled one, when the person has one side only", () => {
+ sidebar(acme({ bots: [MINE], groups: [] }));
+ expect(host.querySelector('[role="radio"]')).toBeNull();
+ sidebar(acme());
+ expect(host.querySelector("[disabled]")).toBeNull();
+ });
+
+ it("choosing Team shows the shared side and opens this bot's shared chat, making nothing", async () => {
+ sidebar(acme({ bots: [bot({ threadId: "ada-own" }), MINE] }));
+ act(() => option("team")!.click());
+ await settle();
+ expect(checked()).toBe("team");
+ expect(teamSide()).toBe("team");
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "scout", threadId: "scout-main" });
+ expect(fixture.calls).toEqual([]);
+ });
+
+ it("choosing Just me opens the person's own chat with this bot, never the shared one", async () => {
+ setTeamSide("team");
+ sidebar();
+ act(() => option("me")!.click());
+ await settle();
+ expect(checked()).toBe("me");
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "scout", threadId: "ada-own" });
+ expect(fixture.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ threadId: "scout-main" }));
+ });
+
+ it("choosing Team from a private-only bot opens the first shared bot instead", async () => {
+ sidebar(acme({ selectedId: "mine" }));
+ act(() => option("team")!.click());
+ await settle();
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "scout", threadId: "scout-main" });
+ });
+
+ it("on a phone's bot list, which covers the conversation, changes the list and opens nothing", async () => {
+ draw(acme({ bots: [bot({ threadId: "ada-own" }), MINE] }), createElement(TeamSideSwitch, { compact: false, listOnly: true }));
+ act(() => option("team")!.click());
+ await settle();
+ expect(checked()).toBe("team");
+ expect(fixture.dispatch).not.toHaveBeenCalled();
+ expect(fixture.calls).toEqual([]);
+ });
+
+ it("never lands on a bot the person keeps out of their sidebar", async () => {
+ setTeamSide("team");
+ sidebar(acme({ selectedId: "room-1", bots: [{ ...MINE, sidebarHidden: true } as Bot, bot()] }));
+ act(() => option("me")!.click());
+ await settle();
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "scout", threadId: "ada-own" });
+ });
+
+ it("moves no conversation while another screen is up, and does nothing for the side already chosen", async () => {
+ sidebar(acme({ activeView: "routines" as never }));
+ act(() => option("me")!.click());
+ act(() => option("team")!.click());
+ await settle();
+ expect(teamSide()).toBe("team");
+ expect(fixture.dispatch).not.toHaveBeenCalled();
+ });
+
+ it("marks the side not shown when this person has something unread there, and never the side shown", () => {
+ sidebar(acme({ bots: [bot({ tasks: [{ ...MAIN, unread: true }, OWN] }), MINE] }));
+ expect(option("team")!.querySelector('[data-team-side-unread="team"]')?.getAttribute("aria-label")).toBe("Unread");
+ expect(option("me")!.querySelector("[data-team-side-unread]")).toBeNull();
+ setTeamSide("team");
+ sidebar(acme({ bots: [bot({ tasks: [{ ...MAIN, unread: true }, { ...OWN, unread: true }] }), MINE] }));
+ expect(option("me")!.querySelector('[data-team-side-unread="me"]')).not.toBeNull();
+ expect(option("team")!.querySelector("[data-team-side-unread]"), "the side shown").toBeNull();
+ sidebar(acme({ groups: [{ ...ROOM, unread: true }] }));
+ expect(host.querySelector("[data-team-side-unread]"), "Team is shown: its group chat's mark is in the list").toBeNull();
+ });
+
+ it("stays reachable when the sidebar is a rail of icons: two named buttons, the same marks", () => {
+ sidebar(acme({ bots: [bot({ tasks: [{ ...MAIN, unread: true }, OWN] }), MINE] }), true);
+ expect([...host.querySelectorAll('[role="radio"]')].map((radio) => radio.getAttribute("aria-label"))).toEqual(["Just me", "Team"]);
+ expect(option("team")!.querySelector("[data-team-side-unread]")).not.toBeNull();
+ expect(host.querySelector("[data-team-side-hint]")).toBeNull();
+ });
+
+ it("explains the switch in one line the first time it is seen on this device, and never again", () => {
+ sidebar();
+ expect(host.querySelector("[data-team-side-hint]")?.textContent).toBe("Just me is private, even from admins. Team is shared.");
+ act(() => root.unmount());
+ root = createRoot(host);
+ sidebar();
+ expect(host.querySelector("[data-team-side-hint]")).toBeNull();
+ });
+});
+
+describe("who can see it, by the message box", () => {
+ const label = () => host.querySelector("[data-team-audience]");
+ const box = (state: AppState, props: { bot?: Bot; group?: Group }) => draw(state, createElement(TeamSideSwitch, { compact: false }), createElement(TeamAudienceLabel, { key: props.group?.threadId ?? props.bot?.threadId, ...props }));
+
+ it("says Private on a private chat and Shared on a shared one, from the conversation itself", () => {
+ box(acme(), { bot: bot({ threadId: "ada-own" }) });
+ expect(label()?.getAttribute("data-team-audience")).toBe("me");
+ expect(label()?.textContent).toBe("Private · only you");
+ box(acme(), { bot: bot({ threadId: "scout-main" }) });
+ expect(label()?.textContent).toBe("Shared · everyone in Acme can see");
+ box(acme(), { bot: bot({ threadId: "scout-main", onlyPeopleAdded: true }) });
+ expect(label()?.textContent).toBe("Shared · only people added and admins can see");
+ box(acme(), { group: ROOM });
+ expect(label()?.textContent).toBe("Shared · everyone in this group chat can see");
+ box(acme(), { bot: MINE });
+ expect(label()?.textContent, "the person's own MausBot").toBe("Private · only you");
+ });
+
+ it("never follows the switch: with Just me chosen, a shared chat on screen still says Shared", () => {
+ setTeamSide("me");
+ forgetShownConversations();
+ draw(acme(), createElement(TeamAudienceLabel, { bot: bot({ threadId: "scout-main", switchingTo: "ada-own" }) }));
+ expect(label()?.textContent).toBe("Shared · everyone in Acme can see");
+ draw(acme(), createElement(TeamAudienceLabel, { bot: bot({ threadId: "never-heard-of", tasks: [MAIN] }) }));
+ expect(label()?.getAttribute("data-team-audience"), "a conversation this page knows nothing of is never called private").toBe("team");
+ });
+
+ it("shows nothing off a team", () => {
+ setTeamChats(null);
+ draw({ ...initialState, bots: [bot()] } as AppState, createElement(TeamAudienceLabel, { bot: bot() }));
+ expect(host.innerHTML).toBe("<div></div>");
+ });
+
+ it("moves the switch to a conversation the person asked for by name, from a notification or a link, and keeps that as their choice", () => {
+ box(acme({ revealThread: { threadId: "scout-main", nonce: 1 } }), { bot: bot({ threadId: "scout-main" }) });
+ expect(checked(), "the shared chat they opened").toBe("team");
+ expect(savedTeamSide()).toBe("team");
+ box(acme({ revealThread: { threadId: "ada-own", nonce: 2 } }), { bot: bot({ threadId: "ada-own" }) });
+ expect(checked()).toBe("me");
+ expect(savedTeamSide()).toBe("me");
+ expect(fixture.dispatch, "following moves the switch, never the conversation").not.toHaveBeenCalled();
+ });
+
+ it("moves the switch when the person goes to another bot or a group chat of the other side", () => {
+ box(acme(), { bot: bot({ threadId: "ada-own" }) });
+ expect(checked()).toBe("me");
+ box(acme({ selectedId: "room-1" }), { group: ROOM });
+ expect(checked()).toBe("team");
+ expect(savedTeamSide()).toBe("team");
+ box(acme({ selectedId: "mine" }), { bot: MINE });
+ expect(checked(), "their own MausBot, picked from search").toBe("me");
+ expect(savedTeamSide()).toBe("me");
+ expect(fixture.dispatch).not.toHaveBeenCalled();
+ });
+
+ it("moves the switch to Just me for a conversation the person just made beside a shared chat", () => {
+ setTeamSide("team");
+ const before = bot({ threadId: "scout-main", tasks: [MAIN] });
+ box(acme({ bots: [before, MINE] }), { bot: before });
+ const made = bot({ threadId: "ada-new", tasks: [MAIN, task("ada-new", "New chat", { private: true })] });
+ box(acme({ bots: [made, MINE] }), { bot: made });
+ expect(checked()).toBe("me");
+ expect(label()?.textContent).toBe("Private · only you");
+ expect(fixture.dispatch).not.toHaveBeenCalled();
+ });
+
+ it("after a reload with Just me chosen, goes to the person's own chat with the bot and never saves Team from what the page showed first", () => {
+ box(acme(), { bot: bot({ threadId: "scout-main" }) });
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "scout", threadId: "ada-own" });
+ expect(checked(), "the switch does not move for it").toBe("me");
+ expect(savedTeamSide()).toBe("me");
+ expect(stored.get("[email protected]")).not.toBe("team");
+ expect(label()?.textContent, "and until their chat is on screen the label says what is").toBe("Shared · everyone in Acme can see");
+ });
+
+ it("goes back to the person's own chat when the bot's own pick puts its shared chat on screen under them, and keeps their choice", () => {
+ box(acme({ revealThread: { threadId: "ada-own", nonce: 1 } }), { bot: bot({ threadId: "ada-own" }) });
+ expect(checked()).toBe("me");
+ fixture.dispatch.mockReset();
+ box(acme({ revealThread: { threadId: "ada-own", nonce: 1 } }), { bot: bot({ threadId: "scout-main" }) });
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "scout", threadId: "ada-own" });
+ expect(checked()).toBe("me");
+ expect(savedTeamSide(), "nobody chose Team").toBe("me");
+ expect(stored.get("[email protected]")).not.toBe("team");
+ });
+
+ it("does not take the shared chat the app opened as it started, before it knew this is a team, for the person's choice", () => {
+ setTeamChats(null);
+ const starting = { ...initialState, bots: [bot({ threadId: "ada-own", switchingTo: "scout-main" }), MINE], revealThread: { threadId: "scout-main", nonce: 7 } } as unknown as AppState;
+ draw(starting, createElement(TeamSideSwitch, { compact: false }));
+ setTeamChats(ADA);
+ box(acme({ revealThread: { threadId: "scout-main", nonce: 7 } }), { bot: bot({ threadId: "scout-main" }) });
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "scout", threadId: "ada-own" });
+ expect(checked()).toBe("me");
+ expect(savedTeamSide(), "nobody chose Team").toBe("me");
+ expect(stored.get("[email protected]")).not.toBe("team");
+ });
+
+ it("after a reload with Team chosen, goes to the bot's shared chat and keeps Team", () => {
+ setTeamSide("team");
+ box(acme(), { bot: bot({ threadId: "ada-own" }) });
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "scout", threadId: "scout-main" });
+ expect(teamSide()).toBe("team");
+ expect(savedTeamSide()).toBe("team");
+ expect(label()?.textContent, "and the label still says what is on screen").toBe("Private · only you");
+ });
+
+ it("waits while a conversation is on its way, and takes no notice of a message box that is not the chat on screen", () => {
+ box(acme(), { bot: bot({ threadId: "scout-main", switchingTo: "ada-own" }) });
+ expect(fixture.dispatch).not.toHaveBeenCalled();
+ expect(checked()).toBe("me");
+ box(acme({ selectedId: "mine" }), { bot: MINE });
+ box(acme(), { bot: bot({ threadId: "scout-main", switchingTo: "ada-own" }) });
+ expect(savedTeamSide(), "coming from another bot, its own chat still loading over the shared one").toBe("me");
+ expect(checked()).toBe("me");
+ setTeamSide("team");
+ box(acme({ selectedId: "scout" }), { bot: MINE });
+ expect(fixture.dispatch).not.toHaveBeenCalled();
+ expect(teamSide(), "an inbox's reply box beside the chat").toBe("team");
+ });
+
+ it("opens a new person's page on Just me, their own chat with the bot on screen made as a click on it makes it", async () => {
+ box(acme({ bots: [bot({ tasks: [MAIN] }), MINE] }), { bot: bot({ tasks: [MAIN] }) });
+ await settle();
+ expect(fixture.calls).toEqual([["/api/bots/scout/tasks", { method: "POST", body: "{}" }]]);
+ expect(teamSide(), "Just me until they choose Team").toBe("me");
+ });
+
+ it("goes to another bot of the chosen side when the one on screen is not listed there", () => {
+ setTeamSide("team");
+ box(acme({ selectedId: "mine" }), { bot: MINE });
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "scout", threadId: "scout-main" });
+ expect(savedTeamSide()).toBe("team");
+ });
+
+ it("with nowhere to go on the chosen side, shows the side on screen without keeping it", async () => {
+ const viewOnly = bot({ yourAccess: "view", tasks: [MAIN] });
+ box(acme({ bots: [viewOnly], groups: [] }), { bot: viewOnly });
+ await settle();
+ expect(fixture.dispatch).not.toHaveBeenCalled();
+ expect(fixture.calls).toEqual([]);
+ expect(teamSide()).toBe("team");
+ expect(savedTeamSide(), "nobody chose it").toBe("me");
+ });
+});
+
+describe("each side's rows carry only that side's marks", () => {
+ const rows = (bots: Bot[], side: "me" | "team") => teamSideView(bots, [ROOM], ADA, side).bots;
+
+ it("puts no unread mark on a Just me row for something unread in the bot's shared chat", () => {
+ const sharedUnread = bot({ unread: true, tasks: [{ ...MAIN, unread: true }] });
+ expect(botShowsUnread(sharedUnread), "the bot as the server sent it").toBe(true);
+ const [row] = rows([sharedUnread, MINE], "me");
+ expect(row!.id).toBe("scout");
+ expect(botShowsUnread(row!), "no private conversation there, so no mark").toBe(false);
+ expect(botShowsUnread(rows([sharedUnread, MINE], "team")[0]!)).toBe(true);
+ });
+
+ it("puts no unread mark on a Team row for something unread in a private chat, and none of a run on the other side", () => {
+ const privateUnread = bot({ unread: true, threadId: "ada-own", busy: true, tasks: [MAIN, { ...OWN, unread: true }] });
+ const team = rows([privateUnread, MINE], "team")[0]!;
+ expect(botShowsUnread(team)).toBe(false);
+ expect(team.busy, "her private run is not the shared chat's").toBe(false);
+ const me = rows([privateUnread, MINE], "me")[0]!;
+ expect(botShowsUnread(me)).toBe(true);
+ expect(me.busy).toBe(true);
+ });
+});
+
+describe("a bot's own list of conversations", () => {
+ const SECOND = task("ada-second", "Supplier call", { private: true });
+ const REPORT = task("report", "Weekly numbers", {});
+ const listed = (shown: Bot, state: AppState = acme()) => {
+ draw(state, createElement(BotConversations, { bot: shown }));
+ return [...host.querySelectorAll("[data-conversation]")].map((row) => row.getAttribute("data-conversation")).sort();
+ };
+
+ it("lists the person's private chats beside a private chat, with New conversation", () => {
+ expect(listed(bot({ threadId: "ada-own", tasks: [MAIN, OWN, SECOND, REPORT] }))).toEqual(["ada-own", "ada-second"]);
+ expect(host.querySelector("[data-conversations-new]")).not.toBeNull();
+ });
+
+ it("lists the shared conversations beside a shared chat, no private one, and offers no new conversation there", () => {
+ expect(listed(bot({ threadId: "scout-main", tasks: [MAIN, OWN, SECOND, REPORT] }))).toEqual(["report", "scout-main"]);
+ expect(host.querySelector("[data-conversations-new]"), "a new conversation is always private, so it is offered under Just me").toBeNull();
+ });
+
+ it("lists every conversation as before off a team", () => {
+ setTeamChats(null);
+ expect(listed(bot({ threadId: "scout-main", tasks: [task("scout-main", "First"), task("second", "Second")] }), initialState)).toEqual(["scout-main", "second"]);
+ expect(host.querySelector("[data-conversations-new]")).not.toBeNull();
+ });
+});
diff --git a/src/components/TeamSideSwitch.tsx b/src/components/TeamSideSwitch.tsx
new file mode 100644
index 0000000000..5869b74746
--- /dev/null
+++ b/src/components/TeamSideSwitch.tsx
@@ -0,0 +1,159 @@
+import { useEffect, useRef, useState } from "react";
+import { Lock, Users } from "lucide-react";
+
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import { useShowThreads } from "@/lib/thread-preferences";
+import { openBot, useStore, type AppState, type Bot, type Group } from "@/state/store";
+import { setTeamSide, showTeamSide, sideOfThread, teamSide, teamSideView, useTeamSide, type TeamSide } from "@/state/team-side";
+import { markTeamPrivateChatsLineSaid, sharedChatAudience } from "./TeamPrivateChatsLine";
+
+const SIDES = [{ side: "me", label: "teamSide.me", Icon: Lock }, { side: "team", label: "teamSide.team", Icon: Users }] as const;
+const HINT_KEY = (teamId: string) => `omb.team-side-hint.${teamId}`;
+const FOCUS = "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus";
+
+let openedAtStart: number | null = null;
+/** A conversation the app opened as it started, before it knew this is a team's Cloud, is not one the person asked for. */
+function noteStart(state: Pick<AppState, "revealThread">, team: unknown): void {
+ if (!team && state.revealThread) openedAtStart = state.revealThread.nonce;
+}
+
+/** What the sidebar lists on the side its switch shows; off a team, everything as ever. */
+export function useTeamSideLists(state: Pick<AppState, "bots" | "groups" | "config" | "revealThread">) {
+ const { team, side } = useTeamSide();
+ noteStart(state, team);
+ const onTeam = state.config?.team ? team : null;
+ const last = useRef<{ inputs: readonly unknown[]; view: ReturnType<typeof teamSideView<Bot, Group>> } | null>(null);
+ const inputs = [state.bots, state.groups, onTeam, side] as const;
+ if (!last.current || inputs.some((input, index) => input !== last.current!.inputs[index])) last.current = { inputs, view: teamSideView(state.bots, state.groups, onTeam, side) };
+ return last.current.view;
+}
+
+/** The side of the conversation a bot has on screen, on a team's Cloud; null anywhere else. */
+export function useConversationSide(bot: Bot): TeamSide | null {
+ const { state } = useStore();
+ const { team } = useTeamSide();
+ return state.config?.team && team ? sideOfThread(bot, bot.threadId) : null;
+}
+
+function hintDue(teamId: string): boolean {
+ try {
+ if (typeof localStorage === "undefined" || localStorage.getItem(HINT_KEY(teamId))) return false;
+ localStorage.setItem(HINT_KEY(teamId), String(Date.now()));
+ markTeamPrivateChatsLineSaid(teamId);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** The first time a person sees the switch on this device, one line says what its two sides are. It says who reads a
+ * private chat too, so the first private chat's own sentence is not said on top of it. */
+function FirstLine({ teamId }: { teamId: string }) {
+ const [due] = useState(() => hintDue(teamId));
+ if (!due) return null;
+ return <p role="status" data-team-side-hint className="px-1 pt-1.5 text-[12px] leading-4 text-ink-secondary">{t("teamSide.hint")}</p>;
+}
+
+/**
+ * At the top of a team's sidebar: "Just me", the person's private chats with each bot, and "Team", what everyone shares.
+ * The sidebar lists the chosen side. `compact`: the sidebar as a rail of icons. `listOnly`: the sidebar covers the
+ * conversation (a phone's bot list), so choosing a side changes the list and opens nothing.
+ */
+export function TeamSideSwitch({ compact, listOnly = false }: { compact: boolean; listOnly?: boolean }) {
+ const { state, dispatch } = useStore();
+ const showThreads = useShowThreads();
+ const { team, side } = useTeamSide();
+ const view = useTeamSideLists(state);
+ if (!team || !view.switchable) return null;
+ const choose = (next: TeamSide) => {
+ if (next === side) return;
+ setTeamSide(next, team);
+ if (listOnly || state.activeView !== "chat") return;
+ const there = teamSideView(state.bots, state.groups, team, next);
+ if (there.groups.some((group) => group.id === state.selectedId)) return;
+ const target = there.bots.find((bot) => bot.id === state.selectedId) ?? there.bots.find((bot) => !bot.sidebarHidden);
+ const bot = target && state.bots.find((candidate) => candidate.id === target.id);
+ if (bot) openBot(dispatch, bot, showThreads);
+ else if (there.groups[0]) dispatch({ type: "select", id: there.groups[0].id });
+ };
+ return (
+ <div data-team-side={side} className={compact ? "mx-auto mb-1" : "px-3 pb-1.5"}>
+ <div role="radiogroup" aria-label={t("teamSide.label")}
+ className={cn("flex rounded-full bg-ink/[0.06] p-0.5 ring-[0.5px] ring-inset ring-ink/[0.07]", compact && "flex-col rounded-[14px]")}>
+ {SIDES.map(({ side: option, label, Icon }) => {
+ const on = option === side;
+ const unread = !on && view.unread[option];
+ return (
+ <button key={option} type="button" role="radio" aria-checked={on} data-team-side-option={option} onClick={() => choose(option)}
+ aria-label={compact ? t(label) : undefined} title={compact ? t(label) : undefined}
+ className={cn("relative flex items-center justify-center gap-1.5 whitespace-nowrap rounded-full font-medium transition-colors", FOCUS,
+ compact ? "size-9 rounded-xl" : "h-8 min-w-0 flex-1 px-3 text-[13px]",
+ on ? "bg-composer text-ink shadow-[0_1px_2px_rgb(0_0_0/0.12)] ring-[0.5px] ring-ink/10" : "text-ink-secondary hover:text-ink")}>
+ {compact ? <Icon size={16} strokeWidth={1.75} aria-hidden="true" /> : t(label)}
+ {unread && <span role="img" data-team-side-unread={option} aria-label={t("task.unread")}
+ className={cn("size-1.5 rounded-full bg-accent", compact && "absolute right-1.5 top-1.5")} />}
+ </button>
+ );
+ })}
+ </div>
+ {!compact && <FirstLine key={team.teamId} teamId={team.teamId} />}
+ </div>
+ );
+}
+
+let known = new Set<string>();
+let lastChat: string | null = null;
+/** Tests only. */
+export function forgetShownConversations(): void {
+ known = new Set();
+ lastChat = null;
+ openedAtStart = null;
+}
+
+/**
+ * By the message box of every conversation on a team's Cloud: who can read what is typed there. It is read from the
+ * conversation itself, as the server sent it, never from the sidebar's switch.
+ *
+ * The switch follows a conversation the person asked for (another bot or group chat, a conversation this page opened by
+ * name, one they just made), and that is kept as their choice. A conversation of the other side that came on screen
+ * unasked (the first one a page shows, one the app opened as it started, or the bot's own pick changing under them) is
+ * never kept: the page goes back to the side they chose, to their own conversation with this bot when it is listed there.
+ */
+export function TeamAudienceLabel({ bot, group }: { bot?: Bot; group?: Group }) {
+ const { state, dispatch } = useStore();
+ const showThreads = useShowThreads();
+ const { team } = useTeamSide();
+ noteStart(state, team);
+ const teamName = state.config?.team?.name;
+ const side: TeamSide | null = !team || !teamName ? null : group ? "team" : bot ? sideOfThread(bot, bot.threadId) : null;
+ const shown = group?.threadId ?? bot?.threadId;
+ const person = team?.person;
+ useEffect(() => {
+ const chat = group?.id ?? bot?.id;
+ if (!team || !person || !side || !shown || !chat) return;
+ const justMade = known.size > 0 && !known.has(shown);
+ known = new Set([...state.bots.flatMap((each) => (each.tasks ?? []).map((task) => task.threadId)), ...state.groups.map((each) => each.threadId)]);
+ if (state.activeView !== "chat" || state.selectedId !== chat) return;
+ const movedHere = lastChat !== null && lastChat !== chat;
+ lastChat = chat;
+ const showing = teamSide(team);
+ if (showing === side || bot?.switchingTo) return;
+ const askedFor = state.revealThread?.threadId === shown && state.revealThread.nonce !== openedAtStart;
+ if (group || movedHere || askedFor || (justMade && side === "me")) { setTeamSide(side, team); return; }
+ const lists = teamSideView(state.bots, state.groups, team, showing);
+ const there = lists.switchable ? lists.bots : [];
+ const target = there.find((candidate) => candidate.id === chat) ?? there.find((candidate) => !candidate.sidebarHidden);
+ const landing = target && state.bots.find((candidate) => candidate.id === target.id);
+ if (landing) openBot(dispatch, landing, showThreads);
+ else showTeamSide(side, team);
+ }, [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);
+ 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>
+ </div>
+ );
+}
diff --git a/src/components/bot-panel/Conversations.tsx b/src/components/bot-panel/Conversations.tsx
index 555568c07f..a2eb9cf4b2 100644
--- a/src/components/bot-panel/Conversations.tsx
+++ b/src/components/bot-panel/Conversations.tsx
@@ -9,6 +9,8 @@ import { api, currentTaskBot, openBotThread, useStore, visibleMessages, type Bot
import { lastLine } from "../sidebar-preview";
import { isArchived, orderedThreadList, SidebarThreadRow, stampClock, threadRecency, threadRowActions, useRelativeNow } from "../SidebarThreadRow";
import { filterTasks } from "../TaskPicker";
+import { useConversationSide } from "../TeamSideSwitch";
+import { tasksOfSide } from "@/state/team-side";
import { CardLabel, panelActionCls } from "./rows";
export const CONVERSATIONS_SHOWN = 3;
@@ -67,7 +69,9 @@ export function BotConversations({ bot }: { bot: Bot }) {
return { onRename, onRegenerateTitle, onDelete, onMove, onPin, onArchive };
}, [bot.id, dispatch, generatedTitles]);
- const threads = (bot.tasks ?? [{ threadId: bot.threadId, title: t("task.newShort"), createdAt: 0 }])
+ const side = useConversationSide(bot);
+ const tasks = bot.tasks ?? [{ threadId: bot.threadId, title: t("task.newShort"), createdAt: 0 }];
+ const threads = (side ? tasksOfSide({ ...bot, tasks }, side) : tasks)
.filter((task) => !task.routineRunId)
.map((task) => {
const thread = currentTaskBot(bot, task.threadId);
@@ -135,7 +139,7 @@ export function BotConversations({ bot }: { bot: Bot }) {
</button>
)}>{t("botPanel.conversations.title")}</CardLabel>
<div className={cn("flex items-center gap-2", listed && "mb-2")}>
- {bot.yourAccess !== "view" && (
+ {bot.yourAccess !== "view" && side !== "team" && (
<button
type="button"
data-conversations-new
diff --git a/src/locales/de.json b/src/locales/de.json
index 70ba56629e..cc9ff519d3 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -833,7 +833,6 @@
"relay.reply": "{name} hat geantwortet",
"relay.assistant": "Der Assistent von {name} hat geantwortet",
"sidebar.people.title": "Personen",
- "sidebar.people.you": "{name} (du)",
"sidebar.people.yourInbox": "Dein Posteingang: alles, was an dich geht",
"sidebar.people.yourInboxWaiting": "Dein Posteingang: wartet auf dich, {count}",
"sidebar.people.invite": "Jemanden einladen",
diff --git a/src/locales/en.json b/src/locales/en.json
index d1ac4dc176..7be61ea591 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -2255,7 +2255,6 @@
"relay.reply": "{name} replied",
"relay.assistant": "{name}'s assistant answered",
"sidebar.people.title": "People",
- "sidebar.people.you": "{name} (you)",
"sidebar.people.yourInbox": "Your inbox: everything sent to you",
"sidebar.people.yourInboxWaiting": "Your inbox: waiting on you, {count}",
"sidebar.people.invite": "Invite someone",
@@ -7572,6 +7571,11 @@
"liveConnection.retry": "Try again",
"liveConnection.offline": "You're offline. New replies show up once you're back online.",
"team.ownHelperHeader": "Own helper · other members can't see it",
+ "teamSide.label": "Whose chats to show",
+ "teamSide.me": "Just me",
+ "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",
"chat.page.usage": "{pages} of {limit} pages",
"chat.page.copyLink": "Copy link",
"chat.page.copied": "Copied",
diff --git a/src/locales/es.json b/src/locales/es.json
index 5a7f92498c..0241920dd5 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -1717,7 +1717,6 @@
"relay.reply": "{name} respondió",
"relay.assistant": "El asistente de {name} respondió",
"sidebar.people.title": "Personas",
- "sidebar.people.you": "{name} (tú)",
"sidebar.people.yourInbox": "Tu bandeja de entrada: todo lo que te envían",
"sidebar.people.yourInboxWaiting": "Tu bandeja de entrada: te esperan, {count}",
"sidebar.people.invite": "Invitar a alguien",
diff --git a/src/locales/fr.json b/src/locales/fr.json
index 5b6d042c1b..3c002bac5e 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -694,7 +694,6 @@
"relay.reply": "{name} a répondu",
"relay.assistant": "L'assistant de {name} a répondu",
"sidebar.people.title": "Personnes",
- "sidebar.people.you": "{name} (vous)",
"sidebar.people.yourInbox": "Votre boîte de réception : tout ce qu'on vous envoie",
"sidebar.people.yourInboxWaiting": "Votre boîte de réception : en attente de vous, {count}",
"sidebar.people.invite": "Inviter quelqu'un",
diff --git a/src/locales/hi.json b/src/locales/hi.json
index aa234b2fe9..30e1bf1aeb 100644
--- a/src/locales/hi.json
+++ b/src/locales/hi.json
@@ -694,7 +694,6 @@
"relay.reply": "{name} ने जवाब दिया",
"relay.assistant": "{name} के सहायक ने जवाब दिया",
"sidebar.people.title": "लोग",
- "sidebar.people.you": "{name} (आप)",
"sidebar.people.yourInbox": "आपका इनबॉक्स: आपको भेजा गया सब कुछ",
"sidebar.people.yourInboxWaiting": "आपका इनबॉक्स: आपके इंतज़ार में, {count}",
"sidebar.people.invite": "किसी को आमंत्रित करें",
diff --git a/src/locales/it.json b/src/locales/it.json
index fa55941e32..eda9748b6e 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -6329,7 +6329,6 @@
"relay.reply": "{name} ha risposto",
"relay.assistant": "L'assistente di {name} ha risposto",
"sidebar.people.title": "Persone",
- "sidebar.people.you": "{name} (tu)",
"sidebar.people.yourInbox": "La tua posta in arrivo: tutto ciò che ti viene inviato",
"sidebar.people.yourInboxWaiting": "La tua posta in arrivo: in attesa di te, {count}",
"sidebar.people.invite": "Invita qualcuno",
diff --git a/src/locales/ja.json b/src/locales/ja.json
index dd4492142a..661125abe8 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -2072,7 +2072,6 @@
"relay.reply": "{name}さんが返信しました",
"relay.assistant": "{name}さんのアシスタントが答えました",
"sidebar.people.title": "メンバー",
- "sidebar.people.you": "{name}(あなた)",
"sidebar.people.yourInbox": "あなたの受信トレイ:あなた宛てのものがすべて届きます",
"sidebar.people.yourInboxWaiting": "あなたの受信トレイ:あなたの対応待ち、{count} 件",
"sidebar.people.invite": "メンバーを招待",
diff --git a/src/locales/ko.json b/src/locales/ko.json
index cffe84d3f0..20803cd078 100644
--- a/src/locales/ko.json
+++ b/src/locales/ko.json
@@ -1979,7 +1979,6 @@
"relay.reply": "{name}이(가) 답했어요",
"relay.assistant": "{name}의 비서가 답했어요",
"sidebar.people.title": "사람",
- "sidebar.people.you": "{name}(나)",
"sidebar.people.yourInbox": "받은편지함: 나에게 온 모든 것",
"sidebar.people.yourInboxWaiting": "받은편지함: 나를 기다리는 것 {count}개",
"sidebar.people.invite": "다른 사람 초대",
diff --git a/src/locales/pl.json b/src/locales/pl.json
index ee9e0f23dc..7509389b56 100644
--- a/src/locales/pl.json
+++ b/src/locales/pl.json
@@ -6467,7 +6467,6 @@
"relay.reply": "Odpowiedź od: {name}",
"relay.assistant": "Asystent odpowiedział za: {name}",
"sidebar.people.title": "Osoby",
- "sidebar.people.you": "{name} (ty)",
"sidebar.people.yourInbox": "Twoja skrzynka: wszystko, co do ciebie trafia",
"sidebar.people.yourInboxWaiting": "Twoja skrzynka: czeka na ciebie, {count}",
"sidebar.people.invite": "Zaproś kogoś",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index e2e309cbdf..b0f7bc247d 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -2126,7 +2126,6 @@
"relay.reply": "{name} respondeu",
"relay.assistant": "O assistente de {name} respondeu",
"sidebar.people.title": "Pessoas",
- "sidebar.people.you": "{name} (você)",
"sidebar.people.yourInbox": "Sua caixa de entrada: tudo o que enviaram a você",
"sidebar.people.yourInboxWaiting": "Sua caixa de entrada: aguardando você, {count}",
"sidebar.people.invite": "Convidar alguém",
@@ -7382,6 +7381,11 @@
"liveConnection.retry": "Tentar novamente",
"liveConnection.offline": "Você está offline. As novas respostas aparecem quando a conexão voltar.",
"team.ownHelperHeader": "Ajudante pessoal · os outros membros não podem ver",
+ "teamSide.label": "Quais conversas mostrar",
+ "teamSide.me": "Só eu",
+ "teamSide.team": "Equipe",
+ "teamSide.hint": "Só eu é privado, até para os administradores. Equipe é compartilhado.",
+ "teamSide.groupAudience": "Compartilhado · todos neste chat em grupo podem ver",
"chat.page.usage": "Páginas: {pages} de {limit}",
"chat.page.copyLink": "Copiar link",
"chat.page.copied": "Copiado",
diff --git a/src/locales/ru.json b/src/locales/ru.json
index 08856d5453..f9edcb25e2 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -1895,7 +1895,6 @@
"relay.reply": "{name} ответил(а)",
"relay.assistant": "Ассистент {name} ответил",
"sidebar.people.title": "Люди",
- "sidebar.people.you": "{name} (вы)",
"sidebar.people.yourInbox": "Ваши входящие: всё, что вам отправили",
"sidebar.people.yourInboxWaiting": "Ваши входящие: ждут вас, {count}",
"sidebar.people.invite": "Пригласить кого-нибудь",
diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.json
index 89bcbf783a..714227142e 100644
--- a/src/locales/source-hashes.json
+++ b/src/locales/source-hashes.json
@@ -2204,7 +2204,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.mention": "3367c9dc49343c4480f793b1b609c524c60b849a25739c016b7f3ed94f97892e",
"engineSetup.usingAppCopy": "064103aafeac9f412241f69da80a107b4cb7725c3d0c1b2806f6b6b766afe93c",
@@ -8559,7 +8558,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.mention": "3367c9dc49343c4480f793b1b609c524c60b849a25739c016b7f3ed94f97892e",
"engineSetup.usingAppCopy": "064103aafeac9f412241f69da80a107b4cb7725c3d0c1b2806f6b6b766afe93c",
@@ -11736,7 +11734,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.mention": "3367c9dc49343c4480f793b1b609c524c60b849a25739c016b7f3ed94f97892e",
"engineSetup.usingAppCopy": "064103aafeac9f412241f69da80a107b4cb7725c3d0c1b2806f6b6b766afe93c",
@@ -15052,7 +15049,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.mention": "3367c9dc49343c4480f793b1b609c524c60b849a25739c016b7f3ed94f97892e",
"engineSetup.usingAppCopy": "064103aafeac9f412241f69da80a107b4cb7725c3d0c1b2806f6b6b766afe93c",
@@ -21991,7 +21987,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.mention": "3367c9dc49343c4480f793b1b609c524c60b849a25739c016b7f3ed94f97892e",
"engineSetup.usingAppCopy": "064103aafeac9f412241f69da80a107b4cb7725c3d0c1b2806f6b6b766afe93c",
@@ -25808,7 +25803,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.yourInboxWaiting": "6b2cd5cd106def71e8e8084f76a94bec70177c189d697a5c16aacf43336019c8",
"sidebar.people.invite": "9b7639e8de286c000db642d9b2dc5407d334f79ee308d25fc48c93f343d80bed",
@@ -36867,7 +36861,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.mention": "3367c9dc49343c4480f793b1b609c524c60b849a25739c016b7f3ed94f97892e",
"engineSetup.usingAppCopy": "064103aafeac9f412241f69da80a107b4cb7725c3d0c1b2806f6b6b766afe93c",
@@ -45515,7 +45508,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.mention": "3367c9dc49343c4480f793b1b609c524c60b849a25739c016b7f3ed94f97892e",
"engineSetup.usingAppCopy": "064103aafeac9f412241f69da80a107b4cb7725c3d0c1b2806f6b6b766afe93c",
@@ -53952,7 +53944,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.mention": "3367c9dc49343c4480f793b1b609c524c60b849a25739c016b7f3ed94f97892e",
"engineSetup.usingAppCopy": "064103aafeac9f412241f69da80a107b4cb7725c3d0c1b2806f6b6b766afe93c",
@@ -59542,7 +59533,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.mention": "3367c9dc49343c4480f793b1b609c524c60b849a25739c016b7f3ed94f97892e",
"engineSetup.usingAppCopy": "064103aafeac9f412241f69da80a107b4cb7725c3d0c1b2806f6b6b766afe93c",
@@ -65130,7 +65120,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.mention": "3367c9dc49343c4480f793b1b609c524c60b849a25739c016b7f3ed94f97892e",
"engineSetup.usingAppCopy": "064103aafeac9f412241f69da80a107b4cb7725c3d0c1b2806f6b6b766afe93c",
@@ -71984,7 +71973,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.mention": "3367c9dc49343c4480f793b1b609c524c60b849a25739c016b7f3ed94f97892e",
"engineSetup.usingAppCopy": "064103aafeac9f412241f69da80a107b4cb7725c3d0c1b2806f6b6b766afe93c",
@@ -78899,7 +78887,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.mention": "3367c9dc49343c4480f793b1b609c524c60b849a25739c016b7f3ed94f97892e",
"cloudBuy.includes": "205cae13e4489a3790f4bbc2ada822481a8cb40987fb9c8df6f643f51e4bad78",
@@ -85608,7 +85595,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.mention": "3367c9dc49343c4480f793b1b609c524c60b849a25739c016b7f3ed94f97892e",
"cloudBuy.includes": "205cae13e4489a3790f4bbc2ada822481a8cb40987fb9c8df6f643f51e4bad78",
@@ -88235,7 +88221,6 @@
"relay.reply": "26aea5bcd5ba0f8fde124f7cb34754d9509a547b6c0af3dd9074c7d3a49c42fd",
"relay.assistant": "32503098cc39a9176f1ca8940d3d2247d8fe5ac9418ceb39ab1481643c4fc3a8",
"sidebar.people.title": "7db20897053bb2780b9b706e5505227b005de80c236e4a4836aab37a3a7bb298",
- "sidebar.people.you": "f6bbb21a1ccae104ddb3f8fdf79e0170b54269a45f783d551d8115df00e2f422",
"sidebar.people.yourInbox": "d268735e5d62ca61384d42257df311283c9156053028aca926b575fc275a18f9",
"sidebar.people.yourInboxWaiting": "6b2cd5cd106def71e8e8084f76a94bec70177c189d697a5c16aacf43336019c8",
"inbox.panel.title": "94835ea2fcf775cd77cb9c9cee01b5cbd9bc515467aab1215f48a5ade9ca5274",
diff --git a/src/locales/tr.json b/src/locales/tr.json
index cbcb899afd..197676fa8c 100644
--- a/src/locales/tr.json
+++ b/src/locales/tr.json
@@ -1421,7 +1421,6 @@
"relay.reply": "{name} yanıtladı",
"relay.assistant": "{name} asistanı yanıtladı",
"sidebar.people.title": "Kişiler",
- "sidebar.people.you": "{name} (sen)",
"sidebar.people.yourInbox": "Gelen kutun: sana gönderilen her şey",
"sidebar.people.yourInboxWaiting": "Gelen kutun: seni bekliyor, {count}",
"sidebar.people.invite": "Birini davet et",
diff --git a/src/locales/uk.json b/src/locales/uk.json
index a9cdee052f..59bcef4e4f 100644
--- a/src/locales/uk.json
+++ b/src/locales/uk.json
@@ -812,7 +812,6 @@
"relay.reply": "Відповідь від: {name}",
"relay.assistant": "Асистент відповів за: {name}",
"sidebar.people.title": "Люди",
- "sidebar.people.you": "{name} (ви)",
"sidebar.people.yourInbox": "Ваші вхідні: усе, що вам надіслали",
"sidebar.people.yourInboxWaiting": "Ваші вхідні: чекає на вас, {count}",
"sidebar.people.invite": "Запросити когось",
diff --git a/src/locales/vi.json b/src/locales/vi.json
index 0f8bdfafc2..1563691c44 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -1421,7 +1421,6 @@
"relay.reply": "{name} đã trả lời",
"relay.assistant": "Trợ lý của {name} đã trả lời",
"sidebar.people.title": "Mọi người",
- "sidebar.people.you": "{name} (bạn)",
"sidebar.people.yourInbox": "Hộp thư của bạn: mọi thứ gửi cho bạn",
"sidebar.people.yourInboxWaiting": "Hộp thư của bạn: đang chờ bạn, {count}",
"sidebar.people.invite": "Mời ai đó",
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index 724b840612..3c079f99a9 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -2212,7 +2212,6 @@
"relay.reply": "{name} 回覆了",
"relay.assistant": "{name} 的助理回答了",
"sidebar.people.title": "成員",
- "sidebar.people.you": "{name}(你)",
"sidebar.people.yourInbox": "你的收件匣:寄給你的一切都在這裡",
"sidebar.people.yourInboxWaiting": "你的收件匣:待你處理,{count}",
"sidebar.people.invite": "邀請他人",
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 18e39b9ee0..95e74bf890 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -2104,7 +2104,6 @@
"relay.reply": "{name} 回复了",
"relay.assistant": "{name} 的助理回答了",
"sidebar.people.title": "成员",
- "sidebar.people.you": "{name}(你)",
"sidebar.people.yourInbox": "你的收件箱:发给你的一切都在这里",
"sidebar.people.yourInboxWaiting": "你的收件箱:待你处理,{count}",
"sidebar.people.invite": "邀请他人",
diff --git a/src/state/team-chats.test.ts b/src/state/team-chats.test.ts
index eea576b05c..bff5ad1086 100644
--- a/src/state/team-chats.test.ts
+++ b/src/state/team-chats.test.ts
@@ -47,7 +47,7 @@ it("opens the person's inbox, their chat with their Chief where everything for t
});
it("with none yet, a click makes one through the server's new-conversation route, opens it and keeps it; a second click while it is made makes no second", async () => {
- setTeamChats({ teamId: "team-gamma", member: false });
+ setTeamChats({ teamId: "team-gamma", member: false, opened: [] });
const dispatch = vi.fn();
server.answer = { bot: { id: "scout", threadId: "ben-chat" }, task: { threadId: "ben-chat", private: true } };
const bot = scout([{ threadId: "ada-chat", private: true, createdAt: 5 }]);
@@ -64,7 +64,7 @@ it("with none yet, a click makes one through the server's new-conversation route
});
it("a Member's existing conversation opens with no request; a refusal shows as an error; off a team the bot opens as it always has", async () => {
- setTeamChats(MEMBER);
+ setTeamChats({ ...MEMBER, opened: [] });
const dispatch = vi.fn();
openBot(dispatch, scout([{ threadId: "ada-chat", private: true, createdAt: 5 }]), true);
expect(dispatch.mock.calls.map(([action]) => action)).toEqual([{ type: "select", id: "scout" }, { type: "switchTask", botId: "scout", threadId: "ada-chat" }]);
@@ -82,7 +82,7 @@ it("a Member's existing conversation opens with no request; a refusal shows as a
});
it("opens the main chat of a bot this person can only view, without trying to start a conversation of their own", async () => {
- setTeamChats(MEMBER);
+ setTeamChats({ ...MEMBER, opened: [] });
const dispatch = vi.fn();
const viewOnly = { ...scout([]), yourAccess: "view" };
expect(openOwnTeamChat(dispatch, viewOnly, () => {})).toBe(false);
@@ -92,3 +92,18 @@ it("opens the main chat of a bot this person can only view, without trying to st
expect(openOwnTeamChat(dispatch, { ...scout([{ threadId: "bob-own", private: true, createdAt: 5 }]), yourAccess: "view" }, opened)).toBe(true);
expect(opened).toHaveBeenCalledWith("bob-own");
});
+
+it("makes nothing before the session has said which conversations are theirs: the click waits, then opens their own chat", async () => {
+ setTeamChats({ teamId: "team-acme", member: false });
+ const dispatch = vi.fn();
+ const bot = scout([{ threadId: "ada-chat", private: true, createdAt: 5 }, { threadId: "ben-chat", private: true, createdAt: 6 }]);
+ openBot(dispatch, bot, false);
+ await settle();
+ expect(server.calls, "an Admin's chat is not known from a member's yet: a second one would be made").toEqual([]);
+ expect(dispatch).not.toHaveBeenCalled();
+ setTeamChats({ teamId: "team-acme", member: false, opened: ["ben-chat"] });
+ expect(dispatch.mock.calls.map(([action]) => action)).toEqual([{ type: "switchTask", botId: "scout", threadId: "ben-chat" }]);
+ setTeamChats({ teamId: "team-acme", member: false, opened: ["ben-chat", "later"] });
+ expect(dispatch, "once").toHaveBeenCalledTimes(1);
+ expect(server.calls).toEqual([]);
+});
diff --git a/src/state/team-chats.ts b/src/state/team-chats.ts
index 0aebd27e62..bf4f4f80bd 100644
--- a/src/state/team-chats.ts
+++ b/src/state/team-chats.ts
@@ -11,16 +11,22 @@ import { api } from "./api";
import type { Action, Bot } from "./store";
import { readSessionState } from "@/lib/session";
-/** The team on screen, whether this person is a Member (no admin scope), and the conversations the server says they
- * opened: null anywhere but a team's Cloud. */
-export type TeamChats = { teamId: string; member: boolean; opened?: readonly string[] };
+/** The team on screen, whether this person is a Member (no admin scope), the conversations the server says they opened
+ * and the address they signed in with: null anywhere but a team's Cloud. */
+export type TeamChats = { teamId: string; member: boolean; opened?: readonly string[]; person?: string };
type TaskLike = { threadId: string; createdAt?: number; updatedAt?: number; private?: unknown; inbox?: unknown; routineRunId?: unknown; openedBy?: unknown; archivedAt?: unknown; closedBy?: unknown };
type BotLike = { id: string; tasks?: TaskLike[]; yourAccess?: string };
let current: TeamChats | null = null;
+const watchers = new Set<() => void>();
+/** Hears every change of the team on screen, the person signed in and the conversations known to be theirs. */
+export function onTeamChats(watcher: () => void): void {
+ watchers.add(watcher);
+}
export function setTeamChats(next: TeamChats | null) {
current = next;
+ for (const watcher of watchers) watcher();
}
export function teamChats(): TeamChats | null {
return current;
@@ -28,7 +34,7 @@ export function teamChats(): TeamChats | null {
/** A conversation this page just made: the person's own, which the session it read before does not list yet. */
export function rememberOwnChat(teamId: string, threadId: string) {
- if (current?.teamId === teamId && !current.opened?.includes(threadId)) current = { ...current, opened: [...(current.opened ?? []), threadId] };
+ if (current?.teamId === teamId && !current.opened?.includes(threadId)) setTeamChats({ ...current, opened: [...(current.opened ?? []), threadId] });
}
/** A conversation this person started on a team (the session's list, and one this page just made before its task arrives):
@@ -50,12 +56,22 @@ export function ownChatOf(bot: BotLike, team: TeamChats): string | null {
}
const making = new Set<string>();
-/** On a team: opens the person's own conversation with `bot` through `open`, or makes it and opens it. False anywhere
- * else, and for a bot this person can only view and has no conversation of their own with, so the caller opens the bot
+/** On a team: opens the person's own conversation with `bot` through `open`, or makes it and opens it, once the session
+ * has said which conversations are theirs: before that their own chat is not known from anyone's, and a second one would
+ * be made. False anywhere else, and for a bot this person can only view and has no conversation of their own with, so the caller opens the bot
* as it always has: its main chat. */
export function openOwnTeamChat(dispatch: (action: Action) => void, bot: BotLike, open: (threadId: string) => void): boolean {
const team = current;
if (!team) return false;
+ if (team.opened === undefined) {
+ const whenRead = () => {
+ if (current && current.opened === undefined) return;
+ watchers.delete(whenRead);
+ if (current) openOwnTeamChat(dispatch, bot, open);
+ };
+ watchers.add(whenRead);
+ return true;
+ }
const own = ownChatOf(bot, team);
if (own) { open(own); return true; }
if (bot.yourAccess === "view") return false;
@@ -79,12 +95,15 @@ export function teamOfConfig(config: unknown): { id: string } | null {
return typeof team?.id === "string" && team.id ? { id: team.id } : null;
}
+const chatsOf = (teamId: string, session: { scopes: string[]; openedThreads?: string[]; email?: string }): TeamChats =>
+ ({ teamId, member: !session.scopes.includes("admin"), opened: session.openedThreads ?? [], ...(session.email?.trim() ? { person: session.email.trim().toLowerCase() } : {}) });
+
/** The person's role may have changed: read the session again. */
export function rereadTeamChats(): void {
const teamId = current?.teamId;
if (!teamId) return;
void readSessionState().then((session) => {
- if (current?.teamId === teamId && session.kind === "session") setTeamChats({ teamId, member: !session.scopes.includes("admin"), opened: session.openedThreads ?? [] });
+ if (current?.teamId === teamId && session.kind === "session") setTeamChats(chatsOf(teamId, session));
}).catch(() => {});
}
@@ -97,8 +116,8 @@ export function useTeamChats(config: unknown) {
setTeamChats({ teamId, member: false });
let alive = true;
void readSessionState().then((session) => {
- if (alive && session.kind === "session") setTeamChats({ teamId, member: !session.scopes.includes("admin"), opened: session.openedThreads ?? [] });
- }).catch(() => {});
+ if (alive) setTeamChats(session.kind === "session" ? chatsOf(teamId, session) : { teamId, member: false, opened: [] });
+ }).catch(() => { if (alive) setTeamChats({ teamId, member: false, opened: [] }); });
return () => { alive = false; };
}, [teamId]);
}
diff --git a/src/state/team-side.test.ts b/src/state/team-side.test.ts
new file mode 100644
index 0000000000..2d9e70e309
--- /dev/null
+++ b/src/state/team-side.test.ts
@@ -0,0 +1,241 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const server = vi.hoisted(() => ({ calls: [] as Array<[string, RequestInit | undefined]>, answer: null as unknown }));
+vi.mock("./api", () => ({
+ api: vi.fn(async (path: string, init?: RequestInit) => {
+ server.calls.push([path, init]);
+ return server.answer;
+ }),
+}));
+
+import { openBot } from "./thread-navigation";
+import { rememberOwnChat, setTeamChats, type TeamChats } from "./team-chats";
+import { botOnSide, savedTeamSide, setTeamSide, showTeamSide, sideOfThread, tasksOfSide, teamSide, teamSideView, teamThreadOf } from "./team-side";
+
+const ADA: TeamChats = { teamId: "team-acme", member: true, opened: [], person: "[email protected]" };
+const BEN: TeamChats = { ...ADA, person: "[email protected]" };
+
+const MAIN = { threadId: "scout-main", title: "Shared chat", createdAt: 1, sharedChat: true as const };
+type Extra = Record<string, unknown>;
+type TestTask = { threadId: string; private?: unknown; sharedChat?: unknown; unread?: boolean };
+type TestBot = { id: string; threadId: string; mainThreadId: string; tasks: TestTask[]; messages: unknown[]; yourAccess?: string; hidden?: boolean; defaultBot?: { person: string } };
+const scout = (tasks: Extra[] = [], extra: Extra = {}) =>
+ ({ id: "scout", threadId: "scout-main", mainThreadId: "scout-main", tasks: [MAIN, ...tasks], messages: [{ id: "m1" }], ...extra }) as unknown as TestBot;
+const mausbot = (extra: Extra = {}) =>
+ ({ id: "mine", threadId: "mine-main", mainThreadId: "mine-main", defaultBot: { person: "[email protected]" }, tasks: [{ threadId: "mine-main", createdAt: 1 }, { threadId: "mine-2", createdAt: 2 }], messages: [], ...extra }) as unknown as TestBot;
+const room = (extra: Extra = {}) => ({ id: "room-1", unread: false, ...extra });
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+const ids = (list: Array<{ id: string }>) => list.map((item) => item.id);
+
+const stored = new Map<string, string>();
+const localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => { stored.set(key, value); } };
+beforeEach(() => { vi.stubGlobal("localStorage", localStorage); stored.clear(); server.calls.length = 0; server.answer = null; });
+afterEach(() => { setTeamChats(null); vi.unstubAllGlobals(); });
+
+describe("the side of a conversation is the server's answer", () => {
+ it("is Just me only for a conversation the server marked private, one this page made through the private route, or the person's own MausBot", () => {
+ setTeamChats(ADA);
+ const bot = scout([{ threadId: "ada-own", private: true, createdAt: 2 }, { threadId: "report", createdAt: 3 }]);
+ expect(sideOfThread(bot, "ada-own")).toBe("me");
+ expect(sideOfThread(bot, "scout-main")).toBe("team");
+ expect(sideOfThread(bot, "report"), "a shared report").toBe("team");
+ expect(sideOfThread(bot, "never-heard-of"), "unknown is never called private").toBe("team");
+ rememberOwnChat("team-acme", "just-made");
+ expect(sideOfThread(bot, "just-made"), "made a moment ago, its task not here yet").toBe("me");
+ expect(sideOfThread(mausbot(), "mine-main"), "nobody else is ever sent it").toBe("me");
+ });
+
+ it("never calls the shared chat Just me, even if the session lists it among the conversations this person opened", () => {
+ setTeamChats({ ...ADA, opened: ["scout-main"] });
+ expect(sideOfThread(scout(), "scout-main")).toBe("team");
+ expect(teamThreadOf({ tasks: [{ threadId: "t1", sharedChat: true, private: true }] }), "a private chat is never the team thread").toBeNull();
+ expect(teamThreadOf(mausbot()), "a person's own MausBot has none").toBeNull();
+ });
+
+ 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 }]);
+ for (const shown of ["me", "team"] as const) {
+ setTeamSide(shown);
+ expect(sideOfThread(bot, "ada-own")).toBe("me");
+ expect(sideOfThread(bot, "scout-main")).toBe("team");
+ }
+ });
+
+ it("holds for every mix of conversations: Just me is exactly the private ones, Team exactly the rest", () => {
+ setTeamChats(ADA);
+ const kinds = [
+ { private: true }, { private: true, routineRunId: "r1" }, { private: true, openedBy: { botId: "x" } }, { private: true, archivedAt: 5 },
+ {}, { routineRunId: "r2" }, { openedBy: { botId: "x" } }, { private: false }, { private: "yes" }, { private: 1 },
+ ];
+ const tasks = kinds.map((kind, index) => ({ threadId: `t${index}`, createdAt: index, ...kind }));
+ const bot = scout(tasks);
+ const me = tasksOfSide(bot, "me"), team = tasksOfSide(bot, "team");
+ expect(me.length).toBe(4);
+ expect(me.every((task) => task.private === true), "no shared conversation under Just me").toBe(true);
+ expect(team.some((task) => task.private === true), "no private conversation under Team").toBe(false);
+ expect(me.length + team.length).toBe(tasks.length + 1);
+ });
+});
+
+describe("what each side of the sidebar lists", () => {
+ it("lists everything, untouched, off a team", () => {
+ const bots = [scout()], groups = [room()];
+ const view = teamSideView(bots, groups, null, "team");
+ expect(view.switchable).toBe(false);
+ expect(view.bots).toBe(bots);
+ expect(view.groups).toBe(groups);
+ });
+
+ it("lists under Just me the bots the person can chat with privately, with their private chats only, and no group chat", () => {
+ const view = teamSideView([scout([{ threadId: "ada-own", private: true, createdAt: 2 }]), mausbot()], [room()], ADA, "me");
+ expect(view.switchable).toBe(true);
+ expect(ids(view.bots)).toEqual(["scout", "mine"]);
+ expect(view.bots[0]!.tasks.map((task) => task.threadId)).toEqual(["ada-own"]);
+ expect(view.bots[1]!.tasks.length, "their own MausBot keeps all its chats").toBe(2);
+ expect(view.groups).toEqual([]);
+ });
+
+ it("lists under Team the bots with a shared chat, with no private chat among their conversations, and the group chats", () => {
+ const view = teamSideView([scout([{ threadId: "ada-own", private: true, createdAt: 2 }, { threadId: "report", createdAt: 3 }]), mausbot()], [room()], ADA, "team");
+ expect(ids(view.bots), "a private-only bot is under Just me only").toEqual(["scout"]);
+ expect(view.bots[0]!.tasks.map((task) => task.threadId)).toEqual(["scout-main", "report"]);
+ expect(ids(view.groups)).toEqual(["room-1"]);
+ });
+
+ it("shows nothing of a private chat in the Team list, and nothing of a shared one under Just me: not even the preview of the one on screen", () => {
+ const privateOnScreen = scout([{ threadId: "ada-own", private: true, createdAt: 2 }], { threadId: "ada-own", messages: [{ id: "secret" }] });
+ expect(teamSideView([privateOnScreen, mausbot()], [], ADA, "team").bots[0]!.messages).toEqual([]);
+ expect(teamSideView([privateOnScreen, mausbot()], [], ADA, "me").bots[0]!.messages).toEqual([{ id: "secret" }]);
+ const sharedOnScreen = scout([{ threadId: "ada-own", private: true, createdAt: 2 }]);
+ expect(teamSideView([sharedOnScreen, mausbot()], [], ADA, "me").bots[0]!.messages).toEqual([]);
+ });
+
+ it("lists a bot the person can only view under Team alone, unless they have a conversation of their own with it", () => {
+ expect(botOnSide(scout([], { yourAccess: "view" }), ADA, "me")).toBe(false);
+ expect(botOnSide(scout([], { yourAccess: "view" }), ADA, "team")).toBe(true);
+ expect(botOnSide(scout([{ threadId: "ada-old", private: true, createdAt: 2 }], { yourAccess: "view" }), ADA, "me")).toBe(true);
+ });
+
+ it("offers no switch, and hides nothing, when one side would be empty", () => {
+ const onlyMine = teamSideView([mausbot()], [], ADA, "team");
+ expect(onlyMine.switchable).toBe(false);
+ expect(ids(onlyMine.bots)).toEqual(["mine"]);
+ const onlyShared = teamSideView([scout([], { yourAccess: "view" })], [room()], ADA, "me");
+ expect(onlyShared.switchable).toBe(false);
+ expect(ids(onlyShared.bots)).toEqual(["scout"]);
+ expect(ids(onlyShared.groups)).toEqual(["room-1"]);
+ expect(teamSideView([mausbot()], [room()], ADA, "me").switchable, "a group chat alone makes a Team side").toBe(true);
+ });
+
+ it("leaves archived bots out of both sides", () => {
+ expect(ids(teamSideView([scout(), mausbot(), scout([], { id: "old", hidden: true })], [], ADA, "team").bots)).toEqual(["scout"]);
+ });
+});
+
+describe("each side's own unread mark", () => {
+ const unread = (tasks: Extra[], groups = [room()]) => teamSideView([scout(tasks), mausbot()], groups, ADA, "me").unread;
+
+ it("marks a side for this person's unread conversations on it, and not for a routine's run or an archived one", () => {
+ expect(unread([])).toEqual({ me: false, team: false });
+ expect(unread([{ threadId: "ada-own", private: true, unread: true }])).toEqual({ me: true, team: false });
+ expect(unread([{ threadId: "ada-own", private: true }, { threadId: "report", unread: true }])).toEqual({ me: false, team: true });
+ expect(unread([{ threadId: "run", unread: true, routineRunId: "r1" }, { threadId: "old", private: true, unread: true, archivedAt: 5 }])).toEqual({ me: false, team: false });
+ });
+
+ it("counts the shared chat and a group chat for Team, the person's own MausBot for Just me", () => {
+ expect(teamSideView([{ ...scout(), tasks: [{ ...MAIN, unread: true }] }, mausbot()], [], ADA, "me").unread).toEqual({ me: false, team: true });
+ expect(unread([], [room({ unread: true })])).toEqual({ me: false, team: true });
+ expect(teamSideView([scout(), mausbot({ tasks: [{ threadId: "mine-main", unread: true }] })], [], ADA, "team").unread).toEqual({ me: true, team: false });
+ });
+});
+
+describe("the remembered side", () => {
+ it("is Just me until the person chose Team: one value for the whole team, kept on this device", () => {
+ expect(teamSide(ADA)).toBe("me");
+ setTeamSide("team", ADA);
+ expect(teamSide(ADA)).toBe("team");
+ expect(stored.get("[email protected]")).toBe("team");
+ setTeamSide("me", ADA);
+ expect(teamSide(ADA)).toBe("me");
+ });
+
+ it("is not rewritten by a side that is only shown: that lasts for the page, and the choice comes back with the next one", () => {
+ setTeamChats(ADA);
+ showTeamSide("team");
+ expect(teamSide(), "what the sidebar shows now").toBe("team");
+ expect(savedTeamSide(), "what the person chose").toBe("me");
+ expect(stored.size, "nothing written").toBe(0);
+ setTeamChats(null);
+ setTeamChats(ADA);
+ expect(teamSide(), "a new page").toBe("me");
+ setTeamSide("team");
+ showTeamSide("me");
+ expect(stored.get("[email protected]")).toBe("team");
+ setTeamSide("team");
+ expect(teamSide(), "choosing again what is kept still moves the sidebar").toBe("team");
+ });
+
+ it("is each person's own on a shared device, and each team's", () => {
+ setTeamSide("team", ADA);
+ expect(teamSide(BEN)).toBe("me");
+ expect(teamSide({ ...ADA, teamId: "team-other" })).toBe("me");
+ expect(teamSide(null), "off a team").toBe("me");
+ });
+
+ it("works for the page's life before the person is known or where nothing can be stored, and never throws", () => {
+ const anonymous: TeamChats = { teamId: "team-acme", member: true };
+ setTeamSide("team", anonymous);
+ expect(stored.size).toBe(0);
+ expect(teamSide(anonymous)).toBe("team");
+ setTeamSide("me", anonymous);
+ stored.set("[email protected]", "nonsense");
+ expect(teamSide(ADA)).toBe("me");
+ expect(teamSide(ADA, null)).toBe("me");
+ });
+});
+
+describe("opening a bot on the side the sidebar shows", () => {
+ it("opens the person's own chat under Just me and the shared chat under Team, making nothing", async () => {
+ setTeamChats(ADA);
+ const bot = scout([{ threadId: "ada-own", private: true, createdAt: 2 }], { threadId: "elsewhere" });
+ const dispatch = vi.fn();
+ openBot(dispatch, bot, false);
+ expect(dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "scout", threadId: "ada-own" });
+ setTeamSide("team");
+ dispatch.mockClear();
+ openBot(dispatch, bot, false);
+ expect(dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "scout", threadId: "scout-main" });
+ expect(dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ threadId: "ada-own" }));
+ await settle();
+ expect(server.calls, "nothing is made").toEqual([]);
+ });
+
+ it("a new chat under Just me is made through the server's private route, with no audience of this page's choosing", async () => {
+ setTeamChats(ADA);
+ server.answer = { bot: scout([{ threadId: "ada-new", private: true }], { threadId: "ada-new" }), task: { threadId: "ada-new" } };
+ const dispatch = vi.fn();
+ openBot(dispatch, scout(), false);
+ await settle();
+ expect(server.calls).toEqual([["/api/bots/scout/tasks", { method: "POST", body: "{}" }]]);
+ expect(dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: "switchTask" }));
+ expect(sideOfThread(scout(), "ada-new"), "and it is Just me from the moment it exists").toBe("me");
+ });
+
+ it("opens the person's own MausBot, which has no shared chat, as their own even under Team", async () => {
+ setTeamChats(ADA);
+ setTeamSide("team");
+ const dispatch = vi.fn();
+ openBot(dispatch, mausbot({ tasks: [{ threadId: "mine-main", private: true, createdAt: 1 }] }), false);
+ await settle();
+ expect(dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ threadId: "scout-main" }));
+ expect(server.calls).toEqual([]);
+ });
+
+ it("is as ever off a team", () => {
+ const dispatch = vi.fn();
+ openBot(dispatch, { id: "scout", threadId: "scout-main", mainThreadId: "scout-main", tasks: [{ threadId: "scout-main" }] }, false);
+ expect(dispatch).toHaveBeenCalledWith({ type: "select", id: "scout" });
+ expect(server.calls).toEqual([]);
+ });
+});
diff --git a/src/state/team-side.ts b/src/state/team-side.ts
new file mode 100644
index 0000000000..a5c28c0dce
--- /dev/null
+++ b/src/state/team-side.ts
@@ -0,0 +1,130 @@
+// On a team's Cloud the sidebar has two sides: "Just me", the person's own private conversations with each bot, and
+// "Team", the conversations everyone who sees a bot or a group chat reads. Which side a conversation belongs to is the
+// server's answer (`private` on the task), never the position of the switch.
+import { useSyncExternalStore } from "react";
+import { onTeamChats, ownChatOf, ownChatStarted, teamChats, type TeamChats } from "./team-chats";
+
+export type TeamSide = "me" | "team";
+
+type SideTask = { threadId: string; private?: 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 };
+
+/**
+ * Security invariant: a conversation is "Just me" only when the server marked it private, or this page made it through
+ * the server's private new-conversation route, or it is a chat with the person's own MausBot, which the server sends to
+ * nobody else. Anything else, a conversation this page knows nothing of included, is the team's. So nothing ever says
+ * "only you" over a composer whose words others can read.
+ */
+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";
+}
+
+/** The bot's shared chat, as the server names it; null for a bot that has none (a person's own MausBot). */
+export const teamThreadOf = (bot: Pick<SideBot, "tasks" | "defaultBot">): string | null =>
+ bot.defaultBot?.person ? null : bot.tasks?.find((task) => task.sharedChat === true && task.private !== true)?.threadId ?? null;
+
+/** The bot's conversations of one side, for a list. */
+export const tasksOfSide = <T extends SideTask>(bot: Pick<SideBot, "defaultBot"> & { tasks?: T[] }, side: TeamSide): T[] =>
+ (bot.tasks ?? []).filter((task) => sideOfThread(bot, task.threadId) === side);
+
+/** Whether the bot is listed on a side: under "Team" with its shared chat; under "Just me" when the person can chat
+ * with it privately, or already has a conversation of their own with it. */
+export function botOnSide(bot: SideBot, team: TeamChats, side: TeamSide): boolean {
+ if (side === "team") return teamThreadOf(bot) !== null;
+ return Boolean(bot.defaultBot?.person) || bot.yourAccess !== "view" || ownChatOf(bot, team) !== null;
+}
+
+/** A bot as one side lists it: that side's conversations only, and nothing of the other side's on its row: no unread
+ * mark, no working line, no words in its preview. */
+export function botForSide<T extends SideBot>(bot: T, side: TeamSide): T {
+ const onScreenHere = sideOfThread(bot, bot.threadId) === side;
+ const tasks = tasksOfSide(bot, side);
+ const elsewhere = onScreenHere ? {} : { busy: false, activity: undefined, waitingForTeammates: false, ...(bot.messages ? { messages: [] } : {}) };
+ return { ...bot, tasks: bot.tasks && tasks, unread: tasks.some(marksUnread), ...elsewhere } as T;
+}
+
+const marksUnread = (task: SideTask) => Boolean(task.unread) && !task.routineRunId && task.archivedAt === undefined;
+
+export interface TeamSideView<B, G> {
+ /** False where there is nothing to switch between: off a team, or with one side empty. */
+ switchable: boolean;
+ bots: B[];
+ groups: G[];
+ /** This person's own unread state, per side. */
+ unread: Record<TeamSide, boolean>;
+}
+
+/** What the sidebar lists on `side`. Off a team, everything, untouched. */
+export function teamSideView<B extends SideBot, G extends SideGroup>(bots: B[], groups: G[], team: TeamChats | null, side: TeamSide): TeamSideView<B, G> {
+ if (!team) return { switchable: false, bots, groups, unread: { me: false, team: false } };
+ const shown = bots.filter((bot) => !bot.hidden);
+ const listed = (which: TeamSide) => shown.filter((bot) => botOnSide(bot, team, which));
+ const me = listed("me"), shared = listed("team");
+ const switchable = me.length > 0 && shared.length + groups.length > 0;
+ const unreadOn = (which: TeamSide) => shown.some((bot) => tasksOfSide(bot, which).some(marksUnread)) || (which === "team" && groups.some((group) => Boolean(group.unread)));
+ const unread = { me: unreadOn("me"), team: unreadOn("team") };
+ if (!switchable) return { switchable, bots, groups, unread };
+ return { switchable, bots: (side === "me" ? me : shared).map((bot) => botForSide(bot, side)), groups: side === "team" ? groups : [], unread };
+}
+
+type SideStorage = Pick<Storage, "getItem" | "setItem">;
+const deviceStorage = (): SideStorage | null => (typeof localStorage === "undefined" ? null : localStorage);
+const keyOf = (team: TeamChats) => (team.person ? `omb.team-side.${team.teamId}.${team.person}` : null);
+
+let shown: { page: string; side: TeamSide } | null = null;
+let version = 0;
+const listeners = new Set<() => void>();
+const changed = () => { version++; for (const listener of listeners) listener(); };
+const pageOf = (team: TeamChats) => `${team.teamId}:${team.person ?? ""}`;
+onTeamChats(() => {
+ const team = teamChats();
+ if (!team || pageOf(team) !== shown?.page) shown = null;
+ changed();
+});
+
+/** The side this person last chose on this device: "Just me" until they chose "Team". */
+export function savedTeamSide(team: TeamChats | null = teamChats(), storage: SideStorage | null = deviceStorage()): TeamSide {
+ const key = team && keyOf(team);
+ try {
+ if (key && storage) return storage.getItem(key) === "team" ? "team" : "me";
+ } catch {}
+ return "me";
+}
+
+/** The side the sidebar shows: the one this page moved to, else the one the person last chose. */
+export function teamSide(team: TeamChats | null = teamChats(), storage: SideStorage | null = deviceStorage()): TeamSide {
+ if (!team) return "me";
+ return shown?.page === pageOf(team) ? shown.side : savedTeamSide(team, storage);
+}
+
+/** Shows a side without keeping it: for a conversation that came on screen without the person asking for it. */
+export function showTeamSide(side: TeamSide, team: TeamChats | null = teamChats()): void {
+ if (!team || teamSide(team) === side) return;
+ shown = { page: pageOf(team), side };
+ changed();
+}
+
+/** The person's own choice, kept for next time: they pressed the switch, or opened a conversation of that side. */
+export function setTeamSide(side: TeamSide, team: TeamChats | null = teamChats(), storage: SideStorage | null = deviceStorage()): void {
+ if (!team) return;
+ const key = keyOf(team), moves = teamSide(team, storage) !== side;
+ try { if (key && storage && savedTeamSide(team, storage) !== side) storage.setItem(key, side); } catch {}
+ if (!moves) return;
+ shown = { page: pageOf(team), side };
+ changed();
+}
+
+/** The team on screen and the side its sidebar shows. */
+export function useTeamSide(): { team: TeamChats | null; side: TeamSide } {
+ useSyncExternalStore((listener) => { listeners.add(listener); return () => { listeners.delete(listener); }; }, () => version, () => version);
+ const team = teamChats();
+ return { team, side: teamSide(team) };
+}
+
+/** The shared chat, when opening this bot should land on "Team": the side the sidebar shows. */
+export function teamThreadToOpen(bot: SideBot, team: TeamChats | null): string | null {
+ return team && teamSide(team) === "team" ? teamThreadOf(bot) : null;
+}
diff --git a/src/state/thread-navigation.test.ts b/src/state/thread-navigation.test.ts
index c84778d204..e90671a2c6 100644
--- a/src/state/thread-navigation.test.ts
+++ b/src/state/thread-navigation.test.ts
@@ -61,7 +61,7 @@ describe("a click on a bot's row or tile", () => {
});
it("leaves a team's Cloud alone: there a bot's row is the person's own conversation", () => {
- setTeamChats({ teamId: "acme", member: true });
+ setTeamChats({ teamId: "acme", member: true, opened: [] });
const bot = { ...chief([work]), tasks: [{ threadId: "mine", private: true, createdAt: 3 }, work] };
expect(opened(bot as ReturnType<typeof chief>, false)).toEqual([{ type: "switchTask", botId: "cos", threadId: "mine" }]);
});
diff --git a/src/state/thread-navigation.ts b/src/state/thread-navigation.ts
index d5564cf01e..1b1a075db0 100644
--- a/src/state/thread-navigation.ts
+++ b/src/state/thread-navigation.ts
@@ -1,6 +1,7 @@
import { notificationTrayPinned } from "@/lib/notification-preferences";
import type { Action, AppState } from "./store";
import { openOwnTeamChat, teamChats } from "./team-chats";
+import { teamThreadToOpen } from "./team-side";
interface NotificationThreadOwner {
id: string;
@@ -36,12 +37,15 @@ export function awayFromMainThread(bot: Pick<NotificationThreadOwner, "threadId"
return !threadsShown && botOpensTo(bot, false) !== bot.threadId;
}
-/** On a team's Cloud, the person's own conversation with the bot, never the team's main chat (team-chats.ts). */
+/** On a team's Cloud, the bot's conversation on the side the sidebar shows: the person's own with it under "Just me", its
+ * shared chat under "Team". */
export function openBot(
dispatch: (action: Action) => void,
bot: Pick<NotificationThreadOwner, "id" | "threadId" | "mainThreadId" | "tasks"> & { yourAccess?: string },
threadsShown: boolean,
) {
+ const shared = teamThreadToOpen(bot, teamChats());
+ if (shared) return openBotThread(dispatch, bot, shared, threadsShown);
if (openOwnTeamChat(dispatch, bot, (threadId) => openBotThread(dispatch, bot, threadId, threadsShown))) return;
const opened = botOpensTo(bot, threadsShown);
if (opened === bot.threadId) dispatch({ type: "select", id: bot.id });