Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
On a team, see who is here and who has a shared chat open (#5198)
Milind Soni84ee2b594e0a
diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex e64a07bdb8..4bf00da1c4 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -437,7 +437,7 @@ the person's picture from their team profile, or their initial when they have no| Route | Who | What ||---|---|---|-| `GET /api/team/people` | any member | the members the Admin has paired here (`team-people.json`), each `{email, name, role, you?, pictureUrl?}` |+| `GET /api/team/people` | any member | the members the Admin has paired here (`team-people.json`), each `{email, name, role, you?, pictureUrl?, here}` (below, "Who is here") || `GET /api/team/people/<person>/picture?v=<version>` | the team's members | that member's picture (`<person>` is their person key). `pictureUrl` names it, and its `v` changes whenever they change it; it is revalidated on every use (`private, no-cache` with an ETag). A session that isn't a member of this team gets 403, anything off a team or not a current member's picture 404 || `PUT /api/bots/<id>/reports-to {email}` | an Admin, or the bot's owner handing it over | one bot's owner; `null` hands it back to its creator || `PUT /api/team/reports-to {botIds, email}` | an Admin | "Set who looks after all bots…" on a department |@@ -666,6 +666,40 @@ leaves takes their inbox with them.On a My Cloud and on a desktop there are no team people: the @ list shows bots, `@you` and the profile name tag the oneperson as before, and `message_person` and the inbox do not exist.+## Who is here++The sidebar's People puts a dot on the face of each teammate who is here now, and lists them first after you; a+screen reader hears *"Write to Ada. Here now"*. A bot's shared chat and a group chat show at the right of their header+the faces of the others who have that conversation open right now (*"Ada and Ben have this open"* to a screen reader).+A private chat shows none of it. Nothing says when someone was last here, and nothing says who is typing.++- **Here.** A person is here while one of their sessions has the event stream open (`GET /api/events`), or a window of+ theirs said so in the last 45 seconds, and for 45 seconds after the last of those ends, so a reconnect or a phone in+ the background for a moment changes nothing. It is kept in memory only (`server/team-presence.ts`) and nothing about+ it is written to disk. A restart forgets who was here until their apps reconnect.+- **What the app sends.** `POST /api/presence/here {tab, threadId}` (any team session): `tab` is the window's own id,+ `threadId` the conversation it shows, or null for none, a hidden window or a private chat. It is sent when the+ conversation changes and every minute while the window shows. A window not heard from for about three minutes no+ longer shows anything.+- **What comes back.** `GET /api/team/people` gives each person `here`. On the event stream, outside the replay buffer+ (frames with no `id`): `team.presence {email, here}` to everyone signed in, at most one every 5 seconds per person,+ with the state it ends in, and `thread.presence {threadId, people}` to the people listed, at most one a conversation+ every 0.75 seconds. `team.people` (replayed, like any frame) says someone joined, left or changed role: the app reads+ the people and its own session again, so a role the Admin changed shows without reopening the team. A stream that+ reconnects without its replay reads the people again and sends its window again. Types: `shared/team-presence.ts`.+- **Private means private.** A conversation counts only when more than one person can read it (the team's or a group+ chat's audience, with nobody's own MausBot in it) and the person sending can read it; anything else, a private chat+ above all, is taken as no conversation and is never kept. Each list is checked again as it is sent, against who may+ read the conversation then (`VisibleSet.thread`). So nobody, the Owner and every Admin included, learns from+ presence that a person has a private chat open, which bot they talk to privately, or that a private chat exists: that+ person only counts as here. `server/cloud-team-presence.e2e.test.ts` proves it from a member's and an admin's side.+- **The People list itself** says *"Loading people…"* while it loads and *"Couldn't load people"* with **Try again** when+ it cannot, and at phone width choosing a person closes the full-screen list.+- **Older apps and servers.** A server that sends no `here` on the people list gets no `POST /api/presence/here` and the+ app shows nothing of this; an older app on a newer server still counts as here by its stream and ignores the frames.++On a My Cloud and on a desktop there is one person: no People list, no presence, nothing sent.+## What is not closed here- **Saved logins per member.** A login saved from a sign-in card is the team's (an Admin saves it, for every bot in the@@ -677,6 +711,9 @@ person as before, and `message_person` and the inbox do not exist.team's sign-in files in each engine home, above); a member cannot sign an engine in as themselves, by design.- **A roster read from the Admin.** Without the Admin's `member-left` request (above), removal takes effect within thehour, and nothing is deleted.+- **Someone invited who never opened the team.** The machine first learns of a member at their first pairing, so until+ then they are in no People list, and nothing says they joined (`team.people`): the Admin sends no roster and no+ "joined" of its own.- **Engine homes without a box, and engines outside the list.** Without the bot box (bubblewrap refused, or switchedoff) a shell reaches every file of the server's user, engine homes included; only the box keeps them apart. An enginewhose sign-in file is not named in `engine-homes/layout.ts` starts signed out in every audience's home. Enginesdiff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex f3fe20b3f8..f65eeec603 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -88,6 +88,7 @@ export const VITEST_SUBSETS = {"server/cloud-team-per-person.e2e.test.ts","server/cloud-team-phones.e2e.test.ts","server/cloud-team-pictures.e2e.test.ts",+ "server/cloud-team-presence.e2e.test.ts","server/cloud-team-private.e2e.test.ts","server/cloud-team-profile.e2e.test.ts","server/cloud-team-requests.e2e.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex 0b89d92932..8dfbb11b0c 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -225,6 +225,7 @@ describe("CI outputs", () => {"server/cloud-team-per-person.e2e.test.ts","server/cloud-team-phones.e2e.test.ts","server/cloud-team-pictures.e2e.test.ts",+ "server/cloud-team-presence.e2e.test.ts","server/cloud-team-private.e2e.test.ts","server/cloud-team-profile.e2e.test.ts","server/cloud-team-requests.e2e.test.ts",diff --git a/server/cloud-team-owners.e2e.test.ts b/server/cloud-team-owners.e2e.test.tsindex 5f3202c222..fdf84f647f 100644--- a/server/cloud-team-owners.e2e.test.ts+++ b/server/cloud-team-owners.e2e.test.ts@@ -124,7 +124,8 @@ it("records who created each team bot, offers everyone who opened the team, andexpect(fox.reportsTo).toBeUndefined();expect(lead).toMatchObject({ createdBy: OLIVE.email, reportsTo: ADA.email });- const people = (await team.as(bob, "GET", "/api/team/people")).body.people;+ const people = ((await team.as(bob, "GET", "/api/team/people")).body.people as Array<Record<string, unknown>>)+ .map(({ here, ...person }) => { expect(typeof here).toBe("boolean"); return person; });expect(people).toEqual(expect.arrayContaining([{ email: OLIVE.email, name: "Olive", role: "owner" }, { email: ADA.email, name: "Ada", role: "admin" }, { email: BOB.email, name: "Bob", role: "member", you: true },]));diff --git a/server/cloud-team-presence.e2e.test.ts b/server/cloud-team-presence.e2e.test.tsnew file mode 100644index 0000000000..29b7a2dc77--- /dev/null+++ b/server/cloud-team-presence.e2e.test.ts@@ -0,0 +1,148 @@+// Who is here on a Team Cloud (docs/team-cloud.md "Who is here"). A real Team Cloud with the Owner, an Admin and Bob, a+// member, each with the event stream open: everyone learns who is here and who went, the people in a shared chat or a+// group chat see each other there, and Bob's private chat is never named to anyone, the Owner+// and the Admin included: not on a stream, not in the people list, not as a count. A bot only the Owner may use keeps+// Bob out of its shared chat's list as well.+import { randomBytes } from "node:crypto";+import { afterAll, beforeAll, expect, it } from "vitest";+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const OWNER = { email: "[email protected]", role: "owner" as const };+const ADMIN = { email: "[email protected]", role: "admin" as const };+const BOB = { email: "[email protected]", role: "member" as const };+const DEE = { email: "[email protected]", role: "member" as const };+const GRACE_MS = 400;++type Frame = { kind: string; email?: string; here?: boolean; threadId?: string; people?: string[] };+type Person = { email: string; here?: boolean };++let fx: CloudSendFixture, team: CloudTeamFixture;+let owner = "", admin = "", bob = "";+let scout: { id: string; mainThreadId: string }, payroll: { id: string; mainThreadId: string };+let bobThread = "", roomThread = "";+const streams: Record<string, Awaited<ReturnType<typeof listen>>> = {};++async function until(done: () => Promise<boolean> | boolean, timeoutMs = 30_000): Promise<void> {+ const end = Date.now() + timeoutMs;+ while (!(await done())) {+ if (Date.now() > end) throw new Error("timed out waiting");+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+}+/** An open event stream as one person: every frame it was sent, the ones without an id included. */+async function listen(token: string) {+ const controller = new AbortController();+ const stream = await fetch(`${team.base}/api/events`, { headers: { ...fx.edge, authorization: `Bearer ${token}`, accept: "text/event-stream" }, signal: controller.signal });+ expect(stream.status).toBe(200);+ const reader = stream.body!.getReader();+ const decoder = new TextDecoder();+ let text = "";+ const done = (async () => { for (;;) { const { value, done } = await reader.read(); if (done) return; text += decoder.decode(value, { stream: true }); } })().catch(() => {});+ await until(() => text.includes("\"hello\""), 10_000);+ const frames = () => [...text.matchAll(/^data: (.*)$/gm)].map((match) => JSON.parse(match[1]!) as Frame);+ return { text: () => text, frames, mark: () => text.length, since: (mark: number) => text.slice(mark), close: async () => { controller.abort(); await done; } };+}+const here = (token: string, threadId: string | null) => team.as(token, "POST", "/api/presence/here", { tab: "w1", threadId });+const peopleOf = async (token: string) => (await team.as(token, "GET", "/api/team/people")).body.people as Person[];+const lastList = (who: string, threadId: string) => streams[who]!.frames().filter((frame) => frame.kind === "thread.presence" && frame.threadId === threadId).at(-1)?.people;++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-1", name: "Acme", env: { OMB_TEAM_PRESENCE_GRACE_MS: String(GRACE_MS) } } });+ team = fx.team!;+ owner = (await team.pair(OWNER)).token!;+ admin = (await team.pair(ADMIN)).token!;+ bob = (await team.pair(BOB)).token!;+ const made = await team.as(owner, "POST", "/api/bots", { name: "Scout" });+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ scout = made.body.bot;+ const other = await team.as(owner, "POST", "/api/bots", { name: "Payroll" });+ expect(other.status, JSON.stringify(other.body)).toBe(201);+ payroll = other.body.bot;+ expect((await team.as(owner, "PUT", `/api/bots/${payroll.id}/access`, { everyone: "none", people: {} })).status).toBe(200);+ const opened = await team.as(bob, "POST", `/api/bots/${scout.id}/tasks`, { title: "Bob's plans" });+ expect(opened.status, JSON.stringify(opened.body)).toBe(201);+ bobThread = opened.body.task.threadId;+ const room = await team.as(owner, "POST", "/api/groups", { name: "Launch", memberIds: [scout.id], setup: { bulletin: "", defaultResponder: { kind: "everyone" } } });+ expect(room.status, JSON.stringify(room.body)).toBe(201);+ roomThread = room.body.group.threadId;+ streams.owner = await listen(owner);+ streams.admin = await listen(admin);+ streams.bob = await listen(bob);+}, hostTimeout(120_000));++afterAll(async () => {+ for (const stream of Object.values(streams)) await stream.close();+ await fx?.close();+});++it("everyone signed in sees who is here", async () => {+ await until(async () => (await peopleOf(owner)).every((person) => person.here === true));+ const seen = await peopleOf(bob);+ expect(seen.map((person) => [person.email, person.here])).toEqual(expect.arrayContaining([[OWNER.email, true], [ADMIN.email, true], [BOB.email, true]]));+ await until(() => streams.owner!.frames().some((frame) => frame.kind === "team.presence" && frame.email === BOB.email && frame.here === true));+}, hostTimeout(60_000));++it("the people in a shared chat see each other there; Bob's private chat is named to nobody", async () => {+ expect((await here(owner, scout.mainThreadId)).status).toBe(200);+ expect((await here(admin, scout.mainThreadId)).status).toBe(200);+ const bobPrivate = await here(bob, bobThread);+ expect(bobPrivate.status).toBe(200);+ expect(bobPrivate.body).toEqual({ ok: true });+ await until(() => lastList("owner", scout.mainThreadId)?.length === 2);+ expect(lastList("owner", scout.mainThreadId)).toEqual([ADMIN.email, OWNER.email]);+ expect(lastList("admin", scout.mainThreadId)).toEqual([ADMIN.email, OWNER.email]);++ // Bob joins the shared chat, and everyone in it sees all three.+ await here(bob, scout.mainThreadId);+ await until(() => lastList("owner", scout.mainThreadId)?.length === 3 && lastList("bob", scout.mainThreadId)?.length === 3);+ expect(lastList("admin", scout.mainThreadId)).toEqual([ADMIN.email, BOB.email, OWNER.email]);++ // Back to his private chat: the shared chat just loses him.+ const mark = { owner: streams.owner!.mark(), admin: streams.admin!.mark() };+ await here(bob, bobThread);+ await until(() => lastList("owner", scout.mainThreadId)?.length === 2);+ expect(lastList("owner", scout.mainThreadId)).toEqual([ADMIN.email, OWNER.email]);+ for (const who of ["owner", "admin"] as const) {+ const after = streams[who]!.since(mark[who]);+ expect(after, who).not.toContain(bobThread);+ for (const frame of streams[who]!.frames().filter((one) => one.kind === "thread.presence")) expect(frame.threadId, who).not.toBe(bobThread);+ }+ for (const who of ["owner", "admin"] as const) expect(streams[who]!.text(), who).not.toContain(bobThread);+ // Not even to Bob: a private chat is no conversation here, only "here".+ expect(streams.bob!.frames().filter((frame) => frame.threadId === bobThread)).toEqual([]);+ const listed = JSON.stringify(await team.as(admin, "GET", "/api/team/people"));+ expect(listed).not.toContain(bobThread);+ expect(listed).not.toContain(scout.id);+ expect(Object.keys((await peopleOf(admin)).find((person) => person.email === BOB.email)!).sort()).toEqual(["email", "here", "name", "role"]);+}, hostTimeout(60_000));++it("a group chat's list reaches the people in it, and a bot Bob may not use keeps him out of its chat", async () => {+ await here(owner, roomThread);+ await here(bob, roomThread);+ await until(() => lastList("bob", roomThread)?.length === 2);+ expect(lastList("owner", roomThread)).toEqual([BOB.email, OWNER.email]);++ await here(owner, payroll.mainThreadId);+ const refused = await here(bob, payroll.mainThreadId);+ expect(refused.status).toBe(404);+ await until(() => lastList("owner", payroll.mainThreadId) !== undefined);+ expect(lastList("owner", payroll.mainThreadId)).toEqual([OWNER.email]);+ expect(streams.bob!.text()).not.toContain(payroll.mainThreadId);+}, hostTimeout(60_000));++it("someone who goes away is gone after the grace", async () => {+ await here(bob, null);+ await streams.bob!.close();+ delete streams.bob;+ await until(() => streams.owner!.frames().some((frame) => frame.kind === "team.presence" && frame.email === BOB.email && frame.here === false));+ const bobNow = (await peopleOf(owner)).find((person) => person.email === BOB.email)!;+ expect(bobNow).toEqual({ email: BOB.email, name: "Bob", role: "member", here: false });+}, hostTimeout(60_000));++it("someone joining the team tells every app to read the people again", async () => {+ const mark = streams.owner!.mark();+ expect((await team.pair(DEE)).token).toBeTruthy();+ await until(() => streams.owner!.since(mark).includes("\"team.people\""));+ expect((await peopleOf(owner)).map((person) => person.email)).toContain(DEE.email);+}, hostTimeout(60_000));diff --git a/server/host/team-presence-host.test.ts b/server/host/team-presence-host.test.tsnew file mode 100644index 0000000000..9080c22f59--- /dev/null+++ b/server/host/team-presence-host.test.ts@@ -0,0 +1,152 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import type { Audience } from "../audience.ts";+import type { Viewer } from "../bot-visibility.ts";+import type { RequestAuth } from "../request-auth.ts";+import type { SessionRecord } from "../sessions.ts";+import { createTeamPeople } from "../team-people.ts";+import type { PresenceClock } from "../team-presence.ts";+import { createTeamPresenceHost, type PresenceStream } from "./team-presence-host.ts";++const ADA = "[email protected]", BEN = "[email protected]";+const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++/** Timers run when the test says, not on their own. */+function manualClock() {+ let now = 1_000;+ const timers: Array<{ at: number; run: () => void; done: boolean }> = [];+ const clock: PresenceClock = { now: () => now, later: (run, ms) => { const timer = { at: now + ms, run, done: false }; timers.push(timer); return { cancel: () => { timer.done = true; } }; } };+ const advance = (ms: number) => {+ now += ms;+ for (const timer of timers) if (!timer.done && timer.at <= now) { timer.done = true; timer.run(); }+ };+ return { clock, advance };+}++const session = (email: string, extra: Partial<SessionRecord> = {}): SessionRecord => ({ id: `s-${email}`, tokenHash: "x".repeat(64), label: "", scopes: ["client"], createdAt: 0, lastSeenAt: 0, expiresAt: Infinity,+ email, membershipAuthority: "team", teamRole: "member", ...extra });++/** A team with a bot's shared chat, Ada's private chat with it, Ada's own MausBot, a group chat with it and one Ben may+ * not read. */+function setup(team = true) {+ const dir = mkdtempSync(join(tmpdir(), "omb-presence-"));+ dirs.push(dir);+ const people = team ? createTeamPeople(dir) : null;+ people?.seen(ADA, "member");+ people?.seen(BEN, "admin");+ const audiences: Record<string, Audience> = { shared: "team", "ada-private": "member:p_ada", "ada-own": "team", room: "room:g1", "room-own": "room:g2", hidden: "team" };+ const bots: Record<string, { defaultBot?: { person?: string } }> = { scout: {}, mausbot: { defaultBot: { person: ADA } } };+ const threadBots: Record<string, string> = { shared: "scout", "ada-private": "scout", "ada-own": "mausbot", hidden: "scout" };+ const groups: Record<string, { memberIds: string[] }> = { room: { memberIds: ["scout"] }, "room-own": { memberIds: ["scout", "mausbot"] } };+ const sent: Array<{ to: string; frame: Record<string, unknown> }> = [];+ /** An open event stream whose writes land in `sent`. */+ const stream = (name: string, person?: SessionRecord): PresenceStream & { name: string } => ({ name, person, backpressured: false, close: () => {},+ res: { writableLength: 0, once: () => {}, write: (frame: string) => { sent.push({ to: name, frame: JSON.parse(frame.replace(/^data: /, "")) as Record<string, unknown> }); return true; } } });+ const streams = [stream(ADA, session(ADA)), stream(BEN, session(BEN, { teamRole: "admin", scopes: ["admin", "client"] })),+ stream("move-in", session("[email protected]", { moveIn: "b1" })), stream("server")];+ const broadcasts: Array<Record<string, unknown>> = [];+ const { clock, advance } = manualClock();+ const host = createTeamPresenceHost<PresenceStream & { name: string }>({+ people,+ broadcast: (payload) => broadcasts.push(payload),+ audienceOf: (threadId) => audiences[threadId] ?? "team",+ store: () => ({ botByThread: (threadId: string) => (threadBots[threadId] ? bots[threadBots[threadId]!] : null), groupByThread: (threadId: string) => groups[threadId], bot: (id: string) => bots[id] ?? null }) as never,+ // Ben (an admin) sees every bot but not "hidden"'s chat in this test; everyone sees their own.+ visibleTo: (viewer: Viewer) => ({ thread: (threadId: string) => !(threadId === "hidden" && viewer.email === BEN) }),+ clock,+ });+ const post = async (email: string | null, body: unknown, extra: Partial<SessionRecord> = {}) => {+ const answers: Array<[number, unknown]> = [];+ const auth: RequestAuth = email ? { kind: "session", session: session(email, extra), via: "bearer", scopes: ["client"] } as RequestAuth : { kind: "loopback", scopes: ["admin", "client"] };+ await host.routes({ req: {} as never, res: {} as never, url: new URL("http://x/api/presence/here"), path: "/api/presence/here", method: "POST", auth,+ json: ((_res: unknown, status: number, value: unknown) => { answers.push([status, value]); }) as never, readBody: (async () => body) as never });+ return answers[0];+ };+ return { host, people, streams, sent, broadcasts, post, advance };+}++describe("the presence host", () => {+ it("counts team sessions' streams only, and tells every team stream", () => {+ const { host, streams, sent } = setup();+ for (const one of streams) host.streams.add(one);+ const arrivals = sent.filter((one) => one.frame.kind === "team.presence");+ // Each arrival reaches the team streams open by then: Ada's only her own, Ben's both.+ expect(arrivals.map((one) => [one.frame.email, one.to])).toEqual([[ADA, ADA], [BEN, ADA], [BEN, BEN]]);+ expect(host.of!(ADA)).toEqual({ here: true });+ expect(host.of!("[email protected]")).toMatchObject({ here: false });+ expect([...host.streams].map((one) => one.name)).toEqual([ADA, BEN, "move-in", "server"]);+ });++ it("starts a person's grace when their stream leaves the set, once", () => {+ const { host, streams, advance } = setup();+ host.streams.add(streams[0]!);+ expect(host.streams.delete(streams[0]!)).toBe(true);+ expect(host.streams.delete(streams[0]!)).toBe(false);+ host.streams.add(streams[0]!);+ advance(60_000);+ expect(host.of!(ADA).here, "the second delete did not count").toBe(true);+ host.streams.delete(streams[0]!);+ advance(60_000);+ expect(host.of!(ADA).here).toBe(false);+ });++ it("shows a person only in a conversation more than one person reads, and only to those who read it", async () => {+ const { host, streams, sent, post, advance } = setup();+ for (const one of streams) host.streams.add(one);+ sent.length = 0;+ for (const threadId of ["ada-private", "ada-own", "room-own", "hidden"]) {+ expect(await post(ADA, { tab: "t1", threadId })).toEqual([200, { ok: true }]);+ expect(await post(BEN, { tab: "t1", threadId })).toEqual([200, { ok: true }]);+ advance(1_000);+ }+ expect(sent.filter((one) => one.frame.kind === "thread.presence").map((one) => [one.to, one.frame.threadId, one.frame.people])).toEqual([[ADA, "hidden", [ADA]]]);+ sent.length = 0;+ await post(ADA, { tab: "t1", threadId: "shared" });+ await post(BEN, { tab: "t1", threadId: "shared" });+ advance(1_000);+ expect(sent.map((one) => [one.to, one.frame])).toEqual([+ [ADA, { kind: "thread.presence", threadId: "shared", people: [ADA, BEN] }],+ [BEN, { kind: "thread.presence", threadId: "shared", people: [ADA, BEN] }],+ ]);+ await post(ADA, { tab: "t1", threadId: "room" });+ advance(1_000);+ expect(sent.filter((one) => one.frame.threadId === "room").map((one) => one.to)).toEqual([ADA]);+ expect(JSON.stringify(sent)).not.toMatch(/ada-private|ada-own|room-own/);+ });++ it("refuses a request without a tab, and counts nothing for the server or a move-in sign-in", async () => {+ const { host, post } = setup();+ expect((await post(ADA, { threadId: "shared" }))?.[0]).toBe(400);+ expect(await post(null, { tab: "t1", threadId: "shared" })).toEqual([200, { ok: true }]);+ expect(await post("[email protected]", { tab: "t1", threadId: "shared" }, { moveIn: "b1" })).toEqual([200, { ok: true }]);+ expect(host.of!("[email protected]").here).toBe(false);+ });++ it("does nothing off a team", async () => {+ const { host, streams, sent, post } = setup(false);+ for (const one of streams) host.streams.add(one);+ expect(sent).toEqual([]);+ expect(host.of).toBeUndefined();+ expect((await post(ADA, { tab: "t1", threadId: "shared" }))?.[0]).toBe(404);+ });++ it("tells every app when someone joins, changes role or leaves, once, and forgets who left", () => {+ const { host, people, broadcasts, streams, advance } = setup();+ host.streams.add(streams[0]!);+ expect(host.of!(ADA).here).toBe(true);+ people!.seen("[email protected]", "member");+ people!.seen(ADA, "admin");+ people!.left(ADA);+ expect(host.of!(ADA).here).toBe(false);+ expect(broadcasts).toEqual([]);+ advance(1_000);+ expect(broadcasts).toEqual([{ kind: "team.people" }]);+ people!.seen(BEN, "admin");+ advance(1_000);+ expect(broadcasts).toHaveLength(1);+ });+});diff --git a/server/host/team-presence-host.ts b/server/host/team-presence-host.tsnew file mode 100644index 0000000000..0ae91dcfc9--- /dev/null+++ b/server/host/team-presence-host.ts@@ -0,0 +1,135 @@+// Who is here on a Team Cloud, wired for the server (docs/team-cloud.md "Who is here"): the server's set of open event+// streams lives here, and each team session's stream in it counts its person here (team-presence.ts). POST+// /api/presence/here says which conversation a window shows, and the frames go out on the streams themselves, outside+// the replay buffer: presence is now or never.+// Security: the one rule is `reads`. A conversation counts only when more than one person can read it (a bot's shared+// chat, a group chat) and the person can; anything else, a private chat above all, is taken as "no conversation", so+// nobody, an admin included, learns that it is open, which bot it is with or that it exists.+import { ownerEmail } from "../../shared/bot-owner.ts";+import { PRESENCE_HERE_PATH, type PersonPresence, type PresenceFrame } from "../../shared/team-presence.ts";+import { audienceMember, type Audience } from "../audience.ts";+import type { VisibleSet, Viewer } from "../bot-visibility.ts";+import { PASS, type RouteHandler } from "../routes/table.ts";+import type { SessionRecord } from "../sessions.ts";+import { deliverSseFrame, type SseFanoutClient } from "../sse-fanout.ts";+import type { Store } from "../store.ts";+import type { TeamPeople } from "../team-people.ts";+import { createTeamPresence, realClock, type PresenceClock, type PresenceEvent } from "../team-presence.ts";++export interface PresenceStream extends SseFanoutClient {+ person?: Pick<SessionRecord, "email" | "membershipAuthority" | "moveIn">;+}++export interface TeamPresenceHostDeps {+ /** Null off a team: then nothing here does anything. */+ people: TeamPeople | null;+ /** A frame every team stream gets, replayed to one that reconnects (`team.people`). */+ broadcast(payload: Record<string, unknown>): void;+ audienceOf(threadId: string): Audience;+ store(): Pick<Store, "botByThread" | "groupByThread" | "bot">;+ visibleTo(viewer: Viewer): Pick<VisibleSet, "thread">;+ clock?: PresenceClock;+ /** OMB_TEAM_PRESENCE_GRACE_MS when not given (tests shorten it). */+ graceMs?: number;+}++const TAB = /^[\w-]{1,64}$/;+const THREAD_ID = /^[\w-]{1,100}$/;+const PEOPLE_GAP_MS = 1_000;++/** The person a team session speaks for; null for anything else (the server itself, a move-in sign-in). */+function teamPerson(session: PresenceStream["person"] | undefined): string | null {+ return session?.membershipAuthority === "team" && session.email && !session.moveIn ? ownerEmail(session.email) : null;+}++const frameOf = (frame: PresenceFrame) => `data: ${JSON.stringify(frame)}\n\n`;++/** Sends a presence frame, cutting loose a stream that cannot take it, as every other frame does. */+function send(stream: SseFanoutClient, frame: string): void {+ if (deliverSseFrame(stream, "presence", frame) === "disconnected") stream.close();+}++/** `streams` is the server's set of open event streams: adding one counts its person here, deleting it starts their+ * grace. */+export function createTeamPresenceHost<Stream extends PresenceStream>(deps: TeamPresenceHostDeps) {+ const { people } = deps;++ /** More than one person can read it: never a conversation that is someone's own, nor one with someone's own bot. */+ function shared(threadId: string): boolean {+ if (audienceMember(deps.audienceOf(threadId)) !== null) return false;+ const store = deps.store();+ const group = store.groupByThread(threadId);+ const bots = group ? group.memberIds.map((id) => store.bot(id)) : [store.botByThread(threadId)];+ return bots.length > 0 && bots.every((bot) => !!bot && !bot.defaultBot?.person);+ }+ function reads(email: string, threadId: string): boolean {+ const role = people?.list().find((person) => person.email === email)?.role;+ if (!role || !shared(threadId)) return false;+ return deps.visibleTo(role === "member" ? { kind: "member", email } : { kind: "all", email }).thread(threadId);+ }++ function sendTo(emails: ReadonlySet<string> | null, frame: PresenceFrame): void {+ const text = frameOf(frame);+ for (const stream of streams) {+ const email = teamPerson(stream.person);+ if (email !== null && (emails === null || emails.has(email))) send(stream, text);+ }+ }+ function emit(event: PresenceEvent): void {+ switch (event.type) {+ case "person":+ return sendTo(null, { kind: "team.presence", email: event.email, here: event.here });+ case "thread":+ return sendTo(new Set(event.people), { kind: "thread.presence", threadId: event.threadId, people: event.people });+ }+ }++ const clock = deps.clock ?? realClock;+ const presence = people ? createTeamPresence({ reads, emit, clock, graceMs: deps.graceMs ?? (Number(process.env.OMB_TEAM_PRESENCE_GRACE_MS) || undefined) }) : null;+ let peopleTimer: { cancel(): void } | undefined;+ people?.onChange((email, change) => {+ if (change === "left") presence?.forget(email);+ peopleTimer ??= clock.later(() => { peopleTimer = undefined; deps.broadcast({ kind: "team.people" }); }, PEOPLE_GAP_MS);+ });++ const routes: RouteHandler = async ({ req, res, path, method, auth, json, readBody }) => {+ if (path !== PRESENCE_HERE_PATH) return PASS;+ if (method !== "POST") return json(res, 405, { error: "POST only" });+ if (!presence) return json(res, 404, { error: "not found" });+ const body: unknown = await readBody(req, 4096);+ const given = body && typeof body === "object" && !Array.isArray(body) ? body as Record<string, unknown> : {};+ const threadId = typeof given.threadId === "string" && THREAD_ID.test(given.threadId) ? given.threadId : null;+ if (typeof given.tab !== "string" || !TAB.test(given.tab)) return json(res, 400, { error: "Send this window's tab id." });+ const email = auth.kind === "session" ? teamPerson(auth.session) : null;+ if (email !== null && auth.kind === "session") presence.window(email, `${auth.session.id}:${given.tab}`, threadId);+ return json(res, 200, { ok: true });+ };++ const streams = new (class extends Set<Stream> {+ override add(stream: Stream): this {+ super.add(stream);+ const email = teamPerson(stream.person);+ if (email !== null) presence?.streamOpened(email);+ return this;+ }+ override delete(stream: Stream): boolean {+ if (!super.delete(stream)) return false;+ const email = teamPerson(stream.person);+ if (email !== null) presence?.streamClosed(email);+ return true;+ }+ })();++ return {+ routes,+ streams,+ /** What the people list says of someone: whether they are here now. Undefined off a team. */+ of: presence ? (email: string): PersonPresence => ({ here: presence.here(email) }) : undefined,+ close(): void {+ presence?.close();+ peopleTimer?.cancel();+ },+ };+}++export type TeamPresenceHost = ReturnType<typeof createTeamPresenceHost>;diff --git a/server/index.ts b/server/index.tsindex fec9794c80..4ffdb4d268 100644--- a/server/index.ts+++ b/server/index.ts@@ -457,7 +457,7 @@ import { createScreenFrameSource, rememberTurnFrame, type ScreenCapture } from "import { screenFrameHash, screenSurfaceForTool, screenTouchingTool, settledFrameIsNews } from "./screen-frame-gate.ts";import { asSchedule, RoutineRequestService } from "./routine-requests.ts"; import { ownerSpokeOnly } from "./cloud-routine-level.ts"; import { routineRunCard, routineRunFallbackText } from "./routine-run-card.ts";import { activeRoutinesContext } from "./active-routines-context.ts";-import { createRefusedHandoffs } from "./host/refused-handoffs.ts"; import { automationContextText, createAutomationReports, newestAutomationLines } from "./automation-reports.ts"; import { createAutomationDestinations } from "./automation-destinations.ts"; import { createProactive } from "./host/proactive.ts"; import { createFirstHourHooks, startFirstHour, welcomeDonePatch } from "./host/first-hour-host.ts"; import { greetingMessage } from "./host/first-hour.ts"; import { READ_AND_DRAFT_PARTS, READ_AND_DRAFT_REFUSAL, READ_AND_DRAFT_TOOLS, recordsAnswer } from "./read-and-draft.ts"; import { createPresenceRoutes } from "./routes/presence.ts"; import { needsYouNow } from "./today.ts";+import { createRefusedHandoffs } from "./host/refused-handoffs.ts"; import { automationContextText, createAutomationReports, newestAutomationLines } from "./automation-reports.ts"; import { createAutomationDestinations } from "./automation-destinations.ts"; import { createProactive } from "./host/proactive.ts"; import { createFirstHourHooks, startFirstHour, welcomeDonePatch } from "./host/first-hour-host.ts"; import { greetingMessage } from "./host/first-hour.ts"; import { READ_AND_DRAFT_PARTS, READ_AND_DRAFT_REFUSAL, READ_AND_DRAFT_TOOLS, recordsAnswer } from "./read-and-draft.ts"; import { createPresenceRoutes } from "./routes/presence.ts"; import { createTeamPresenceHost } from "./host/team-presence-host.ts"; import { needsYouNow } from "./today.ts";import { engineLabel, LimitResetClock, nearLimitNote } from "./limit-resets.ts"; import { loadPlanUsage, planAccountsFromInstances } from "./plan-usage.ts"; import { LimitFailovers, limitBackupAllowed } from "./limit-failover.ts"; import { createLimitResetRoutes } from "./routes/limit-resets.ts";import { parseTriggerRequest, triggerTarget } from "./trigger-tools.ts"; import { WebhookRequestError, WebhookRequestService } from "./webhook-requests.ts"; import { createAppTriggerHost } from "./app-trigger-host.ts";import { appliesNow, directApply, UNDO_STALE, type DirectApply } from "./direct-apply.ts";@@ -4637,7 +4637,7 @@ interface SseClient {/** Stops the heartbeat and leaves `sseClients` before ending the response; every way a stream ends goes through it. */close: () => void;}-const sseClients = new Set<SseClient>();+const { streams: sseClients, ...teamPresence } = createTeamPresenceHost<SseClient>({ people: teamOwners.people, broadcast, audienceOf: (threadId) => teamHost.audienceOf(threadId), store: () => store, visibleTo });let audienceChangedAt = 0;function audienceChanged(): void {@@ -12159,7 +12159,7 @@ ROUTES.push(createBotCreateRoutes({routines: () => routines,storedAvatarExists, defaultSelection, checkedModelSelection, cloudOwnerSession, wireBot, team: CLOUD_TEAM && teamOwners.people ? { name: CLOUD_TEAM.name, people: teamOwners.people } : null,personaliseSetupCard: (bot) => setupSuggestions.personalise(bot.id),-}), createTeamOwnerRoutes({ team: CLOUD_TEAM, people: teamOwners.people, store, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }), sees: (auth, botId) => visibleTo(viewerFor(auth)).bot(botId), publicBot,+}), createTeamOwnerRoutes({ team: CLOUD_TEAM, people: teamOwners.people, store, presence: teamPresence.of, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }), sees: (auth, botId) => visibleTo(viewerFor(auth)).bot(botId), publicBot,profileOf: (email) => teamHost.people.profile(personKey({ id: "", email })) }));ROUTES.push(createBotSettingsRoutes({store, cfg, registry, commandAllowlist, commandAllowlistDrivers: COMMAND_ALLOWLIST_DRIVERS,@@ -12220,7 +12220,7 @@ ROUTES.push(createBotMemoryRoutes({}));const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));-ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),+ROUTES.push(teamPresence.routes, createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) }));ROUTES.push(createRoomHoldRoutes({group: (id) => store.group(id),diff --git a/server/request-auth.ts b/server/request-auth.tsindex b4e677282d..3bb15b070c 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -430,6 +430,8 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg{ methods: ["DELETE"], path: /^\/api\/team\/my-connections\/(?:apps\/[\w-]{1,64}|mcp\/[a-z][a-z0-9_-]{0,31})$/ },// the person opened the app: their own brief on a Team Cloud, nothing recorded for anyone else{ methods: ["POST"], path: /^\/api\/presence\/active$/ },+ // which shared conversation a team member's window shows: the handler keeps only one they and others may read+ { methods: ["POST"], path: /^\/api\/presence\/here$/ },// what a bot asks of this person: their own questions and approvals only{ methods: ["GET"], path: /^\/api\/needs-you$/ },// a person's own inbox: its lines, how many wait, and one of them read or done; the handler serves the session's own alonediff --git a/server/routes/team-owners.ts b/server/routes/team-owners.tsindex 59f6d4ffbc..4ddad646e8 100644--- a/server/routes/team-owners.ts+++ b/server/routes/team-owners.ts@@ -1,6 +1,6 @@import { userError } from "../user-errors.ts";// Who a Team Cloud bot reports to. GET /api/team/people lists the members a bot can report to, with each one's-// picture; GET /api/team/people/<person>/picture serves it. PUT /api/bots/<id>/reports-to {email} changes one bot's+// picture and, to a member, whether they are here now; GET /api/team/people/<person>/picture serves it. PUT /api/bots/<id>/reports-to {email} changes one bot's// owner: an Admin may, and so may the member who owns it now, to hand it over. PUT /api/team/reports-to {botIds, email}// sets a whole department's at once, for an Admin.// Security: all but the last are client-scoped, so the checks here are the gate. A member's name and picture are shown@@ -10,6 +10,7 @@ import { createHash } from "node:crypto";import { z } from "zod";import { botAvatarUrlSchema } from "../../shared/bot-avatar.ts";+import type { PersonPresence } from "../../shared/team-presence.ts";import { botOwner, nameFromEmail, ownerEmail } from "../../shared/bot-owner.ts";import { attachmentExists, readAttachment } from "../attachments.ts";import { setReportsTo } from "../bot-owners.ts";@@ -40,6 +41,8 @@ export interface TeamOwnerRouteDeps {publicBot(bot: BotRecord): unknown;/** Settings → Activity: who a bot reports to decides who edits it. */record?(auth: RequestAuth, row: Omit<AdminActionRow, "at" | "actor">): void;+ /** Whether a member is here now (docs/team-cloud.md "Who is here"). */+ presence?(email: string): PersonPresence;}/** The address a session speaks for: a team member's, or none (a loopback service, a session the Admin never signed). */@@ -88,7 +91,8 @@ export function createTeamOwnerRoutes(deps: TeamOwnerRouteDeps): RouteHandler {return json(res, 200, { people: members().map(({ email, role }) => {const avatarUrl = me ? profileOf(email).avatarUrl : undefined;return { email, name: nameOf(email), role, ...(email === me ? { you: true } : {}),- ...(avatarUrl && storedPicture(avatarUrl) ? { pictureUrl: teamPictureUrl(email, avatarUrl) } : {}) };+ ...(avatarUrl && storedPicture(avatarUrl) ? { pictureUrl: teamPictureUrl(email, avatarUrl) } : {}),+ ...(me && deps.presence ? deps.presence(email) : {}) };}) });}diff --git a/server/team-people.test.ts b/server/team-people.test.tsindex 5990105c74..5436c637e7 100644--- a/server/team-people.test.ts+++ b/server/team-people.test.ts@@ -31,4 +31,17 @@ describe("the people a Team Cloud bot can report to", () => {reread.seen("[email protected]", "member");expect([reread.has("[email protected]"), reread.gone("[email protected]")]).toEqual([true, false]);});++ it("say who joined, changed role or left, not each pairing", () => {+ const people = createTeamPeople(dir());+ const changes: string[] = [];+ people.onChange((email, change) => changes.push(`${email} ${change}`));+ people.seen("[email protected]", "member");+ people.seen("[email protected]", "member");+ people.seen("[email protected]", "admin");+ people.left("[email protected]");+ people.left("[email protected]");+ people.seen("[email protected]", "admin");+ expect(changes).toEqual(["[email protected] joined", "[email protected] role", "[email protected] left", "[email protected] joined"]);+ });});diff --git a/server/team-people.ts b/server/team-people.tsindex 9e0ad2ee73..c201d9d6a3 100644--- a/server/team-people.ts+++ b/server/team-people.ts@@ -22,6 +22,8 @@ const personSchema = z.object({const fileSchema = z.object({ version: z.literal(1), people: z.array(personSchema).max(MAX_PEOPLE) });export type TeamPerson = z.infer<typeof personSchema>;+/** What changed about the team's people: someone new, someone's role, someone gone. */+export type TeamPeopleChange = "joined" | "role" | "left";export function createTeamPeople(dataDir: string, now: () => number = Date.now) {const file = join(dataDir, TEAM_PEOPLE_FILE);@@ -33,6 +35,12 @@ export function createTeamPeople(dataDir: string, now: () => number = Date.now)} catch (error) {if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.warn(`team people: ${file} is unreadable; starting fresh`);}+ const listeners = new Set<(email: string, change: TeamPeopleChange) => void>();+ const changed = (email: string, change: TeamPeopleChange) => {+ for (const listener of listeners) {+ try { listener(email, change); } catch (error) { console.warn(`team people: ${error instanceof Error ? error.message : String(error)}`); }+ }+ };const save = () => {try {writeFileAtomic(file, `${JSON.stringify({ version: 1, people })}\n`, { mode: 0o600 });@@ -52,6 +60,8 @@ export function createTeamPeople(dataDir: string, now: () => number = Date.now)...people.filter((person) => person.email !== address),].slice(0, MAX_PEOPLE);save();+ if (!known || known.leftAt !== undefined) changed(address, "joined");+ else if (known.role !== role) changed(address, "role");},/** The Admin said this member left: no bot reports to them any more, and the picker stops offering them. */left(email: string): void {@@ -61,6 +71,11 @@ export function createTeamPeople(dataDir: string, now: () => number = Date.now)people = [{ email: address, role: known?.role ?? "member", firstSeenAt: known?.firstSeenAt ?? at, lastSeenAt: known?.lastSeenAt ?? at, leftAt: at },...people.filter((person) => person.email !== address)].slice(0, MAX_PEOPLE);save();+ if (known?.leftAt === undefined) changed(address, "left");+ },+ onChange(listener: (email: string, change: TeamPeopleChange) => void): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);},gone(email: string): boolean {const address = ownerEmail(email);diff --git a/server/team-presence.test.ts b/server/team-presence.test.tsnew file mode 100644index 0000000000..c6832d0381--- /dev/null+++ b/server/team-presence.test.ts@@ -0,0 +1,168 @@+import { describe, expect, it } from "vitest";+import { createTeamPresence, GRACE_MS, PERSON_GAP_MS, THREAD_GAP_MS, WINDOW_TTL_MS, type PresenceClock, type PresenceEvent } from "./team-presence.ts";++function fakeClock() {+ let now = 1_000_000;+ const timers: Array<{ at: number; run: () => void; done: boolean }> = [];+ const clock: PresenceClock = {+ now: () => now,+ later(run, ms) {+ const timer = { at: now + ms, run, done: false };+ timers.push(timer);+ return { cancel: () => { timer.done = true; } };+ },+ };+ const advance = (ms: number) => {+ const end = now + ms;+ for (;;) {+ const next = timers.filter((timer) => !timer.done && timer.at <= end).sort((a, b) => a.at - b.at)[0];+ if (!next) break;+ now = next.at;+ next.done = true;+ next.run();+ }+ now = end;+ };+ return { clock, advance };+}++const SHARED = "t-shared", PRIVATE = "t-private", ROOM = "t-room";++function setup(readers: Record<string, string[]> = { [SHARED]: [ADA, BEN, CY], [ROOM]: [ADA, BEN] }) {+ const { clock, advance } = fakeClock();+ const events: PresenceEvent[] = [];+ const presence = createTeamPresence({ clock, emit: (event) => events.push(event),+ reads: (email, threadId) => readers[threadId]?.includes(email) ?? false });+ return { presence, events, advance };+}++describe("who is here", () => {+ it("counts a person here while a stream is open, and away only after the grace", () => {+ const { presence, events, advance } = setup();+ presence.streamOpened(ADA);+ expect(events).toEqual([{ type: "person", email: ADA, here: true }]);+ expect(presence.here(ADA)).toBe(true);+ presence.streamClosed(ADA);+ advance(GRACE_MS - 1);+ expect(presence.here(ADA)).toBe(true);+ advance(1);+ expect(presence.here(ADA)).toBe(false);+ expect(events.at(-1)).toEqual({ type: "person", email: ADA, here: false });+ });++ it("a reconnect within the grace sends nothing, and two devices keep a person here", () => {+ const { presence, events, advance } = setup();+ presence.streamOpened(ADA);+ presence.streamOpened(ADA);+ presence.streamClosed(ADA);+ advance(GRACE_MS * 2);+ expect(presence.here(ADA)).toBe(true);+ presence.streamClosed(ADA);+ advance(GRACE_MS / 2);+ presence.streamOpened(ADA);+ advance(GRACE_MS * 2);+ expect(events).toEqual([{ type: "person", email: ADA, here: true }]);+ });++ it("a flapping connection sends at most one frame per gap, with the state it ends in", () => {+ const { presence, events, advance } = setup();+ presence.streamOpened(BEN);+ presence.streamClosed(BEN);+ advance(GRACE_MS);+ expect(events.map((event) => event.type === "person" && event.here)).toEqual([true, false]);+ // Back and gone again inside the gap: the arrival waits, and by then he is gone, so nothing more goes out.+ for (let round = 0; round < 20; round += 1) { presence.streamOpened(BEN); presence.streamClosed(BEN); }+ expect(events).toHaveLength(2);+ advance(PERSON_GAP_MS);+ expect(events).toHaveLength(3);+ advance(GRACE_MS * 3);+ expect(events.filter((event) => event.type === "person")).toHaveLength(4);+ expect(events.at(-1)).toMatchObject({ here: false });+ });++ it("a window's ping alone counts, and lapses after the grace", () => {+ const { presence, advance } = setup();+ presence.window(CY, "s1:tab", null);+ expect(presence.here(CY)).toBe(true);+ advance(GRACE_MS);+ expect(presence.here(CY)).toBe(false);+ });+});++describe("who is in this conversation", () => {+ it("lists the people who have a shared conversation open, to them, coalesced", () => {+ const { presence, events, advance } = setup();+ for (const email of [ADA, BEN, CY]) presence.streamOpened(email);+ events.length = 0;+ presence.window(ADA, "a:1", SHARED);+ presence.window(BEN, "b:1", SHARED);+ expect(events).toEqual([]);+ advance(THREAD_GAP_MS);+ expect(events).toEqual([{ type: "thread", threadId: SHARED, people: [ADA, BEN] }]);+ presence.window(BEN, "b:1", ROOM);+ advance(THREAD_GAP_MS);+ expect(events.slice(1)).toEqual(expect.arrayContaining([+ { type: "thread", threadId: SHARED, people: [ADA] },+ { type: "thread", threadId: ROOM, people: [BEN] },+ ]));+ });++ it("never keeps or sends a conversation the person may not be shown in: a private chat is no conversation", () => {+ const { presence, events, advance } = setup();+ presence.streamOpened(ADA);+ presence.streamOpened(BEN);+ events.length = 0;+ presence.window(ADA, "a:1", PRIVATE);+ presence.window(CY, "c:1", ROOM);+ advance(THREAD_GAP_MS * 4);+ expect(events.filter((event) => event.type !== "person")).toEqual([]);+ expect(presence.viewers(PRIVATE)).toEqual([]);+ expect(presence.viewers(ROOM)).toEqual([]);+ expect(JSON.stringify(events)).not.toContain(PRIVATE);+ // Moving from a shared chat to a private one reads as leaving the shared one, nothing more.+ presence.window(ADA, "a:1", SHARED);+ presence.window(BEN, "b:1", SHARED);+ advance(THREAD_GAP_MS);+ presence.window(ADA, "a:1", PRIVATE);+ advance(THREAD_GAP_MS);+ expect(events.at(-1)).toEqual({ type: "thread", threadId: SHARED, people: [BEN] });+ expect(JSON.stringify(events)).not.toContain(PRIVATE);+ });++ it("checks who may read it again when it sends, and drops a person who went away", () => {+ const readers = { [SHARED]: [ADA, BEN] };+ const { presence, events, advance } = setup(readers);+ presence.streamOpened(ADA);+ presence.streamOpened(BEN);+ presence.window(ADA, "a:1", SHARED);+ presence.window(BEN, "b:1", SHARED);+ advance(THREAD_GAP_MS);+ readers[SHARED] = [BEN];+ expect(presence.viewers(SHARED)).toEqual([BEN]);+ events.length = 0;+ presence.streamClosed(BEN);+ advance(GRACE_MS + THREAD_GAP_MS);+ expect(presence.viewers(SHARED)).toEqual([]);+ expect(events.filter((event) => event.type === "thread")).toEqual([]);+ });++ it("forgets a window not heard from", () => {+ const { presence, advance } = setup();+ presence.streamOpened(ADA);+ presence.window(ADA, "a:1", SHARED);+ advance(WINDOW_TTL_MS + WINDOW_TTL_MS / 3 + 1);+ expect(presence.viewers(SHARED)).toEqual([]);+ expect(presence.here(ADA)).toBe(true);+ });++ it("forgets everything of a person who left", () => {+ const { presence, advance } = setup();+ presence.streamOpened(ADA);+ presence.window(ADA, "a:1", SHARED);+ presence.forget(ADA);+ advance(THREAD_GAP_MS);+ expect(presence.viewers(SHARED)).toEqual([]);+ expect(presence.here(ADA)).toBe(false);+ });+});diff --git a/server/team-presence.ts b/server/team-presence.tsnew file mode 100644index 0000000000..22098e5ed2--- /dev/null+++ b/server/team-presence.ts@@ -0,0 +1,200 @@+// Who is here on a Team Cloud, in memory only (docs/team-cloud.md "Who is here"). A person is here while one of their+// sessions has the event stream open or a window of theirs said so lately, and for GRACE_MS after, so a reconnect or a+// phone in the background for a moment changes nothing. Each window says which conversation it shows; only a+// conversation `reads` allows (shared, and theirs to read) is ever kept, so a private chat is never recorded anywhere.+// Security: `reads` is the privacy gate. Every list is checked against it again when it is sent.++export const GRACE_MS = 45_000;+/** At most one arrival or departure frame per person this often; what changed in between is sent once, at the end. */+export const PERSON_GAP_MS = 5_000;+/** A window not heard from this long no longer shows its conversation. */+export const WINDOW_TTL_MS = 150_000;+/** A conversation's list of who has it open is sent at most this often. */+export const THREAD_GAP_MS = 750;++export type PresenceEvent =+ | { type: "person"; email: string; here: boolean }+ | { type: "thread"; threadId: string; people: string[] };++export interface PresenceClock {+ now(): number;+ later(run: () => void, ms: number): { cancel(): void };+}++export interface TeamPresenceDeps {+ /** Whether this person may be shown in this conversation: one more than one person can read, and they can. */+ reads(email: string, threadId: string): boolean;+ emit(event: PresenceEvent): void;+ clock?: PresenceClock;+ graceMs?: number;+}++export const realClock: PresenceClock = {+ now: Date.now,+ later(run, ms) {+ const timer = setTimeout(run, ms);+ timer.unref?.();+ return { cancel: () => clearTimeout(timer) };+ },+};++interface Person {+ streams: number;+ /** The last moment one of their streams closed or a window said it was open. */+ lastActive: number;+ here: boolean;+ announced: boolean;+ lastFrameAt: number;+ awayTimer?: { cancel(): void };+ frameTimer?: { cancel(): void };+}++interface Window {+ email: string;+ threadId: string | null;+ at: number;+}++export function createTeamPresence(deps: TeamPresenceDeps) {+ const clock = deps.clock ?? realClock;+ const graceMs = deps.graceMs ?? GRACE_MS;+ const people = new Map<string, Person>();+ const windows = new Map<string, Window>();+ const dirty = new Set<string>();+ let threadTimer: { cancel(): void } | undefined;+ let sweepTimer: { cancel(): void } | undefined;++ const person = (email: string): Person => {+ let known = people.get(email);+ if (!known) {+ known = { streams: 0, lastActive: 0, here: false, announced: false, lastFrameAt: -Infinity };+ people.set(email, known);+ }+ return known;+ };++ function announce(email: string): void {+ const one = people.get(email);+ if (!one || one.announced === one.here || one.frameTimer) return;+ const wait = one.lastFrameAt + PERSON_GAP_MS - clock.now();+ if (wait > 0) {+ one.frameTimer = clock.later(() => { one.frameTimer = undefined; announce(email); }, wait);+ return;+ }+ one.announced = one.here;+ one.lastFrameAt = clock.now();+ deps.emit({ type: "person", email, here: one.here });+ }++ function arrive(email: string): Person {+ const one = person(email);+ one.lastActive = clock.now();+ one.awayTimer?.cancel();+ one.awayTimer = undefined;+ if (!one.here) {+ one.here = true;+ announce(email);+ }+ return one;+ }++ function scheduleAway(email: string, one: Person): void {+ if (one.streams > 0) return;+ one.awayTimer?.cancel();+ one.awayTimer = clock.later(() => {+ one.awayTimer = undefined;+ if (one.streams > 0 || !one.here) return;+ const left = clock.now() - one.lastActive;+ if (left < graceMs) return scheduleAway(email, one);+ one.here = false;+ for (const [key, window] of windows) if (window.email === email) dropWindow(key);+ announce(email);+ }, Math.max(0, one.lastActive + graceMs - clock.now()));+ }++ function touched(threadId: string | null): void {+ if (threadId === null) return;+ dirty.add(threadId);+ threadTimer ??= clock.later(flushThreads, THREAD_GAP_MS);+ }++ function dropWindow(key: string): void {+ const window = windows.get(key);+ if (!window) return;+ windows.delete(key);+ touched(window.threadId);+ }++ /** Who has this conversation open now, each checked against `reads` again. */+ function viewers(threadId: string): string[] {+ const emails = new Set<string>();+ for (const window of windows.values()) {+ if (window.threadId === threadId && people.get(window.email)?.here) emails.add(window.email);+ }+ return [...emails].filter((email) => deps.reads(email, threadId)).sort();+ }++ function flushThreads(): void {+ threadTimer = undefined;+ const threads = [...dirty];+ dirty.clear();+ for (const threadId of threads) {+ const open = viewers(threadId);+ if (open.length > 0) deps.emit({ type: "thread", threadId, people: open });+ }+ }++ function sweep(): void {+ sweepTimer = undefined;+ const stale = clock.now() - WINDOW_TTL_MS;+ for (const [key, window] of windows) if (window.at < stale) dropWindow(key);+ if (windows.size > 0) sweepTimer = clock.later(sweep, WINDOW_TTL_MS / 3);+ }++ return {+ /** One of this person's sessions opened the event stream. */+ streamOpened(email: string): void {+ arrive(email).streams += 1;+ },+ streamClosed(email: string): void {+ const one = people.get(email);+ if (!one || one.streams === 0) return;+ one.streams -= 1;+ one.lastActive = clock.now();+ scheduleAway(email, one);+ },+ /** A window of this person's is open, showing `threadId`: kept only when `reads` allows it, else as showing none. */+ window(email: string, key: string, threadId: string | null): void {+ const one = arrive(email);+ scheduleAway(email, one);+ const shown = threadId !== null && deps.reads(email, threadId) ? threadId : null;+ const before = windows.get(key);+ if (before && before.email !== email) return;+ windows.set(key, { email, threadId: shown, at: clock.now() });+ sweepTimer ??= clock.later(sweep, WINDOW_TTL_MS / 3);+ if (before?.threadId !== shown) {+ touched(before?.threadId ?? null);+ touched(shown);+ }+ },+ here(email: string): boolean {+ return people.get(email)?.here === true;+ },+ viewers,+ /** The person left the team: nothing of theirs stays, and nobody hears of it here (the people list does). */+ forget(email: string): void {+ const one = people.get(email);+ one?.awayTimer?.cancel();+ one?.frameTimer?.cancel();+ people.delete(email);+ for (const [key, window] of windows) if (window.email === email) dropWindow(key);+ },+ close(): void {+ threadTimer?.cancel();+ sweepTimer?.cancel();+ for (const one of people.values()) { one.awayTimer?.cancel(); one.frameTimer?.cancel(); }+ },+ };+}++export type TeamPresence = ReturnType<typeof createTeamPresence>;diff --git a/shared/team-presence.ts b/shared/team-presence.tsnew file mode 100644index 0000000000..ac18129267--- /dev/null+++ b/shared/team-presence.ts@@ -0,0 +1,44 @@+// Who is here on a Team Cloud (docs/team-cloud.md "Who is here"): the wire between the server and the app. A person is+// named by their address, as in GET /api/team/people. Nothing here ever names a private chat: a conversation only one+// person can read is never reported, and its person only counts as here.++/** POST {tab, threadId}: this app window is open, with that conversation in front of the person (null: none, or one that+ * is theirs alone). `tab` is the window's own id, made when it loads. Sent when the conversation changes and every+ * HERE_REPEAT_MS while the window shows. */+export const PRESENCE_HERE_PATH = "/api/presence/here";++export interface PresenceHereBody {+ tab: string;+ threadId: string | null;+}++/** How often a showing window repeats its POST; a window not heard from for a few of these no longer counts. */+export const HERE_REPEAT_MS = 60_000;++/** A person on GET /api/team/people, with presence: `here` while one of their apps is open. A server that sends no+ * `here` has no presence, and the app shows none. */+export interface PersonPresence {+ here?: boolean;+}++/** A teammate came or went. Sent to everyone signed in to the team, at most once every few seconds per person. */+export interface TeamPresenceFrame {+ kind: "team.presence";+ email: string;+ here: boolean;+}++/** Who has a shared conversation (a bot's shared chat, a group chat) open now, the receiver included. Sent only to the+ * people listed, each of whom may read it; never for a conversation that is one person's own. */+export interface ThreadPresenceFrame {+ kind: "thread.presence";+ threadId: string;+ people: string[];+}++/** Someone joined the team, left it or changed role: the app reads the people and its own session again. */+export interface TeamPeopleFrame {+ kind: "team.people";+}++export type PresenceFrame = TeamPresenceFrame | ThreadPresenceFrame | TeamPeopleFrame;diff --git a/shared/wire.ts b/shared/wire.tsindex 1a60bd191b..26af63b981 100644--- a/shared/wire.ts+++ b/shared/wire.ts@@ -1,6 +1,7 @@/** The client-visible wire model for tasks, bots, messages and rooms. A field* here is one the server emits in every response and SSE frame that carries* the shape. */+import type { PresenceFrame } from "./team-presence.ts";import type { DataBroadcast } from "./data-surface.ts";import type { ApprovalMode } from "./approval-mode.ts";import type { ToolScope } from "./tool-scope.ts";@@ -992,5 +993,7 @@ export type ServerFrame =| { kind: "live.call"; botId: string; threadId: string; call: LiveCallState | null }/** A job is waiting for the phone whose registry key this is; it polls now. */| { kind: "device.job"; phone: string; id: string }+ /** Who is here on a Team Cloud (shared/team-presence.ts). */+ | PresenceFrame/** The config status object spread flat into the frame. */| ({ kind: "config" } & Record<string, unknown>);diff --git a/src/App.tsx b/src/App.tsxindex 901f22964d..96751a7435 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -36,6 +36,7 @@ import { CloudSendStrip } from "@/components/CloudSendStrip";import { HomeLine } from "@/components/HomeLine";import { useTeamChats } from "@/state/team-chats";import { needsYouVersion, useTeamPeopleLoader } from "@/state/team-people";+import { useTeamPresence } from "@/state/team-presence";import { inboxVersion, useInboxLoader, useInboxPanel, useInboxReady } from "@/state/inbox";import { InboxPanel } from "@/components/inbox/InboxPanel";import { PlacesRail } from "@/components/PlacesRail";@@ -131,7 +132,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {dispatch("section" in request ? { type: "toggleAppSettings", open: true, section: request.section } : { type: "togglePlugins", open: true, surface: request.surface });}, [dispatch]);useExternalChatLinks(state, dispatch); useDesktopNotificationOpens(state, dispatch);- usePresence(state, dispatch);+ usePresence(state, dispatch); useTeamPresence(state);const [drawerOpen, setDrawerOpen] = useState(false);usePageLanguage(effectiveLanguage(useLanguageChoice(), state.config?.language), true);const [paletteOpen, setPaletteOpen] = useState(false);diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex e4c00cc6ac..91f5ca0539 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -92,7 +92,7 @@ import { AttachmentGallery, collectMessageFiles, replyAttachmentGroup, splitMessimport { ScreenFrame } from "./ScreenFrame";import { CompactionChip, DigestChip } from "./DigestChip";import { RenameTitle } from "./RenameTitle"; import { ChatHeadRole, chiefOfStaffBadge } from "./BotRole";-import { BotActivityPicker } from "./TaskPicker"; import { ChatHeadPill } from "./ChatHeadPill"; import { useStoreRef } from "@/state/store-ref";+import { BotActivityPicker } from "./TaskPicker"; import { ChatHeadPill } from "./ChatHeadPill"; import { ThreadPresenceFaces } from "./TeamPresence"; import { useStoreRef } from "@/state/store-ref";import { ELEVATED_FLOAT, ELEVATED_HOVER } from "./elevated";import { ModelPicker } from "./ModelPicker";import { ChatHeaderMenu, ChatMoreMenu } from "./ChatMoreMenu"; import { TeamOwnHelperHeader, TeamPrivateFirstLine, TeamPrivateHeader, TeamSharedHeader } from "./TeamPrivateChatsLine";@@ -1095,7 +1095,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {<divdata-chathead-controlsclassName={cn("flex shrink-0 items-center gap-2", !phone && "@max-[30rem]/chathead:ml-auto @max-[30rem]/chathead:flex-wrap @max-[30rem]/chathead:justify-end @min-[30rem]/chathead:col-start-3 @min-[30rem]/chathead:justify-self-end")}- >+ >{sharedChat && <ThreadPresenceFaces threadId={bot.threadId} />}{!simpleHead && (bot.busy || bot.waitingForTeammates) && (<buttononClick={() => dispatch({ type: "interrupt", botId: bot.id, threadId: bot.threadId })}diff --git a/src/components/RoomHeader.tsx b/src/components/RoomHeader.tsxindex 931eeb0818..3ebef2316e 100644--- a/src/components/RoomHeader.tsx+++ b/src/components/RoomHeader.tsx@@ -23,6 +23,7 @@ import { roomMemberQueueTitle } from "./RoomQueueList";import { RoomWorkingFolderChip } from "./RoomWorkingFolder";import { Select } from "./Select";import { GroupTaskPicker } from "./TaskPicker";+import { ThreadPresenceFaces } from "./TeamPresence";export function DefaultResponderSelect({ group, members }: { group: Group; members: Bot[] }) {const { state, dispatch } = useStore();@@ -171,7 +172,8 @@ export function RoomHeader({</button>{group.description && <p className="max-w-full truncate text-[12px] leading-4 text-ink-secondary">{group.description}</p>}</div>- <div data-roomhead-controls className="flex shrink-0 items-center">+ <div data-roomhead-controls className="flex shrink-0 items-center gap-1.5">+ <ThreadPresenceFaces threadId={group.threadId} /><buttonref={membersTriggerRef}type="button"@@ -219,6 +221,7 @@ export function RoomHeader({data-roomhead-controlsclassName="flex items-center gap-1.5 @max-3xl/roomhead:ml-auto @max-3xl/roomhead:flex-wrap @max-3xl/roomhead:justify-end">+ <ThreadPresenceFaces threadId={group.threadId} /><buttontype="button"onClick={onToggleFind}diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex fdb9e74486..673f9d43b9 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -1380,7 +1380,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {{matchingBots.length === 0 && visibleGroups.length === 0 && q && q.length < MIN_QUERY && (<div className="px-3 py-6 text-center text-[13px] text-ink-secondary">{t("sidebar.noMatch", { query })}</div>)}- {!q && <NeedsYouButton compact={rail} />}{!q && <SidebarPeople compact={rail} />}+ {!q && <NeedsYouButton compact={rail} />}{!q && <SidebarPeople compact={rail} onOpened={phone ? onClose : undefined} />}{unsectionedChief && (phone ? (<PhoneHero bot={unsectionedChief} selected={botRow(unsectionedChief).selected} onOpen={() => openBotRow(dispatch, unsectionedChief, showThreads, botRow(unsectionedChief).selected)} onMenu={setMenu} />) : (diff --git a/src/components/SidebarPeople.test.ts b/src/components/SidebarPeople.test.tsindex 32604d68d6..20a9357a19 100644--- a/src/components/SidebarPeople.test.ts+++ b/src/components/SidebarPeople.test.ts@@ -3,10 +3,10 @@ import { renderToStaticMarkup } from "react-dom/server";import { afterEach, describe, expect, it, vi } from "vitest";import { initialState, StoreContext, type AppState, type Bot, type Message } from "@/state/store";-import { needsYouVersion, setTeamPeople, type TeamPeople } from "@/state/team-people";+import { needsYouVersion, retryTeamPeople, setTeamPeople, type TeamPeople } from "@/state/team-people";import { InboxAnswers, InboxCaption, RelayLabel } from "./InboxLine";-import { inboxBotOf, SidebarPeople } from "./SidebarPeople";+import { inboxBotOf, peopleInOrder, SidebarPeople } from "./SidebarPeople";import { pendingApprovals, PendingApprovalPanel } from "./PendingApproval";const CLEO = { email: "[email protected]", name: "Cleo", role: "owner" };@@ -97,6 +97,44 @@ describe("the team's people in the sidebar", () => {});});+describe("who is here, in the people list", () => {+ const ADA = { email: "[email protected]", name: "Ada", role: "member" };+ const config = { team: { id: "team-acme", name: "Acme" } } as AppState["config"];++ it("puts a dot on whoever is here now and lists them after you and before the rest, with no time for the others", () => {+ setTeamPeople({ ...asBen, presence: true, people: [{ ...ADA, here: false }, { ...CLEO, here: true }, { ...BEN, here: true }] });+ const markup = render(createElement(SidebarPeople, { compact: false }), { config });+ expect(markup.indexOf("[email protected]")).toBeLessThan(markup.indexOf("[email protected]"));+ expect(markup.indexOf("[email protected]")).toBeLessThan(markup.indexOf("[email protected]"));+ expect(markup).toMatch(/aria-label="Write to Cleo. Here now"[^>]*data-person="[email protected]"/);+ expect(markup).toMatch(/aria-label="Write to Ada"[^>]*data-person="[email protected]"/);+ expect(markup.match(/data-here-dot/g)).toHaveLength(1);+ expect(peopleInOrder([ADA, CLEO, BEN].map((person) => ({ ...person, here: person === ADA }))).map((person) => person.name)).toEqual(["Ben", "Ada", "Cleo"]);+ });++ it("shows no dot and no time against a server that says nothing about presence", () => {+ setTeamPeople(asBen);+ const markup = render(createElement(SidebarPeople, { compact: false }), { config });+ expect(markup).not.toContain("data-here-dot");+ expect(markup).toContain('aria-label="Write to Cleo"');+ });++ it("says the people are loading, and when they could not be read offers to try again", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("offline"); }));+ try {+ retryTeamPeople();+ expect(render(createElement(SidebarPeople, { compact: false }), { config })).toContain("Loading people…");+ await vi.waitFor(() => expect(render(createElement(SidebarPeople, { compact: false }), { config })).toContain("data-people-retry"));+ const failed = render(createElement(SidebarPeople, { compact: false }), { config });+ expect(failed).toContain("Couldn't load people");+ expect(render(createElement(SidebarPeople, { compact: true }), { config }), "nothing on the rail").toBe("");+ expect(render(createElement(SidebarPeople, { compact: false })), "nothing off a team").toBe("");+ } finally {+ vi.unstubAllGlobals();+ }+ });+});+describe("a line in the inbox", () => {it("says who it is from, through which bot, and offers the conversation it came from", () => {setTeamPeople(asBen);diff --git a/src/components/SidebarPeople.tsx b/src/components/SidebarPeople.tsxindex 81b75f3235..9dea655d1c 100644--- a/src/components/SidebarPeople.tsx+++ b/src/components/SidebarPeople.tsx@@ -1,4 +1,5 @@-// On a Team Cloud: the team's people, with their pictures. Your own row opens your inbox, your chat with your Chief where+// 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.@@ -11,8 +12,9 @@ import { t } from "@/lib/i18n";import { useShowThreads } from "@/lib/thread-preferences";import { openBot, openThread, useStore, type AppState, type Bot } from "@/state/store";import { openInbox } from "@/state/inbox";-import { useTeamPeople, type TeamPerson } from "@/state/team-people";+import { retryTeamPeople, useTeamPeople, useTeamPeopleStatus, type TeamPerson } from "@/state/team-people";import { PersonFace } from "./TeamOwner";+import { HereDot } from "./TeamPresence";/** The bot that is this person's inbox: their own Chief, else their own MausBot. */export function inboxBotOf(bots: readonly Bot[], email: string | undefined): Bot | undefined {@@ -37,19 +39,51 @@ export function teamPeoplePage(team: { id: string; cloudPage?: string } | null |const focusComposer = () => requestAnimationFrame(() => document.querySelector<HTMLTextAreaElement>('[data-tour="composer"] textarea')?.focus());-export function SidebarPeople({ compact }: { compact: boolean }) {+/** You first, then whoever is here now, then everyone else, each by name. */+export function peopleInOrder(people: readonly TeamPerson[]): TeamPerson[] {+ return [...people].sort((a, b) => Number(Boolean(b.you)) - Number(Boolean(a.you)) || Number(b.here === true) - Number(a.here === true) || a.name.localeCompare(b.name));+}++/** A teammate's row label: what pressing it does, and that they are here now when they are. */+const teammateLabel = (person: TeamPerson, presence: boolean) =>+ t(presence && person.here ? "sidebar.people.mentionHere" : "sidebar.people.mention", { name: person.name });++/** While the people load, or when they could not: a quiet line in their place, with a way to try again. */+function PeopleStatusLine({ compact }: { compact: boolean }) {+ const status = useTeamPeopleStatus();+ if (compact || status === "ready") return null;+ return (+ <section aria-label={t("sidebar.people.title")} data-sidebar-people={status} className="px-2 pb-1">+ <div className="px-2 pb-0.5 pt-1 text-[11px] font-medium text-ink-tertiary">{t("sidebar.people.title")}</div>+ {status === "loading" ? <div role="status" className="px-2 py-1 text-[13px] text-ink-tertiary">{t("sidebar.people.loading")}</div> : (+ <div role="alert" className="flex items-center gap-2 px-2 py-1 text-[13px] text-ink-secondary">+ <span className="min-w-0 flex-1 truncate">{t("sidebar.people.failed")}</span>+ <button type="button" onClick={retryTeamPeople} data-people-retry className="shrink-0 rounded-md px-1.5 text-[12px] font-medium text-accent hover:bg-raised/60">{t("sidebar.people.retry")}</button>+ </div>+ )}+ </section>+ );+}++/** `onOpened`: a row was chosen (the phone's full-screen list closes then). */+export function SidebarPeople({ compact, onOpened }: { compact: boolean; onOpened?: () => void }) {const team = useTeamPeople();const { state, dispatch } = useStore();const showThreads = useShowThreads();- if (!team) return null;+ if (!team) return state.config?.team ? <PeopleStatusLine compact={compact} /> : null;const invite = team.admin ? teamPeoplePage(state.config?.team) : null;if (team.people.length < 2 && !invite) return null;const me = team.me;- const people = [...team.people].sort((a, b) => Number(Boolean(b.you)) - Number(Boolean(a.you)) || a.name.localeCompare(b.name));+ const presence = team.presence === true;+ const people = peopleInOrder(team.people);const inbox = inboxBotOf(state.bots, me?.email);const inboxThread = inbox?.tasks?.find((task) => task.inbox)?.threadId;const waiting = inbox ? openAsksOf(inbox) : 0;const open = (person: TeamPerson) => {+ openPerson(person);+ onOpened?.();+ };+ const openPerson = (person: TeamPerson) => {if (person.you) {if (inbox) openBot(dispatch, inbox, showThreads);if (inboxThread) openInbox();@@ -69,13 +103,17 @@ export function SidebarPeople({ compact }: { compact: boolean }) {{!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")}>{people.map((person) => {- const label = !person.you ? t("sidebar.people.mention", { name: person.name })+ const label = !person.you ? teammateLabel(person, presence): waiting ? t("sidebar.people.yourInboxWaiting", { count: waiting }) : t("sidebar.people.yourInbox");+ const here = presence && !person.you && person.here === true;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")}>- <PersonFace person={person} size={compact ? 22 : 18} />+ <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} />}+ </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}diff --git a/src/components/TeamPresence.tsx b/src/components/TeamPresence.tsxnew file mode 100644index 0000000000..8fb3e26619--- /dev/null+++ b/src/components/TeamPresence.tsx@@ -0,0 +1,36 @@+// Who is here on a team: the dot on a teammate's face, and the faces of the others who have a shared chat or a group+// chat open, at the right of its header. Nothing in a private chat, and nothing at all against a server that sends no+// presence.+import { cn } from "@/lib/cn";+import { activeLocale, t } from "@/lib/i18n";+import { useThreadPresence } from "@/state/team-presence";+import { PersonFace } from "./TeamOwner";++/** On a face of `size`: this person is here now. `edge` is the surface behind it, so the dot reads as cut out of it. */+export function HereDot({ size, edge = "panel" }: { size: number; edge?: "panel" | "app" }) {+ const dot = Math.max(7, Math.round(size * 0.3));+ return <span aria-hidden="true" data-here-dot style={{ width: dot, height: dot }}+ className={cn("absolute -bottom-px -right-px rounded-full bg-success ring-2", edge === "app" ? "ring-app" : "ring-panel")} />;+}++const FACES = 3;+const FACE = 24;+const names = (people: ReadonlyArray<{ name: string }>) => new Intl.ListFormat(activeLocale(), { type: "conjunction" }).format(people.map((person) => person.name));++/** At the right of a shared conversation's header: the faces of the others who have it open now. */+export function ThreadPresenceFaces({ threadId }: { threadId: string }) {+ const { here } = useThreadPresence(threadId);+ if (here.length === 0) return null;+ const label = t(here.length === 1 ? "presence.hasOpen" : "presence.haveOpen", { names: names(here) });+ const more = here.length - FACES;+ return (+ <span role="img" aria-label={label} title={label} data-thread-presence={here.length} className="flex shrink-0 items-center -space-x-1.5">+ {here.slice(0, FACES).map((person) => (+ <span key={person.email} className="relative inline-flex rounded-full ring-2 ring-app"><PersonFace person={person} size={FACE} /><HereDot size={FACE} edge="app" /></span>+ ))}+ {more > 0 && (+ <span className="relative flex h-6 min-w-6 items-center justify-center rounded-full border border-app bg-raised px-1 text-[11px] font-medium tabular-nums text-ink-secondary">+{more}</span>+ )}+ </span>+ );+}diff --git a/src/locales/en.json b/src/locales/en.jsonindex df0e4cfd02..249878d302 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -2281,6 +2281,12 @@"inbox.headline.connect": "Connect {app}","inbox.youReplied": "You replied","sidebar.people.mention": "Write to {name}",+ "sidebar.people.mentionHere": "Write to {name}. Here now",+ "sidebar.people.loading": "Loading people…",+ "sidebar.people.failed": "Couldn't load people",+ "sidebar.people.retry": "Try again",+ "presence.hasOpen": "{names} has this open",+ "presence.haveOpen": "{names} have this open","orgChart.mode.departments": "Departments","orgChart.chief": "Chief of Staff","newBot.sharedWith": "Shared with everyone in {team}.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex eaae453b01..2139b4bd1a 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -2158,6 +2158,12 @@"inbox.headline.connect": "Conectar {app}","inbox.youReplied": "Você respondeu","sidebar.people.mention": "Escrever para {name}",+ "sidebar.people.mentionHere": "Escrever para {name}. Aqui agora",+ "sidebar.people.loading": "Carregando pessoas…",+ "sidebar.people.failed": "Não foi possível carregar as pessoas",+ "sidebar.people.retry": "Tentar novamente",+ "presence.hasOpen": "{names} está com esta conversa aberta",+ "presence.haveOpen": "{names} estão com esta conversa aberta","orgChart.mode.departments": "Equipes","orgChart.chief": "Chefe de gabinete","newBot.sharedWith": "Compartilhado com todos em {team}.",diff --git a/src/state/team-chats.ts b/src/state/team-chats.tsindex 0ae0889d0e..cf1e7a3f46 100644--- a/src/state/team-chats.ts+++ b/src/state/team-chats.ts@@ -75,6 +75,15 @@ export function teamOfConfig(config: unknown): { id: string } | null {return typeof team?.id === "string" && team.id ? { id: team.id } : null;}+/** 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 ?? [] });+ }).catch(() => {});+}+/** Keeps the sidebar's rule in step with the page's server: on a team, the person's own conversations; a Member until* the session says otherwise is never assumed (an Admin's rule is the safe one). */export function useTeamChats(config: unknown) {diff --git a/src/state/team-people.ts b/src/state/team-people.tsindex 6703b2fa15..2516f21965 100644--- a/src/state/team-people.ts+++ b/src/state/team-people.ts@@ -3,15 +3,18 @@import { useEffect, useMemo, useSyncExternalStore } from "react";import { botOwner, nameFromEmail } from "../../shared/bot-owner";import { mentionablePeople } from "../../shared/person-mention";+import type { PersonPresence } from "../../shared/team-presence";import type { NeedsYouItem } from "../../shared/today";import { api } from "./api";import { teamOfConfig } from "./team-chats";import { openAsksOf } from "@/lib/bot-unread";import { readSessionState } from "@/lib/session";-/** `pictureUrl`: their picture, served to the team's members only; absent when they have none. */-export interface TeamPerson { email: string; name: string; role: string; you?: true; pictureUrl?: string }-export interface TeamPeople { people: TeamPerson[]; me: TeamPerson | null; admin: boolean; needsYou: NeedsYouItem[] }+/** `pictureUrl`: their picture, served to the team's members only; absent when they have none. `here`: whether they are+ * here now (shared/team-presence.ts). */+export interface TeamPerson extends PersonPresence { email: string; name: string; role: string; you?: true; pictureUrl?: string }+/** `presence`: the server says who is here; an older one does not, and nothing about it shows. */+export interface TeamPeople { people: TeamPerson[]; me: TeamPerson | null; admin: boolean; needsYou: NeedsYouItem[]; presence?: boolean }let snapshot: TeamPeople | null = null;const listeners = new Set<() => void>();@@ -87,8 +90,9 @@ export function askingWhom(bot: { createdBy?: string; reportsTo?: string }, taskasync function loadPeople(): Promise<Omit<TeamPeople, "admin" | "needsYou">> {const answer = await api<{ people?: TeamPerson[] }>("/api/team/people", { background: true });const people = Array.isArray(answer?.people) ? answer.people : [];- return { people, me: people.find((person) => person.you) ?? null };+ return { people, me: people.find((person) => person.you) ?? null, presence: people.some((person) => typeof person.here === "boolean") };}+const adminOf = (session: Awaited<ReturnType<typeof readSessionState>>) => session.kind === "session" ? session.scopes.includes("admin") : session.kind === "loopback";async function loadNeedsYou(): Promise<NeedsYouItem[]> {const answer = await api<{ items?: NeedsYouItem[] }>("/api/needs-you", { background: true });return Array.isArray(answer?.items) ? answer.items : [];@@ -123,16 +127,49 @@ function refreshPeople(): void {}, 800);}+/** Someone joined, left or changed role (theirs or this person's own): the people and this session's role again. */+export function reloadTeamPeople(): void {+ if (!snapshot) return;+ void Promise.all([loadPeople(), readSessionState()]).then(([people, session]) => {+ if (snapshot) publish({ ...snapshot, ...people, admin: adminOf(session) });+ }).catch(() => {});+}++/** Whether the people are on their way, or could not be read. */+export type TeamPeopleStatus = "loading" | "failed" | "ready";+let status: TeamPeopleStatus = "ready";+const statusListeners = new Set<() => void>();+function setStatus(next: TeamPeopleStatus): void {+ status = next;+ for (const listener of statusListeners) listener();+}+export function useTeamPeopleStatus(): TeamPeopleStatus {+ return useSyncExternalStore((listener) => {+ statusListeners.add(listener);+ return () => statusListeners.delete(listener);+ }, () => status, () => status);+}++let generation = 0;+function loadTeam(): void {+ const mine = ++generation;+ setStatus("loading");+ void Promise.all([loadPeople(), readSessionState(), loadNeedsYou()]).then(([people, session, needsYou]) => {+ if (mine !== generation) return;+ publish({ ...people, admin: adminOf(session), needsYou });+ setStatus("ready");+ }).catch(() => { if (mine === generation) setStatus("failed"); });+}+/** The people could not be read: try again. */+export const retryTeamPeople = loadTeam;+/** Keeps the people and this person's Needs you in step with the page's server; nothing off a team. */export function useTeamPeopleLoader(config: unknown, botsVersion: unknown) {const teamId = teamOfConfig(config)?.id ?? null;useEffect(() => {- if (!teamId) { publish(null); return; }- let alive = true;- void Promise.all([loadPeople(), readSessionState(), loadNeedsYou()]).then(([people, session, needsYou]) => {- if (alive) publish({ ...people, admin: session.kind === "session" ? session.scopes.includes("admin") : session.kind === "loopback", needsYou });- }).catch(() => {});- return () => { alive = false; };+ if (!teamId) { generation += 1; publish(null); setStatus("ready"); return; }+ loadTeam();+ return () => { generation += 1; };}, [teamId]);useEffect(() => { if (teamId) refreshNeedsYou(); }, [teamId, botsVersion]);useEffect(() => { if (teamId) refreshPeople(); }, [teamId, config]);diff --git a/src/state/team-presence.dom.test.ts b/src/state/team-presence.dom.test.tsnew file mode 100644index 0000000000..f4cd6f01cf--- /dev/null+++ b/src/state/team-presence.dom.test.ts@@ -0,0 +1,147 @@+// @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";++const sent = vi.hoisted(() => [] as Array<{ path: string; body: unknown; background?: boolean }>);+const { BEN, CLEO, ADA } = vi.hoisted(() => ({+ BEN: { email: "[email protected]", name: "Ben", role: "member", you: true as const, here: true },+ CLEO: { email: "[email protected]", name: "Cleo", role: "owner", here: true },+ ADA: { email: "[email protected]", name: "Ada", role: "admin", here: false },+}));+vi.mock("./api", async (original) => ({ ...await original<typeof import("./api")>(),+ api: vi.fn(async (path: string, init?: { body?: string; background?: boolean }) => {+ if (path === "/api/team/people") return { people: [BEN, CLEO, ADA] };+ sent.push({ path, body: init?.body ? JSON.parse(init.body) : undefined, background: init?.background });+ return {};+ }) }));++import { HereDot, ThreadPresenceFaces } from "@/components/TeamPresence";+import { SidebarPeople } from "@/components/SidebarPeople";+import { setLocale } from "@/lib/i18n";+import { publishLiveFrame, publishMissedFrames } from "@/lib/live-events";+import { initialState, StoreContext, type AppState, type Bot } from "./store";+import { setTeamPeople, type TeamPeople } from "./team-people";+import { sharedThreadOf, useTeamPresence } from "./team-presence";++const team: TeamPeople = { people: [BEN, CLEO, ADA], me: BEN, admin: false, needsYou: [], presence: true };+const bot = (overrides: Partial<Bot> = {}): Bot => ({+ id: "scout", threadId: "scout-main", name: "Scout", title: "", description: "", notifications: true, color: "green", unread: false,+ modelSelection: { instanceId: "claude", model: "test" }, messages: [],+ tasks: [{ threadId: "scout-main", title: "Shared chat", createdAt: 1 }, { threadId: "ben-own", title: "Mine", createdAt: 2, private: true }], ...overrides,+});++let container: HTMLDivElement, root: Root;+const state = (overrides: Partial<AppState> = {}) => ({ ...initialState, hydrated: true, activeView: "chat", selectedId: "scout", bots: [bot()], config: { team: { id: "t", name: "Acme" } }, ...overrides }) as AppState;+const draw = (child: ReturnType<typeof createElement>, value: AppState = state(), dispatch = vi.fn()) => act(() => {+ root.render(createElement(StoreContext.Provider, { value: { state: value, dispatch, flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn() } as never }, child));+});+function Pinger({ value }: { value: AppState }) {+ useTeamPresence(value);+ return null;+}++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ kind: "session", id: "s1", scopes: ["client"] }), { status: 200 })));+ setLocale("en");+ sent.length = 0;+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(() => {+ act(() => root.unmount());+ container.remove();+ act(() => setTeamPeople(null));+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe("the conversation the server is told about", () => {+ it("is a shared chat or a group chat, never a private chat or a member's own MausBot", () => {+ expect(sharedThreadOf(state())).toBe("scout-main");+ expect(sharedThreadOf(state({ bots: [bot({ threadId: "ben-own" })] }))).toBeNull();+ expect(sharedThreadOf(state({ bots: [bot({ defaultBot: { person: BEN.email } })] }))).toBeNull();+ expect(sharedThreadOf(state({ selectedId: "g1", groups: [{ id: "g1", threadId: "room-1" }] as AppState["groups"] }))).toBe("room-1");+ expect(sharedThreadOf(state({ activeView: "routines" }))).toBeNull();+ });++ it("is sent when it changes, and as no conversation in a private chat", async () => {+ vi.useFakeTimers();+ act(() => setTeamPeople(team));+ await draw(createElement(Pinger, { value: state() }));+ await act(async () => { vi.advanceTimersByTime(300); });+ expect(sent.at(-1)).toMatchObject({ path: "/api/presence/here", body: { threadId: "scout-main" } });+ const tab = (sent.at(-1)!.body as { tab: string }).tab;+ expect(tab).toMatch(/^[\w-]{1,64}$/);+ await draw(createElement(Pinger, { value: state({ bots: [bot({ threadId: "ben-own" })] }) }));+ await act(async () => { vi.advanceTimersByTime(300); });+ expect(sent.at(-1)!.body).toEqual({ tab, threadId: null });+ expect(JSON.stringify(sent), "the private chat is never named").not.toContain("ben-own");+ });++ it("is sent again as a new window when the stream missed frames, so the server sends the lists again", async () => {+ vi.useFakeTimers();+ act(() => setTeamPeople(team));+ await draw(createElement(Pinger, { value: state() }));+ await act(async () => { vi.advanceTimersByTime(300); });+ const first = sent.at(-1)!.body as { tab: string };+ act(() => publishMissedFrames());+ const again = sent.at(-1)!.body as { tab: string; threadId: string };+ expect(again.threadId).toBe("scout-main");+ expect(again.tab).not.toBe(first.tab);+ await act(async () => { await vi.runOnlyPendingTimersAsync(); });+ });++ it("is never sent to a server that says nothing about presence", async () => {+ vi.useFakeTimers();+ act(() => setTeamPeople({ ...team, presence: undefined }));+ await draw(createElement(Pinger, { value: state() }));+ await act(async () => { vi.advanceTimersByTime(70_000); });+ expect(sent).toEqual([]);+ });+});++describe("what the server says back", () => {+ it("shows the faces of the others who have a shared chat open", async () => {+ act(() => setTeamPeople(team));+ await draw(createElement("div", null, createElement(Pinger, { value: state() }), createElement(ThreadPresenceFaces, { threadId: "scout-main" })));+ expect(container.querySelector("[data-thread-presence]")).toBeNull();+ act(() => publishLiveFrame({ kind: "thread.presence", threadId: "scout-main", people: [BEN.email, CLEO.email] }));+ const faces = container.querySelector("[data-thread-presence]")!;+ expect(faces.getAttribute("data-thread-presence")).toBe("1");+ expect(faces.getAttribute("aria-label")).toBe("Cleo has this open");+ expect(faces.querySelectorAll("[data-here-dot]")).toHaveLength(1);+ act(() => publishLiveFrame({ kind: "thread.presence", threadId: "scout-main", people: [ADA.email, BEN.email, CLEO.email] }));+ expect(container.querySelector("[data-thread-presence]")!.getAttribute("aria-label")).toBe("Ada and Cleo have this open");+ act(() => publishLiveFrame({ kind: "thread.presence", threadId: "scout-main", people: [BEN.email] }));+ expect(container.querySelector("[data-thread-presence]")).toBeNull();+ });++ it("moves the dot as people come and go, and never shows one on your own row", async () => {+ act(() => setTeamPeople(team));+ await draw(createElement("div", null, createElement(Pinger, { value: state() }), createElement(SidebarPeople, { compact: false })));+ const dotOn = (email: string) => container.querySelector(`[data-person="${email}"] [data-here-dot]`) !== null;+ expect([dotOn(BEN.email), dotOn(CLEO.email), dotOn(ADA.email)]).toEqual([false, true, false]);+ act(() => publishLiveFrame({ kind: "team.presence", email: CLEO.email, here: false }));+ act(() => publishLiveFrame({ kind: "team.presence", email: ADA.email, here: true }));+ expect([dotOn(CLEO.email), dotOn(ADA.email)]).toEqual([false, true]);+ expect(container.querySelector(`[data-person="${CLEO.email}"]`)!.getAttribute("aria-label")).toBe("Write to Cleo");+ expect(container.querySelector(`[data-person="${ADA.email}"]`)!.getAttribute("aria-label")).toBe("Write to Ada. Here now");+ expect(container.querySelector("[data-sidebar-people]")!.textContent, "no time of when anyone was here").not.toMatch(/ago|last/i);+ });++ it("closes the phone's full-screen list when a person is chosen", async () => {+ act(() => setTeamPeople(team));+ const onOpened = vi.fn();+ await draw(createElement(SidebarPeople, { compact: false, onOpened }));+ act(() => (container.querySelector(`[data-person="${CLEO.email}"]`) as HTMLButtonElement).click());+ expect(onOpened).toHaveBeenCalledTimes(1);+ });++ it("has a dot that reads as part of the face", () => {+ act(() => root.render(createElement(HereDot, { size: 24, edge: "app" })));+ expect(container.querySelector("[data-here-dot]")!.className).toContain("ring-app");+ });+});diff --git a/src/state/team-presence.ts b/src/state/team-presence.tsnew file mode 100644index 0000000000..e253ec3d52--- /dev/null+++ b/src/state/team-presence.ts@@ -0,0 +1,118 @@+// Who is here on a team's Cloud (docs/team-cloud.md "Who is here"): this window tells the server which shared+// conversation is in front of the person, and keeps what the server says back: who is here (on the people list) and who+// else has a shared conversation open. A private chat is never named to the server here: the window says it shows no+// conversation. Nothing at all against a server that sends no presence.+import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";+import { HERE_REPEAT_MS, PRESENCE_HERE_PATH, type PresenceFrame, type PresenceHereBody } from "../../shared/team-presence";+import type { ServerFrame } from "../../shared/wire";+import { listenLiveFrames } from "@/lib/live-events";+import { api } from "./api";+import type { AppState } from "./store";+import { rereadTeamChats } from "./team-chats";+import { currentTeamPeople, reloadTeamPeople, setTeamPeople, useTeamPeople, type TeamPerson } from "./team-people";++const NOBODY: readonly string[] = [];+let threads = new Map<string, readonly string[]>();+const listeners = new Set<() => void>();+function setThreads(next: Map<string, readonly string[]>): void {+ threads = next;+ for (const listener of listeners) listener();+}++/** A frame about presence, from the live stream. */+export function applyPresenceFrame(frame: PresenceFrame): void {+ switch (frame.kind) {+ case "team.presence": {+ const team = currentTeamPeople();+ if (!team) return;+ if (!team.people.some((person) => person.email === frame.email)) return reloadTeamPeople();+ const people = team.people.map((person) => person.email === frame.email ? { ...person, here: frame.here } : person);+ setTeamPeople({ ...team, people, me: people.find((person) => person.you) ?? null, presence: true });+ return;+ }+ case "thread.presence":+ return setThreads(new Map(threads).set(frame.threadId, frame.people));+ case "team.people":+ reloadTeamPeople();+ rereadTeamChats();+ }+}++const PRESENCE_KINDS = new Set<string>(["team.presence", "thread.presence", "team.people"]);+const isPresenceFrame = (frame: ServerFrame): frame is PresenceFrame => PRESENCE_KINDS.has(frame.kind);++/** The others who have this shared conversation open now; empty for any other conversation. */+export function useThreadPresence(threadId: string | null | undefined): { here: TeamPerson[] } {+ const team = useTeamPeople();+ const emails = useSyncExternalStore((listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ }, () => (threadId ? threads.get(threadId) : undefined) ?? NOBODY, () => NOBODY);+ return useMemo(() => {+ if (!team?.presence || !threadId) return { here: [] };+ return { here: emails.flatMap((email) => {+ const person = team.people.find((one) => one.email === email);+ return person && !person.you ? [person] : [];+ }) };+ }, [team, threadId, emails]);+}++/** The conversation in front of the person when it is one others can read too: a team bot's shared chat or a group+ * chat. Null for a private chat, a member's own MausBot, and anywhere that is not a chat. */+export function sharedThreadOf(state: Pick<AppState, "activeView" | "selectedId" | "bots" | "groups">): string | null {+ if (state.activeView !== "chat") return null;+ const group = state.groups.find((one) => one.id === state.selectedId);+ if (group) return group.threadId;+ const bot = state.bots.find((one) => one.id === state.selectedId);+ if (!bot || bot.defaultBot?.person) return null;+ const threadId = bot.switchingTo ?? bot.threadId;+ return bot.tasks?.find((task) => task.threadId === threadId)?.private === true ? null : threadId;+}++const newTab = () => (globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`).slice(0, 64);++/** On a team whose server says who is here: keeps the server told which shared conversation this window shows, and keeps+ * what it says back. */+export function useTeamPresence(state: Pick<AppState, "activeView" | "selectedId" | "bots" | "groups">): void {+ const team = useTeamPeople();+ const supported = team?.presence === true;+ const open = supported ? sharedThreadOf(state) : null;+ const latest = useRef({ open, supported });+ latest.current = { open, supported };+ const send = useRef<() => void>(() => {});+ const missed = useRef<() => void>(() => {});++ // A stream that came back without its replay missed frames: the people again, and this window anew, so the server+ // sends the lists again.+ useEffect(() => listenLiveFrames({+ onFrame: (frame) => { if (isPresenceFrame(frame)) applyPresenceFrame(frame); },+ onMissedFrames: () => { setThreads(new Map()); reloadTeamPeople(); missed.current(); },+ }), []);++ useEffect(() => {+ if (!supported) { setThreads(new Map()); return; }+ let tab = newTab();+ const visible = () => typeof document === "undefined" || document.visibilityState !== "hidden";+ const post = (body: PresenceHereBody, background: boolean) =>+ void api(PRESENCE_HERE_PATH, { method: "POST", body: JSON.stringify(body), background }).catch(() => {});+ send.current = () => {+ if (latest.current.supported) post({ tab, threadId: visible() ? latest.current.open : null }, visible());+ };+ const onVisibility = () => send.current();+ const repeat = setInterval(() => { if (visible()) send.current(); }, HERE_REPEAT_MS);+ missed.current = () => { tab = newTab(); send.current(); };+ document.addEventListener("visibilitychange", onVisibility);+ return () => {+ clearInterval(repeat);+ document.removeEventListener("visibilitychange", onVisibility);+ send.current = () => {};+ missed.current = () => {};+ };+ }, [supported]);++ useEffect(() => {+ if (!supported) return;+ const timer = setTimeout(() => send.current(), 250);+ return () => clearTimeout(timer);+ }, [supported, open]);+}